|
| 1 | +#!/usr/bin/env node |
| 2 | +'use strict' |
| 3 | + |
| 4 | +const Module = require('node:module') |
| 5 | +const path = require('node:path') |
| 6 | +const { pathToFileURL } = require('node:url') |
| 7 | +const minimist = require('minimist') |
| 8 | + |
| 9 | +const { argv } = require('#internal/options') |
| 10 | + |
| 11 | +Object.assign(argv, minimist(process.argv.slice(2), { |
| 12 | + boolean: ['test', 'test-only'], |
| 13 | + default: Object.prototype.hasOwnProperty.call(argv, 'test') ? { test: argv.test } : undefined |
| 14 | +})) |
| 15 | + |
| 16 | +process.argv.splice(1, Infinity, ...argv._) |
| 17 | +if (argv.test) { |
| 18 | + require('#internal/main/test_runner') |
| 19 | +} else { |
| 20 | + const entryPointPath = path.resolve(argv._[0]) |
| 21 | + try { |
| 22 | + loadMainModule(entryPointPath) |
| 23 | + } catch (err) { |
| 24 | + if (err.code !== 'ERR_REQUIRE_ESM') throw err |
| 25 | + |
| 26 | + // Override process exit code logic to handle TLA: |
| 27 | + |
| 28 | + let shouldOverwriteExitCode = true |
| 29 | + const { exit: originalExitFunction } = process |
| 30 | + process.exit = function exit (code) { |
| 31 | + if (code === undefined && shouldOverwriteExitCode) { |
| 32 | + process.exitCode = 0 |
| 33 | + } |
| 34 | + Reflect.apply(originalExitFunction, process, arguments) |
| 35 | + } |
| 36 | + Object.defineProperty(process, 'exitCode', { |
| 37 | + get: () => 13, |
| 38 | + set (val) { |
| 39 | + shouldOverwriteExitCode = false |
| 40 | + delete process.exitCode |
| 41 | + process.exitCode = val |
| 42 | + }, |
| 43 | + configurable: true, |
| 44 | + enumerable: true |
| 45 | + }) |
| 46 | + |
| 47 | + // Import module |
| 48 | + |
| 49 | + import(pathToFileURL(entryPointPath)).then(() => { |
| 50 | + if (shouldOverwriteExitCode) process.exitCode = 0 |
| 51 | + }, (err) => { |
| 52 | + console.error(err) |
| 53 | + process.exit(1) |
| 54 | + }) |
| 55 | + } |
| 56 | +} |
| 57 | + |
| 58 | +/** |
| 59 | + * Loads a module as a main module, enabling the `require.main === module` pattern. |
| 60 | + * https://github.com/nodejs/corepack/blob/5ff6e82028e58448ba5ba986854b61ecdc69885b/sources/nodeUtils.ts#L24 |
| 61 | + */ |
| 62 | +function loadMainModule (id) { |
| 63 | + const modulePath = Module._resolveFilename(id, null, true) |
| 64 | + |
| 65 | + const module = new Module(modulePath, undefined) |
| 66 | + |
| 67 | + module.filename = modulePath |
| 68 | + module.paths = Module._nodeModulePaths(path.dirname(modulePath)) |
| 69 | + |
| 70 | + Module._cache[modulePath] = module |
| 71 | + |
| 72 | + process.mainModule = module |
| 73 | + module.id = '.' |
| 74 | + |
| 75 | + try { |
| 76 | + return module.load(modulePath) |
| 77 | + } catch (error) { |
| 78 | + delete Module._cache[modulePath] |
| 79 | + throw error |
| 80 | + } |
| 81 | +} |
0 commit comments