Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

ts-node

Package Overview
Dependencies
Maintainers
1
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 8.2.0 to 8.3.0

164

dist/bin.js
#!/usr/bin/env node
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var _a;
var path_1 = require("path");
var repl_1 = require("repl");
var util_1 = require("util");
var Module = require("module");
var arg = require("arg");
var diff_1 = require("diff");
var vm_1 = require("vm");
var fs_1 = require("fs");
var index_1 = require("./index");
var args = arg({
const path_1 = require("path");
const repl_1 = require("repl");
const util_1 = require("util");
const Module = require("module");
const arg = require("arg");
const diff_1 = require("diff");
const vm_1 = require("vm");
const fs_1 = require("fs");
const index_1 = require("./index");
const args = arg({
// Node.js-like options.

@@ -34,2 +33,3 @@ '--eval': String,

'--skip-ignore': Boolean,
'--prefer-ts-exts': Boolean,
'--log-error': Boolean,

@@ -51,5 +51,29 @@ // Aliases.

});
var _b = args["--help"], help = _b === void 0 ? false : _b, _c = args["--version"], version = _c === void 0 ? 0 : _c, _d = args["--files"], files = _d === void 0 ? index_1.DEFAULTS.files : _d, _e = args["--compiler"], compiler = _e === void 0 ? index_1.DEFAULTS.compiler : _e, _f = args["--compiler-options"], compilerOptions = _f === void 0 ? index_1.DEFAULTS.compilerOptions : _f, _g = args["--project"], project = _g === void 0 ? index_1.DEFAULTS.project : _g, _h = args["--ignore-diagnostics"], ignoreDiagnostics = _h === void 0 ? index_1.DEFAULTS.ignoreDiagnostics : _h, _j = args["--ignore"], ignore = _j === void 0 ? index_1.DEFAULTS.ignore : _j, _k = args["--transpile-only"], transpileOnly = _k === void 0 ? index_1.DEFAULTS.transpileOnly : _k, _l = args["--type-check"], typeCheck = _l === void 0 ? index_1.DEFAULTS.typeCheck : _l, _m = args["--pretty"], pretty = _m === void 0 ? index_1.DEFAULTS.pretty : _m, _o = args["--skip-project"], skipProject = _o === void 0 ? index_1.DEFAULTS.skipProject : _o, _p = args["--skip-ignore"], skipIgnore = _p === void 0 ? index_1.DEFAULTS.skipIgnore : _p, _q = args["--log-error"], logError = _q === void 0 ? index_1.DEFAULTS.logError : _q;
const { '--help': help = false, '--version': version = 0, '--files': files = index_1.DEFAULTS.files, '--compiler': compiler = index_1.DEFAULTS.compiler, '--compiler-options': compilerOptions = index_1.DEFAULTS.compilerOptions, '--project': project = index_1.DEFAULTS.project, '--ignore-diagnostics': ignoreDiagnostics = index_1.DEFAULTS.ignoreDiagnostics, '--ignore': ignore = index_1.DEFAULTS.ignore, '--transpile-only': transpileOnly = index_1.DEFAULTS.transpileOnly, '--type-check': typeCheck = index_1.DEFAULTS.typeCheck, '--pretty': pretty = index_1.DEFAULTS.pretty, '--skip-project': skipProject = index_1.DEFAULTS.skipProject, '--skip-ignore': skipIgnore = index_1.DEFAULTS.skipIgnore, '--prefer-ts-exts': preferTsExts = index_1.DEFAULTS.preferTsExts, '--log-error': logError = index_1.DEFAULTS.logError } = args;
if (help) {
console.log("\nUsage: ts-node [options] [ -e script | script.ts ] [arguments]\n\nOptions:\n\n -e, --eval [code] Evaluate code\n -p, --print Print result of `--eval`\n -r, --require [path] Require a node module before execution\n\n -h, --help Print CLI usage\n -v, --version Print module version information\n\n -T, --transpile-only Use TypeScript's faster `transpileModule`\n -I, --ignore [pattern] Override the path patterns to skip compilation\n -P, --project [path] Path to TypeScript JSON project file\n -C, --compiler [name] Specify a custom TypeScript compiler\n -D, --ignore-diagnostics [code] Ignore TypeScript warnings by diagnostic code\n -O, --compiler-options [opts] JSON object to merge with compiler options\n\n --files Load files from `tsconfig.json` on startup\n --pretty Use pretty diagnostic formatter\n --skip-project Skip reading `tsconfig.json`\n --skip-ignore Skip `--ignore` checks\n");
console.log(`
Usage: ts-node [options] [ -e script | script.ts ] [arguments]
Options:
-e, --eval [code] Evaluate code
-p, --print Print result of \`--eval\`
-r, --require [path] Require a node module before execution
-h, --help Print CLI usage
-v, --version Print module version information
-T, --transpile-only Use TypeScript's faster \`transpileModule\`
-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
-D, --ignore-diagnostics [code] Ignore TypeScript warnings by diagnostic code
-O, --compiler-options [opts] JSON object to merge with compiler options
--files Load files from \`tsconfig.json\` on startup
--pretty Use pretty diagnostic formatter
--skip-project Skip reading \`tsconfig.json\`
--skip-ignore Skip \`--ignore\` checks
--prefer-ts-exts Prefer importing TypeScript files over JavaScript files
`);
process.exit(0);

@@ -59,22 +83,29 @@ }

if (version === 1) {
console.log("v" + index_1.VERSION);
console.log(`v${index_1.VERSION}`);
process.exit(0);
}
var cwd = process.cwd();
var code = args['--eval'];
var isPrinted = args['--print'] !== undefined;
const cwd = process.cwd();
const code = args['--eval'];
const isPrinted = args['--print'] !== undefined;
/**
* Eval helpers.
*/
const EVAL_FILENAME = `[eval].ts`;
const EVAL_PATH = path_1.join(cwd, EVAL_FILENAME);
const EVAL_INSTANCE = { input: '', output: '', version: 0, lines: 0 };
// Register the TypeScript compiler instance.
var service = index_1.register({
files: files,
pretty: pretty,
typeCheck: typeCheck,
transpileOnly: transpileOnly,
ignore: ignore,
project: project,
skipIgnore: skipIgnore,
logError: logError,
skipProject: skipProject,
compiler: compiler,
ignoreDiagnostics: ignoreDiagnostics,
compilerOptions: compilerOptions,
const service = index_1.register({
files,
pretty,
typeCheck,
transpileOnly,
ignore,
project,
skipIgnore,
preferTsExts,
logError,
skipProject,
compiler,
ignoreDiagnostics,
compilerOptions,
readFile: code ? readFileEval : undefined,

@@ -85,5 +116,5 @@ fileExists: code ? fileExistsEval : undefined

if (version >= 2) {
console.log("ts-node v" + index_1.VERSION);
console.log("node " + process.version);
console.log("compiler v" + service.ts.version);
console.log(`ts-node v${index_1.VERSION}`);
console.log(`node ${process.version}`);
console.log(`compiler v${service.ts.version}`);
process.exit(0);

@@ -94,10 +125,4 @@ }

Module._preloadModules(args['--require']);
/**
* Eval helpers.
*/
var EVAL_FILENAME = "[eval].ts";
var EVAL_PATH = path_1.join(cwd, EVAL_FILENAME);
var EVAL_INSTANCE = { input: '', output: '', version: 0, lines: 0 };
// Prepend `ts-node` arguments to CLI for child processes.
(_a = process.execArgv).unshift.apply(_a, [__filename].concat(process.argv.slice(2, process.argv.length - args._.length)));
process.execArgv.unshift(__filename, ...process.argv.slice(2, process.argv.length - args._.length));
process.argv = [process.argv[1]].concat(args._.length ? path_1.resolve(cwd, args._[0]) : []).concat(args._.slice(1));

@@ -118,5 +143,5 @@ // Execute the main contents (either eval, script or piped).

else {
var code_1 = '';
process.stdin.on('data', function (chunk) { return code_1 += chunk; });
process.stdin.on('end', function () { return evalAndExit(code_1, isPrinted); });
let code = '';
process.stdin.on('data', (chunk) => code += chunk);
process.stdin.on('end', () => evalAndExit(code, isPrinted));
}

@@ -129,3 +154,3 @@ }

function evalAndExit(code, isPrinted) {
var module = new Module(EVAL_FILENAME);
const module = new Module(EVAL_FILENAME);
module.filename = EVAL_FILENAME;

@@ -138,3 +163,3 @@ module.paths = Module._nodeModulePaths(cwd);

global.require = module.require.bind(module);
var result;
let result;
try {

@@ -158,6 +183,6 @@ result = _eval(code);

function _eval(input) {
var lines = EVAL_INSTANCE.lines;
var isCompletion = !/\n$/.test(input);
var undo = appendEval(input);
var output;
const lines = EVAL_INSTANCE.lines;
const isCompletion = !/\n$/.test(input);
const undo = appendEval(input);
let output;
try {

@@ -171,3 +196,3 @@ output = service.compile(EVAL_INSTANCE.input, EVAL_PATH, -lines);

// Use `diff` to check for new JavaScript to execute.
var changes = diff_1.diffLines(EVAL_INSTANCE.output, output);
const changes = diff_1.diffLines(EVAL_INSTANCE.output, output);
if (isCompletion) {

@@ -179,3 +204,3 @@ undo();

}
return changes.reduce(function (result, change) {
return changes.reduce((result, change) => {
return change.added ? exec(change.value, EVAL_FILENAME) : result;

@@ -188,3 +213,3 @@ }, undefined);

function exec(code, filename) {
var script = new vm_1.Script(code, { filename: filename });
const script = new vm_1.Script(code, { filename: filename });
return script.runInThisContext();

@@ -196,3 +221,3 @@ }

function startRepl() {
var repl = repl_1.start({
const repl = repl_1.start({
prompt: '> ',

@@ -206,3 +231,3 @@ input: process.stdin,

// Bookmark the point where we should reset the REPL state.
var resetEval = appendEval('');
const resetEval = appendEval('');
function reset() {

@@ -222,6 +247,6 @@ resetEval();

}
var undo = appendEval(identifier);
var _a = service.getTypeInfo(EVAL_INSTANCE.input, EVAL_PATH, EVAL_INSTANCE.input.length), name = _a.name, comment = _a.comment;
const undo = appendEval(identifier);
const { name, comment } = service.getTypeInfo(EVAL_INSTANCE.input, EVAL_PATH, EVAL_INSTANCE.input.length);
undo();
repl.outputStream.write(name + "\n" + (comment ? comment + "\n" : ''));
repl.outputStream.write(`${name}\n${comment ? `${comment}\n` : ''}`);
repl.displayPrompt();

@@ -235,4 +260,4 @@ }

function replEval(code, _context, _filename, callback) {
var err = null;
var result;
let err = null;
let result;
// TODO: Figure out how to handle completion here.

@@ -266,9 +291,9 @@ if (code === '.scope') {

function appendEval(input) {
var undoInput = EVAL_INSTANCE.input;
var undoVersion = EVAL_INSTANCE.version;
var undoOutput = EVAL_INSTANCE.output;
var undoLines = EVAL_INSTANCE.lines;
const undoInput = EVAL_INSTANCE.input;
const undoVersion = EVAL_INSTANCE.version;
const undoOutput = EVAL_INSTANCE.output;
const undoLines = EVAL_INSTANCE.lines;
// Handle ASI issues with TypeScript re-evaluation.
if (undoInput.charAt(undoInput.length - 1) === '\n' && /^\s*[\[\(\`]/.test(input) && !/;\s*$/.test(undoInput)) {
EVAL_INSTANCE.input = EVAL_INSTANCE.input.slice(0, -1) + ";\n";
EVAL_INSTANCE.input = `${EVAL_INSTANCE.input.slice(0, -1)};\n`;
}

@@ -289,5 +314,4 @@ EVAL_INSTANCE.input += input;

function lineCount(value) {
var count = 0;
for (var _i = 0, value_1 = value; _i < value_1.length; _i++) {
var char = value_1[_i];
let count = 0;
for (const char of value) {
if (char === '\n') {

@@ -317,3 +341,3 @@ count++;

try {
var stats = fs_1.statSync(path);
const stats = fs_1.statSync(path);
return stats.isFile() || stats.isFIFO();

@@ -325,3 +349,3 @@ }

}
var RECOVERY_CODES = new Set([
const RECOVERY_CODES = new Set([
1003,

@@ -339,4 +363,4 @@ 1005,

function isRecoverable(error) {
return error.diagnosticCodes.every(function (code) { return RECOVERY_CODES.has(code); });
return error.diagnosticCodes.every(code => RECOVERY_CODES.has(code));
}
//# sourceMappingURL=bin.js.map

@@ -46,2 +46,3 @@ import { BaseError } from 'make-error';

skipProject?: boolean | null;
preferTsExts?: boolean | null;
compilerOptions?: object;

@@ -48,0 +49,0 @@ ignoreDiagnostics?: Array<number | string>;

"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
var path_1 = require("path");
var sourceMapSupport = require("source-map-support");
var yn_1 = require("yn");
var make_error_1 = require("make-error");
var util = require("util");
const path_1 = require("path");
const sourceMapSupport = require("source-map-support");
const yn_1 = require("yn");
const make_error_1 = require("make-error");
const util = require("util");
/**

@@ -28,8 +15,8 @@ * @internal

*/
var shouldDebug = yn_1.default(process.env.TS_NODE_DEBUG);
var debug = shouldDebug ? console.log.bind(console, 'ts-node') : function () { return undefined; };
var debugFn = shouldDebug ?
function (key, fn) {
var i = 0;
return function (x) {
const shouldDebug = yn_1.default(process.env.TS_NODE_DEBUG);
const debug = shouldDebug ? console.log.bind(console, 'ts-node') : () => undefined;
const debugFn = shouldDebug ?
(key, fn) => {
let i = 0;
return (x) => {
debug(key, x, ++i);

@@ -39,3 +26,3 @@ return fn(x);

} :
function (_, fn) { return fn; };
(_, fn) => fn;
/**

@@ -48,14 +35,10 @@ * Export the current version.

*/
var MemoryCache = /** @class */ (function () {
function MemoryCache(rootFileNames) {
if (rootFileNames === void 0) { rootFileNames = []; }
class MemoryCache {
constructor(rootFileNames = []) {
this.fileContents = new Map();
this.fileVersions = new Map();
for (var _i = 0, rootFileNames_1 = rootFileNames; _i < rootFileNames_1.length; _i++) {
var fileName = rootFileNames_1[_i];
for (const fileName of rootFileNames)
this.fileVersions.set(fileName, 1);
}
}
return MemoryCache;
}());
}
/**

@@ -73,2 +56,3 @@ * Default register options.

skipProject: yn_1.default(process.env['TS_NODE_SKIP_PROJECT']),
preferTsExts: yn_1.default(process.env['TS_NODE_PREFER_TS_EXTS']),
ignoreDiagnostics: split(process.env['TS_NODE_IGNORE_DIAGNOSTICS']),

@@ -82,3 +66,3 @@ typeCheck: yn_1.default(process.env['TS_NODE_TYPE_CHECK']),

*/
var TS_NODE_COMPILER_OPTIONS = {
const TS_NODE_COMPILER_OPTIONS = {
sourceMap: true,

@@ -115,10 +99,8 @@ inlineSourceMap: false,

*/
var TSError = /** @class */ (function (_super) {
__extends(TSError, _super);
function TSError(diagnosticText, diagnosticCodes) {
var _this = _super.call(this, "\u2A2F Unable to compile TypeScript:\n" + diagnosticText) || this;
_this.diagnosticText = diagnosticText;
_this.diagnosticCodes = diagnosticCodes;
_this.name = 'TSError';
return _this;
class TSError extends make_error_1.BaseError {
constructor(diagnosticText, diagnosticCodes) {
super(`⨯ Unable to compile TypeScript:\n${diagnosticText}`);
this.diagnosticText = diagnosticText;
this.diagnosticCodes = diagnosticCodes;
this.name = 'TSError';
}

@@ -128,7 +110,6 @@ /**

*/
TSError.prototype[exports.INSPECT_CUSTOM] = function () {
[exports.INSPECT_CUSTOM]() {
return this.diagnosticText;
};
return TSError;
}(make_error_1.BaseError));
}
}
exports.TSError = TSError;

@@ -139,4 +120,4 @@ /**

function cachedLookup(fn) {
var cache = new Map();
return function (arg) {
const cache = new Map();
return (arg) => {
if (!cache.has(arg)) {

@@ -151,28 +132,28 @@ cache.set(arg, fn(arg));

*/
function register(opts) {
if (opts === void 0) { opts = {}; }
var options = Object.assign({}, exports.DEFAULTS, opts);
var originalJsHandler = require.extensions['.js']; // tslint:disable-line
var ignoreDiagnostics = [
function register(opts = {}) {
const options = Object.assign({}, exports.DEFAULTS, opts);
const originalJsHandler = require.extensions['.js']; // tslint:disable-line
const ignoreDiagnostics = [
6059,
18002,
18003
].concat((options.ignoreDiagnostics || [])).map(Number);
var ignore = options.skipIgnore ? [] : (options.ignore || ['/node_modules/']).map(function (str) { return new RegExp(str); });
18003,
...(options.ignoreDiagnostics || [])
].map(Number);
const ignore = options.skipIgnore ? [] : (options.ignore || ['/node_modules/']).map(str => new RegExp(str));
// Require the TypeScript compiler and configuration.
var cwd = process.cwd();
var typeCheck = options.typeCheck === true || options.transpileOnly !== true;
var compiler = require.resolve(options.compiler || 'typescript', { paths: [cwd, __dirname] });
var ts = require(compiler);
var transformers = options.transformers || undefined;
var readFile = options.readFile || ts.sys.readFile;
var fileExists = options.fileExists || ts.sys.fileExists;
var config = readConfig(cwd, ts, fileExists, readFile, options);
var configDiagnosticList = filterDiagnostics(config.errors, ignoreDiagnostics);
var extensions = ['.ts'];
var outputCache = new Map();
var diagnosticHost = {
getNewLine: function () { return ts.sys.newLine; },
getCurrentDirectory: function () { return cwd; },
getCanonicalFileName: function (path) { return path; }
const cwd = process.cwd();
const typeCheck = options.typeCheck === true || options.transpileOnly !== true;
const compiler = require.resolve(options.compiler || 'typescript', { paths: [cwd, __dirname] });
const ts = require(compiler);
const transformers = options.transformers || undefined;
const readFile = options.readFile || ts.sys.readFile;
const fileExists = options.fileExists || ts.sys.fileExists;
const config = readConfig(cwd, ts, fileExists, readFile, options);
const configDiagnosticList = filterDiagnostics(config.errors, ignoreDiagnostics);
const extensions = ['.ts'];
const outputCache = new Map();
const diagnosticHost = {
getNewLine: () => ts.sys.newLine,
getCurrentDirectory: () => cwd,
getCanonicalFileName: (path) => path
};

@@ -182,16 +163,16 @@ // Install source map support and read from memory cache.

environment: 'node',
retrieveFile: function (path) {
retrieveFile(path) {
return outputCache.get(path) || '';
}
});
var formatDiagnostics = process.stdout.isTTY || options.pretty
const formatDiagnostics = process.stdout.isTTY || options.pretty
? ts.formatDiagnosticsWithColorAndContext
: ts.formatDiagnostics;
function createTSError(diagnostics) {
var diagnosticText = formatDiagnostics(diagnostics, diagnosticHost);
var diagnosticCodes = diagnostics.map(function (x) { return x.code; });
const diagnosticText = formatDiagnostics(diagnostics, diagnosticHost);
const diagnosticCodes = diagnostics.map(x => x.code);
return new TSError(diagnosticText, diagnosticCodes);
}
function reportTSError(configDiagnosticList) {
var error = createTSError(configDiagnosticList);
const error = createTSError(configDiagnosticList);
if (options.logError) {

@@ -219,17 +200,16 @@ // Print error in red color and continue execution.

*/
var getExtension = config.options.jsx === ts.JsxEmit.Preserve ?
(function (path) { return /\.[tj]sx$/.test(path) ? '.jsx' : '.js'; }) :
(function (_) { return '.js'; });
const getExtension = config.options.jsx === ts.JsxEmit.Preserve ?
((path) => /\.[tj]sx$/.test(path) ? '.jsx' : '.js') :
((_) => '.js');
/**
* Create the basic required function using transpile mode.
*/
var getOutput = function (code, fileName, lineOffset) {
if (lineOffset === void 0) { lineOffset = 0; }
var result = ts.transpileModule(code, {
fileName: fileName,
transformers: transformers,
let getOutput = function (code, fileName, lineOffset = 0) {
const result = ts.transpileModule(code, {
fileName,
transformers,
compilerOptions: config.options,
reportDiagnostics: true
});
var diagnosticList = result.diagnostics ?
const diagnosticList = result.diagnostics ?
filterDiagnostics(result.diagnostics, ignoreDiagnostics) :

@@ -241,29 +221,29 @@ [];

};
var getTypeInfo = function (_code, _fileName, _position) {
throw new TypeError("Type information is unavailable without \"--type-check\"");
let getTypeInfo = function (_code, _fileName, _position) {
throw new TypeError(`Type information is unavailable without "--type-check"`);
};
// Use full language services when the fast option is disabled.
if (typeCheck) {
var memoryCache_1 = new MemoryCache(config.fileNames);
var cachedReadFile_1 = cachedLookup(debugFn('readFile', readFile));
const memoryCache = new MemoryCache(config.fileNames);
const cachedReadFile = cachedLookup(debugFn('readFile', readFile));
// Create the compiler host for type checking.
var serviceHost = {
getScriptFileNames: function () { return Array.from(memoryCache_1.fileVersions.keys()); },
getScriptVersion: function (fileName) {
var version = memoryCache_1.fileVersions.get(fileName);
const serviceHost = {
getScriptFileNames: () => Array.from(memoryCache.fileVersions.keys()),
getScriptVersion: (fileName) => {
const version = memoryCache.fileVersions.get(fileName);
return version === undefined ? '' : version.toString();
},
getScriptSnapshot: function (fileName) {
var contents = memoryCache_1.fileContents.get(fileName);
getScriptSnapshot(fileName) {
let contents = memoryCache.fileContents.get(fileName);
// Read contents into TypeScript memory cache.
if (contents === undefined) {
contents = cachedReadFile_1(fileName);
contents = cachedReadFile(fileName);
if (contents === undefined)
return;
memoryCache_1.fileVersions.set(fileName, 1);
memoryCache_1.fileContents.set(fileName, contents);
memoryCache.fileVersions.set(fileName, 1);
memoryCache.fileContents.set(fileName, contents);
}
return ts.ScriptSnapshot.fromString(contents);
},
readFile: cachedReadFile_1,
readFile: cachedReadFile,
readDirectory: cachedLookup(debugFn('readDirectory', ts.sys.readDirectory)),

@@ -273,32 +253,31 @@ getDirectories: cachedLookup(debugFn('getDirectories', ts.sys.getDirectories)),

directoryExists: cachedLookup(debugFn('directoryExists', ts.sys.directoryExists)),
getNewLine: function () { return ts.sys.newLine; },
useCaseSensitiveFileNames: function () { return ts.sys.useCaseSensitiveFileNames; },
getCurrentDirectory: function () { return cwd; },
getCompilationSettings: function () { return config.options; },
getDefaultLibFileName: function () { return ts.getDefaultLibFilePath(config.options); },
getCustomTransformers: function () { return transformers; }
getNewLine: () => ts.sys.newLine,
useCaseSensitiveFileNames: () => ts.sys.useCaseSensitiveFileNames,
getCurrentDirectory: () => cwd,
getCompilationSettings: () => config.options,
getDefaultLibFileName: () => ts.getDefaultLibFilePath(config.options),
getCustomTransformers: () => transformers
};
var registry = ts.createDocumentRegistry(ts.sys.useCaseSensitiveFileNames, cwd);
var service_1 = ts.createLanguageService(serviceHost, registry);
const registry = ts.createDocumentRegistry(ts.sys.useCaseSensitiveFileNames, cwd);
const service = ts.createLanguageService(serviceHost, registry);
// Set the file contents into cache manually.
var updateMemoryCache_1 = function (contents, fileName) {
var fileVersion = memoryCache_1.fileVersions.get(fileName) || 0;
const updateMemoryCache = function (contents, fileName) {
const fileVersion = memoryCache.fileVersions.get(fileName) || 0;
// Avoid incrementing cache when nothing has changed.
if (memoryCache_1.fileContents.get(fileName) === contents)
if (memoryCache.fileContents.get(fileName) === contents)
return;
memoryCache_1.fileVersions.set(fileName, fileVersion + 1);
memoryCache_1.fileContents.set(fileName, contents);
memoryCache.fileVersions.set(fileName, fileVersion + 1);
memoryCache.fileContents.set(fileName, contents);
};
getOutput = function (code, fileName, lineOffset) {
if (lineOffset === void 0) { lineOffset = 0; }
updateMemoryCache_1(code, fileName);
var output = service_1.getEmitOutput(fileName);
getOutput = function (code, fileName, lineOffset = 0) {
updateMemoryCache(code, fileName);
const output = service.getEmitOutput(fileName);
// Get the relevant diagnostics - this is 3x faster than `getPreEmitDiagnostics`.
var diagnostics = service_1.getSemanticDiagnostics(fileName)
.concat(service_1.getSyntacticDiagnostics(fileName));
var diagnosticList = filterDiagnostics(diagnostics, ignoreDiagnostics);
const diagnostics = service.getSemanticDiagnostics(fileName)
.concat(service.getSyntacticDiagnostics(fileName));
const diagnosticList = filterDiagnostics(diagnostics, ignoreDiagnostics);
if (diagnosticList.length)
reportTSError(diagnosticList);
if (output.emitSkipped) {
throw new TypeError(path_1.relative(cwd, fileName) + ": Emit skipped");
throw new TypeError(`${path_1.relative(cwd, fileName)}: Emit skipped`);
}

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

'loader (attached before `ts-node`) available alongside ' +
("`" + path_1.basename(fileName) + "`."));
`\`${path_1.basename(fileName)}\`.`);
}

@@ -317,7 +296,7 @@ return [output.outputFiles[1].text, output.outputFiles[0].text];

getTypeInfo = function (code, fileName, position) {
updateMemoryCache_1(code, fileName);
var info = service_1.getQuickInfoAtPosition(fileName, position);
var name = ts.displayPartsToString(info ? info.displayParts : []);
var comment = ts.displayPartsToString(info ? info.documentation : []);
return { name: name, comment: comment };
updateMemoryCache(code, fileName);
const info = service.getQuickInfoAtPosition(fileName, position);
const name = ts.displayPartsToString(info ? info.displayParts : []);
const comment = ts.displayPartsToString(info ? info.documentation : []);
return { name, comment };
};

@@ -327,12 +306,10 @@ }

function compile(code, fileName, lineOffset) {
var _a = getOutput(code, fileName, lineOffset), value = _a[0], sourceMap = _a[1];
var output = updateOutput(value, fileName, sourceMap, getExtension);
const [value, sourceMap] = getOutput(code, fileName, lineOffset);
const output = updateOutput(value, fileName, sourceMap, getExtension);
outputCache.set(fileName, output);
return output;
}
var register = { cwd: cwd, compile: compile, getTypeInfo: getTypeInfo, extensions: extensions, ts: ts };
const register = { cwd, compile, getTypeInfo, extensions, ts };
// Register the extensions.
extensions.forEach(function (extension) {
registerExtension(extension, ignore, register, originalJsHandler);
});
registerExtensions(opts, extensions, ignore, register, originalJsHandler);
return register;

@@ -345,10 +322,35 @@ }

function shouldIgnore(filename, ignore) {
var relname = normalizeSlashes(filename);
return ignore.some(function (x) { return x.test(relname); });
const relname = normalizeSlashes(filename);
return ignore.some(x => x.test(relname));
}
/**
* "Refreshes" an extension on `require.extentions`.
*
* @param {string} ext
*/
function reorderRequireExtension(ext) {
const old = require.extensions[ext]; // tslint:disable-line
delete require.extensions[ext]; // tslint:disable-line
require.extensions[ext] = old; // tslint:disable-line
}
/**
* Register the extensions to support when importing files.
*/
function registerExtensions(opts, extensions, ignore, register, originalJsHandler) {
// Register new extensions.
for (const ext of extensions) {
registerExtension(ext, ignore, register, originalJsHandler);
}
if (opts.preferTsExts) {
// tslint:disable-next-line
const preferredExtensions = new Set([...extensions, ...Object.keys(require.extensions)]);
for (const ext of preferredExtensions)
reorderRequireExtension(ext);
}
}
/**
* Register the extension for node.
*/
function registerExtension(ext, ignore, register, originalHandler) {
var old = require.extensions[ext] || originalHandler; // tslint:disable-line
const old = require.extensions[ext] || originalHandler; // tslint:disable-line
require.extensions[ext] = function (m, filename) {

@@ -358,3 +360,3 @@ if (shouldIgnore(filename, ignore)) {

}
var _compile = m._compile;
const _compile = m._compile;
m._compile = function (code, fileName) {

@@ -394,5 +396,5 @@ debug('module._compile', fileName);

function readConfig(cwd, ts, fileExists, readFile, options) {
var config = { compilerOptions: {} };
var basePath = normalizeSlashes(cwd);
var configFileName = undefined;
let config = { compilerOptions: {} };
let basePath = normalizeSlashes(cwd);
let configFileName = undefined;
// Read project configuration when available.

@@ -404,3 +406,3 @@ if (!options.skipProject) {

if (configFileName) {
var result = ts.readConfigFile(configFileName, readFile);
const result = ts.readConfigFile(configFileName, readFile);
// Return diagnostics.

@@ -427,5 +429,5 @@ if (result.error) {

function updateOutput(outputText, fileName, sourceMap, getExtension) {
var base64Map = Buffer.from(updateSourceMap(sourceMap, fileName), 'utf8').toString('base64');
var sourceMapContent = "data:application/json;charset=utf-8;base64," + base64Map;
var sourceMapLength = (path_1.basename(fileName) + ".map").length + (getExtension(fileName).length - path_1.extname(fileName).length);
const base64Map = Buffer.from(updateSourceMap(sourceMap, fileName), 'utf8').toString('base64');
const sourceMapContent = `data:application/json;charset=utf-8;base64,${base64Map}`;
const sourceMapLength = `${path_1.basename(fileName)}.map`.length + (getExtension(fileName).length - path_1.extname(fileName).length);
return outputText.slice(0, -sourceMapLength) + sourceMapContent;

@@ -437,3 +439,3 @@ }

function updateSourceMap(sourceMapText, fileName) {
var sourceMap = JSON.parse(sourceMapText);
const sourceMap = JSON.parse(sourceMapText);
sourceMap.file = fileName;

@@ -448,4 +450,4 @@ sourceMap.sources = [fileName];

function filterDiagnostics(diagnostics, ignore) {
return diagnostics.filter(function (x) { return ignore.indexOf(x.code) === -1; });
return diagnostics.filter(x => ignore.indexOf(x.code) === -1);
}
//# sourceMappingURL=index.js.map
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var chai_1 = require("chai");
var child_process_1 = require("child_process");
var path_1 = require("path");
var semver = require("semver");
var ts = require("typescript");
var proxyquire = require("proxyquire");
var index_1 = require("./index");
var TEST_DIR = path_1.join(__dirname, '../tests');
var EXEC_PATH = path_1.join(__dirname, '../dist/bin');
var PROJECT = path_1.join(TEST_DIR, semver.gte(ts.version, '2.5.0') ? 'tsconfig.json5' : 'tsconfig.json');
var BIN_EXEC = "node \"" + EXEC_PATH + "\" --project \"" + PROJECT + "\"";
var SOURCE_MAP_REGEXP = /\/\/# sourceMappingURL=data:application\/json;charset=utf\-8;base64,[\w\+]+=*$/;
const chai_1 = require("chai");
const child_process_1 = require("child_process");
const path_1 = require("path");
const semver = require("semver");
const ts = require("typescript");
const proxyquire = require("proxyquire");
const index_1 = require("./index");
const TEST_DIR = path_1.join(__dirname, '../tests');
const EXEC_PATH = path_1.join(__dirname, '../dist/bin');
const PROJECT = path_1.join(TEST_DIR, semver.gte(ts.version, '2.5.0') ? 'tsconfig.json5' : 'tsconfig.json');
const BIN_EXEC = `node "${EXEC_PATH}" --project "${PROJECT}"`;
const SOURCE_MAP_REGEXP = /\/\/# sourceMappingURL=data:application\/json;charset=utf\-8;base64,[\w\+]+=*$/;
describe('ts-node', function () {

@@ -23,3 +23,3 @@ this.timeout(10000);

it('should execute cli', function (done) {
child_process_1.exec(BIN_EXEC + " tests/hello-world", function (err, stdout) {
child_process_1.exec(`${BIN_EXEC} tests/hello-world`, function (err, stdout) {
chai_1.expect(err).to.equal(null);

@@ -31,3 +31,3 @@ chai_1.expect(stdout).to.equal('Hello, world!\n');

it('should register via cli', function (done) {
child_process_1.exec("node -r ../register hello-world.ts", {
child_process_1.exec(`node -r ../register hello-world.ts`, {
cwd: TEST_DIR

@@ -41,3 +41,3 @@ }, function (err, stdout) {

it('should execute cli with absolute path', function (done) {
child_process_1.exec(BIN_EXEC + " \"" + path_1.join(TEST_DIR, 'hello-world') + "\"", function (err, stdout) {
child_process_1.exec(`${BIN_EXEC} "${path_1.join(TEST_DIR, 'hello-world')}"`, function (err, stdout) {
chai_1.expect(err).to.equal(null);

@@ -49,3 +49,3 @@ chai_1.expect(stdout).to.equal('Hello, world!\n');

it('should print scripts', function (done) {
child_process_1.exec(BIN_EXEC + " -pe \"import { example } from './tests/complex/index';example()\"", function (err, stdout) {
child_process_1.exec(`${BIN_EXEC} -pe "import { example } from './tests/complex/index';example()"`, function (err, stdout) {
chai_1.expect(err).to.equal(null);

@@ -81,3 +81,3 @@ chai_1.expect(stdout).to.equal('example\n');

it('should eval code', function (done) {
child_process_1.exec(BIN_EXEC + " -e \"import * as m from './tests/module';console.log(m.example('test'))\"", function (err, stdout) {
child_process_1.exec(`${BIN_EXEC} -e "import * as m from './tests/module';console.log(m.example('test'))"`, function (err, stdout) {
chai_1.expect(err).to.equal(null);

@@ -89,3 +89,3 @@ chai_1.expect(stdout).to.equal('TEST\n');

it('should import empty files', function (done) {
child_process_1.exec(BIN_EXEC + " -e \"import './tests/empty'\"", function (err, stdout) {
child_process_1.exec(`${BIN_EXEC} -e "import './tests/empty'"`, function (err, stdout) {
chai_1.expect(err).to.equal(null);

@@ -97,3 +97,3 @@ chai_1.expect(stdout).to.equal('');

it('should throw errors', function (done) {
child_process_1.exec(BIN_EXEC + " -e \"import * as m from './tests/module';console.log(m.example(123))\"", function (err) {
child_process_1.exec(`${BIN_EXEC} -e "import * as m from './tests/module';console.log(m.example(123))"`, function (err) {
if (err === null) {

@@ -108,3 +108,3 @@ return done('Command was expected to fail, but it succeeded.');

it('should be able to ignore diagnostic', function (done) {
child_process_1.exec(BIN_EXEC + " --ignore-diagnostics 2345 -e \"import * as m from './tests/module';console.log(m.example(123))\"", function (err) {
child_process_1.exec(`${BIN_EXEC} --ignore-diagnostics 2345 -e "import * as m from './tests/module';console.log(m.example(123))"`, function (err) {
if (err === null) {

@@ -118,3 +118,3 @@ return done('Command was expected to fail, but it succeeded.');

it('should work with source maps', function (done) {
child_process_1.exec(BIN_EXEC + " tests/throw", function (err) {
child_process_1.exec(`${BIN_EXEC} tests/throw`, function (err) {
if (err === null) {

@@ -124,3 +124,3 @@ return done('Command was expected to fail, but it succeeded.');

chai_1.expect(err.message).to.contain([
path_1.join(__dirname, '../tests/throw.ts') + ":3",
`${path_1.join(__dirname, '../tests/throw.ts')}:3`,
' bar () { throw new Error(\'this is a demo\') }',

@@ -134,3 +134,3 @@ ' ^',

it.skip('eval should work with source maps', function (done) {
child_process_1.exec(BIN_EXEC + " -pe \"import './tests/throw'\"", function (err) {
child_process_1.exec(`${BIN_EXEC} -pe "import './tests/throw'"`, function (err) {
if (err === null) {

@@ -140,3 +140,3 @@ return done('Command was expected to fail, but it succeeded.');

chai_1.expect(err.message).to.contain([
path_1.join(__dirname, '../tests/throw.ts') + ":3",
`${path_1.join(__dirname, '../tests/throw.ts')}:3`,
' bar () { throw new Error(\'this is a demo\') }',

@@ -149,3 +149,3 @@ ' ^'

it('should support transpile only mode', function (done) {
child_process_1.exec(BIN_EXEC + " --transpile-only -pe \"x\"", function (err) {
child_process_1.exec(`${BIN_EXEC} --transpile-only -pe "x"`, function (err) {
if (err === null) {

@@ -159,3 +159,3 @@ return done('Command was expected to fail, but it succeeded.');

it('should pipe into `ts-node` and evaluate', function (done) {
var cp = child_process_1.exec(BIN_EXEC, function (err, stdout) {
const cp = child_process_1.exec(BIN_EXEC, function (err, stdout) {
chai_1.expect(err).to.equal(null);

@@ -168,3 +168,3 @@ chai_1.expect(stdout).to.equal('hello\n');

it('should pipe into `ts-node`', function (done) {
var cp = child_process_1.exec(BIN_EXEC + " -p", function (err, stdout) {
const cp = child_process_1.exec(`${BIN_EXEC} -p`, function (err, stdout) {
chai_1.expect(err).to.equal(null);

@@ -177,3 +177,3 @@ chai_1.expect(stdout).to.equal('true\n');

it('should pipe into an eval script', function (done) {
var cp = child_process_1.exec(BIN_EXEC + " --transpile-only -pe 'process.stdin.isTTY'", function (err, stdout) {
const cp = child_process_1.exec(`${BIN_EXEC} --transpile-only -pe 'process.stdin.isTTY'`, function (err, stdout) {
chai_1.expect(err).to.equal(null);

@@ -186,3 +186,3 @@ chai_1.expect(stdout).to.equal('undefined\n');

it('should support require flags', function (done) {
child_process_1.exec(BIN_EXEC + " -r ./tests/hello-world -pe \"console.log('success')\"", function (err, stdout) {
child_process_1.exec(`${BIN_EXEC} -r ./tests/hello-world -pe "console.log('success')"`, function (err, stdout) {
chai_1.expect(err).to.equal(null);

@@ -194,3 +194,3 @@ chai_1.expect(stdout).to.equal('Hello, world!\nsuccess\nundefined\n');

it('should support require from node modules', function (done) {
child_process_1.exec(BIN_EXEC + " -r typescript -e \"console.log('success')\"", function (err, stdout) {
child_process_1.exec(`${BIN_EXEC} -r typescript -e "console.log('success')"`, function (err, stdout) {
chai_1.expect(err).to.equal(null);

@@ -202,3 +202,3 @@ chai_1.expect(stdout).to.equal('success\n');

it.skip('should use source maps with react tsx', function (done) {
child_process_1.exec(BIN_EXEC + " -r ./tests/emit-compiled.ts tests/jsx-react.tsx", function (err, stdout) {
child_process_1.exec(`${BIN_EXEC} -r ./tests/emit-compiled.ts tests/jsx-react.tsx`, function (err, stdout) {
chai_1.expect(err).to.equal(null);

@@ -210,3 +210,3 @@ chai_1.expect(stdout).to.equal('todo');

it('should allow custom typings', function (done) {
child_process_1.exec(BIN_EXEC + " tests/custom-types", function (err, stdout) {
child_process_1.exec(`${BIN_EXEC} tests/custom-types`, function (err, stdout) {
chai_1.expect(err).to.match(/Error: Cannot find module 'does-not-exist'/);

@@ -217,3 +217,3 @@ return done();

it('should preserve `ts-node` context with child process', function (done) {
child_process_1.exec(BIN_EXEC + " tests/child-process", function (err, stdout) {
child_process_1.exec(`${BIN_EXEC} tests/child-process`, function (err, stdout) {
chai_1.expect(err).to.equal(null);

@@ -224,2 +224,23 @@ chai_1.expect(stdout).to.equal('Hello, world!\n');

});
it('should import js before ts by default', function (done) {
child_process_1.exec(`${BIN_EXEC} tests/import-order/compiled`, function (err, stdout) {
chai_1.expect(err).to.equal(null);
chai_1.expect(stdout).to.equal('Hello, JavaScript!\n');
return done();
});
});
it('should import ts before js when --prefer-ts-exts flag is present', function (done) {
child_process_1.exec(`${BIN_EXEC} --prefer-ts-exts tests/import-order/compiled`, function (err, stdout) {
chai_1.expect(err).to.equal(null);
chai_1.expect(stdout).to.equal('Hello, TypeScript!\n');
return done();
});
});
it('should ignore .d.ts files', function (done) {
child_process_1.exec(`${BIN_EXEC} tests/import-order/importer`, function (err, stdout) {
chai_1.expect(err).to.equal(null);
chai_1.expect(stdout).to.equal('Hello, World!\n');
return done();
});
});
});

@@ -234,11 +255,11 @@ describe('register', function () {

it('should be able to require typescript', function () {
var m = require('../tests/module');
const m = require('../tests/module');
chai_1.expect(m.example('foo')).to.equal('FOO');
});
it('should compile through js and ts', function () {
var m = require('../tests/complex');
const m = require('../tests/complex');
chai_1.expect(m.example()).to.equal('example');
});
it('should work with proxyquire', function () {
var m = proxyquire('../tests/complex', {
const m = proxyquire('../tests/complex', {
'./example': 'hello'

@@ -248,2 +269,6 @@ });

});
it('should work with `require.cache`', function () {
const { example1, example2 } = require('../tests/require-cache');
chai_1.expect(example1).to.not.equal(example2);
});
it('should use source maps', function (done) {

@@ -256,3 +281,3 @@ try {

'Error: this is a demo',
" at Foo.bar (" + path_1.join(__dirname, '../tests/throw.ts') + ":3:18)"
` at Foo.bar (${path_1.join(__dirname, '../tests/throw.ts')}:3:18)`
].join('\n'));

@@ -262,12 +287,11 @@ done();

});
describe('JSX preserve', function () {
var old = require.extensions['.tsx']; // tslint:disable-line
var compiled;
describe('JSX preserve', () => {
let old = require.extensions['.tsx']; // tslint:disable-line
let compiled;
before(function () {
var _this = this;
require.extensions['.tsx'] = function (m, fileName) {
var _compile = m._compile;
m._compile = function (code, fileName) {
require.extensions['.tsx'] = (m, fileName) => {
const _compile = m._compile;
m._compile = (code, fileName) => {
compiled = code;
return _compile.call(_this, code, fileName);
return _compile.call(this, code, fileName);
};

@@ -274,0 +298,0 @@ return old(m, fileName);

{
"name": "ts-node",
"version": "8.2.0",
"version": "8.3.0",
"description": "TypeScript execution environment and REPL for node.js, with source map support",

@@ -5,0 +5,0 @@ "main": "dist/index.js",

@@ -139,2 +139,3 @@ # ![TypeScript Node](logo.svg)

* `--log-error` Logs errors of types instead of exit the process (`TS_NODE_LOG_ERROR`, default: `false`)
* `--prefer-ts-exts` Re-order file extensions so that TypeScript imports are preferred (`TS_NODE_PREFER_TS_EXTS`, default: `false`)

@@ -141,0 +142,0 @@ ### Programmatic Only Options

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

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