Socket
Socket
Sign inDemoInstall

ts-node

Package Overview
Dependencies
Maintainers
2
Versions
128
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

ts-node - npm Package Compare versions

Comparing version 10.4.0 to 10.5.0

dist/cjs-resolve-filename-hook.d.ts

1

dist-raw/node-errors.js

@@ -15,2 +15,3 @@ exports.codes = {

ERR_UNSUPPORTED_ESM_URL_SCHEME: createErrorCtor(joinArgs('ERR_UNSUPPORTED_ESM_URL_SCHEME')),
ERR_UNKNOWN_FILE_EXTENSION: createErrorCtor(joinArgs('ERR_UNKNOWN_FILE_EXTENSION')),
}

@@ -17,0 +18,0 @@

4

dist-raw/node-options.js

@@ -37,3 +37,5 @@ // Replacement for node's internal 'internal/options' module

'--conditions': [String],
'--pending-deprecation': Boolean
'--pending-deprecation': Boolean,
'--experimental-json-modules': Boolean,
'--experimental-wasm-modules': Boolean,
}, {

@@ -40,0 +42,0 @@ argv,

@@ -5,3 +5,3 @@ #!/usr/bin/env node

const bin_1 = require("./bin");
(0, bin_1.main)(undefined, { '--cwd-mode': true });
(0, bin_1.main)(undefined, { '--cwdMode': true });
//# sourceMappingURL=bin-cwd.js.map

@@ -6,3 +6,3 @@ #!/usr/bin/env node

console.warn('ts-script has been deprecated and will be removed in the next major release.', 'Please use ts-node-script instead');
(0, bin_1.main)(undefined, { '--script-mode': true });
(0, bin_1.main)(undefined, { '--scriptMode': true });
//# sourceMappingURL=bin-script-deprecated.js.map

@@ -5,3 +5,3 @@ #!/usr/bin/env node

const bin_1 = require("./bin");
(0, bin_1.main)(undefined, { '--script-mode': true });
(0, bin_1.main)(undefined, { '--scriptMode': true });
//# sourceMappingURL=bin-script.js.map

@@ -5,3 +5,3 @@ #!/usr/bin/env node

const bin_1 = require("./bin");
(0, bin_1.main)(undefined, { '--transpile-only': true });
(0, bin_1.main)(undefined, { '--transpileOnly': true });
//# sourceMappingURL=bin-transpile.js.map

@@ -17,99 +17,125 @@ #!/usr/bin/env node

function main(argv = process.argv.slice(2), entrypointArgs = {}) {
var _a, _b, _c, _d;
const args = Object.assign(Object.assign({}, entrypointArgs), arg({
// Node.js-like options.
'--eval': String,
'--interactive': Boolean,
'--print': Boolean,
'--require': [String],
// CLI options.
'--help': Boolean,
'--cwd-mode': Boolean,
'--script-mode': Boolean,
'--version': arg.COUNT,
'--show-config': Boolean,
// Project options.
'--cwd': String,
'--files': Boolean,
'--compiler': String,
'--compiler-options': util_2.parse,
'--project': String,
'--ignore-diagnostics': [String],
'--ignore': [String],
'--transpile-only': Boolean,
'--transpiler': String,
'--type-check': Boolean,
'--compiler-host': Boolean,
'--pretty': Boolean,
'--skip-project': Boolean,
'--skip-ignore': Boolean,
'--prefer-ts-exts': Boolean,
'--log-error': Boolean,
'--emit': Boolean,
'--scope': Boolean,
'--scope-dir': String,
'--no-experimental-repl-await': Boolean,
// Aliases.
'-e': '--eval',
'-i': '--interactive',
'-p': '--print',
'-r': '--require',
'-h': '--help',
'-s': '--script-mode',
'-v': '--version',
'-T': '--transpile-only',
'-H': '--compiler-host',
'-I': '--ignore',
'-P': '--project',
'-C': '--compiler',
'-D': '--ignore-diagnostics',
'-O': '--compiler-options',
'--dir': '--cwd',
'--showConfig': '--show-config',
'--scopeDir': '--scope-dir',
}, {
argv,
stopAtPositional: true,
}));
var _a, _b, _c, _d, _e, _f, _g;
// HACK: technically, this function is not marked @internal so it's possible
// that libraries in the wild are doing `require('ts-node/dist/bin').main({'--transpile-only': true})`
// We can mark this function @internal in next major release.
// For now, rewrite args to avoid a breaking change.
entrypointArgs = { ...entrypointArgs };
for (const key of Object.keys(entrypointArgs)) {
entrypointArgs[key.replace(/([a-z])-([a-z])/g, (_$0, $1, $2) => `${$1}${$2.toUpperCase()}`)] = entrypointArgs[key];
}
const args = {
...entrypointArgs,
...arg({
// Node.js-like options.
'--eval': String,
'--interactive': Boolean,
'--print': Boolean,
'--require': [String],
// CLI options.
'--help': Boolean,
'--cwdMode': Boolean,
'--scriptMode': Boolean,
'--version': arg.COUNT,
'--showConfig': Boolean,
// Project options.
'--cwd': String,
'--files': Boolean,
'--compiler': String,
'--compilerOptions': util_2.parse,
'--project': String,
'--ignoreDiagnostics': [String],
'--ignore': [String],
'--transpileOnly': Boolean,
'--transpiler': String,
'--swc': Boolean,
'--typeCheck': Boolean,
'--compilerHost': Boolean,
'--pretty': Boolean,
'--skipProject': Boolean,
'--skipIgnore': Boolean,
'--preferTsExts': Boolean,
'--logError': Boolean,
'--emit': Boolean,
'--scope': Boolean,
'--scopeDir': String,
'--noExperimentalReplAwait': Boolean,
// Aliases.
'-e': '--eval',
'-i': '--interactive',
'-p': '--print',
'-r': '--require',
'-h': '--help',
'-s': '--script-mode',
'-v': '--version',
'-T': '--transpileOnly',
'-H': '--compilerHost',
'-I': '--ignore',
'-P': '--project',
'-C': '--compiler',
'-D': '--ignoreDiagnostics',
'-O': '--compilerOptions',
'--dir': '--cwd',
// Support both tsc-style camelCase and node-style hypen-case for *all* flags
'--cwd-mode': '--cwdMode',
'--script-mode': '--scriptMode',
'--show-config': '--showConfig',
'--compiler-options': '--compilerOptions',
'--ignore-diagnostics': '--ignoreDiagnostics',
'--transpile-only': '--transpileOnly',
'--type-check': '--typeCheck',
'--compiler-host': '--compilerHost',
'--skip-project': '--skipProject',
'--skip-ignore': '--skipIgnore',
'--prefer-ts-exts': '--preferTsExts',
'--log-error': '--logError',
'--scope-dir': '--scopeDir',
'--no-experimental-repl-await': '--noExperimentalReplAwait',
}, {
argv,
stopAtPositional: true,
}),
};
// Only setting defaults for CLI-specific flags
// Anything passed to `register()` can be `undefined`; `create()` will apply
// defaults.
const { '--cwd': cwdArg, '--help': help = false, '--script-mode': scriptMode, '--cwd-mode': cwdMode, '--version': version = 0, '--show-config': showConfig, '--require': argsRequire = [], '--eval': code = undefined, '--print': print = false, '--interactive': interactive = false, '--files': files, '--compiler': compiler, '--compiler-options': compilerOptions, '--project': project, '--ignore-diagnostics': ignoreDiagnostics, '--ignore': ignore, '--transpile-only': transpileOnly, '--type-check': typeCheck, '--transpiler': transpiler, '--compiler-host': compilerHost, '--pretty': pretty, '--skip-project': skipProject, '--skip-ignore': skipIgnore, '--prefer-ts-exts': preferTsExts, '--log-error': logError, '--emit': emit, '--scope': scope = undefined, '--scope-dir': scopeDir = undefined, '--no-experimental-repl-await': noExperimentalReplAwait, } = args;
const { '--cwd': cwdArg, '--help': help = false, '--scriptMode': scriptMode, '--cwdMode': cwdMode, '--version': version = 0, '--showConfig': showConfig, '--require': argsRequire = [], '--eval': code = undefined, '--print': print = false, '--interactive': interactive = false, '--files': files, '--compiler': compiler, '--compilerOptions': compilerOptions, '--project': project, '--ignoreDiagnostics': ignoreDiagnostics, '--ignore': ignore, '--transpileOnly': transpileOnly, '--typeCheck': typeCheck, '--transpiler': transpiler, '--swc': swc, '--compilerHost': compilerHost, '--pretty': pretty, '--skipProject': skipProject, '--skipIgnore': skipIgnore, '--preferTsExts': preferTsExts, '--logError': logError, '--emit': emit, '--scope': scope = undefined, '--scopeDir': scopeDir = undefined, '--noExperimentalReplAwait': noExperimentalReplAwait, } = args;
if (help) {
console.log(`
Usage: ts-node [options] [ -e script | script.ts ] [arguments]
Usage: ts-node [options] [ -e script | script.ts ] [arguments]
Options:
Options:
-e, --eval [code] Evaluate code
-p, --print Print result of \`--eval\`
-r, --require [path] Require a node module before execution
-i, --interactive Opens the REPL even if stdin does not appear to be a terminal
-e, --eval [code] Evaluate code
-p, --print Print result of \`--eval\`
-r, --require [path] Require a node module before execution
-i, --interactive Opens the REPL even if stdin does not appear to be a terminal
-h, --help Print CLI usage
-v, --version Print module version information
--cwd-mode Use current directory instead of <script.ts> for config resolution
--show-config Print resolved configuration and exit
-h, --help Print CLI usage
-v, --version Print module version information
--cwdMode Use current directory instead of <script.ts> for config resolution
--showConfig Print resolved configuration and exit
-T, --transpile-only Use TypeScript's faster \`transpileModule\` or a third-party transpiler
-H, --compiler-host Use TypeScript's compiler host API
-I, --ignore [pattern] Override the path patterns to skip compilation
-P, --project [path] Path to TypeScript JSON project file
-C, --compiler [name] Specify a custom TypeScript compiler
--transpiler [name] Specify a third-party, non-typechecking transpiler
-D, --ignore-diagnostics [code] Ignore TypeScript warnings by diagnostic code
-O, --compiler-options [opts] JSON object to merge with compiler options
-T, --transpileOnly Use TypeScript's faster \`transpileModule\` or a third-party transpiler
--swc Use the swc transpiler
-H, --compilerHost Use TypeScript's compiler host API
-I, --ignore [pattern] Override the path patterns to skip compilation
-P, --project [path] Path to TypeScript JSON project file
-C, --compiler [name] Specify a custom TypeScript compiler
--transpiler [name] Specify a third-party, non-typechecking transpiler
-D, --ignoreDiagnostics [code] Ignore TypeScript warnings by diagnostic code
-O, --compilerOptions [opts] JSON object to merge with compiler options
--cwd Behave as if invoked within this working directory.
--files Load \`files\`, \`include\` and \`exclude\` from \`tsconfig.json\` on startup
--pretty Use pretty diagnostic formatter (usually enabled by default)
--skip-project Skip reading \`tsconfig.json\`
--skip-ignore Skip \`--ignore\` checks
--emit Emit output files into \`.ts-node\` directory
--scope Scope compiler to files within \`scopeDir\`. Anything outside this directory is ignored.
--scope-dir Directory for \`--scope\`
--prefer-ts-exts Prefer importing TypeScript files over JavaScript files
--log-error Logs TypeScript errors to stderr instead of throwing exceptions
--no-experimental-repl-await Disable top-level await in REPL. Equivalent to node's --no-experimental-repl-await
`);
--cwd Behave as if invoked within this working directory.
--files Load \`files\`, \`include\` and \`exclude\` from \`tsconfig.json\` on startup
--pretty Use pretty diagnostic formatter (usually enabled by default)
--skipProject Skip reading \`tsconfig.json\`
--skipIgnore Skip \`--ignore\` checks
--emit Emit output files into \`.ts-node\` directory
--scope Scope compiler to files within \`scopeDir\`. Anything outside this directory is ignored.
--scopeDir Directory for \`--scope\`
--preferTsExts Prefer importing TypeScript files over JavaScript files
--logError Logs TypeScript errors to stderr instead of throwing exceptions
--noExperimentalReplAwait Disable top-level await in REPL. Equivalent to node's --no-experimental-repl-await
`);
process.exit(0);

@@ -190,2 +216,3 @@ }

transpiler,
swc,
compilerHost,

@@ -213,3 +240,3 @@ ignore,

// Output project information.
if (version >= 2) {
if (version === 2) {
console.log(`ts-node v${index_1.VERSION}`);

@@ -220,9 +247,36 @@ console.log(`node ${process.version}`);

}
if (version >= 3) {
console.log(`ts-node v${index_1.VERSION} ${(0, path_1.dirname)(__dirname)}`);
console.log(`node ${process.version}`);
console.log(`compiler v${service.ts.version} ${(_c = service.compilerPath) !== null && _c !== void 0 ? _c : ''}`);
process.exit(0);
}
if (showConfig) {
const ts = service.ts;
if (typeof ts.convertToTSConfig !== 'function') {
console.error('Error: --show-config requires a typescript versions >=3.2 that support --showConfig');
console.error('Error: --showConfig requires a typescript versions >=3.2 that support --showConfig');
process.exit(1);
}
const json = Object.assign({ ['ts-node']: Object.assign(Object.assign({}, service.options), { optionBasePaths: undefined, compilerOptions: undefined, project: (_c = service.configFilePath) !== null && _c !== void 0 ? _c : service.options.project }) }, ts.convertToTSConfig(service.config, (_d = service.configFilePath) !== null && _d !== void 0 ? _d : (0, path_1.join)(cwd, 'ts-node-implicit-tsconfig.json'), service.ts.sys));
let moduleTypes = undefined;
if (service.options.moduleTypes) {
// Assumption: this codepath requires CLI invocation, so moduleTypes must have come from a tsconfig, not API.
const showRelativeTo = (0, path_1.dirname)(service.configFilePath);
moduleTypes = {};
for (const [key, value] of Object.entries(service.options.moduleTypes)) {
moduleTypes[(0, path_1.relative)(showRelativeTo, (0, path_1.resolve)((_d = service.options.optionBasePaths) === null || _d === void 0 ? void 0 : _d.moduleTypes, key))] = value;
}
}
const json = {
['ts-node']: {
...service.options,
require: ((_e = service.options.require) === null || _e === void 0 ? void 0 : _e.length)
? service.options.require
: undefined,
moduleTypes,
optionBasePaths: undefined,
compilerOptions: undefined,
project: (_f = service.configFilePath) !== null && _f !== void 0 ? _f : service.options.project,
},
...ts.convertToTSConfig(service.config, (_g = service.configFilePath) !== null && _g !== void 0 ? _g : (0, path_1.join)(cwd, 'ts-node-implicit-tsconfig.json'), service.ts.sys),
};
console.log(

@@ -315,7 +369,7 @@ // Assumes that all configuration options which can possibly be specified via the CLI are JSON-compatible.

function requireResolveNonCached(absoluteModuleSpecifier) {
// node 10 and 11 fallback: The trick below triggers a node 10 & 11 bug
// On those node versions, pollute the require cache instead. This is a deliberate
// ts-node limitation that will *rarely* manifest, and will not matter once node 10
// is end-of-life'd on 2021-04-30
const isSupportedNodeVersion = parseInt(process.versions.node.split('.')[0], 10) >= 12;
// node <= 12.1.x fallback: The trick below triggers a node bug on old versions.
// On these old versions, pollute the require cache instead. This is a deliberate
// ts-node limitation that will *rarely* manifest, and will not matter once node 12
// is end-of-life'd on 2022-04-30
const isSupportedNodeVersion = (0, index_1.versionGteLt)(process.versions.node, '12.2.0');
if (!isSupportedNodeVersion)

@@ -322,0 +376,0 @@ return require.resolve(absoluteModuleSpecifier);

"use strict";
var __rest = (this && this.__rest) || function (s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
};
Object.defineProperty(exports, "__esModule", { value: true });

@@ -69,3 +58,3 @@ exports.readConfig = void 0;

const projectSearchDir = (0, path_1.resolve)(cwd, (_a = rawApiOptions.projectSearchDir) !== null && _a !== void 0 ? _a : cwd);
const { fileExists = ts.sys.fileExists, readFile = ts.sys.readFile, skipProject = index_1.DEFAULTS.skipProject, project = index_1.DEFAULTS.project, } = rawApiOptions;
const { fileExists = ts.sys.fileExists, readFile = ts.sys.readFile, skipProject = index_1.DEFAULTS.skipProject, project = index_1.DEFAULTS.project, tsTrace = index_1.DEFAULTS.tsTrace, } = rawApiOptions;
// Read project configuration when available.

@@ -106,3 +95,3 @@ if (!skipProject) {

useCaseSensitiveFileNames: ts.sys.useCaseSensitiveFileNames,
trace: util_1.trace,
trace: tsTrace,
}, bp, errors, ts.createCompilerDiagnostic);

@@ -129,9 +118,8 @@ if (errors.length) {

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) {
// Modules are found relative to the tsconfig file, not the `dir` option
const tsconfigRelativeRequire = (0, util_1.createRequire)(configPath);
options.require = options.require.map((path) => tsconfigRelativeRequire.resolve(path));
const tsconfigRelativeResolver = (0, util_1.createProjectLocalResolveHelper)((0, path_1.dirname)(configPath));
options.require = options.require.map((path) => tsconfigRelativeResolver(path, false));
}

@@ -145,2 +133,8 @@ if (options.scopeDir) {

}
if (options.transpiler != null) {
optionBasePaths.transpiler = basePath;
}
if (options.compiler != null) {
optionBasePaths.compiler = basePath;
}
(0, util_1.assign)(tsNodeOptionsFromTsconfig, options);

@@ -158,3 +152,6 @@ }

? undefined
: Object.assign(Object.assign({}, (0, tsconfigs_1.getDefaultTsconfigJsonForNodeVersion)(ts).compilerOptions), { types: ['node'] });
: {
...(0, tsconfigs_1.getDefaultTsconfigJsonForNodeVersion)(ts).compilerOptions,
types: ['node'],
};
// Merge compilerOptions from all sources

@@ -195,3 +192,3 @@ config.compilerOptions = Object.assign({},

return { recognized: {}, unrecognized: {} };
const _a = jsonObject, { compiler, compilerHost, compilerOptions, emit, files, ignore, ignoreDiagnostics, logError, preferTsExts, pretty, require, skipIgnore, transpileOnly, typeCheck, transpiler, scope, scopeDir, moduleTypes, experimentalReplAwait } = _a, unrecognized = __rest(_a, ["compiler", "compilerHost", "compilerOptions", "emit", "files", "ignore", "ignoreDiagnostics", "logError", "preferTsExts", "pretty", "require", "skipIgnore", "transpileOnly", "typeCheck", "transpiler", "scope", "scopeDir", "moduleTypes", "experimentalReplAwait"]);
const { compiler, compilerHost, compilerOptions, emit, files, ignore, ignoreDiagnostics, logError, preferTsExts, pretty, require, skipIgnore, transpileOnly, typeCheck, transpiler, scope, scopeDir, moduleTypes, experimentalReplAwait, swc, experimentalResolverFeatures, ...unrecognized } = jsonObject;
const filteredTsConfigOptions = {

@@ -217,2 +214,4 @@ compiler,

moduleTypes,
swc,
experimentalResolverFeatures,
};

@@ -219,0 +218,0 @@ // Use the typechecker to make sure this implementation has the correct set of properties

@@ -26,2 +26,4 @@ /// <reference types="node" />

type ResolveHook = (specifier: string, context: {
conditions?: NodeImportConditions;
importAssertions?: NodeImportAssertions;
parentURL: string;

@@ -33,2 +35,3 @@ }, defaultResolve: ResolveHook) => Promise<{

format: NodeLoaderHooksFormat | null | undefined;
importAssertions?: NodeImportAssertions;
}, defaultLoad: NodeLoaderHooksAPI2['load']) => Promise<{

@@ -38,4 +41,8 @@ format: NodeLoaderHooksFormat;

}>;
type NodeImportConditions = unknown;
interface NodeImportAssertions {
type?: 'json';
}
}
export declare type NodeLoaderHooksFormat = 'builtin' | 'commonjs' | 'dynamic' | 'json' | 'module' | 'wasm';
export declare function createEsmHooks(tsNodeService: Service): NodeLoaderHooksAPI1 | NodeLoaderHooksAPI2;
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });

