diff --git a/esm.mjs b/esm.mjs index 4d404070d..0843cf349 100644 --- a/esm.mjs +++ b/esm.mjs @@ -4,9 +4,5 @@ const require = createRequire(fileURLToPath(import.meta.url)); /** @type {import('./dist/esm')} */ const esm = require('./dist/esm'); -export const { - resolve, - load, - getFormat, - transformSource, -} = esm.registerAndCreateEsmHooks(); +export const { resolve, load, getFormat, transformSource } = + esm.registerAndCreateEsmHooks(); diff --git a/esm/transpile-only.mjs b/esm/transpile-only.mjs index 07b2c7ae6..2e154da09 100644 --- a/esm/transpile-only.mjs +++ b/esm/transpile-only.mjs @@ -4,9 +4,5 @@ const require = createRequire(fileURLToPath(import.meta.url)); /** @type {import('../dist/esm')} */ const esm = require('../dist/esm'); -export const { - resolve, - load, - getFormat, - transformSource, -} = esm.registerAndCreateEsmHooks({ transpileOnly: true }); +export const { resolve, load, getFormat, transformSource } = + esm.registerAndCreateEsmHooks({ transpileOnly: true }); diff --git a/scripts/create-merged-schema.ts b/scripts/create-merged-schema.ts index 4016fd339..934ff4717 100755 --- a/scripts/create-merged-schema.ts +++ b/scripts/create-merged-schema.ts @@ -37,8 +37,7 @@ async function main() { .compilerOptions, allOf: [ { - $ref: - '#/definitions/compilerOptionsDefinition/properties/compilerOptions', + $ref: '#/definitions/compilerOptionsDefinition/properties/compilerOptions', }, ], }, @@ -62,9 +61,7 @@ async function main() { } export async function getSchemastoreSchema() { - const { - data: schemastoreSchema, - } = await axios.get( + const { data: schemastoreSchema } = await axios.get( 'https://schemastore.azurewebsites.net/schemas/json/tsconfig.json', { responseType: 'json' } ); diff --git a/src/bin.ts b/src/bin.ts index d97261a3b..a0420e1e6 100644 --- a/src/bin.ts +++ b/src/bin.ts @@ -292,7 +292,7 @@ export function main( } if (showConfig) { - const ts = (service.ts as any) as TSInternal; + const ts = service.ts as any as TSInternal; if (typeof ts.convertToTSConfig !== 'function') { console.error( 'Error: --show-config requires a typescript versions >=3.2 that support --showConfig' diff --git a/src/configuration.ts b/src/configuration.ts index 8acff0503..4ac594155 100644 --- a/src/configuration.ts +++ b/src/configuration.ts @@ -142,7 +142,7 @@ export function readConfig( }, bp, errors, - ((ts as unknown) as TSInternal).createCompilerDiagnostic + (ts as unknown as TSInternal).createCompilerDiagnostic ); if (errors.length) { return { @@ -165,8 +165,9 @@ export function readConfig( const optionBasePaths: OptionBasePaths = {}; for (let i = configChain.length - 1; i >= 0; i--) { const { config, basePath, configPath } = configChain[i]; - const options = filterRecognizedTsConfigTsNodeOptions(config['ts-node']) - .recognized; + const options = filterRecognizedTsConfigTsNodeOptions( + config['ts-node'] + ).recognized; // Some options are relative to the config file, so must be converted to absolute paths here if (options.require) { @@ -250,9 +251,7 @@ export function readConfig( * Given the raw "ts-node" sub-object from a tsconfig, return an object with only the properties * recognized by "ts-node" */ -function filterRecognizedTsConfigTsNodeOptions( - jsonObject: any -): { +function filterRecognizedTsConfigTsNodeOptions(jsonObject: any): { recognized: TsConfigOptions; unrecognized: any; } { @@ -303,7 +302,9 @@ function filterRecognizedTsConfigTsNodeOptions( swc, }; // Use the typechecker to make sure this implementation has the correct set of properties - const catchExtraneousProps: keyof TsConfigOptions = (null as any) as keyof typeof filteredTsConfigOptions; - const catchMissingProps: keyof typeof filteredTsConfigOptions = (null as any) as keyof TsConfigOptions; + const catchExtraneousProps: keyof TsConfigOptions = + null as any as keyof typeof filteredTsConfigOptions; + const catchMissingProps: keyof typeof filteredTsConfigOptions = + null as any as keyof TsConfigOptions; return { recognized: filteredTsConfigOptions, unrecognized }; } diff --git a/src/index.ts b/src/index.ts index b3506a4cd..a8918a741 100644 --- a/src/index.ts +++ b/src/index.ts @@ -577,12 +577,8 @@ export function create(rawOptions: CreateOptions = {}): Service { ); // Read config file and merge new options between env and CLI options. - const { - configFilePath, - config, - tsNodeOptionsFromTsconfig, - optionBasePaths, - } = readConfig(cwd, ts, rawOptions); + const { configFilePath, config, tsNodeOptionsFromTsconfig, optionBasePaths } = + readConfig(cwd, ts, rawOptions); const options = assign( {}, DEFAULTS, @@ -817,9 +813,9 @@ export function create(rawOptions: CreateOptions = {}): Service { _position: number ) => TypeInfo; - const getCanonicalFileName = ((ts as unknown) as TSInternal).createGetCanonicalFileName( - ts.sys.useCaseSensitiveFileNames - ); + const getCanonicalFileName = ( + ts as unknown as TSInternal + ).createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames); const moduleTypeClassifier = createModuleTypeClassifier({ basePath: options.optionBasePaths?.moduleTypes, @@ -908,8 +904,10 @@ export function create(rawOptions: CreateOptions = {}): Service { configFilePath, }); serviceHost.resolveModuleNames = resolveModuleNames; - serviceHost.getResolvedModuleWithFailedLookupLocationsFromCache = getResolvedModuleWithFailedLookupLocationsFromCache; - serviceHost.resolveTypeReferenceDirectives = resolveTypeReferenceDirectives; + serviceHost.getResolvedModuleWithFailedLookupLocationsFromCache = + getResolvedModuleWithFailedLookupLocationsFromCache; + serviceHost.resolveTypeReferenceDirectives = + resolveTypeReferenceDirectives; const registry = ts.createDocumentRegistry( ts.sys.useCaseSensitiveFileNames, @@ -1272,9 +1270,8 @@ export function create(rawOptions: CreateOptions = {}): Service { // Create a simple TypeScript compiler proxy. function compile(code: string, fileName: string, lineOffset = 0) { const normalizedFileName = normalizeSlashes(fileName); - const classification = moduleTypeClassifier.classifyModule( - normalizedFileName - ); + const classification = + moduleTypeClassifier.classifyModule(normalizedFileName); // Must always call normal getOutput to throw typechecking errors let [value, sourceMap] = getOutput(code, normalizedFileName); // If module classification contradicts the above, call the relevant transpiler diff --git a/src/resolver-functions.ts b/src/resolver-functions.ts index df7db9aab..a624e6940 100644 --- a/src/resolver-functions.ts +++ b/src/resolver-functions.ts @@ -13,14 +13,8 @@ export function createResolverFunctions(kwargs: { config: _ts.ParsedCommandLine; configFilePath: string | undefined; }) { - const { - host, - ts, - config, - cwd, - getCanonicalFileName, - configFilePath, - } = kwargs; + const { host, ts, config, cwd, getCanonicalFileName, configFilePath } = + kwargs; const moduleResolutionCache = ts.createModuleResolutionCache( cwd, getCanonicalFileName, @@ -105,69 +99,71 @@ export function createResolverFunctions(kwargs: { }; // language service never calls this, but TS docs recommend that we implement it - const getResolvedModuleWithFailedLookupLocationsFromCache: _ts.LanguageServiceHost['getResolvedModuleWithFailedLookupLocationsFromCache'] = ( - moduleName, - containingFile - ): _ts.ResolvedModuleWithFailedLookupLocations | undefined => { - const ret = ts.resolveModuleNameFromCache( + const getResolvedModuleWithFailedLookupLocationsFromCache: _ts.LanguageServiceHost['getResolvedModuleWithFailedLookupLocationsFromCache'] = + ( moduleName, - containingFile, - moduleResolutionCache - ); - if (ret && ret.resolvedModule) { - fixupResolvedModule(ret.resolvedModule); - } - return ret; - }; - - const resolveTypeReferenceDirectives: _ts.LanguageServiceHost['resolveTypeReferenceDirectives'] = ( - typeDirectiveNames: string[], - containingFile: string, - redirectedReference: _ts.ResolvedProjectReference | undefined, - options: _ts.CompilerOptions - ): (_ts.ResolvedTypeReferenceDirective | undefined)[] => { - // Note: seems to be called with empty typeDirectiveNames array for all files. - return typeDirectiveNames.map((typeDirectiveName) => { - let { resolvedTypeReferenceDirective } = ts.resolveTypeReferenceDirective( - typeDirectiveName, + containingFile + ): _ts.ResolvedModuleWithFailedLookupLocations | undefined => { + const ret = ts.resolveModuleNameFromCache( + moduleName, containingFile, - config.options, - host, - redirectedReference + moduleResolutionCache ); - if (typeDirectiveName === 'node' && !resolvedTypeReferenceDirective) { - // Resolve @types/node relative to project first, then __dirname (copy logic from elsewhere / refactor into reusable function) - let typesNodePackageJsonPath: string | undefined; - try { - typesNodePackageJsonPath = require.resolve( - '@types/node/package.json', - { - paths: [configFilePath ?? cwd, __dirname], - } - ); - } catch {} // gracefully do nothing when @types/node is not installed for any reason - if (typesNodePackageJsonPath) { - const typeRoots = [resolve(typesNodePackageJsonPath, '../..')]; - ({ - resolvedTypeReferenceDirective, - } = ts.resolveTypeReferenceDirective( + if (ret && ret.resolvedModule) { + fixupResolvedModule(ret.resolvedModule); + } + return ret; + }; + + const resolveTypeReferenceDirectives: _ts.LanguageServiceHost['resolveTypeReferenceDirectives'] = + ( + typeDirectiveNames: string[], + containingFile: string, + redirectedReference: _ts.ResolvedProjectReference | undefined, + options: _ts.CompilerOptions + ): (_ts.ResolvedTypeReferenceDirective | undefined)[] => { + // Note: seems to be called with empty typeDirectiveNames array for all files. + return typeDirectiveNames.map((typeDirectiveName) => { + let { resolvedTypeReferenceDirective } = + ts.resolveTypeReferenceDirective( typeDirectiveName, containingFile, - { - ...config.options, - typeRoots, - }, + config.options, host, redirectedReference - )); + ); + if (typeDirectiveName === 'node' && !resolvedTypeReferenceDirective) { + // Resolve @types/node relative to project first, then __dirname (copy logic from elsewhere / refactor into reusable function) + let typesNodePackageJsonPath: string | undefined; + try { + typesNodePackageJsonPath = require.resolve( + '@types/node/package.json', + { + paths: [configFilePath ?? cwd, __dirname], + } + ); + } catch {} // gracefully do nothing when @types/node is not installed for any reason + if (typesNodePackageJsonPath) { + const typeRoots = [resolve(typesNodePackageJsonPath, '../..')]; + ({ resolvedTypeReferenceDirective } = + ts.resolveTypeReferenceDirective( + typeDirectiveName, + containingFile, + { + ...config.options, + typeRoots, + }, + host, + redirectedReference + )); + } } - } - if (resolvedTypeReferenceDirective) { - fixupResolvedModule(resolvedTypeReferenceDirective); - } - return resolvedTypeReferenceDirective; - }); - }; + if (resolvedTypeReferenceDirective) { + fixupResolvedModule(resolvedTypeReferenceDirective); + } + return resolvedTypeReferenceDirective; + }); + }; return { resolveModuleNames, diff --git a/src/test/index.spec.ts b/src/test/index.spec.ts index 1c7bbcc21..40f12ca59 100644 --- a/src/test/index.spec.ts +++ b/src/test/index.spec.ts @@ -1086,10 +1086,7 @@ test.suite('ts-node', (test) => { test.suite('supports experimental-specifier-resolution=node', (test) => { test('via --experimental-specifier-resolution', async () => { - const { - err, - stdout, - } = await exec( + const { err, stdout } = await exec( `${CMD_ESM_LOADER_WITHOUT_PROJECT} --experimental-specifier-resolution=node index.ts`, { cwd: join(TEST_DIR, './esm-node-resolver') } ); @@ -1097,10 +1094,7 @@ test.suite('ts-node', (test) => { expect(stdout).toBe('foo bar baz biff libfoo\n'); }); test('via --es-module-specifier-resolution alias', async () => { - const { - err, - stdout, - } = await exec( + const { err, stdout } = await exec( `${CMD_ESM_LOADER_WITHOUT_PROJECT} ${EXPERIMENTAL_MODULES_FLAG} --es-module-specifier-resolution=node index.ts`, { cwd: join(TEST_DIR, './esm-node-resolver') } ); diff --git a/src/test/register.spec.ts b/src/test/register.spec.ts index db04b2846..97769283c 100644 --- a/src/test/register.spec.ts +++ b/src/test/register.spec.ts @@ -12,7 +12,8 @@ import * as exp from 'expect'; import { join, resolve } from 'path'; import proxyquire = require('proxyquire'); -const SOURCE_MAP_REGEXP = /\/\/# sourceMappingURL=data:application\/json;charset=utf\-8;base64,[\w\+]+=*$/; +const SOURCE_MAP_REGEXP = + /\/\/# sourceMappingURL=data:application\/json;charset=utf\-8;base64,[\w\+]+=*$/; const createOptions: tsNodeTypes.CreateOptions = { project: PROJECT, diff --git a/src/test/repl/helpers.ts b/src/test/repl/helpers.ts index 310b8e221..a085a266e 100644 --- a/src/test/repl/helpers.ts +++ b/src/test/repl/helpers.ts @@ -39,9 +39,9 @@ export async function contextReplHelpers( stderr, ...createReplOpts, }); - const service = (registerHooks - ? tsNodeUnderTest.register - : tsNodeUnderTest.create)({ + const service = ( + registerHooks ? tsNodeUnderTest.register : tsNodeUnderTest.create + )({ ...replService.evalAwarePartialHost, project: `${TEST_DIR}/tsconfig.json`, ...createServiceOpts, diff --git a/src/test/repl/node-repl-tla.ts b/src/test/repl/node-repl-tla.ts index 616237926..5c4962e78 100644 --- a/src/test/repl/node-repl-tla.ts +++ b/src/test/repl/node-repl-tla.ts @@ -39,9 +39,11 @@ export async function upstreamTopLevelAwaitTests({ }, }); replService.setService(service); - (replService.stdout as NodeJS.WritableStream & { - isTTY: boolean; - }).isTTY = true; + ( + replService.stdout as NodeJS.WritableStream & { + isTTY: boolean; + } + ).isTTY = true; const replServer = replService.startInternal({ prompt: PROMPT, terminal: true, diff --git a/src/test/repl/repl-environment.spec.ts b/src/test/repl/repl-environment.spec.ts index 9071688c6..209f96487 100644 --- a/src/test/repl/repl-environment.spec.ts +++ b/src/test/repl/repl-environment.spec.ts @@ -45,53 +45,50 @@ test.suite( const globalInRepl = global as GlobalInRepl; const programmaticTest = test.macro( ( - { - evalCodeBefore, - stdinCode, - waitFor, - }: { - evalCodeBefore: string | null; - stdinCode: string; - waitFor?: () => boolean; - }, - assertions: (stdout: string) => Promise | void - ) => async (t) => { - delete globalInRepl.testReport; - delete globalInRepl.replReport; - delete globalInRepl.stdinReport; - delete globalInRepl.evalReport; - delete globalInRepl.module; - delete globalInRepl.exports; - delete globalInRepl.fs; - delete globalInRepl.__filename; - delete globalInRepl.__dirname; - const { - stdin, - stderr, - stdout, - replService, - } = t.context.createReplViaApi({ registerHooks: true }); - if (typeof evalCodeBefore === 'string') { - replService.evalCode(evalCodeBefore); + { + evalCodeBefore, + stdinCode, + waitFor, + }: { + evalCodeBefore: string | null; + stdinCode: string; + waitFor?: () => boolean; + }, + assertions: (stdout: string) => Promise | void + ) => + async (t) => { + delete globalInRepl.testReport; + delete globalInRepl.replReport; + delete globalInRepl.stdinReport; + delete globalInRepl.evalReport; + delete globalInRepl.module; + delete globalInRepl.exports; + delete globalInRepl.fs; + delete globalInRepl.__filename; + delete globalInRepl.__dirname; + const { stdin, stderr, stdout, replService } = + t.context.createReplViaApi({ registerHooks: true }); + if (typeof evalCodeBefore === 'string') { + replService.evalCode(evalCodeBefore); + } + replService.start(); + stdin.write(stdinCode); + stdin.end(); + let done = false; + await Promise.race([ + promisify(setTimeout)(20e3), + (async () => { + while (!done && !waitFor?.()) { + await promisify(setTimeout)(1e3); + } + })(), + ]); + done = true; + stdout.end(); + stderr.end(); + expect(await getStream(stderr)).toBe(''); + await assertions(await getStream(stdout)); } - replService.start(); - stdin.write(stdinCode); - stdin.end(); - let done = false; - await Promise.race([ - promisify(setTimeout)(20e3), - (async () => { - while (!done && !waitFor?.()) { - await promisify(setTimeout)(1e3); - } - })(), - ]); - done = true; - stdout.end(); - stderr.end(); - expect(await getStream(stderr)).toBe(''); - await assertions(await getStream(stdout)); - } ); const declareGlobals = `declare var replReport: any, stdinReport: any, evalReport: any, restReport: any, global: any, __filename: any, __dirname: any, module: any, exports: any;`; diff --git a/src/test/testlib.ts b/src/test/testlib.ts index ce97a07a3..72d059b39 100644 --- a/src/test/testlib.ts +++ b/src/test/testlib.ts @@ -20,12 +20,12 @@ const concurrencyLimiter = throat(16); function once(func: T): T { let run = false; let ret: any = undefined; - return (function (...args: any[]) { + return function (...args: any[]) { if (run) return ret; run = true; ret = func(...args); return ret; - } as any) as T; + } as any as T; } export const test = createTestInterface({ diff --git a/src/tsconfigs.ts b/src/tsconfigs.ts index 74a927449..cc104fd75 100644 --- a/src/tsconfigs.ts +++ b/src/tsconfigs.ts @@ -7,7 +7,7 @@ const nodeMajor = parseInt(process.versions.node.split('.')[0], 10); * @internal */ export function getDefaultTsconfigJsonForNodeVersion(ts: TSCommon): any { - const tsInternal = (ts as any) as TSInternal; + const tsInternal = ts as any as TSInternal; if (nodeMajor >= 16) { const config = require('@tsconfig/node16/tsconfig.json'); if (configCompatible(config)) return config; diff --git a/tests/esm-custom-loader/loader.mjs b/tests/esm-custom-loader/loader.mjs index bf82e766b..1e3113acc 100755 --- a/tests/esm-custom-loader/loader.mjs +++ b/tests/esm-custom-loader/loader.mjs @@ -11,6 +11,5 @@ const tsNodeInstance = register({ }, }); -export const { resolve, getFormat, transformSource, load } = createEsmHooks( - tsNodeInstance -); +export const { resolve, getFormat, transformSource, load } = + createEsmHooks(tsNodeInstance);