index.spec.js 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817
  1. "use strict";
  2. var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
  3. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  4. return new (P || (P = Promise))(function (resolve, reject) {
  5. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  6. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  7. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  8. step((generator = generator.apply(thisArg, _arguments || [])).next());
  9. });
  10. };
  11. Object.defineProperty(exports, "__esModule", { value: true });
  12. const chai_1 = require("chai");
  13. const child_process_1 = require("child_process");
  14. const path_1 = require("path");
  15. const semver = require("semver");
  16. const ts = require("typescript");
  17. const proxyquire = require("proxyquire");
  18. const fs_1 = require("fs");
  19. const promisify = require("util.promisify");
  20. const rimraf_1 = require("rimraf");
  21. const createRequire = require('create-require');
  22. const url_1 = require("url");
  23. const stream_1 = require("stream");
  24. const getStream = require("get-stream");
  25. const execP = promisify(child_process_1.exec);
  26. const TEST_DIR = path_1.join(__dirname, '../tests');
  27. const PROJECT = path_1.join(TEST_DIR, 'tsconfig.json');
  28. const BIN_PATH = path_1.join(TEST_DIR, 'node_modules/.bin/ts-node');
  29. const BIN_SCRIPT_PATH = path_1.join(TEST_DIR, 'node_modules/.bin/ts-node-script');
  30. const SOURCE_MAP_REGEXP = /\/\/# sourceMappingURL=data:application\/json;charset=utf\-8;base64,[\w\+]+=*$/;
  31. // `createRequire` does not exist on older node versions
  32. const testsDirRequire = createRequire(path_1.join(TEST_DIR, 'index.js')); // tslint:disable-line
  33. // Set after ts-node is installed locally
  34. let { register, create, VERSION, createRepl } = {};
  35. // Pack and install ts-node locally, necessary to test package "exports"
  36. before(function () {
  37. return __awaiter(this, void 0, void 0, function* () {
  38. this.timeout(5 * 60e3);
  39. rimraf_1.sync(path_1.join(TEST_DIR, 'node_modules'));
  40. yield execP(`npm install`, { cwd: TEST_DIR });
  41. const packageLockPath = path_1.join(TEST_DIR, 'package-lock.json');
  42. fs_1.existsSync(packageLockPath) && fs_1.unlinkSync(packageLockPath);
  43. ({ register, create, VERSION, createRepl } = testsDirRequire('ts-node'));
  44. });
  45. });
  46. describe('ts-node', function () {
  47. const cmd = `"${BIN_PATH}" --project "${PROJECT}"`;
  48. const cmdNoProject = `"${BIN_PATH}"`;
  49. this.timeout(10000);
  50. it('should export the correct version', function () {
  51. chai_1.expect(VERSION).to.equal(require('../package.json').version);
  52. });
  53. it('should export all CJS entrypoints', function () {
  54. // Ensure our package.json "exports" declaration allows `require()`ing all our entrypoints
  55. // https://github.com/TypeStrong/ts-node/pull/1026
  56. testsDirRequire.resolve('ts-node');
  57. // only reliably way to ask node for the root path of a dependency is Path.resolve(require.resolve('ts-node/package'), '..')
  58. testsDirRequire.resolve('ts-node/package');
  59. testsDirRequire.resolve('ts-node/package.json');
  60. // All bin entrypoints for people who need to augment our CLI: `node -r otherstuff ./node_modules/ts-node/dist/bin`
  61. testsDirRequire.resolve('ts-node/dist/bin');
  62. testsDirRequire.resolve('ts-node/dist/bin.js');
  63. testsDirRequire.resolve('ts-node/dist/bin-transpile');
  64. testsDirRequire.resolve('ts-node/dist/bin-transpile.js');
  65. testsDirRequire.resolve('ts-node/dist/bin-script');
  66. testsDirRequire.resolve('ts-node/dist/bin-script.js');
  67. // Must be `require()`able obviously
  68. testsDirRequire.resolve('ts-node/register');
  69. testsDirRequire.resolve('ts-node/register/files');
  70. testsDirRequire.resolve('ts-node/register/transpile-only');
  71. testsDirRequire.resolve('ts-node/register/type-check');
  72. // `node --loader ts-node/esm`
  73. testsDirRequire.resolve('ts-node/esm');
  74. testsDirRequire.resolve('ts-node/esm.mjs');
  75. testsDirRequire.resolve('ts-node/esm/transpile-only');
  76. testsDirRequire.resolve('ts-node/esm/transpile-only.mjs');
  77. });
  78. describe('cli', function () {
  79. this.slow(1000);
  80. it('should execute cli', function (done) {
  81. child_process_1.exec(`${cmd} tests/hello-world`, function (err, stdout) {
  82. chai_1.expect(err).to.equal(null);
  83. chai_1.expect(stdout).to.equal('Hello, world!\n');
  84. return done();
  85. });
  86. });
  87. it('shows usage via --help', function (done) {
  88. child_process_1.exec(`${cmdNoProject} --help`, function (err, stdout) {
  89. chai_1.expect(err).to.equal(null);
  90. chai_1.expect(stdout).to.match(/Usage: ts-node /);
  91. return done();
  92. });
  93. });
  94. it('shows version via -v', function (done) {
  95. child_process_1.exec(`${cmdNoProject} -v`, function (err, stdout) {
  96. chai_1.expect(err).to.equal(null);
  97. chai_1.expect(stdout.trim()).to.equal('v' + testsDirRequire('ts-node/package').version);
  98. return done();
  99. });
  100. });
  101. it('shows version of compiler via -vv', function (done) {
  102. child_process_1.exec(`${cmdNoProject} -vv`, function (err, stdout) {
  103. chai_1.expect(err).to.equal(null);
  104. chai_1.expect(stdout.trim()).to.equal(`ts-node v${testsDirRequire('ts-node/package').version}\n` +
  105. `node ${process.version}\n` +
  106. `compiler v${testsDirRequire('typescript/package').version}`);
  107. return done();
  108. });
  109. });
  110. it('should register via cli', function (done) {
  111. child_process_1.exec(`node -r ts-node/register hello-world.ts`, {
  112. cwd: TEST_DIR
  113. }, function (err, stdout) {
  114. chai_1.expect(err).to.equal(null);
  115. chai_1.expect(stdout).to.equal('Hello, world!\n');
  116. return done();
  117. });
  118. });
  119. it('should execute cli with absolute path', function (done) {
  120. child_process_1.exec(`${cmd} "${path_1.join(TEST_DIR, 'hello-world')}"`, function (err, stdout) {
  121. chai_1.expect(err).to.equal(null);
  122. chai_1.expect(stdout).to.equal('Hello, world!\n');
  123. return done();
  124. });
  125. });
  126. it('should print scripts', function (done) {
  127. child_process_1.exec(`${cmd} -pe "import { example } from './tests/complex/index';example()"`, function (err, stdout) {
  128. chai_1.expect(err).to.equal(null);
  129. chai_1.expect(stdout).to.equal('example\n');
  130. return done();
  131. });
  132. });
  133. it('should provide registered information globally', function (done) {
  134. child_process_1.exec(`${cmd} tests/env`, function (err, stdout) {
  135. chai_1.expect(err).to.equal(null);
  136. chai_1.expect(stdout).to.equal('object\n');
  137. return done();
  138. });
  139. });
  140. it('should provide registered information on register', function (done) {
  141. child_process_1.exec(`node -r ts-node/register env.ts`, {
  142. cwd: TEST_DIR
  143. }, function (err, stdout) {
  144. chai_1.expect(err).to.equal(null);
  145. chai_1.expect(stdout).to.equal('object\n');
  146. return done();
  147. });
  148. });
  149. if (semver.gte(ts.version, '1.8.0')) {
  150. it('should allow js', function (done) {
  151. child_process_1.exec([
  152. cmd,
  153. '-O "{\\\"allowJs\\\":true}"',
  154. '-pe "import { main } from \'./tests/allow-js/run\';main()"'
  155. ].join(' '), function (err, stdout) {
  156. chai_1.expect(err).to.equal(null);
  157. chai_1.expect(stdout).to.equal('hello world\n');
  158. return done();
  159. });
  160. });
  161. it('should include jsx when `allow-js` true', function (done) {
  162. child_process_1.exec([
  163. cmd,
  164. '-O "{\\\"allowJs\\\":true}"',
  165. '-pe "import { Foo2 } from \'./tests/allow-js/with-jsx\'; Foo2.sayHi()"'
  166. ].join(' '), function (err, stdout) {
  167. chai_1.expect(err).to.equal(null);
  168. chai_1.expect(stdout).to.equal('hello world\n');
  169. return done();
  170. });
  171. });
  172. }
  173. it('should eval code', function (done) {
  174. child_process_1.exec(`${cmd} -e "import * as m from './tests/module';console.log(m.example('test'))"`, function (err, stdout) {
  175. chai_1.expect(err).to.equal(null);
  176. chai_1.expect(stdout).to.equal('TEST\n');
  177. return done();
  178. });
  179. });
  180. it('should import empty files', function (done) {
  181. child_process_1.exec(`${cmd} -e "import './tests/empty'"`, function (err, stdout) {
  182. chai_1.expect(err).to.equal(null);
  183. chai_1.expect(stdout).to.equal('');
  184. return done();
  185. });
  186. });
  187. it('should throw errors', function (done) {
  188. child_process_1.exec(`${cmd} -e "import * as m from './tests/module';console.log(m.example(123))"`, function (err) {
  189. if (err === null) {
  190. return done('Command was expected to fail, but it succeeded.');
  191. }
  192. chai_1.expect(err.message).to.match(new RegExp('TS2345: Argument of type \'(?:number|123)\' ' +
  193. 'is not assignable to parameter of type \'string\'\\.'));
  194. return done();
  195. });
  196. });
  197. it('should be able to ignore diagnostic', function (done) {
  198. child_process_1.exec(`${cmd} --ignore-diagnostics 2345 -e "import * as m from './tests/module';console.log(m.example(123))"`, function (err) {
  199. if (err === null) {
  200. return done('Command was expected to fail, but it succeeded.');
  201. }
  202. chai_1.expect(err.message).to.match(/TypeError: (?:(?:undefined|foo\.toUpperCase) is not a function|.*has no method \'toUpperCase\')/);
  203. return done();
  204. });
  205. });
  206. it('should work with source maps', function (done) {
  207. child_process_1.exec(`${cmd} tests/throw`, function (err) {
  208. if (err === null) {
  209. return done('Command was expected to fail, but it succeeded.');
  210. }
  211. chai_1.expect(err.message).to.contain([
  212. `${path_1.join(__dirname, '../tests/throw.ts')}:100`,
  213. ' bar () { throw new Error(\'this is a demo\') }',
  214. ' ^',
  215. 'Error: this is a demo'
  216. ].join('\n'));
  217. return done();
  218. });
  219. });
  220. it('eval should work with source maps', function (done) {
  221. child_process_1.exec(`${cmd} -pe "import './tests/throw'"`, function (err) {
  222. if (err === null) {
  223. return done('Command was expected to fail, but it succeeded.');
  224. }
  225. chai_1.expect(err.message).to.contain([
  226. `${path_1.join(__dirname, '../tests/throw.ts')}:100`,
  227. ' bar () { throw new Error(\'this is a demo\') }',
  228. ' ^'
  229. ].join('\n'));
  230. return done();
  231. });
  232. });
  233. it('should support transpile only mode', function (done) {
  234. child_process_1.exec(`${cmd} --transpile-only -pe "x"`, function (err) {
  235. if (err === null) {
  236. return done('Command was expected to fail, but it succeeded.');
  237. }
  238. chai_1.expect(err.message).to.contain('ReferenceError: x is not defined');
  239. return done();
  240. });
  241. });
  242. it('should throw error even in transpileOnly mode', function (done) {
  243. child_process_1.exec(`${cmd} --transpile-only -pe "console."`, function (err) {
  244. if (err === null) {
  245. return done('Command was expected to fail, but it succeeded.');
  246. }
  247. chai_1.expect(err.message).to.contain('error TS1003: Identifier expected');
  248. return done();
  249. });
  250. });
  251. it('should pipe into `ts-node` and evaluate', function (done) {
  252. const cp = child_process_1.exec(cmd, function (err, stdout) {
  253. chai_1.expect(err).to.equal(null);
  254. chai_1.expect(stdout).to.equal('hello\n');
  255. return done();
  256. });
  257. cp.stdin.end("console.log('hello')");
  258. });
  259. it('should pipe into `ts-node`', function (done) {
  260. const cp = child_process_1.exec(`${cmd} -p`, function (err, stdout) {
  261. chai_1.expect(err).to.equal(null);
  262. chai_1.expect(stdout).to.equal('true\n');
  263. return done();
  264. });
  265. cp.stdin.end('true');
  266. });
  267. it('should pipe into an eval script', function (done) {
  268. const cp = child_process_1.exec(`${cmd} --transpile-only -pe "process.stdin.isTTY"`, function (err, stdout) {
  269. chai_1.expect(err).to.equal(null);
  270. chai_1.expect(stdout).to.equal('undefined\n');
  271. return done();
  272. });
  273. cp.stdin.end('true');
  274. });
  275. it('should run REPL when --interactive passed and stdin is not a TTY', function (done) {
  276. const cp = child_process_1.exec(`${cmd} --interactive`, function (err, stdout) {
  277. chai_1.expect(err).to.equal(null);
  278. chai_1.expect(stdout).to.equal('> 123\n' +
  279. 'undefined\n' +
  280. '> ');
  281. return done();
  282. });
  283. cp.stdin.end('console.log("123")\n');
  284. });
  285. it('REPL has command to get type information', function (done) {
  286. const cp = child_process_1.exec(`${cmd} --interactive`, function (err, stdout) {
  287. chai_1.expect(err).to.equal(null);
  288. chai_1.expect(stdout).to.equal('> undefined\n' +
  289. '> undefined\n' +
  290. '> const a: 123\n' +
  291. '> ');
  292. return done();
  293. });
  294. cp.stdin.end('\nconst a = 123\n.type a');
  295. });
  296. it('REPL can be created via API', () => __awaiter(this, void 0, void 0, function* () {
  297. const stdin = new stream_1.PassThrough();
  298. const stdout = new stream_1.PassThrough();
  299. const stderr = new stream_1.PassThrough();
  300. const replService = createRepl({
  301. stdin,
  302. stdout,
  303. stderr
  304. });
  305. const service = create(replService.evalAwarePartialHost);
  306. replService.setService(service);
  307. replService.start();
  308. stdin.write('\nconst a = 123\n.type a\n');
  309. stdin.end();
  310. yield promisify(setTimeout)(1e3);
  311. stdout.end();
  312. stderr.end();
  313. chai_1.expect(yield getStream(stderr)).to.equal('');
  314. chai_1.expect(yield getStream(stdout)).to.equal('> \'use strict\'\n' +
  315. '> undefined\n' +
  316. '> const a: 123\n' +
  317. '> ');
  318. }));
  319. it('should support require flags', function (done) {
  320. child_process_1.exec(`${cmd} -r ./tests/hello-world -pe "console.log('success')"`, function (err, stdout) {
  321. chai_1.expect(err).to.equal(null);
  322. chai_1.expect(stdout).to.equal('Hello, world!\nsuccess\nundefined\n');
  323. return done();
  324. });
  325. });
  326. it('should support require from node modules', function (done) {
  327. child_process_1.exec(`${cmd} -r typescript -e "console.log('success')"`, function (err, stdout) {
  328. chai_1.expect(err).to.equal(null);
  329. chai_1.expect(stdout).to.equal('success\n');
  330. return done();
  331. });
  332. });
  333. it('should use source maps with react tsx', function (done) {
  334. child_process_1.exec(`${cmd} tests/throw-react-tsx.tsx`, function (err, stdout) {
  335. chai_1.expect(err).not.to.equal(null);
  336. chai_1.expect(err.message).to.contain([
  337. `${path_1.join(__dirname, '../tests/throw-react-tsx.tsx')}:100`,
  338. ' bar () { throw new Error(\'this is a demo\') }',
  339. ' ^',
  340. 'Error: this is a demo'
  341. ].join('\n'));
  342. return done();
  343. });
  344. });
  345. it('should allow custom typings', function (done) {
  346. child_process_1.exec(`${cmd} tests/custom-types`, function (err, stdout) {
  347. chai_1.expect(err).to.match(/Error: Cannot find module 'does-not-exist'/);
  348. return done();
  349. });
  350. });
  351. it('should preserve `ts-node` context with child process', function (done) {
  352. child_process_1.exec(`${cmd} tests/child-process`, function (err, stdout) {
  353. chai_1.expect(err).to.equal(null);
  354. chai_1.expect(stdout).to.equal('Hello, world!\n');
  355. return done();
  356. });
  357. });
  358. it('should import js before ts by default', function (done) {
  359. child_process_1.exec(`${cmd} tests/import-order/compiled`, function (err, stdout) {
  360. chai_1.expect(err).to.equal(null);
  361. chai_1.expect(stdout).to.equal('Hello, JavaScript!\n');
  362. return done();
  363. });
  364. });
  365. it('should import ts before js when --prefer-ts-exts flag is present', function (done) {
  366. child_process_1.exec(`${cmd} --prefer-ts-exts tests/import-order/compiled`, function (err, stdout) {
  367. chai_1.expect(err).to.equal(null);
  368. chai_1.expect(stdout).to.equal('Hello, TypeScript!\n');
  369. return done();
  370. });
  371. });
  372. it('should import ts before js when TS_NODE_PREFER_TS_EXTS env is present', function (done) {
  373. child_process_1.exec(`${cmd} tests/import-order/compiled`, { env: Object.assign(Object.assign({}, process.env), { TS_NODE_PREFER_TS_EXTS: 'true' }) }, function (err, stdout) {
  374. chai_1.expect(err).to.equal(null);
  375. chai_1.expect(stdout).to.equal('Hello, TypeScript!\n');
  376. return done();
  377. });
  378. });
  379. it('should ignore .d.ts files', function (done) {
  380. child_process_1.exec(`${cmd} tests/import-order/importer`, function (err, stdout) {
  381. chai_1.expect(err).to.equal(null);
  382. chai_1.expect(stdout).to.equal('Hello, World!\n');
  383. return done();
  384. });
  385. });
  386. describe('issue #884', function () {
  387. it('should compile', function (done) {
  388. // TODO disabled because it consistently fails on Windows on TS 2.7
  389. if (process.platform === 'win32' && semver.satisfies(ts.version, '2.7')) {
  390. this.skip();
  391. }
  392. else {
  393. child_process_1.exec(`"${BIN_PATH}" --project tests/issue-884/tsconfig.json tests/issue-884`, function (err, stdout) {
  394. chai_1.expect(err).to.equal(null);
  395. chai_1.expect(stdout).to.equal('');
  396. return done();
  397. });
  398. }
  399. });
  400. });
  401. describe('issue #986', function () {
  402. it('should not compile', function (done) {
  403. child_process_1.exec(`"${BIN_PATH}" --project tests/issue-986/tsconfig.json tests/issue-986`, function (err, stdout, stderr) {
  404. chai_1.expect(err).not.to.equal(null);
  405. chai_1.expect(stderr).to.contain('Cannot find name \'TEST\''); // TypeScript error.
  406. chai_1.expect(stdout).to.equal('');
  407. return done();
  408. });
  409. });
  410. it('should compile with `--files`', function (done) {
  411. child_process_1.exec(`"${BIN_PATH}" --files --project tests/issue-986/tsconfig.json tests/issue-986`, function (err, stdout, stderr) {
  412. chai_1.expect(err).not.to.equal(null);
  413. chai_1.expect(stderr).to.contain('ReferenceError: TEST is not defined'); // Runtime error.
  414. chai_1.expect(stdout).to.equal('');
  415. return done();
  416. });
  417. });
  418. });
  419. if (semver.gte(ts.version, '2.7.0')) {
  420. it('should support script mode', function (done) {
  421. child_process_1.exec(`${BIN_SCRIPT_PATH} tests/scope/a/log`, function (err, stdout) {
  422. chai_1.expect(err).to.equal(null);
  423. chai_1.expect(stdout).to.equal('.ts\n');
  424. return done();
  425. });
  426. });
  427. it('should read tsconfig relative to realpath, not symlink, in scriptMode', function (done) {
  428. if (fs_1.lstatSync(path_1.join(TEST_DIR, 'main-realpath/symlink/symlink.tsx')).isSymbolicLink()) {
  429. child_process_1.exec(`${BIN_SCRIPT_PATH} tests/main-realpath/symlink/symlink.tsx`, function (err, stdout) {
  430. chai_1.expect(err).to.equal(null);
  431. chai_1.expect(stdout).to.equal('');
  432. return done();
  433. });
  434. }
  435. else {
  436. this.skip();
  437. }
  438. });
  439. }
  440. describe('should read ts-node options from tsconfig.json', function () {
  441. const BIN_EXEC = `"${BIN_PATH}" --project tests/tsconfig-options/tsconfig.json`;
  442. it('should override compiler options from env', function (done) {
  443. child_process_1.exec(`${BIN_EXEC} tests/tsconfig-options/log-options1.js`, {
  444. env: Object.assign(Object.assign({}, process.env), { TS_NODE_COMPILER_OPTIONS: '{"typeRoots": ["env-typeroots"]}' })
  445. }, function (err, stdout) {
  446. chai_1.expect(err).to.equal(null);
  447. const { config } = JSON.parse(stdout);
  448. chai_1.expect(config.options.typeRoots).to.deep.equal([path_1.join(__dirname, '../tests/tsconfig-options/env-typeroots').replace(/\\/g, '/')]);
  449. return done();
  450. });
  451. });
  452. it('should use options from `tsconfig.json`', function (done) {
  453. child_process_1.exec(`${BIN_EXEC} tests/tsconfig-options/log-options1.js`, function (err, stdout) {
  454. chai_1.expect(err).to.equal(null);
  455. const { options, config } = JSON.parse(stdout);
  456. chai_1.expect(config.options.typeRoots).to.deep.equal([path_1.join(__dirname, '../tests/tsconfig-options/tsconfig-typeroots').replace(/\\/g, '/')]);
  457. chai_1.expect(config.options.types).to.deep.equal(['tsconfig-tsnode-types']);
  458. chai_1.expect(options.pretty).to.equal(undefined);
  459. chai_1.expect(options.skipIgnore).to.equal(false);
  460. chai_1.expect(options.transpileOnly).to.equal(true);
  461. chai_1.expect(options.require).to.deep.equal([path_1.join(__dirname, '../tests/tsconfig-options/required1.js')]);
  462. return done();
  463. });
  464. });
  465. it('should have flags override / merge with `tsconfig.json`', function (done) {
  466. child_process_1.exec(`${BIN_EXEC} --skip-ignore --compiler-options "{\\"types\\":[\\"flags-types\\"]}" --require ./tests/tsconfig-options/required2.js tests/tsconfig-options/log-options2.js`, function (err, stdout) {
  467. chai_1.expect(err).to.equal(null);
  468. const { options, config } = JSON.parse(stdout);
  469. chai_1.expect(config.options.typeRoots).to.deep.equal([path_1.join(__dirname, '../tests/tsconfig-options/tsconfig-typeroots').replace(/\\/g, '/')]);
  470. chai_1.expect(config.options.types).to.deep.equal(['flags-types']);
  471. chai_1.expect(options.pretty).to.equal(undefined);
  472. chai_1.expect(options.skipIgnore).to.equal(true);
  473. chai_1.expect(options.transpileOnly).to.equal(true);
  474. chai_1.expect(options.require).to.deep.equal([
  475. path_1.join(__dirname, '../tests/tsconfig-options/required1.js'),
  476. './tests/tsconfig-options/required2.js'
  477. ]);
  478. return done();
  479. });
  480. });
  481. it('should have `tsconfig.json` override environment', function (done) {
  482. child_process_1.exec(`${BIN_EXEC} tests/tsconfig-options/log-options1.js`, {
  483. env: Object.assign(Object.assign({}, process.env), { TS_NODE_PRETTY: 'true', TS_NODE_SKIP_IGNORE: 'true' })
  484. }, function (err, stdout) {
  485. chai_1.expect(err).to.equal(null);
  486. const { options, config } = JSON.parse(stdout);
  487. chai_1.expect(config.options.typeRoots).to.deep.equal([path_1.join(__dirname, '../tests/tsconfig-options/tsconfig-typeroots').replace(/\\/g, '/')]);
  488. chai_1.expect(config.options.types).to.deep.equal(['tsconfig-tsnode-types']);
  489. chai_1.expect(options.pretty).to.equal(true);
  490. chai_1.expect(options.skipIgnore).to.equal(false);
  491. chai_1.expect(options.transpileOnly).to.equal(true);
  492. chai_1.expect(options.require).to.deep.equal([path_1.join(__dirname, '../tests/tsconfig-options/required1.js')]);
  493. return done();
  494. });
  495. });
  496. });
  497. describe('compiler host', function () {
  498. it('should execute cli', function (done) {
  499. child_process_1.exec(`${cmd} --compiler-host tests/hello-world`, function (err, stdout) {
  500. chai_1.expect(err).to.equal(null);
  501. chai_1.expect(stdout).to.equal('Hello, world!\n');
  502. return done();
  503. });
  504. });
  505. });
  506. it('should transpile files inside a node_modules directory when not ignored', function (done) {
  507. child_process_1.exec(`${cmdNoProject} --script-mode tests/from-node-modules/from-node-modules`, function (err, stdout, stderr) {
  508. if (err)
  509. return done(`Unexpected error: ${err}\nstdout:\n${stdout}\nstderr:\n${stderr}`);
  510. chai_1.expect(JSON.parse(stdout)).to.deep.equal({
  511. external: {
  512. tsmri: { name: 'typescript-module-required-internally' },
  513. jsmri: { name: 'javascript-module-required-internally' },
  514. tsmii: { name: 'typescript-module-imported-internally' },
  515. jsmii: { name: 'javascript-module-imported-internally' }
  516. },
  517. tsmie: { name: 'typescript-module-imported-externally' },
  518. jsmie: { name: 'javascript-module-imported-externally' },
  519. tsmre: { name: 'typescript-module-required-externally' },
  520. jsmre: { name: 'javascript-module-required-externally' }
  521. });
  522. done();
  523. });
  524. });
  525. describe('should respect maxNodeModulesJsDepth', function () {
  526. it('for unscoped modules', function (done) {
  527. child_process_1.exec(`${cmdNoProject} --script-mode tests/maxnodemodulesjsdepth`, function (err, stdout, stderr) {
  528. chai_1.expect(err).to.not.equal(null);
  529. chai_1.expect(stderr.replace(/\r\n/g, '\n')).to.contain('TSError: ⨯ Unable to compile TypeScript:\n' +
  530. "other.ts(4,7): error TS2322: Type 'string' is not assignable to type 'boolean'.\n" +
  531. '\n');
  532. done();
  533. });
  534. });
  535. it('for @scoped modules', function (done) {
  536. child_process_1.exec(`${cmdNoProject} --script-mode tests/maxnodemodulesjsdepth-scoped`, function (err, stdout, stderr) {
  537. chai_1.expect(err).to.not.equal(null);
  538. chai_1.expect(stderr.replace(/\r\n/g, '\n')).to.contain('TSError: ⨯ Unable to compile TypeScript:\n' +
  539. "other.ts(7,7): error TS2322: Type 'string' is not assignable to type 'boolean'.\n" +
  540. '\n');
  541. done();
  542. });
  543. });
  544. });
  545. });
  546. describe('register', function () {
  547. let registered;
  548. let moduleTestPath;
  549. before(() => {
  550. registered = register({
  551. project: PROJECT,
  552. compilerOptions: {
  553. jsx: 'preserve'
  554. }
  555. });
  556. moduleTestPath = require.resolve('../tests/module');
  557. });
  558. afterEach(() => {
  559. // Re-enable project after every test.
  560. registered.enabled(true);
  561. });
  562. it('should be able to require typescript', function () {
  563. const m = require(moduleTestPath);
  564. chai_1.expect(m.example('foo')).to.equal('FOO');
  565. });
  566. it('should support dynamically disabling', function () {
  567. delete require.cache[moduleTestPath];
  568. chai_1.expect(registered.enabled(false)).to.equal(false);
  569. chai_1.expect(() => require(moduleTestPath)).to.throw(/Unexpected token/);
  570. delete require.cache[moduleTestPath];
  571. chai_1.expect(registered.enabled()).to.equal(false);
  572. chai_1.expect(() => require(moduleTestPath)).to.throw(/Unexpected token/);
  573. delete require.cache[moduleTestPath];
  574. chai_1.expect(registered.enabled(true)).to.equal(true);
  575. chai_1.expect(() => require(moduleTestPath)).to.not.throw();
  576. delete require.cache[moduleTestPath];
  577. chai_1.expect(registered.enabled()).to.equal(true);
  578. chai_1.expect(() => require(moduleTestPath)).to.not.throw();
  579. });
  580. if (semver.gte(ts.version, '2.7.0')) {
  581. it('should support compiler scopes', function () {
  582. const calls = [];
  583. registered.enabled(false);
  584. const compilers = [
  585. register({ dir: path_1.join(TEST_DIR, 'scope/a'), scope: true }),
  586. register({ dir: path_1.join(TEST_DIR, 'scope/b'), scope: true })
  587. ];
  588. compilers.forEach(c => {
  589. const old = c.compile;
  590. c.compile = (code, fileName, lineOffset) => {
  591. calls.push(fileName);
  592. return old(code, fileName, lineOffset);
  593. };
  594. });
  595. try {
  596. chai_1.expect(require('../tests/scope/a').ext).to.equal('.ts');
  597. chai_1.expect(require('../tests/scope/b').ext).to.equal('.ts');
  598. }
  599. finally {
  600. compilers.forEach(c => c.enabled(false));
  601. }
  602. chai_1.expect(calls).to.deep.equal([
  603. path_1.join(TEST_DIR, 'scope/a/index.ts'),
  604. path_1.join(TEST_DIR, 'scope/b/index.ts')
  605. ]);
  606. delete require.cache[moduleTestPath];
  607. chai_1.expect(() => require(moduleTestPath)).to.throw();
  608. });
  609. }
  610. it('should compile through js and ts', function () {
  611. const m = require('../tests/complex');
  612. chai_1.expect(m.example()).to.equal('example');
  613. });
  614. it('should work with proxyquire', function () {
  615. const m = proxyquire('../tests/complex', {
  616. './example': 'hello'
  617. });
  618. chai_1.expect(m.example()).to.equal('hello');
  619. });
  620. it('should work with `require.cache`', function () {
  621. const { example1, example2 } = require('../tests/require-cache');
  622. chai_1.expect(example1).to.not.equal(example2);
  623. });
  624. it('should use source maps', function (done) {
  625. try {
  626. require('../tests/throw');
  627. }
  628. catch (error) {
  629. chai_1.expect(error.stack).to.contain([
  630. 'Error: this is a demo',
  631. ` at Foo.bar (${path_1.join(__dirname, '../tests/throw.ts')}:100:18)`
  632. ].join('\n'));
  633. done();
  634. }
  635. });
  636. describe('JSX preserve', () => {
  637. let old;
  638. let compiled;
  639. before(function () {
  640. old = require.extensions['.tsx']; // tslint:disable-line
  641. require.extensions['.tsx'] = (m, fileName) => {
  642. const _compile = m._compile;
  643. m._compile = (code, fileName) => {
  644. compiled = code;
  645. return _compile.call(this, code, fileName);
  646. };
  647. return old(m, fileName);
  648. };
  649. });
  650. after(function () {
  651. require.extensions['.tsx'] = old; // tslint:disable-line
  652. });
  653. it('should use source maps', function (done) {
  654. try {
  655. require('../tests/with-jsx.tsx');
  656. }
  657. catch (error) {
  658. chai_1.expect(error.stack).to.contain('SyntaxError: Unexpected token');
  659. }
  660. chai_1.expect(compiled).to.match(SOURCE_MAP_REGEXP);
  661. done();
  662. });
  663. });
  664. });
  665. describe('create', () => {
  666. let service;
  667. before(() => {
  668. service = create({ compilerOptions: { target: 'es5' }, skipProject: true });
  669. });
  670. it('should create generic compiler instances', () => {
  671. const output = service.compile('const x = 10', 'test.ts');
  672. chai_1.expect(output).to.contain('var x = 10;');
  673. });
  674. describe('should get type information', () => {
  675. it('given position of identifier', () => {
  676. chai_1.expect(service.getTypeInfo('/**jsdoc here*/const x = 10', 'test.ts', 21)).to.deep.equal({
  677. comment: 'jsdoc here',
  678. name: 'const x: 10'
  679. });
  680. });
  681. it('given position that does not point to an identifier', () => {
  682. chai_1.expect(service.getTypeInfo('/**jsdoc here*/const x = 10', 'test.ts', 0)).to.deep.equal({
  683. comment: '',
  684. name: ''
  685. });
  686. });
  687. });
  688. });
  689. describe('issue #1098', () => {
  690. function testIgnored(ignored, allowed, disallowed) {
  691. for (const ext of allowed) {
  692. chai_1.expect(ignored(path_1.join(__dirname, `index${ext}`))).equal(false, `should accept ${ext} files`);
  693. }
  694. for (const ext of disallowed) {
  695. chai_1.expect(ignored(path_1.join(__dirname, `index${ext}`))).equal(true, `should ignore ${ext} files`);
  696. }
  697. }
  698. it('correctly filters file extensions from the compiler when allowJs=false and jsx=false', () => {
  699. const { ignored } = create({ compilerOptions: {}, skipProject: true });
  700. testIgnored(ignored, ['.ts', '.d.ts'], ['.js', '.tsx', '.jsx', '.mjs', '.cjs', '.xyz', '']);
  701. });
  702. it('correctly filters file extensions from the compiler when allowJs=true and jsx=false', () => {
  703. const { ignored } = create({ compilerOptions: { allowJs: true }, skipProject: true });
  704. testIgnored(ignored, ['.ts', '.js', '.d.ts'], ['.tsx', '.jsx', '.mjs', '.cjs', '.xyz', '']);
  705. });
  706. it('correctly filters file extensions from the compiler when allowJs=false and jsx=true', () => {
  707. const { ignored } = create({ compilerOptions: { allowJs: false, jsx: 'preserve' }, skipProject: true });
  708. testIgnored(ignored, ['.ts', '.tsx', '.d.ts'], ['.js', '.jsx', '.mjs', '.cjs', '.xyz', '']);
  709. });
  710. it('correctly filters file extensions from the compiler when allowJs=true and jsx=true', () => {
  711. const { ignored } = create({ compilerOptions: { allowJs: true, jsx: 'preserve' }, skipProject: true });
  712. testIgnored(ignored, ['.ts', '.tsx', '.js', '.jsx', '.d.ts'], ['.mjs', '.cjs', '.xyz', '']);
  713. });
  714. });
  715. describe('esm', () => {
  716. this.slow(1000);
  717. const cmd = `node --loader ts-node/esm`;
  718. if (semver.gte(process.version, '13.0.0')) {
  719. it('should compile and execute as ESM', (done) => {
  720. child_process_1.exec(`${cmd} index.ts`, { cwd: path_1.join(__dirname, '../tests/esm') }, function (err, stdout) {
  721. chai_1.expect(err).to.equal(null);
  722. chai_1.expect(stdout).to.equal('foo bar baz biff libfoo\n');
  723. return done();
  724. });
  725. });
  726. it('should use source maps', function (done) {
  727. child_process_1.exec(`${cmd} throw.ts`, { cwd: path_1.join(__dirname, '../tests/esm') }, function (err, stdout) {
  728. chai_1.expect(err).not.to.equal(null);
  729. chai_1.expect(err.message).to.contain([
  730. `${url_1.pathToFileURL(path_1.join(__dirname, '../tests/esm/throw.ts'))}:100`,
  731. ' bar () { throw new Error(\'this is a demo\') }',
  732. ' ^',
  733. 'Error: this is a demo'
  734. ].join('\n'));
  735. return done();
  736. });
  737. });
  738. describe('supports experimental-specifier-resolution=node', () => {
  739. it('via --experimental-specifier-resolution', (done) => {
  740. child_process_1.exec(`${cmd} --experimental-specifier-resolution=node index.ts`, { cwd: path_1.join(__dirname, '../tests/esm-node-resolver') }, function (err, stdout) {
  741. chai_1.expect(err).to.equal(null);
  742. chai_1.expect(stdout).to.equal('foo bar baz biff libfoo\n');
  743. return done();
  744. });
  745. });
  746. it('via --es-module-specifier-resolution alias', (done) => {
  747. child_process_1.exec(`${cmd} --experimental-modules --es-module-specifier-resolution=node index.ts`, { cwd: path_1.join(__dirname, '../tests/esm-node-resolver') }, function (err, stdout) {
  748. chai_1.expect(err).to.equal(null);
  749. chai_1.expect(stdout).to.equal('foo bar baz biff libfoo\n');
  750. return done();
  751. });
  752. });
  753. it('via NODE_OPTIONS', (done) => {
  754. child_process_1.exec(`${cmd} index.ts`, {
  755. cwd: path_1.join(__dirname, '../tests/esm-node-resolver'),
  756. env: Object.assign(Object.assign({}, process.env), { NODE_OPTIONS: '--experimental-specifier-resolution=node' })
  757. }, function (err, stdout) {
  758. chai_1.expect(err).to.equal(null);
  759. chai_1.expect(stdout).to.equal('foo bar baz biff libfoo\n');
  760. return done();
  761. });
  762. });
  763. });
  764. it('throws ERR_REQUIRE_ESM when attempting to require() an ESM script while ESM loader is enabled', function (done) {
  765. child_process_1.exec(`${cmd} ./index.js`, { cwd: path_1.join(__dirname, '../tests/esm-err-require-esm') }, function (err, stdout, stderr) {
  766. chai_1.expect(err).to.not.equal(null);
  767. chai_1.expect(stderr).to.contain('Error [ERR_REQUIRE_ESM]: Must use import to load ES Module:');
  768. return done();
  769. });
  770. });
  771. it('defers to fallback loaders when URL should not be handled by ts-node', function (done) {
  772. child_process_1.exec(`${cmd} index.mjs`, {
  773. cwd: path_1.join(__dirname, '../tests/esm-import-http-url')
  774. }, function (err, stdout, stderr) {
  775. chai_1.expect(err).to.not.equal(null);
  776. // expect error from node's default resolver
  777. chai_1.expect(stderr).to.match(/Error \[ERR_UNSUPPORTED_ESM_URL_SCHEME\]:.*(?:\n.*){0,1}\n *at defaultResolve/);
  778. return done();
  779. });
  780. });
  781. it('should bypass import cache when changing search params', (done) => {
  782. child_process_1.exec(`${cmd} index.ts`, { cwd: path_1.join(__dirname, '../tests/esm-import-cache') }, function (err, stdout) {
  783. chai_1.expect(err).to.equal(null);
  784. chai_1.expect(stdout).to.equal('log1\nlog2\nlog2\n');
  785. return done();
  786. });
  787. });
  788. it('should support transpile only mode via dedicated loader entrypoint', (done) => {
  789. child_process_1.exec(`${cmd}/transpile-only index.ts`, { cwd: path_1.join(__dirname, '../tests/esm-transpile-only') }, function (err, stdout) {
  790. chai_1.expect(err).to.equal(null);
  791. chai_1.expect(stdout).to.equal('');
  792. return done();
  793. });
  794. });
  795. it('should throw type errors without transpile-only enabled', (done) => {
  796. child_process_1.exec(`${cmd} index.ts`, { cwd: path_1.join(__dirname, '../tests/esm-transpile-only') }, function (err, stdout) {
  797. if (err === null) {
  798. return done('Command was expected to fail, but it succeeded.');
  799. }
  800. chai_1.expect(err.message).to.contain('Unable to compile TypeScript');
  801. chai_1.expect(err.message).to.match(new RegExp('TS2345: Argument of type \'(?:number|1101)\' is not assignable to parameter of type \'string\'\\.'));
  802. chai_1.expect(err.message).to.match(new RegExp('TS2322: Type \'(?:"hello world"|string)\' is not assignable to type \'number\'\\.'));
  803. chai_1.expect(stdout).to.equal('');
  804. return done();
  805. });
  806. });
  807. }
  808. it('executes ESM as CJS, ignoring package.json "types" field (for backwards compatibility; should be changed in next major release to throw ERR_REQUIRE_ESM)', function (done) {
  809. child_process_1.exec(`${BIN_PATH} ./tests/esm-err-require-esm/index.js`, function (err, stdout) {
  810. chai_1.expect(err).to.equal(null);
  811. chai_1.expect(stdout).to.equal('CommonJS\n');
  812. return done();
  813. });
  814. });
  815. });
  816. });
  817. //# sourceMappingURL=index.spec.js.map