@@ -30,3 +21,6 @@ exports.createEsmHooks = exports.registerAndCreateEsmHooks = void 0;

// Custom implementation that considers additional file extensions and automatically adds file extensions
const nodeResolveImplementation = createResolve(Object.assign(Object.assign({}, (0, index_1.getExtensions)(tsNodeService.config)), { preferTsExts: tsNodeService.options.preferTsExts }));
const nodeResolveImplementation = createResolve({
...(0, index_1.getExtensions)(tsNodeService.config),
preferTsExts: tsNodeService.options.preferTsExts,
});
// The hooks API changed in node version X so we need to check for backwards compatibility.

@@ -48,100 +42,95 @@ // TODO: When the new API is backported to v12, v14, update these version checks accordingly.

}
function resolve(specifier, context, defaultResolve) {
return __awaiter(this, void 0, void 0, function* () {
const defer = () => __awaiter(this, void 0, void 0, function* () {
const r = yield defaultResolve(specifier, context, defaultResolve);
return r;
});
const parsed = (0, url_1.parse)(specifier);
const { pathname, protocol, hostname } = parsed;
if (!isFileUrlOrNodeStyleSpecifier(parsed)) {
return defer();
}
if (protocol !== null && protocol !== 'file:') {
return defer();
}
// Malformed file:// URL? We should always see `null` or `''`
if (hostname) {
// TODO file://./foo sets `hostname` to `'.'`. Perhaps we should special-case this.
return defer();
}
// pathname is the path to be resolved
return nodeResolveImplementation.defaultResolve(specifier, context, defaultResolve);
});
async function resolve(specifier, context, defaultResolve) {
const defer = async () => {
const r = await defaultResolve(specifier, context, defaultResolve);
return r;
};
const parsed = (0, url_1.parse)(specifier);
const { pathname, protocol, hostname } = parsed;
if (!isFileUrlOrNodeStyleSpecifier(parsed)) {
return defer();
}
if (protocol !== null && protocol !== 'file:') {
return defer();
}
// Malformed file:// URL? We should always see `null` or `''`
if (hostname) {
// TODO file://./foo sets `hostname` to `'.'`. Perhaps we should special-case this.
return defer();
}
// pathname is the path to be resolved
return nodeResolveImplementation.defaultResolve(specifier, context, defaultResolve);
}
// `load` from new loader hook API (See description at the top of this file)
function load(url, context, defaultLoad) {
async function load(url, context, defaultLoad) {
var _a;
return __awaiter(this, void 0, void 0, function* () {
// If we get a format hint from resolve() on the context then use it
// otherwise call the old getFormat() hook using node's old built-in defaultGetFormat() that ships with ts-node
const format = (_a = context.format) !== null && _a !== void 0 ? _a : (yield getFormat(url, context, defaultGetFormat)).format;
let source = undefined;
if (format !== 'builtin' && format !== 'commonjs') {
// Call the new defaultLoad() to get the source
const { source: rawSource } = yield defaultLoad(url, { format }, defaultLoad);
if (rawSource === undefined || rawSource === null) {
throw new Error(`Failed to load raw source: Format was '${format}' and url was '${url}''.`);
}
// Emulate node's built-in old defaultTransformSource() so we can re-use the old transformSource() hook
const defaultTransformSource = (source, _context, _defaultTransformSource) => __awaiter(this, void 0, void 0, function* () { return ({ source }); });
// Call the old hook
const { source: transformedSource } = yield transformSource(rawSource, { url, format }, defaultTransformSource);
source = transformedSource;
// If we get a format hint from resolve() on the context then use it
// otherwise call the old getFormat() hook using node's old built-in defaultGetFormat() that ships with ts-node
const format = (_a = context.format) !== null && _a !== void 0 ? _a : (await getFormat(url, context, defaultGetFormat)).format;
let source = undefined;
if (format !== 'builtin' && format !== 'commonjs') {
// Call the new defaultLoad() to get the source
const { source: rawSource } = await defaultLoad(url, {
...context,
format,
}, defaultLoad);
if (rawSource === undefined || rawSource === null) {
throw new Error(`Failed to load raw source: Format was '${format}' and url was '${url}''.`);
}
return { format, source };
});
// Emulate node's built-in old defaultTransformSource() so we can re-use the old transformSource() hook
const defaultTransformSource = async (source, _context, _defaultTransformSource) => ({ source });
// Call the old hook
const { source: transformedSource } = await transformSource(rawSource, { url, format }, defaultTransformSource);
source = transformedSource;
}
return { format, source };
}
function getFormat(url, context, defaultGetFormat) {
return __awaiter(this, void 0, void 0, function* () {
const defer = (overrideUrl = url) => defaultGetFormat(overrideUrl, context, defaultGetFormat);
const parsed = (0, url_1.parse)(url);
if (!isFileUrlOrNodeStyleSpecifier(parsed)) {
return defer();
async function getFormat(url, context, defaultGetFormat) {
const defer = (overrideUrl = url) => defaultGetFormat(overrideUrl, context, defaultGetFormat);
const parsed = (0, url_1.parse)(url);
if (!isFileUrlOrNodeStyleSpecifier(parsed)) {
return defer();
}
const { pathname } = parsed;
assert(pathname !== null, 'ESM getFormat() hook: URL should never have null pathname');
const nativePath = (0, url_1.fileURLToPath)(url);
// If file has .ts, .tsx, or .jsx extension, then ask node how it would treat this file if it were .js
const ext = (0, path_1.extname)(nativePath);
let nodeSays;
if (ext !== '.js' && !tsNodeService.ignored(nativePath)) {
nodeSays = await defer((0, url_1.format)((0, url_1.pathToFileURL)(nativePath + '.js')));
}
else {
nodeSays = await defer();
}
// For files compiled by ts-node that node believes are either CJS or ESM, check if we should override that classification
if (!tsNodeService.ignored(nativePath) &&
(nodeSays.format === 'commonjs' || nodeSays.format === 'module')) {
const { moduleType } = tsNodeService.moduleTypeClassifier.classifyModule((0, util_1.normalizeSlashes)(nativePath));
if (moduleType === 'cjs') {
return { format: 'commonjs' };
}
const { pathname } = parsed;
assert(pathname !== null, 'ESM getFormat() hook: URL should never have null pathname');
const nativePath = (0, url_1.fileURLToPath)(url);
// If file has .ts, .tsx, or .jsx extension, then ask node how it would treat this file if it were .js
const ext = (0, path_1.extname)(nativePath);
let nodeSays;
if (ext !== '.js' && !tsNodeService.ignored(nativePath)) {
nodeSays = yield defer((0, url_1.format)((0, url_1.pathToFileURL)(nativePath + '.js')));
else if (moduleType === 'esm') {
return { format: 'module' };
}
else {
nodeSays = yield defer();
}
// For files compiled by ts-node that node believes are either CJS or ESM, check if we should override that classification
if (!tsNodeService.ignored(nativePath) &&
(nodeSays.format === 'commonjs' || nodeSays.format === 'module')) {
const { moduleType } = tsNodeService.moduleTypeClassifier.classifyModule((0, util_1.normalizeSlashes)(nativePath));
if (moduleType === 'cjs') {
return { format: 'commonjs' };
}
else if (moduleType === 'esm') {
return { format: 'module' };
}
}
return nodeSays;
});
}
return nodeSays;
}
function transformSource(source, context, defaultTransformSource) {
return __awaiter(this, void 0, void 0, function* () {
if (source === null || source === undefined) {
throw new Error('No source');
}
const defer = () => defaultTransformSource(source, context, defaultTransformSource);
const sourceAsString = typeof source === 'string' ? source : source.toString('utf8');
const { url } = context;
const parsed = (0, url_1.parse)(url);
if (!isFileUrlOrNodeStyleSpecifier(parsed)) {
return defer();
}
const nativePath = (0, url_1.fileURLToPath)(url);
if (tsNodeService.ignored(nativePath)) {
return defer();
}
const emittedJs = tsNodeService.compile(sourceAsString, nativePath);
return { source: emittedJs };
});
async function transformSource(source, context, defaultTransformSource) {
if (source === null || source === undefined) {
throw new Error('No source');
}
const defer = () => defaultTransformSource(source, context, defaultTransformSource);
const sourceAsString = typeof source === 'string' ? source : source.toString('utf8');
const { url } = context;
const parsed = (0, url_1.parse)(url);
if (!isFileUrlOrNodeStyleSpecifier(parsed)) {
return defer();
}
const nativePath = (0, url_1.fileURLToPath)(url);
if (tsNodeService.ignored(nativePath)) {
return defer();
}
const emittedJs = tsNodeService.compile(sourceAsString, nativePath);
return { source: emittedJs };
}

@@ -148,0 +137,0 @@ }

@@ -108,2 +108,10 @@ import { BaseError } from 'make-error';

/**
* Transpile with swc instead of the TypeScript compiler, and skip typechecking.
*
* Equivalent to setting both `transpileOnly: true` and `transpiler: 'ts-node/transpilers/swc'`
*
* For complete instructions: https://typestrong.org/ts-node/docs/transpilers
*/
swc?: boolean;
/**
* Paths which should not be compiled.

@@ -188,4 +196,11 @@ *

*/
moduleTypes?: Record<string, 'cjs' | 'esm' | 'package'>;
moduleTypes?: ModuleTypes;
/**
* A function to collect trace messages from the TypeScript compiler, for example when `traceResolution` is enabled.
*
* @default console.log
*/
tsTrace?: (str: string) => void;
}
export declare type ModuleTypes = Record<string, 'cjs' | 'esm' | 'package'>;
/**

@@ -203,2 +218,10 @@ * Options for registering a TypeScript compiler instance globally.

preferTsExts?: boolean;
/**
* Enable experimental features that re-map imports and require calls to support:
* `baseUrl`, `paths`, `rootDirs`, `.js` to `.ts` file extension mappings,
* `outDir` to `rootDir` mappings for composite projects and monorepos.
*
* For details, see https://github.com/TypeStrong/ts-node/issues/1514
*/
experimentalResolverFeatures?: boolean;
}

@@ -208,3 +231,3 @@ /**

*/
export interface TsConfigOptions extends Omit<RegisterOptions, 'transformers' | 'readFile' | 'fileExists' | 'skipProject' | 'project' | 'dir' | 'cwd' | 'projectSearchDir' | 'optionBasePaths'> {
export interface TsConfigOptions extends Omit<RegisterOptions, 'transformers' | 'readFile' | 'fileExists' | 'skipProject' | 'project' | 'dir' | 'cwd' | 'projectSearchDir' | 'optionBasePaths' | 'tsTrace'> {
}

@@ -222,5 +245,5 @@ /**

export declare class TSError extends BaseError {
diagnosticText: string;
diagnosticCodes: number[];
name: string;
diagnosticText: string;
constructor(diagnosticText: string, diagnosticCodes: number[]);

@@ -227,0 +250,0 @@ }

@@ -15,2 +15,3 @@ "use strict";

const resolver_functions_1 = require("./resolver-functions");
const cjs_resolve_filename_hook_1 = require("./cjs-resolve-filename-hook");
var repl_1 = require("./repl");

@@ -111,2 +112,3 @@ Object.defineProperty(exports, "createRepl", { enumerable: true, get: function () { return repl_1.createRepl; } });

experimentalReplAwait: (_b = (0, util_1.yn)(exports.env.TS_NODE_EXPERIMENTAL_REPL_AWAIT)) !== null && _b !== void 0 ? _b : undefined,
tsTrace: console.log.bind(console),
};

@@ -119,5 +121,9 @@ /**

super(`⨯ Unable to compile TypeScript:\n${diagnosticText}`);
this.diagnosticText = diagnosticText;
this.diagnosticCodes = diagnosticCodes;
this.name = 'TSError';
Object.defineProperty(this, 'diagnosticText', {
configurable: true,
writable: true,
value: diagnosticText,
});
}

@@ -162,2 +168,3 @@ /**

registerExtensions(service.options.preferTsExts, extensions, service, originalJsHandler);
(0, cjs_resolve_filename_hook_1.installCommonjsResolveHookIfNecessary)(service);
// Require specified modules before start-up.

@@ -172,3 +179,3 @@ module_1.Module._preloadModules(service.options.require);

function create(rawOptions = {}) {
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l;
var _a, _b, _c, _d, _e, _f, _g, _h, _j;
const cwd = (0, path_1.resolve)((_c = (_b = (_a = rawOptions.cwd) !== null && _a !== void 0 ? _a : rawOptions.dir) !== null && _b !== void 0 ? _b : exports.DEFAULTS.cwd) !== null && _c !== void 0 ? _c : process.cwd());

@@ -181,12 +188,11 @@ const compilerName = (_d = rawOptions.compiler) !== null && _d !== void 0 ? _d : exports.DEFAULTS.compiler;

function loadCompiler(name, relativeToPath) {
const compiler = require.resolve(name || 'typescript', {
paths: [relativeToPath, __dirname],
});
const ts = require(compiler);
return { compiler, ts };
const projectLocalResolveHelper = (0, util_1.createProjectLocalResolveHelper)(relativeToPath);
const compiler = projectLocalResolveHelper(name || 'typescript', true);
const ts = (0, util_1.attemptRequireWithV8CompileCache)(require, compiler);
return { compiler, ts, projectLocalResolveHelper };
}
// Compute minimum options to read the config file.
let { compiler, ts } = loadCompiler(compilerName, (_f = (_e = rawOptions.projectSearchDir) !== null && _e !== void 0 ? _e : rawOptions.project) !== null && _f !== void 0 ? _f : cwd);
let { compiler, ts, projectLocalResolveHelper } = loadCompiler(compilerName, (0, util_1.getBasePathForProjectLocalDependencyResolution)(undefined, rawOptions.projectSearchDir, rawOptions.project, cwd));
// Read config file and merge new options between env and CLI options.
const { configFilePath, config, tsNodeOptionsFromTsconfig, optionBasePaths, } = (0, configuration_1.readConfig)(cwd, ts, rawOptions);
const { configFilePath, config, tsNodeOptionsFromTsconfig, optionBasePaths } = (0, configuration_1.readConfig)(cwd, ts, rawOptions);
const options = (0, util_1.assign)({}, exports.DEFAULTS, tsNodeOptionsFromTsconfig || {}, { optionBasePaths }, rawOptions);

@@ -197,2 +203,8 @@ options.require = [

];
// Re-load the compiler in case it has changed.
// Compiler is loaded relative to tsconfig.json, so tsconfig discovery may cause us to load a
// different compiler than we did above, even if the name has not changed.
if (configFilePath) {
({ compiler, ts, projectLocalResolveHelper } = loadCompiler(options.compiler, (0, util_1.getBasePathForProjectLocalDependencyResolution)(configFilePath, rawOptions.projectSearchDir, rawOptions.project, cwd)));
}
// Experimental REPL await is not compatible targets lower than ES2018

@@ -211,7 +223,12 @@ const targetSupportsTla = config.options.target >= ts.ScriptTarget.ES2018;

targetSupportsTla;
// Re-load the compiler in case it has changed.
// Compiler is loaded relative to tsconfig.json, so tsconfig discovery may cause us to load a
// different compiler than we did above, even if the name has not changed.
if (configFilePath) {
({ compiler, ts } = loadCompiler(options.compiler, configFilePath));
// swc implies two other options
// typeCheck option was implemented specifically to allow overriding tsconfig transpileOnly from the command-line
// So we should allow using typeCheck to override swc
if (options.swc && !options.typeCheck) {
if (options.transpileOnly === false) {
throw new Error("Cannot enable 'swc' option with 'transpileOnly: false'. 'swc' implies 'transpileOnly'.");
}
if (options.transpiler) {
throw new Error("Cannot specify both 'swc' and 'transpiler' options. 'swc' uses the built-in swc transpiler.");
}
}

@@ -221,3 +238,9 @@ const readFile = options.readFile || ts.sys.readFile;

// typeCheck can override transpileOnly, useful for CLI flag to override config file
const transpileOnly = options.transpileOnly === true && options.typeCheck !== true;
const transpileOnly = (options.transpileOnly === true || options.swc === true) &&
options.typeCheck !== true;
const transpiler = options.transpiler
? options.transpiler
: options.swc
? require.resolve('./transpilers/swc.js')
: undefined;
const transformers = options.transformers || undefined;

@@ -239,3 +262,3 @@ const diagnosticFilters = [

const configFileDirname = configFilePath ? (0, path_1.dirname)(configFilePath) : null;
const scopeDir = (_j = (_h = (_g = options.scopeDir) !== null && _g !== void 0 ? _g : config.options.rootDir) !== null && _h !== void 0 ? _h : configFileDirname) !== null && _j !== void 0 ? _j : cwd;
const scopeDir = (_g = (_f = (_e = options.scopeDir) !== null && _e !== void 0 ? _e : config.options.rootDir) !== null && _f !== void 0 ? _f : configFileDirname) !== null && _g !== void 0 ? _g : cwd;
const ignoreBaseDir = configFileDirname !== null && configFileDirname !== void 0 ? configFileDirname : cwd;

@@ -259,16 +282,13 @@ const isScoped = options.scope

let customTranspiler = undefined;
if (options.transpiler) {
if (transpiler) {
if (!transpileOnly)
throw new Error('Custom transpiler can only be used when transpileOnly is enabled.');
const transpilerName = typeof options.transpiler === 'string'
? options.transpiler
: options.transpiler[0];
const transpilerOptions = typeof options.transpiler === 'string' ? {} : (_k = options.transpiler[1]) !== null && _k !== void 0 ? _k : {};
// TODO mimic fixed resolution logic from loadCompiler main
// TODO refactor into a more generic "resolve dep relative to project" helper
const transpilerPath = require.resolve(transpilerName, {
paths: [cwd, __dirname],
const transpilerName = typeof transpiler === 'string' ? transpiler : transpiler[0];
const transpilerOptions = typeof transpiler === 'string' ? {} : (_h = transpiler[1]) !== null && _h !== void 0 ? _h : {};
const transpilerPath = projectLocalResolveHelper(transpilerName, true);
const transpilerFactory = require(transpilerPath).create;
customTranspiler = transpilerFactory({
service: { options, config, projectLocalResolveHelper },
...transpilerOptions,
});
const transpilerFactory = require(transpilerPath).create;
customTranspiler = transpilerFactory(Object.assign({ service: { options, config } }, transpilerOptions));
}

@@ -347,3 +367,3 @@ /**

const moduleTypeClassifier = (0, module_type_classifier_1.createModuleTypeClassifier)({
basePath: (_l = options.optionBasePaths) === null || _l === void 0 ? void 0 : _l.moduleTypes,
basePath: (_j = options.optionBasePaths) === null || _j === void 0 ? void 0 : _j.moduleTypes,
patterns: options.moduleTypes,

@@ -403,5 +423,6 @@ });

getCustomTransformers: getCustomTransformers,
trace: options.tsTrace,
};
const { resolveModuleNames, getResolvedModuleWithFailedLookupLocationsFromCache, resolveTypeReferenceDirectives, isFileKnownToBeInternal, markBucketOfFilenameInternal, } = (0, resolver_functions_1.createResolverFunctions)({
serviceHost,
host: serviceHost,
getCanonicalFileName,

@@ -411,7 +432,9 @@ ts,

config,
configFilePath,
projectLocalResolveHelper,
});
serviceHost.resolveModuleNames = resolveModuleNames;
serviceHost.getResolvedModuleWithFailedLookupLocationsFromCache = getResolvedModuleWithFailedLookupLocationsFromCache;
serviceHost.resolveTypeReferenceDirectives = resolveTypeReferenceDirectives;
serviceHost.getResolvedModuleWithFailedLookupLocationsFromCache =
getResolvedModuleWithFailedLookupLocationsFromCache;
serviceHost.resolveTypeReferenceDirectives =
resolveTypeReferenceDirectives;
const registry = ts.createDocumentRegistry(ts.sys.useCaseSensitiveFileNames, cwd);

@@ -458,3 +481,3 @@ const service = ts.createLanguageService(serviceHost, registry);

if (output.emitSkipped) {
throw new TypeError(`${(0, path_1.relative)(cwd, fileName)}: Emit skipped`);
return [undefined, undefined, true];
}

@@ -468,3 +491,3 @@ // Throw an error when requiring `.d.ts` files.

}
return [output.outputFiles[1].text, output.outputFiles[0].text];
return [output.outputFiles[1].text, output.outputFiles[0].text, false];
};

@@ -480,3 +503,6 @@ getTypeInfo = (code, fileName, position) => {

else {
const sys = Object.assign(Object.assign(Object.assign({}, ts.sys), diagnosticHost), { readFile: (fileName) => {
const sys = {
...ts.sys,
...diagnosticHost,
readFile: (fileName) => {
const cacheContents = fileContents.get(fileName);

@@ -489,8 +515,17 @@ if (cacheContents !== undefined)

return contents;
}, readDirectory: ts.sys.readDirectory, getDirectories: (0, util_1.cachedLookup)(debugFn('getDirectories', ts.sys.getDirectories)), fileExists: (0, util_1.cachedLookup)(debugFn('fileExists', fileExists)), directoryExists: (0, util_1.cachedLookup)(debugFn('directoryExists', ts.sys.directoryExists)), resolvePath: (0, util_1.cachedLookup)(debugFn('resolvePath', ts.sys.resolvePath)), realpath: ts.sys.realpath
},
readDirectory: ts.sys.readDirectory,
getDirectories: (0, util_1.cachedLookup)(debugFn('getDirectories', ts.sys.getDirectories)),
fileExists: (0, util_1.cachedLookup)(debugFn('fileExists', fileExists)),
directoryExists: (0, util_1.cachedLookup)(debugFn('directoryExists', ts.sys.directoryExists)),
resolvePath: (0, util_1.cachedLookup)(debugFn('resolvePath', ts.sys.resolvePath)),
realpath: ts.sys.realpath
? (0, util_1.cachedLookup)(debugFn('realpath', ts.sys.realpath))
: undefined });
: undefined,
};
const host = ts.createIncrementalCompilerHost
? ts.createIncrementalCompilerHost(config.options, sys)
: Object.assign(Object.assign({}, sys), { getSourceFile: (fileName, languageVersion) => {
: {
...sys,
getSourceFile: (fileName, languageVersion) => {
const contents = sys.readFile(fileName);

@@ -500,10 +535,15 @@ if (contents === undefined)

return ts.createSourceFile(fileName, contents, languageVersion);
}, getDefaultLibLocation: () => (0, util_1.normalizeSlashes)((0, path_1.dirname)(compiler)), getDefaultLibFileName: () => (0, util_1.normalizeSlashes)((0, path_1.join)((0, path_1.dirname)(compiler), ts.getDefaultLibFileName(config.options))), useCaseSensitiveFileNames: () => sys.useCaseSensitiveFileNames });
},
getDefaultLibLocation: () => (0, util_1.normalizeSlashes)((0, path_1.dirname)(compiler)),
getDefaultLibFileName: () => (0, util_1.normalizeSlashes)((0, path_1.join)((0, path_1.dirname)(compiler), ts.getDefaultLibFileName(config.options))),
useCaseSensitiveFileNames: () => sys.useCaseSensitiveFileNames,
};
host.trace = options.tsTrace;
const { resolveModuleNames, resolveTypeReferenceDirectives, isFileKnownToBeInternal, markBucketOfFilenameInternal, } = (0, resolver_functions_1.createResolverFunctions)({
serviceHost: host,
host,
cwd,
configFilePath,
config,
ts,
getCanonicalFileName,
projectLocalResolveHelper,
});

@@ -517,3 +557,3 @@ host.resolveModuleNames = resolveModuleNames;

options: config.options,
host: host,
host,
configFileParsingDiagnostics: config.errors,

@@ -548,3 +588,4 @@ projectReferences: config.projectReferences,

getOutput = (code, fileName) => {
const output = ['', ''];
let outText = '';
let outMap = '';
updateMemoryCache(code, fileName);

@@ -561,6 +602,6 @@ const sourceFile = builderProgram.getSourceFile(fileName);

if (path.endsWith('.map')) {
output[1] = file;
outMap = file;
}
else {
output[0] = file;
outText = file;
}

@@ -571,6 +612,6 @@ if (options.emit)

if (result.emitSkipped) {
throw new TypeError(`${(0, path_1.relative)(cwd, fileName)}: Emit skipped`);
return [undefined, undefined, true];
}
// Throw an error when requiring files that cannot be compiled.
if (output[0] === '') {
if (outText === '') {
if (program.isSourceFileFromExternalLibrary(sourceFile)) {

@@ -584,3 +625,3 @@ throw new TypeError(`Unable to compile file from external library: ${(0, path_1.relative)(cwd, fileName)}`);

}
return output;
return [outText, outMap, false];
};

@@ -625,3 +666,3 @@ getTypeInfo = (code, fileName, position) => {

function createTranspileOnlyGetOutputFunction(overrideModuleType) {
const compilerOptions = Object.assign({}, config.options);
const compilerOptions = { ...config.options };
if (overrideModuleType !== undefined)

@@ -647,3 +688,3 @@ compilerOptions.module = overrideModuleType;

reportTSError(diagnosticList);
return [result.outputText, result.sourceMapText];
return [result.outputText, result.sourceMapText, false];
};

@@ -660,2 +701,3 @@ }

: createTranspileOnlyGetOutputFunction(ts.ModuleKind.ES2020 || ts.ModuleKind.ES2015);
const getOutputTranspileOnly = createTranspileOnlyGetOutputFunction();
// Create a simple TypeScript compiler proxy.

@@ -666,3 +708,3 @@ function compile(code, fileName, lineOffset = 0) {

// Must always call normal getOutput to throw typechecking errors
let [value, sourceMap] = getOutput(code, normalizedFileName);
let [value, sourceMap, emitSkipped] = getOutput(code, normalizedFileName);
// If module classification contradicts the above, call the relevant transpiler

@@ -675,2 +717,5 @@ if (classification.moduleType === 'cjs' && getOutputForceCommonJS) {

}
else if (emitSkipped) {
[value, sourceMap] = getOutputTranspileOnly(code, normalizedFileName);
}
const output = updateOutput(value, normalizedFileName, sourceMap, getExtension);

@@ -694,3 +739,6 @@ outputCache.set(normalizedFileName, { content: output });

function addDiagnosticFilter(filter) {
diagnosticFilters.push(Object.assign(Object.assign({}, filter), { filenamesAbsolute: filter.filenamesAbsolute.map((f) => (0, util_1.normalizeSlashes)(f)) }));
diagnosticFilters.push({
...filter,
filenamesAbsolute: filter.filenamesAbsolute.map((f) => (0, util_1.normalizeSlashes)(f)),
});
}

@@ -700,2 +748,3 @@ return {

ts,
compilerPath: compiler,
config,

@@ -713,2 +762,4 @@ compile,

enableExperimentalEsmLoaderInterop,
transpileOnly,
projectLocalResolveHelper,
};

@@ -715,0 +766,0 @@ }

"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __rest = (this && this.__rest) || function (s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
};
Object.defineProperty(exports, "__esModule", { value: true });

@@ -149,5 +129,5 @@ exports.setupContext = exports.createEvalAwarePartialHost = exports.EvalState = exports.createRepl = exports.REPL_NAME = exports.REPL_FILENAME = exports.STDIN_NAME = exports.STDIN_FILENAME = exports.EVAL_NAME = exports.EVAL_FILENAME = void 0;

if (evalResult.containsTopLevelAwait) {
(() => __awaiter(this, void 0, void 0, function* () {
(async () => {
try {
callback(null, yield evalResult.valuePromise);
callback(null, await evalResult.valuePromise);
}

@@ -157,3 +137,3 @@ catch (promiseError) {

}
}))();
})();
}

@@ -200,3 +180,3 @@ else {

}
catch (_c) { }
catch { }
}

@@ -216,3 +196,3 @@ callback(_error);

function startInternal(options) {
const _a = options !== null && options !== void 0 ? options : {}, { code, forceToBeModule = true } = _a, optionsOverride = __rest(_a, ["code", "forceToBeModule"]);
const { code, forceToBeModule = true, ...optionsOverride } = options !== null && options !== void 0 ? options : {};
// TODO assert that `service` is set; remove all `service!` non-null assertions

@@ -231,6 +211,17 @@ // Eval incoming code before the REPL starts.

}
const repl = (0, repl_1.start)(Object.assign({ prompt: '> ', input: replService.stdin, output: replService.stdout,
// In case the typescript compiler hasn't compiled anything yet,
// make it run though compilation at least one time before
// the REPL starts for a snappier user experience on startup.
service === null || service === void 0 ? void 0 : service.compile('', state.path);
const repl = (0, repl_1.start)({
prompt: '> ',
input: replService.stdin,
output: replService.stdout,
// Mimicking node's REPL implementation: https://github.com/nodejs/node/blob/168b22ba073ee1cbf8d0bcb4ded7ff3099335d04/lib/internal/repl.js#L28-L30
terminal: stdout.isTTY &&
!parseInt(index_1.env.NODE_NO_READLINE, 10), eval: nodeEval, useGlobal: true }, optionsOverride));
!parseInt(index_1.env.NODE_NO_READLINE, 10),
eval: nodeEval,
useGlobal: true,
...optionsOverride,
});
nodeReplServer = repl;

@@ -252,9 +243,13 @@ context = repl.context;

// those that already exist as globals
// Intentionally suppress type errors in case @types/node does not declare any of them.
state.input += `// @ts-ignore\n${module_1.builtinModules
.filter((name) => !name.startsWith('_') &&
!name.includes('/') &&
!['console', 'module', 'process'].includes(name))
.map((name) => `declare import ${name} = require('${name}')`)
.join(';')}\n`;
// Intentionally suppress type errors in case @types/node does not declare any of them, and because
// `declare import` is technically invalid syntax.
// Avoid this when in transpileOnly, because third-party transpilers may not handle `declare import`.
if (!(service === null || service === void 0 ? void 0 : service.transpileOnly)) {
state.input += `// @ts-ignore\n${module_1.builtinModules
.filter((name) => !name.startsWith('_') &&
!name.includes('/') &&
!['console', 'module', 'process'].includes(name))
.map((name) => `declare import ${name} = require('${name}')`)
.join(';')}\n`;
}
}

@@ -340,2 +335,3 @@ reset();

exports.createEvalAwarePartialHost = createEvalAwarePartialHost;
const sourcemapCommentRe = /\/\/# ?sourceMappingURL=\S+[\s\r\n]*$/;
/**

@@ -367,4 +363,12 @@ * Evaluate the code snippet.

output = adjustUseStrict(output);
// Note: REPL does not respect sourcemaps!
// To properly do that, we'd need to prefix the code we eval -- which comes
// from `diffLines` -- with newlines so that it's at the proper line numbers.
// Then we'd need to ensure each bit of eval-ed code, if there are multiples,
// has the sourcemap appended to it.
// We might also need to integrate with our sourcemap hooks' cache; I'm not sure.
const outputWithoutSourcemapComment = output.replace(sourcemapCommentRe, '');
const oldOutputWithoutSourcemapComment = state.output.replace(sourcemapCommentRe, '');
// Use `diff` to check for new JavaScript to execute.
const changes = (0, diff_1.diffLines)(state.output, output);
const changes = (0, diff_1.diffLines)(oldOutputWithoutSourcemapComment, outputWithoutSourcemapComment);
if (isCompletion) {

@@ -415,10 +419,10 @@ undo();

containsTopLevelAwait,
valuePromise: (() => __awaiter(this, void 0, void 0, function* () {
valuePromise: (async () => {
let value;
for (const command of commands) {
const r = command.execCommand();
value = command.mustAwait ? yield r : r;
value = command.mustAwait ? await r : r;
}
return value;
}))(),
})(),
};

@@ -425,0 +429,0 @@ }

@@ -10,3 +10,3 @@ "use strict";

function createResolverFunctions(kwargs) {
const { serviceHost, ts, config, cwd, getCanonicalFileName, configFilePath, } = kwargs;
const { host, ts, config, cwd, getCanonicalFileName, projectLocalResolveHelper, } = kwargs;
const moduleResolutionCache = ts.createModuleResolutionCache(cwd, getCanonicalFileName, config.options);

@@ -63,3 +63,3 @@ const knownInternalFilenames = new Set();

return moduleNames.map((moduleName) => {
const { resolvedModule } = ts.resolveModuleName(moduleName, containingFile, config.options, serviceHost, moduleResolutionCache, redirectedReference);
const { resolvedModule } = ts.resolveModuleName(moduleName, containingFile, config.options, host, moduleResolutionCache, redirectedReference);
if (resolvedModule) {

@@ -82,3 +82,3 @@ fixupResolvedModule(resolvedModule);

return typeDirectiveNames.map((typeDirectiveName) => {
let { resolvedTypeReferenceDirective } = ts.resolveTypeReferenceDirective(typeDirectiveName, containingFile, config.options, serviceHost, redirectedReference);
let { resolvedTypeReferenceDirective } = ts.resolveTypeReferenceDirective(typeDirectiveName, containingFile, config.options, host, redirectedReference);
if (typeDirectiveName === 'node' && !resolvedTypeReferenceDirective) {

@@ -88,12 +88,12 @@ // Resolve @types/node relative to project first, then __dirname (copy logic from elsewhere / refactor into reusable function)

try {
typesNodePackageJsonPath = require.resolve('@types/node/package.json', {
paths: [configFilePath !== null && configFilePath !== void 0 ? configFilePath : cwd, __dirname],
});
typesNodePackageJsonPath = projectLocalResolveHelper('@types/node/package.json', true);
}
catch (_a) { } // gracefully do nothing when @types/node is not installed for any reason
catch { } // gracefully do nothing when @types/node is not installed for any reason
if (typesNodePackageJsonPath) {
const typeRoots = [(0, path_1.resolve)(typesNodePackageJsonPath, '../..')];
({
resolvedTypeReferenceDirective,
} = ts.resolveTypeReferenceDirective(typeDirectiveName, containingFile, Object.assign(Object.assign({}, config.options), { typeRoots }), serviceHost, redirectedReference));
({ resolvedTypeReferenceDirective } =
ts.resolveTypeReferenceDirective(typeDirectiveName, containingFile, {
...config.options,
typeRoots,
}, host, redirectedReference));
}

@@ -100,0 +100,0 @@ }

@@ -5,7 +5,7 @@ "use strict";

function create(createOptions) {
const { swc, service: { config }, } = createOptions;
const { swc, service: { config, projectLocalResolveHelper }, } = createOptions;
// Load swc compiler
let swcInstance;
if (typeof swc === 'string') {
swcInstance = require(swc);
swcInstance = require(projectLocalResolveHelper(swc, true));
}

@@ -15,10 +15,10 @@ else if (swc == null) {

try {
swcResolved = require.resolve('@swc/core');
swcResolved = projectLocalResolveHelper('@swc/core', true);
}
catch (e) {
try {
swcResolved = require.resolve('@swc/wasm');
swcResolved = projectLocalResolveHelper('@swc/wasm', true);
}
catch (e) {
throw new Error('swc compiler requires either @swc/core or @swc/wasm to be installed as dependencies');
throw new Error('swc compiler requires either @swc/core or @swc/wasm to be installed as a dependency. See https://typestrong.org/ts-node/docs/transpilers');
}

@@ -33,3 +33,3 @@ }

const compilerOptions = config.options;
const { esModuleInterop, sourceMap, importHelpers, experimentalDecorators, emitDecoratorMetadata, target, module, jsxFactory, jsxFragmentFactory, } = compilerOptions;
const { esModuleInterop, sourceMap, importHelpers, experimentalDecorators, emitDecoratorMetadata, target, module, jsxFactory, jsxFragmentFactory, strict, alwaysStrict, noImplicitUseStrict, } = compilerOptions;
const nonTsxOptions = createSwcOptions(false);

@@ -55,2 +55,3 @@ const tsxOptions = createSwcOptions(true);

const keepClassNames = target >= /* ts.ScriptTarget.ES2016 */ 3;
// swc only supports these 4x module options
const moduleType = module === ModuleKind.CommonJS

@@ -62,3 +63,18 @@ ? 'commonjs'

? 'umd'
: undefined;
: 'es6';
// In swc:
// strictMode means `"use strict"` is *always* emitted for non-ES module, *never* for ES module where it is assumed it can be omitted.
// (this assumption is invalid, but that's the way swc behaves)
// tsc is a bit more complex:
// alwaysStrict will force emitting it always unless `import`/`export` syntax is emitted which implies it per the JS spec.
// if not alwaysStrict, will emit implicitly whenever module target is non-ES *and* transformed module syntax is emitted.
// For node, best option is to assume that all scripts are modules (commonjs or esm) and thus should get tsc's implicit strict behavior.
// Always set strictMode, *unless* alwaysStrict is disabled and noImplicitUseStrict is enabled
const strictMode =
// if `alwaysStrict` is disabled, remembering that `strict` defaults `alwaysStrict` to true
(alwaysStrict === false || (alwaysStrict !== true && strict !== true)) &&
// if noImplicitUseStrict is enabled
noImplicitUseStrict === true
? false
: true;
return {

@@ -71,2 +87,3 @@ sourceMaps: sourceMap,

type: moduleType,
strictMode,
}

@@ -104,3 +121,6 @@ : undefined,

: nonTsxOptions;
const { code, map } = swcInstance.transformSync(input, Object.assign(Object.assign({}, swcOptions), { filename: fileName }));
const { code, map } = swcInstance.transformSync(input, {
...swcOptions,
filename: fileName,
});
return { outputText: code, sourceMapText: map };

@@ -124,3 +144,4 @@ };

exports.targetMapping.set(/* ts.ScriptTarget.ES2021 */ 8, 'es2021');
exports.targetMapping.set(/* ts.ScriptTarget.ESNext */ 99, 'es2021');
exports.targetMapping.set(/* ts.ScriptTarget.ES2022 */ 9, 'es2022');
exports.targetMapping.set(/* ts.ScriptTarget.ESNext */ 99, 'es2022');
/**

@@ -140,2 +161,3 @@ * @internal

'es2021',
'es2022',
];

@@ -142,0 +164,0 @@ const ModuleKind = {

@@ -15,3 +15,3 @@ import type * as ts from 'typescript';

export interface CreateTranspilerOptions {
service: Pick<Service, 'config' | 'options'>;
service: Pick<Service, Extract<'config' | 'options' | 'projectLocalResolveHelper', keyof Service>>;
}

@@ -18,0 +18,0 @@ export interface Transpiler {

@@ -5,6 +5,1 @@ /**

export declare function cachedLookup<T, R>(fn: (arg: T) => R): (arg: T) => R;
/**
* We do not support ts's `trace` option yet. In the meantime, rather than omit
* `trace` options in hosts, I am using this placeholder.
*/
export declare function trace(s: string): void;
"use strict";
var _a;
Object.defineProperty(exports, "__esModule", { value: true });
exports.trace = exports.cachedLookup = exports.hasOwnProperty = exports.normalizeSlashes = exports.parse = exports.split = exports.assign = exports.yn = exports.createRequire = void 0;
exports.getBasePathForProjectLocalDependencyResolution = exports.createProjectLocalResolveHelper = exports.attemptRequireWithV8CompileCache = exports.cachedLookup = exports.hasOwnProperty = exports.normalizeSlashes = exports.parse = exports.split = exports.assign = exports.yn = exports.createRequire = void 0;
const module_1 = require("module");
const ynModule = require("yn");
const path_1 = require("path");
/** @internal */

@@ -88,7 +89,53 @@ exports.createRequire = (_a = module_1.createRequire !== null && module_1.createRequire !== void 0 ? module_1.createRequire : module_1.createRequireFromPath) !== null && _a !== void 0 ? _a : require('create-require');

/**
* We do not support ts's `trace` option yet. In the meantime, rather than omit
* `trace` options in hosts, I am using this placeholder.
* @internal
* Require something with v8-compile-cache, which should make subsequent requires faster.
* Do lots of error-handling so that, worst case, we require without the cache, and users are not blocked.
*/
function trace(s) { }
exports.trace = trace;
function attemptRequireWithV8CompileCache(requireFn, specifier) {
try {
const v8CC = require('v8-compile-cache-lib').install();
try {
return requireFn(specifier);
}
finally {
v8CC === null || v8CC === void 0 ? void 0 : v8CC.uninstall();
}
}
catch (e) {
return requireFn(specifier);
}
}
exports.attemptRequireWithV8CompileCache = attemptRequireWithV8CompileCache;
/**
* Helper to discover dependencies relative to a user's project, optionally
* falling back to relative to ts-node. This supports global installations of
* ts-node, for example where someone does `#!/usr/bin/env -S ts-node --swc` and
* we need to fallback to a global install of @swc/core
* @internal
*/
function createProjectLocalResolveHelper(localDirectory) {
return function projectLocalResolveHelper(specifier, fallbackToTsNodeRelative) {
return require.resolve(specifier, {
paths: fallbackToTsNodeRelative
? [localDirectory, __dirname]
: [localDirectory],
});
};
}
exports.createProjectLocalResolveHelper = createProjectLocalResolveHelper;
/**
* Used as a reminder of all the factors we must consider when finding project-local dependencies and when a config file
* on disk may or may not exist.
* @internal
*/
function getBasePathForProjectLocalDependencyResolution(configFilePath, projectSearchDirOption, projectOption, cwdOption) {
var _a;
if (configFilePath != null)
return (0, path_1.dirname)(configFilePath);
return (_a = projectSearchDirOption !== null && projectSearchDirOption !== void 0 ? projectSearchDirOption : projectOption) !== null && _a !== void 0 ? _a : cwdOption;
// TODO technically breaks if projectOption is path to a file, not a directory,
// and we attempt to resolve relative specifiers. By the time we resolve relative specifiers,
// should have configFilePath, so not reach this codepath.
}
exports.getBasePathForProjectLocalDependencyResolution = getBasePathForProjectLocalDependencyResolution;
//# sourceMappingURL=util.js.map
{
"name": "ts-node",
"version": "10.4.0",
"version": "10.5.0",
"description": "TypeScript execution environment and REPL for node.js, with source map support",

@@ -26,2 +26,3 @@ "main": "dist/index.js",

"./esm/transpile-only.mjs": "./esm/transpile-only.mjs",
"./transpilers/swc": "./transpilers/swc.js",
"./transpilers/swc-experimental": "./transpilers/swc-experimental.js",

@@ -129,3 +130,3 @@ "./node10/tsconfig.json": "./node10/tsconfig.json",

"nyc": "^15.0.1",
"prettier": "^2.2.1",
"prettier": "^2.5.1",
"proper-lockfile": "^4.1.2",

@@ -137,4 +138,4 @@ "proxyquire": "^2.0.0",

"throat": "^6.0.1",
"typedoc": "^0.22.4",
"typescript": "4.4.3",
"typedoc": "^0.22.10",
"typescript": "4.5.2",
"typescript-json-schema": "^0.51.0",

@@ -169,2 +170,3 @@ "util.promisify": "^1.0.1"

"make-error": "^1.1.1",
"v8-compile-cache-lib": "^3.0.0",
"yn": "3.1.1"

@@ -171,0 +173,0 @@ },

@@ -13,3 +13,3 @@ <!--

# ![TypeScript Node](logo.svg?sanitize=true)
# [![TypeScript Node](logo.svg?sanitize=true)](https://typestrong.org/ts-node)

@@ -64,2 +64,3 @@ [![NPM version](https://img.shields.io/npm/v/ts-node.svg?style=flat)](https://npmjs.org/package/ts-node)

* [Skipping `node_modules`](#skipping-node_modules)
* [Skipping pre-compiled TypeScript](#skipping-pre-compiled-typescript)
* [paths and baseUrl

@@ -70,4 +71,5 @@ ](#paths-and-baseurl)

* [Third-party compilers](#third-party-compilers)
* [Third-party transpilers](#third-party-transpilers)
* [Bundled `swc` integration](#bundled-swc-integration)
* [Transpilers](#transpilers)
* [swc](#swc)
* [Third-party transpilers](#third-party-transpilers)
* [Writing your own integration](#writing-your-own-integration)

@@ -152,6 +154,6 @@ * [Module type overrides](#module-type-overrides)

# Equivalent to ts-node --transpile-only
# Equivalent to ts-node --transpileOnly
ts-node-transpile-only script.ts
# Equivalent to ts-node --cwd-mode
# Equivalent to ts-node --cwdMode
ts-node-cwd script.ts

@@ -168,9 +170,24 @@ ```

Passing CLI arguments via shebang is allowed on Mac but not Linux. For example, the following will fail on Linux:
Passing options via shebang requires the [`env -S` flag](https://manpages.debian.org/bullseye/coreutils/env.1.en.html#S), which is available on recent versions of `env`. ([compatibility](https://github.com/TypeStrong/ts-node/pull/1448#issuecomment-913895766))
#!/usr/bin/env ts-node --files
// This shebang is not portable. It only works on Mac
```typescript
#!/usr/bin/env -S ts-node --files
// This shebang works on Mac and Linux with newer versions of env
// Technically, Mac allows omitting `-S`, but Linux requires it
```
Instead, specify all ts-node options in your `tsconfig.json`.
To write scripts with maximum portability, [specify all options in your `tsconfig.json`](#via-tsconfigjson-recommended) and omit them from the shebang.
```typescript
#!/usr/bin/env ts-node
// This shebang works everywhere
```
To test your version of `env` for compatibility:
```shell
# Note that these unusual quotes are necessary
/usr/bin/env --debug '-S echo foo bar'
```
## Programmatic

@@ -205,5 +222,5 @@

Use `--skip-project` to skip loading the `tsconfig.json`. Use `--project` to explicitly specify the path to a `tsconfig.json`.
Use `--skipProject` to skip loading the `tsconfig.json`. Use `--project` to explicitly specify the path to a `tsconfig.json`.
When searching, it is resolved using [the same search behavior as `tsc`](https://www.typescriptlang.org/docs/handbook/tsconfig-json.html). By default, this search is performed relative to the entrypoint script. In `--cwd-mode` or if no entrypoint is specified -- for example when using the REPL -- the search is performed relative to `--cwd` / `process.cwd()`.
When searching, it is resolved using [the same search behavior as `tsc`](https://www.typescriptlang.org/docs/handbook/tsconfig-json.html). By default, this search is performed relative to the entrypoint script. In `--cwdMode` or if no entrypoint is specified -- for example when using the REPL -- the search is performed relative to `--cwd` / `process.cwd()`.

@@ -261,3 +278,3 @@ You can use this sample configuration as a starting point:

When in doubt, `ts-node --show-config` will log the configuration being used, and `ts-node -vv` will log `node` and `typescript` versions.
When in doubt, `ts-node --showConfig` will log the configuration being used, and `ts-node -vv` will log `node` and `typescript` versions.

@@ -284,2 +301,4 @@ ## `node` flags

All command-line flags support both `--camelCase` and `--hyphen-case`.
*Environment variables, where available, are in `ALL_CAPS`*

@@ -298,14 +317,14 @@

* `-P, --project [path]` Path to TypeScript JSON project file <br/>*Environment:* `TS_NODE_PROJECT`
* `--skip-project` Skip project config resolution and loading <br/>*Default:* `false` <br/>*Environment:* `TS_NODE_SKIP_PROJECT`
* `-c, --cwd-mode` Resolve config relative to the current directory instead of the directory of the entrypoint script
* `-O, --compiler-options [opts]` JSON object to merge with compiler options <br/>*Environment:* `TS_NODE_COMPILER_OPTIONS`
* `--show-config` Print resolved `tsconfig.json`, including `ts-node` options, and exit
* `--skipProject` Skip project config resolution and loading <br/>*Default:* `false` <br/>*Environment:* `TS_NODE_SKIP_PROJECT`
* `-c, --cwdMode` Resolve config relative to the current directory instead of the directory of the entrypoint script
* `-O, --compilerOptions [opts]` JSON object to merge with compiler options <br/>*Environment:* `TS_NODE_COMPILER_OPTIONS`
* `--showConfig` Print resolved `tsconfig.json`, including `ts-node` options, and exit
## Typechecking
* `-T, --transpile-only` Use TypeScript's faster `transpileModule` <br/>*Default:* `false` <br/>*Environment:* `TS_NODE_TRANSPILE_ONLY`
* `--type-check` Opposite of `--transpile-only` <br/>*Default:* `true`<br/>*Environment:* `TS_NODE_TYPE_CHECK`
* `-H, --compiler-host` Use TypeScript's compiler host API <br/>*Default:* `false` <br/>*Environment:* `TS_NODE_COMPILER_HOST`
* `-T, --transpileOnly` Use TypeScript's faster `transpileModule` <br/>*Default:* `false` <br/>*Environment:* `TS_NODE_TRANSPILE_ONLY`
* `--typeCheck` Opposite of `--transpileOnly` <br/>*Default:* `true`<br/>*Environment:* `TS_NODE_TYPE_CHECK`
* `-H, --compilerHost` Use TypeScript's compiler host API <br/>*Default:* `false` <br/>*Environment:* `TS_NODE_COMPILER_HOST`
* `--files` Load `files`, `include` and `exclude` from `tsconfig.json` on startup <br/>*Default:* `false` <br/>*Environment:* `TS_NODE_FILES`
* `-D, --ignore-diagnostics [code]` Ignore TypeScript warnings by diagnostic code <br/>*Environment:* `TS_NODE_IGNORE_DIAGNOSTICS`
* `-D, --ignoreDiagnostics [code]` Ignore TypeScript warnings by diagnostic code <br/>*Environment:* `TS_NODE_IGNORE_DIAGNOSTICS`

@@ -315,10 +334,11 @@ ## Transpilation

* `-I, --ignore [pattern]` Override the path patterns to skip compilation <br/>*Default:* `/node_modules/` <br/>*Environment:* `TS_NODE_IGNORE`
* `--skip-ignore` Skip ignore checks <br/>*Default:* `false` <br/>*Environment:* `TS_NODE_SKIP_IGNORE`
* `--skipIgnore` Skip ignore checks <br/>*Default:* `false` <br/>*Environment:* `TS_NODE_SKIP_IGNORE`
* `-C, --compiler [name]` Specify a custom TypeScript compiler <br/>*Default:* `typescript` <br/>*Environment:* `TS_NODE_COMPILER`
* `--swc` Transpile with [swc](#swc). Implies `--transpileOnly` <br/>*Default:* `false`
* `--transpiler [name]` Specify a third-party, non-typechecking transpiler
* `--prefer-ts-exts` Re-order file extensions so that TypeScript imports are preferred <br/>*Default:* `false` <br/>*Environment:* `TS_NODE_PREFER_TS_EXTS`
* `--preferTsExts` Re-order file extensions so that TypeScript imports are preferred <br/>*Default:* `false` <br/>*Environment:* `TS_NODE_PREFER_TS_EXTS`
## Diagnostics
* `--log-error` Logs TypeScript errors to stderr instead of throwing exceptions <br/>*Default:* `false` <br/>*Environment:* `TS_NODE_LOG_ERROR`
* `--logError` Logs TypeScript errors to stderr instead of throwing exceptions <br/>*Default:* `false` <br/>*Environment:* `TS_NODE_LOG_ERROR`
* `--pretty` Use pretty diagnostic formatter <br/>*Default:* `false` <br/>*Environment:* `TS_NODE_PRETTY`

@@ -334,5 +354,6 @@ * `TS_NODE_DEBUG` Enable debug logging<br/>

* `--scopeDir` Directory within which compiler is limited when `scope` is enabled. <br/>*Default:* First of: `tsconfig.json` "rootDir" if specified, directory containing `tsconfig.json`, or cwd if no `tsconfig.json` is loaded.<br/>*Environment:* `TS_NODE_SCOPE_DIR`
* `moduleType` Override the module type of certain files, ignoring the `package.json` `"type"` field. See [Module type overrides](#module-type-overrides) for details.<br/>*Default:* obeys `package.json` `"type"` and `tsconfig.json` `"module"` <br/>*Can only be specified via `tsconfig.json` or API.*
* `moduleTypes` Override the module type of certain files, ignoring the `package.json` `"type"` field. See [Module type overrides](#module-type-overrides) for details.<br/>*Default:* obeys `package.json` `"type"` and `tsconfig.json` `"module"` <br/>*Can only be specified via `tsconfig.json` or API.*
* `TS_NODE_HISTORY` Path to history file for REPL <br/>*Default:* `~/.ts_node_repl_history`<br/>
* `--no-experimental-repl-await` Disable top-level await in REPL. Equivalent to node's [`--no-experimental-repl-await`](https://nodejs.org/api/cli.html#cli_no_experimental_repl_await)<br/>*Default:* Enabled if TypeScript version is 3.8 or higher and target is ES2018 or higher.<br/>*Environment:* `TS_NODE_EXPERIMENTAL_REPL_AWAIT` set `false` to disable
* `--noExperimentalReplAwait` Disable top-level await in REPL. Equivalent to node's [`--no-experimental-repl-await`](https://nodejs.org/api/cli.html#cli_no_experimental_repl_await)<br/>*Default:* Enabled if TypeScript version is 3.8 or higher and target is ES2018 or higher.<br/>*Environment:* `TS_NODE_EXPERIMENTAL_REPL_AWAIT` set `false` to disable
* `experimentalResolverFeatures` Enable experimental features that re-map imports and require calls to support: `baseUrl`, `paths`, `rootDirs`, `.js` to `.ts` file extension mappings, `outDir` to `rootDir` mappings for composite projects and monorepos. For details, see [#1514](https://github.com/TypeStrong/ts-node/issues/1514)<br/>*Default:* `false`<br/>*Can only be specified via `tsconfig.json` or API.*

@@ -417,3 +438,3 @@ ## API

ts-node uses sensible default configurations to reduce boilerplate while still respecting `tsconfig.json` if you
have one. If you are unsure which configuration is used, you can log it with `ts-node --show-config`. This is similar to
have one. If you are unsure which configuration is used, you can log it with `ts-node --showConfig`. This is similar to
`tsc --showConfig` but includes `"ts-node"` options as well.

@@ -430,3 +451,3 @@

$ ts-node --show-config
$ ts-node --showConfig
{

@@ -506,3 +527,3 @@ "compilerOptions": {

* Enable [`transpileOnly`](#options) to skip typechecking
* Use our [`swc` integration](#bundled-swc-integration)
* Use our [`swc` integration](#swc)
* This is by far the fastest option

@@ -536,3 +557,3 @@

By default, **TypeScript Node** avoids compiling files in `/node_modules/` for three reasons:
By default, ts-node avoids compiling files in `/node_modules/` for three reasons:

@@ -543,2 +564,10 @@ 1. Modules should always be published in a format node.js can consume

If you need to import uncompiled TypeScript in `node_modules`, use [`--skipIgnore`](#transpilation) or [`TS_NODE_SKIP_IGNORE`](#transpilation) to bypass this restriction.
### Skipping pre-compiled TypeScript
If a compiled JavaScript file with the same name as a TypeScript file already exists, the TypeScript file will be ignored. ts-node will import the pre-compiled JavaScript.
To force ts-node to import the TypeScript source, not the precompiled JavaScript, use [`--preferTsExts`](#transpilation).
## paths and baseUrl&#xA;

@@ -647,3 +676,3 @@

## Third-party transpilers
## Transpilers

@@ -661,8 +690,7 @@ In transpile-only mode, we skip typechecking to speed up execution time. You can go a step further and use a

### Bundled `swc` integration
### swc
We have bundled an experimental `swc` integration.
swc support is built-in via the `--swc` flag or `"swc": true` tsconfig option.
[`swc`](https://swc.rs) is a TypeScript-compatible transpiler implemented in Rust. This makes it an order of magnitude faster
than `transpileModule`.
[`swc`](https://swc.rs) is a TypeScript-compatible transpiler implemented in Rust. This makes it an order of magnitude faster than vanilla `transpileOnly`.

@@ -680,4 +708,3 @@ To use it, first install `@swc/core` or `@swc/wasm`. If using `importHelpers`, also install `@swc/helpers`. If `target` is less than "es2015" and using either `async`/`await` or generator functions, also install `regenerator-runtime`.

"ts-node": {
"transpileOnly": true,
"transpiler": "ts-node/transpilers/swc-experimental"
"swc": true
}

@@ -689,2 +716,20 @@ }

### Third-party transpilers
The `transpiler` option allows using third-party transpiler integrations with ts-node. `transpiler` must be given the
name of a module which can be `require()`d. The built-in `swc` integration is exposed as `ts-node/transpilers/swc`.
For example, to use a hypothetical "speedy-ts-compiler", first install it into your project: `npm install speedy-ts-compiler`
Then add the following to your tsconfig:
```jsonc title="tsconfig.json"
{
"ts-node": {
"transpileOnly": true,
"transpiler": "speedy-ts-compiler"
}
}
```
### Writing your own integration

@@ -694,4 +739,5 @@

Integrations are `require()`d, so they can be published to npm. The module must export a `create` function matching the
[`TranspilerModule`](https://typestrong.org/ts-node/api/interfaces/TranspilerModule.html) interface.
Integrations are `require()`d by ts-node, so they can be published to npm for convenience. The module must export a `create` function described by our
[`TranspilerModule`](https://typestrong.org/ts-node/api/interfaces/TranspilerModule.html) interface. `create` is invoked by ts-node
at startup to create the transpiler. The transpiler is used repeatedly to transform TypeScript into JavaScript.

@@ -698,0 +744,0 @@ ## Module type overrides

@@ -5,3 +5,3 @@ {

"definitions": {
"Record<string,\"cjs\"|\"esm\"|\"package\">": {
"ModuleTypes": {
"type": "object"

@@ -43,2 +43,6 @@ },

},
"experimentalResolverFeatures": {
"description": "Enable experimental features that re-map imports and require calls to support:\n`baseUrl`, `paths`, `rootDirs`, `.js` to `.ts` file extension mappings,\n`outDir` to `rootDir` mappings for composite projects and monorepos.\n\nFor details, see https://github.com/TypeStrong/ts-node/issues/1514",
"type": "boolean"
},
"files": {

@@ -75,3 +79,3 @@ "default": false,

"moduleTypes": {
"$ref": "#/definitions/Record<string,\"cjs\"|\"esm\"|\"package\">",
"$ref": "#/definitions/ModuleTypes",
"description": "Override certain paths to be compiled and executed as CommonJS or ECMAScript modules.\nWhen overridden, the tsconfig \"module\" and package.json \"type\" fields are overridden.\nThis is useful because TypeScript files cannot use the .cjs nor .mjs file extensions;\nit achieves the same effect.\n\nEach key is a glob pattern following the same rules as tsconfig's \"include\" array.\nWhen multiple patterns match the same file, the last pattern takes precedence.\n\n`cjs` overrides matches files to compile and execute as CommonJS.\n`esm` overrides matches files to compile and execute as native ECMAScript modules.\n`package` overrides either of the above to default behavior, which obeys package.json \"type\" and\ntsconfig.json \"module\" options."

@@ -110,2 +114,6 @@ },

},
"swc": {
"description": "Transpile with swc instead of the TypeScript compiler, and skip typechecking.\n\nEquivalent to setting both `transpileOnly: true` and `transpiler: 'ts-node/transpilers/swc'`\n\nFor complete instructions: https://typestrong.org/ts-node/docs/transpilers",
"type": "boolean"
},
"transpileOnly": {

@@ -112,0 +120,0 @@ "default": false,

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is too big to display

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc