Next release of setup-bun
This commit is contained in:
+21
@@ -0,0 +1,21 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2014 Blake Embrey ([email protected])
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
+1442
File diff suppressed because it is too large
Load Diff
+8
@@ -0,0 +1,8 @@
|
||||
import { fileURLToPath } from 'url';
|
||||
import { createRequire } from 'module';
|
||||
const require = createRequire(fileURLToPath(import.meta.url));
|
||||
|
||||
// TODO why use require() here? I think we can just `import`
|
||||
/** @type {import('./dist/child-loader')} */
|
||||
const childLoader = require('./dist/child/child-loader');
|
||||
export const { resolve, load, getFormat, transformSource } = childLoader;
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
This directory contains portions of Node.js source code which is licensed as follows:
|
||||
|
||||
---
|
||||
|
||||
Copyright Joyent, Inc. and other Node contributors.
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a
|
||||
copy of this software and associated documentation files (the
|
||||
"Software"), to deal in the Software without restriction, including
|
||||
without limitation the rights to use, copy, modify, merge, publish,
|
||||
distribute, sublicense, and/or sell copies of the Software, and to permit
|
||||
persons to whom the Software is furnished to do so, subject to the
|
||||
following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included
|
||||
in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
|
||||
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
|
||||
NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
|
||||
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
|
||||
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
|
||||
USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
The `dist-raw` directory contains JS sources that are distributed verbatim, not compiled nor typechecked via TS.
|
||||
|
||||
To implement ESM support, we unfortunately must duplicate some of node's built-in functionality that is not
|
||||
exposed via an API. We have copy-pasted the necessary code from https://github.com/nodejs/node/tree/master/lib
|
||||
then modified it to suite our needs.
|
||||
|
||||
Formatting may be intentionally bad to keep the diff as small as possible, to make it easier to merge
|
||||
upstream changes and understand our modifications. For example, when we need to wrap node's source code
|
||||
in a factory function, we will not indent the function body, to avoid whitespace changes in the diff.
|
||||
|
||||
One obvious problem with this approach: the code has been pulled from one version of node, whereas users of ts-node
|
||||
run multiple versions of node.
|
||||
Users running node 12 may see that ts-node behaves like node 14, for example.
|
||||
|
||||
## `raw` directory
|
||||
|
||||
Within the `raw` directory, we keep unmodified copies of the node source files. This allows us to use diffing tools to
|
||||
compare files in `raw` to those in `dist-raw`, which will highlight all of the changes we have made. Hopefully, these
|
||||
changes are as minimal as possible.
|
||||
|
||||
## Naming convention
|
||||
|
||||
Not used consistently, but the idea is:
|
||||
|
||||
`node-<directory>(...-<directory>)-<filename>.js`
|
||||
|
||||
`node-internal-errors.js` -> `github.com/nodejs/node/blob/TAG/lib/internal/errors.js`
|
||||
|
||||
So, take the path within node's `lib/` directory, and replace slashes with hyphens.
|
||||
|
||||
In the `raw` directory, files are suffixed with the version number or revision from which
|
||||
they were downloaded.
|
||||
|
||||
If they have a `stripped` suffix, this means they have large chunks of code deleted, but no other modifications.
|
||||
This is useful when diffing. Sometimes our `dist-raw` files only have a small part of a much larger node source file.
|
||||
It is easier to diff `raw/*-stripped.js` against `dist-raw/*.js`.
|
||||
+4
@@ -0,0 +1,4 @@
|
||||
// Copied from https://github.com/nodejs/node/blob/master/lib/internal/constants.js
|
||||
module.exports = {
|
||||
CHAR_FORWARD_SLASH: 47, /* / */
|
||||
};
|
||||
+82
@@ -0,0 +1,82 @@
|
||||
'use strict';
|
||||
|
||||
const path = require('path');
|
||||
|
||||
exports.codes = {
|
||||
ERR_INPUT_TYPE_NOT_ALLOWED: createErrorCtor(joinArgs('ERR_INPUT_TYPE_NOT_ALLOWED')),
|
||||
ERR_INVALID_ARG_VALUE: createErrorCtor(joinArgs('ERR_INVALID_ARG_VALUE')),
|
||||
ERR_INVALID_MODULE_SPECIFIER: createErrorCtor(joinArgs('ERR_INVALID_MODULE_SPECIFIER')),
|
||||
ERR_INVALID_PACKAGE_CONFIG: createErrorCtor(joinArgs('ERR_INVALID_PACKAGE_CONFIG')),
|
||||
ERR_INVALID_PACKAGE_TARGET: createErrorCtor(joinArgs('ERR_INVALID_PACKAGE_TARGET')),
|
||||
ERR_MANIFEST_DEPENDENCY_MISSING: createErrorCtor(joinArgs('ERR_MANIFEST_DEPENDENCY_MISSING')),
|
||||
ERR_MODULE_NOT_FOUND: createErrorCtor((path, base, type = 'package') => {
|
||||
return `Cannot find ${type} '${path}' imported from ${base}`
|
||||
}),
|
||||
ERR_PACKAGE_IMPORT_NOT_DEFINED: createErrorCtor(joinArgs('ERR_PACKAGE_IMPORT_NOT_DEFINED')),
|
||||
ERR_PACKAGE_PATH_NOT_EXPORTED: createErrorCtor(joinArgs('ERR_PACKAGE_PATH_NOT_EXPORTED')),
|
||||
ERR_UNSUPPORTED_DIR_IMPORT: createErrorCtor(joinArgs('ERR_UNSUPPORTED_DIR_IMPORT')),
|
||||
ERR_UNSUPPORTED_ESM_URL_SCHEME: createErrorCtor(joinArgs('ERR_UNSUPPORTED_ESM_URL_SCHEME')),
|
||||
ERR_UNKNOWN_FILE_EXTENSION: createErrorCtor(joinArgs('ERR_UNKNOWN_FILE_EXTENSION')),
|
||||
}
|
||||
|
||||
function joinArgs(name) {
|
||||
return (...args) => {
|
||||
return [name, ...args].join(' ')
|
||||
}
|
||||
}
|
||||
|
||||
function createErrorCtor(errorMessageCreator) {
|
||||
return class CustomError extends Error {
|
||||
constructor(...args) {
|
||||
super(errorMessageCreator(...args))
|
||||
}
|
||||
}
|
||||
}
|
||||
exports.createErrRequireEsm = createErrRequireEsm;
|
||||
|
||||
// Native ERR_REQUIRE_ESM Error is declared here:
|
||||
// https://github.com/nodejs/node/blob/2d5d77306f6dff9110c1f77fefab25f973415770/lib/internal/errors.js#L1294-L1313
|
||||
// Error class factory is implemented here:
|
||||
// function E: https://github.com/nodejs/node/blob/2d5d77306f6dff9110c1f77fefab25f973415770/lib/internal/errors.js#L323-L341
|
||||
// function makeNodeErrorWithCode: https://github.com/nodejs/node/blob/2d5d77306f6dff9110c1f77fefab25f973415770/lib/internal/errors.js#L251-L278
|
||||
// The code below should create an error that matches the native error as closely as possible.
|
||||
// Third-party libraries which attempt to catch the native ERR_REQUIRE_ESM should recognize our imitation error.
|
||||
function createErrRequireEsm(filename, parentPath, packageJsonPath) {
|
||||
const code = 'ERR_REQUIRE_ESM'
|
||||
const err = new Error(getErrRequireEsmMessage(filename, parentPath, packageJsonPath))
|
||||
// Set `name` to be used in stack trace, generate stack trace with that name baked in, then re-declare the `name` field.
|
||||
// This trick is copied from node's source.
|
||||
err.name = `Error [${ code }]`
|
||||
err.stack
|
||||
Object.defineProperty(err, 'name', {
|
||||
value: 'Error',
|
||||
enumerable: false,
|
||||
writable: true,
|
||||
configurable: true
|
||||
})
|
||||
err.code = code
|
||||
return err
|
||||
}
|
||||
|
||||
// Copy-pasted from https://github.com/nodejs/node/blob/b533fb3508009e5f567cc776daba8fbf665386a6/lib/internal/errors.js#L1293-L1311
|
||||
// so that our error message is identical to the native message.
|
||||
function getErrRequireEsmMessage(filename, parentPath = null, packageJsonPath = null) {
|
||||
const ext = path.extname(filename)
|
||||
let msg = `Must use import to load ES Module: ${filename}`;
|
||||
if (parentPath && packageJsonPath) {
|
||||
const path = require('path');
|
||||
const basename = path.basename(filename) === path.basename(parentPath) ?
|
||||
filename : path.basename(filename);
|
||||
msg +=
|
||||
'\nrequire() of ES modules is not supported.\nrequire() of ' +
|
||||
`${filename} ${parentPath ? `from ${parentPath} ` : ''}` +
|
||||
`is an ES module file as it is a ${ext} file whose nearest parent ` +
|
||||
`package.json contains "type": "module" which defines all ${ext} ` +
|
||||
'files in that package scope as ES modules.\nInstead ' +
|
||||
'change the requiring code to use ' +
|
||||
'import(), or remove "type": "module" from ' +
|
||||
`${packageJsonPath}.\n`;
|
||||
return msg;
|
||||
}
|
||||
return msg;
|
||||
}
|
||||
+89
@@ -0,0 +1,89 @@
|
||||
// Copied from https://github.com/nodejs/node/blob/v17.0.1/lib/internal/modules/cjs/helpers.js
|
||||
|
||||
'use strict';
|
||||
|
||||
const {
|
||||
ArrayPrototypeForEach,
|
||||
ObjectDefineProperty,
|
||||
ObjectPrototypeHasOwnProperty,
|
||||
SafeSet,
|
||||
StringPrototypeIncludes,
|
||||
StringPrototypeStartsWith,
|
||||
} = require('./node-primordials');
|
||||
|
||||
const { getOptionValue } = require('./node-options');
|
||||
const userConditions = getOptionValue('--conditions');
|
||||
|
||||
const noAddons = getOptionValue('--no-addons');
|
||||
const addonConditions = noAddons ? [] : ['node-addons'];
|
||||
|
||||
// TODO: Use this set when resolving pkg#exports conditions in loader.js.
|
||||
const cjsConditions = new SafeSet([
|
||||
'require',
|
||||
'node',
|
||||
...addonConditions,
|
||||
...userConditions,
|
||||
]);
|
||||
|
||||
/**
|
||||
* @param {any} object
|
||||
* @param {string} [dummyModuleName]
|
||||
* @return {void}
|
||||
*/
|
||||
function addBuiltinLibsToObject(object, dummyModuleName) {
|
||||
// Make built-in modules available directly (loaded lazily).
|
||||
const Module = require('module').Module;
|
||||
const { builtinModules } = Module;
|
||||
|
||||
// To require built-in modules in user-land and ignore modules whose
|
||||
// `canBeRequiredByUsers` is false. So we create a dummy module object and not
|
||||
// use `require()` directly.
|
||||
const dummyModule = new Module(dummyModuleName);
|
||||
|
||||
ArrayPrototypeForEach(builtinModules, (name) => {
|
||||
// Neither add underscored modules, nor ones that contain slashes (e.g.,
|
||||
// 'fs/promises') or ones that are already defined.
|
||||
if (StringPrototypeStartsWith(name, '_') ||
|
||||
StringPrototypeIncludes(name, '/') ||
|
||||
ObjectPrototypeHasOwnProperty(object, name)) {
|
||||
return;
|
||||
}
|
||||
// Goals of this mechanism are:
|
||||
// - Lazy loading of built-in modules
|
||||
// - Having all built-in modules available as non-enumerable properties
|
||||
// - Allowing the user to re-assign these variables as if there were no
|
||||
// pre-existing globals with the same name.
|
||||
|
||||
const setReal = (val) => {
|
||||
// Deleting the property before re-assigning it disables the
|
||||
// getter/setter mechanism.
|
||||
delete object[name];
|
||||
object[name] = val;
|
||||
};
|
||||
|
||||
ObjectDefineProperty(object, name, {
|
||||
get: () => {
|
||||
// Node 12 hack; remove when we drop node12 support
|
||||
const lib = (dummyModule.require || require)(name);
|
||||
|
||||
// Disable the current getter/setter and set up a new
|
||||
// non-enumerable property.
|
||||
delete object[name];
|
||||
ObjectDefineProperty(object, name, {
|
||||
get: () => lib,
|
||||
set: setReal,
|
||||
configurable: true,
|
||||
enumerable: false
|
||||
});
|
||||
|
||||
return lib;
|
||||
},
|
||||
set: setReal,
|
||||
configurable: true,
|
||||
enumerable: false
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
exports.addBuiltinLibsToObject = addBuiltinLibsToObject;
|
||||
exports.cjsConditions = cjsConditions;
|
||||
+593
File diff suppressed because it is too large
Load Diff
+106
@@ -0,0 +1,106 @@
|
||||
// Copied from https://raw.githubusercontent.com/nodejs/node/v15.3.0/lib/internal/modules/esm/get_format.js
|
||||
|
||||
'use strict';
|
||||
const {
|
||||
RegExpPrototypeExec,
|
||||
StringPrototypeStartsWith,
|
||||
} = require('./node-primordials');
|
||||
const { extname } = require('path');
|
||||
const { getOptionValue } = require('./node-options');
|
||||
|
||||
const [nodeMajor, nodeMinor] = process.versions.node.split('.').map(s => parseInt(s, 10));
|
||||
const experimentalJsonModules =
|
||||
nodeMajor > 17
|
||||
|| (nodeMajor === 17 && nodeMinor >= 5)
|
||||
|| (nodeMajor === 16 && nodeMinor >= 15)
|
||||
|| getOptionValue('--experimental-json-modules');
|
||||
const experimentalWasmModules = getOptionValue('--experimental-wasm-modules');
|
||||
const { URL, fileURLToPath } = require('url');
|
||||
const { ERR_UNKNOWN_FILE_EXTENSION } = require('./node-internal-errors').codes;
|
||||
|
||||
const extensionFormatMap = {
|
||||
'__proto__': null,
|
||||
'.cjs': 'commonjs',
|
||||
'.js': 'module',
|
||||
'.mjs': 'module'
|
||||
};
|
||||
|
||||
const legacyExtensionFormatMap = {
|
||||
'__proto__': null,
|
||||
'.cjs': 'commonjs',
|
||||
'.js': 'commonjs',
|
||||
'.json': 'commonjs',
|
||||
'.mjs': 'module',
|
||||
'.node': 'commonjs'
|
||||
};
|
||||
|
||||
if (experimentalWasmModules)
|
||||
extensionFormatMap['.wasm'] = legacyExtensionFormatMap['.wasm'] = 'wasm';
|
||||
|
||||
if (experimentalJsonModules)
|
||||
extensionFormatMap['.json'] = legacyExtensionFormatMap['.json'] = 'json';
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {'node' | 'explicit'} [tsNodeExperimentalSpecifierResolution]
|
||||
* @param {ReturnType<
|
||||
* typeof import('../dist-raw/node-internal-modules-esm-resolve').createResolve
|
||||
* >} nodeEsmResolver
|
||||
*/
|
||||
function createGetFormat(tsNodeExperimentalSpecifierResolution, nodeEsmResolver) {
|
||||
// const experimentalSpeciferResolution = tsNodeExperimentalSpecifierResolution ?? getOptionValue('--experimental-specifier-resolution');
|
||||
let experimentalSpeciferResolution = tsNodeExperimentalSpecifierResolution != null ? tsNodeExperimentalSpecifierResolution : getOptionValue('--experimental-specifier-resolution');
|
||||
const { getPackageType } = nodeEsmResolver;
|
||||
|
||||
/**
|
||||
* @param {string} url
|
||||
* @param {{}} context
|
||||
* @param {any} defaultGetFormatUnused
|
||||
* @returns {ReturnType<import('../src/esm').NodeLoaderHooksAPI1.GetFormatHook>}
|
||||
*/
|
||||
function defaultGetFormat(url, context, defaultGetFormatUnused) {
|
||||
if (StringPrototypeStartsWith(url, 'node:')) {
|
||||
return { format: 'builtin' };
|
||||
}
|
||||
const parsed = new URL(url);
|
||||
if (parsed.protocol === 'data:') {
|
||||
const [ , mime ] = RegExpPrototypeExec(
|
||||
/^([^/]+\/[^;,]+)(?:[^,]*?)(;base64)?,/,
|
||||
parsed.pathname,
|
||||
) || [ null, null, null ];
|
||||
const format = ({
|
||||
'__proto__': null,
|
||||
'text/javascript': 'module',
|
||||
'application/json': experimentalJsonModules ? 'json' : null,
|
||||
'application/wasm': experimentalWasmModules ? 'wasm' : null
|
||||
})[mime] || null;
|
||||
return { format };
|
||||
} else if (parsed.protocol === 'file:') {
|
||||
const ext = extname(parsed.pathname);
|
||||
let format;
|
||||
if (ext === '.js') {
|
||||
format = getPackageType(parsed.href) === 'module' ? 'module' : 'commonjs';
|
||||
} else {
|
||||
format = extensionFormatMap[ext];
|
||||
}
|
||||
if (!format) {
|
||||
if (experimentalSpeciferResolution === 'node') {
|
||||
process.emitWarning(
|
||||
'The Node.js specifier resolution in ESM is experimental.',
|
||||
'ExperimentalWarning');
|
||||
format = legacyExtensionFormatMap[ext];
|
||||
} else {
|
||||
throw new ERR_UNKNOWN_FILE_EXTENSION(ext, fileURLToPath(url));
|
||||
}
|
||||
}
|
||||
return { format: format || null };
|
||||
}
|
||||
return { format: null };
|
||||
}
|
||||
|
||||
return {defaultGetFormat};
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
createGetFormat
|
||||
};
|
||||
+962
File diff suppressed because it is too large
Load Diff
+44
@@ -0,0 +1,44 @@
|
||||
// copied from https://github.com/nodejs/node/blob/v15.3.0/lib/internal/modules/package_json_reader.js
|
||||
'use strict';
|
||||
|
||||
const { SafeMap } = require('./node-primordials');
|
||||
const { internalModuleReadJSON } = require('./node-internalBinding-fs');
|
||||
const { pathToFileURL } = require('url');
|
||||
const { toNamespacedPath } = require('path');
|
||||
// const { getOptionValue } = require('./node-options');
|
||||
|
||||
const cache = new SafeMap();
|
||||
|
||||
let manifest;
|
||||
|
||||
/**
|
||||
* @param {string} jsonPath
|
||||
* @return {{string: string, containsKeys: boolean}}
|
||||
*/
|
||||
function read(jsonPath) {
|
||||
if (cache.has(jsonPath)) {
|
||||
return cache.get(jsonPath);
|
||||
}
|
||||
|
||||
const [string, containsKeys] = internalModuleReadJSON(
|
||||
toNamespacedPath(jsonPath)
|
||||
);
|
||||
const result = { string, containsKeys };
|
||||
if (string !== undefined) {
|
||||
if (manifest === undefined) {
|
||||
// manifest = getOptionValue('--experimental-policy') ?
|
||||
// require('internal/process/policy').manifest :
|
||||
// null;
|
||||
// disabled for now. I am not sure if/how we should support this
|
||||
manifest = null;
|
||||
}
|
||||
if (manifest !== null) {
|
||||
const jsonURL = pathToFileURL(jsonPath);
|
||||
manifest.assertIntegrity(jsonURL, string);
|
||||
}
|
||||
}
|
||||
cache.set(jsonPath, result);
|
||||
return result;
|
||||
}
|
||||
|
||||
module.exports = { read };
|
||||
+254
@@ -0,0 +1,254 @@
|
||||
// copied from https://github.com/nodejs/node/blob/88799930794045795e8abac874730f9eba7e2300/lib/internal/repl/await.js
|
||||
'use strict';
|
||||
|
||||
const {
|
||||
ArrayFrom,
|
||||
ArrayPrototypeForEach,
|
||||
ArrayPrototypeIncludes,
|
||||
ArrayPrototypeJoin,
|
||||
ArrayPrototypePop,
|
||||
ArrayPrototypePush,
|
||||
FunctionPrototype,
|
||||
ObjectKeys,
|
||||
RegExpPrototypeSymbolReplace,
|
||||
StringPrototypeEndsWith,
|
||||
StringPrototypeIncludes,
|
||||
StringPrototypeIndexOf,
|
||||
StringPrototypeRepeat,
|
||||
StringPrototypeSplit,
|
||||
StringPrototypeStartsWith,
|
||||
SyntaxError,
|
||||
} = require('./node-primordials');
|
||||
|
||||
const parser = require('acorn').Parser;
|
||||
const walk = require('acorn-walk');
|
||||
const { Recoverable } = require('repl');
|
||||
|
||||
function isTopLevelDeclaration(state) {
|
||||
return state.ancestors[state.ancestors.length - 2] === state.body;
|
||||
}
|
||||
|
||||
const noop = FunctionPrototype;
|
||||
const visitorsWithoutAncestors = {
|
||||
ClassDeclaration(node, state, c) {
|
||||
if (isTopLevelDeclaration(state)) {
|
||||
state.prepend(node, `${node.id.name}=`);
|
||||
ArrayPrototypePush(
|
||||
state.hoistedDeclarationStatements,
|
||||
`let ${node.id.name}; `
|
||||
);
|
||||
}
|
||||
|
||||
walk.base.ClassDeclaration(node, state, c);
|
||||
},
|
||||
ForOfStatement(node, state, c) {
|
||||
if (node.await === true) {
|
||||
state.containsAwait = true;
|
||||
}
|
||||
walk.base.ForOfStatement(node, state, c);
|
||||
},
|
||||
FunctionDeclaration(node, state, c) {
|
||||
state.prepend(node, `${node.id.name}=`);
|
||||
ArrayPrototypePush(
|
||||
state.hoistedDeclarationStatements,
|
||||
`var ${node.id.name}; `
|
||||
);
|
||||
},
|
||||
FunctionExpression: noop,
|
||||
ArrowFunctionExpression: noop,
|
||||
MethodDefinition: noop,
|
||||
AwaitExpression(node, state, c) {
|
||||
state.containsAwait = true;
|
||||
walk.base.AwaitExpression(node, state, c);
|
||||
},
|
||||
ReturnStatement(node, state, c) {
|
||||
state.containsReturn = true;
|
||||
walk.base.ReturnStatement(node, state, c);
|
||||
},
|
||||
VariableDeclaration(node, state, c) {
|
||||
const variableKind = node.kind;
|
||||
const isIterableForDeclaration = ArrayPrototypeIncludes(
|
||||
['ForOfStatement', 'ForInStatement'],
|
||||
state.ancestors[state.ancestors.length - 2].type
|
||||
);
|
||||
|
||||
if (variableKind === 'var' || isTopLevelDeclaration(state)) {
|
||||
state.replace(
|
||||
node.start,
|
||||
node.start + variableKind.length + (isIterableForDeclaration ? 1 : 0),
|
||||
variableKind === 'var' && isIterableForDeclaration ?
|
||||
'' :
|
||||
'void' + (node.declarations.length === 1 ? '' : ' (')
|
||||
);
|
||||
|
||||
if (!isIterableForDeclaration) {
|
||||
ArrayPrototypeForEach(node.declarations, (decl) => {
|
||||
state.prepend(decl, '(');
|
||||
state.append(decl, decl.init ? ')' : '=undefined)');
|
||||
});
|
||||
|
||||
if (node.declarations.length !== 1) {
|
||||
state.append(node.declarations[node.declarations.length - 1], ')');
|
||||
}
|
||||
}
|
||||
|
||||
const variableIdentifiersToHoist = [
|
||||
['var', []],
|
||||
['let', []],
|
||||
];
|
||||
function registerVariableDeclarationIdentifiers(node) {
|
||||
switch (node.type) {
|
||||
case 'Identifier':
|
||||
ArrayPrototypePush(
|
||||
variableIdentifiersToHoist[variableKind === 'var' ? 0 : 1][1],
|
||||
node.name
|
||||
);
|
||||
break;
|
||||
case 'ObjectPattern':
|
||||
ArrayPrototypeForEach(node.properties, (property) => {
|
||||
registerVariableDeclarationIdentifiers(property.value);
|
||||
});
|
||||
break;
|
||||
case 'ArrayPattern':
|
||||
ArrayPrototypeForEach(node.elements, (element) => {
|
||||
registerVariableDeclarationIdentifiers(element);
|
||||
});
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
ArrayPrototypeForEach(node.declarations, (decl) => {
|
||||
registerVariableDeclarationIdentifiers(decl.id);
|
||||
});
|
||||
|
||||
ArrayPrototypeForEach(
|
||||
variableIdentifiersToHoist,
|
||||
({ 0: kind, 1: identifiers }) => {
|
||||
if (identifiers.length > 0) {
|
||||
ArrayPrototypePush(
|
||||
state.hoistedDeclarationStatements,
|
||||
`${kind} ${ArrayPrototypeJoin(identifiers, ', ')}; `
|
||||
);
|
||||
}
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
walk.base.VariableDeclaration(node, state, c);
|
||||
}
|
||||
};
|
||||
|
||||
const visitors = {};
|
||||
for (const nodeType of ObjectKeys(walk.base)) {
|
||||
const callback = visitorsWithoutAncestors[nodeType] || walk.base[nodeType];
|
||||
visitors[nodeType] = (node, state, c) => {
|
||||
const isNew = node !== state.ancestors[state.ancestors.length - 1];
|
||||
if (isNew) {
|
||||
ArrayPrototypePush(state.ancestors, node);
|
||||
}
|
||||
callback(node, state, c);
|
||||
if (isNew) {
|
||||
ArrayPrototypePop(state.ancestors);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function processTopLevelAwait(src) {
|
||||
const wrapPrefix = '(async () => { ';
|
||||
const wrapped = `${wrapPrefix}${src} })()`;
|
||||
const wrappedArray = ArrayFrom(wrapped);
|
||||
let root;
|
||||
try {
|
||||
root = parser.parse(wrapped, { ecmaVersion: 'latest' });
|
||||
} catch (e) {
|
||||
if (StringPrototypeStartsWith(e.message, 'Unterminated '))
|
||||
throw new Recoverable(e);
|
||||
// If the parse error is before the first "await", then use the execution
|
||||
// error. Otherwise we must emit this parse error, making it look like a
|
||||
// proper syntax error.
|
||||
const awaitPos = StringPrototypeIndexOf(src, 'await');
|
||||
const errPos = e.pos - wrapPrefix.length;
|
||||
if (awaitPos > errPos)
|
||||
return null;
|
||||
// Convert keyword parse errors on await into their original errors when
|
||||
// possible.
|
||||
if (errPos === awaitPos + 6 &&
|
||||
StringPrototypeIncludes(e.message, 'Expecting Unicode escape sequence'))
|
||||
return null;
|
||||
if (errPos === awaitPos + 7 &&
|
||||
StringPrototypeIncludes(e.message, 'Unexpected token'))
|
||||
return null;
|
||||
const line = e.loc.line;
|
||||
const column = line === 1 ? e.loc.column - wrapPrefix.length : e.loc.column;
|
||||
let message = '\n' + StringPrototypeSplit(src, '\n')[line - 1] + '\n' +
|
||||
StringPrototypeRepeat(' ', column) +
|
||||
'^\n\n' + RegExpPrototypeSymbolReplace(/ \([^)]+\)/, e.message, '');
|
||||
// V8 unexpected token errors include the token string.
|
||||
if (StringPrototypeEndsWith(message, 'Unexpected token'))
|
||||
message += " '" +
|
||||
// Wrapper end may cause acorn to report error position after the source
|
||||
((src.length - 1) >= (e.pos - wrapPrefix.length)
|
||||
? src[e.pos - wrapPrefix.length]
|
||||
: src[src.length - 1]) +
|
||||
"'";
|
||||
// eslint-disable-next-line no-restricted-syntax
|
||||
throw new SyntaxError(message);
|
||||
}
|
||||
const body = root.body[0].expression.callee.body;
|
||||
const state = {
|
||||
body,
|
||||
ancestors: [],
|
||||
hoistedDeclarationStatements: [],
|
||||
replace(from, to, str) {
|
||||
for (let i = from; i < to; i++) {
|
||||
wrappedArray[i] = '';
|
||||
}
|
||||
if (from === to) str += wrappedArray[from];
|
||||
wrappedArray[from] = str;
|
||||
},
|
||||
prepend(node, str) {
|
||||
wrappedArray[node.start] = str + wrappedArray[node.start];
|
||||
},
|
||||
append(node, str) {
|
||||
wrappedArray[node.end - 1] += str;
|
||||
},
|
||||
containsAwait: false,
|
||||
containsReturn: false
|
||||
};
|
||||
|
||||
walk.recursive(body, state, visitors);
|
||||
|
||||
// Do not transform if
|
||||
// 1. False alarm: there isn't actually an await expression.
|
||||
// 2. There is a top-level return, which is not allowed.
|
||||
if (!state.containsAwait || state.containsReturn) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const last = body.body[body.body.length - 1];
|
||||
if (last.type === 'ExpressionStatement') {
|
||||
// For an expression statement of the form
|
||||
// ( expr ) ;
|
||||
// ^^^^^^^^^^ // last
|
||||
// ^^^^ // last.expression
|
||||
//
|
||||
// We do not want the left parenthesis before the `return` keyword;
|
||||
// therefore we prepend the `return (` to `last`.
|
||||
//
|
||||
// On the other hand, we do not want the right parenthesis after the
|
||||
// semicolon. Since there can only be more right parentheses between
|
||||
// last.expression.end and the semicolon, appending one more to
|
||||
// last.expression should be fine.
|
||||
state.prepend(last, 'return (');
|
||||
state.append(last.expression, ')');
|
||||
}
|
||||
|
||||
return (
|
||||
ArrayPrototypeJoin(state.hoistedDeclarationStatements, '') +
|
||||
ArrayPrototypeJoin(wrappedArray, '')
|
||||
);
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
processTopLevelAwait
|
||||
};
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
const fs = require('fs');
|
||||
const {versionGteLt} = require('../dist/util');
|
||||
|
||||
// In node's core, this is implemented in C
|
||||
// https://github.com/nodejs/node/blob/v15.3.0/src/node_file.cc#L891-L985
|
||||
/**
|
||||
* @param {string} path
|
||||
* @returns {[] | [string, boolean]}
|
||||
*/
|
||||
function internalModuleReadJSON(path) {
|
||||
let string
|
||||
try {
|
||||
string = fs.readFileSync(path, 'utf8')
|
||||
} catch (e) {
|
||||
if (e.code === 'ENOENT') return []
|
||||
throw e
|
||||
}
|
||||
// Node's implementation checks for the presence of relevant keys: main, name, type, exports, imports
|
||||
// Node does this for performance to skip unnecessary parsing.
|
||||
// This would slow us down and, based on our usage, we can skip it.
|
||||
const containsKeys = true
|
||||
return [string, containsKeys]
|
||||
}
|
||||
|
||||
// In node's core, this is implemented in C
|
||||
// https://github.com/nodejs/node/blob/63e7dc1e5c71b70c80ed9eda230991edb00811e2/src/node_file.cc#L987-L1005
|
||||
/**
|
||||
* @param {string} path
|
||||
* @returns {number} 0 = file, 1 = dir, negative = error
|
||||
*/
|
||||
function internalModuleStat(path) {
|
||||
const stat = fs.statSync(path, { throwIfNoEntry: false });
|
||||
if(!stat) return -1;
|
||||
if(stat.isFile()) return 0;
|
||||
if(stat.isDirectory()) return 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} path
|
||||
* @returns {number} 0 = file, 1 = dir, negative = error
|
||||
*/
|
||||
function internalModuleStatInefficient(path) {
|
||||
try {
|
||||
const stat = fs.statSync(path);
|
||||
if(stat.isFile()) return 0;
|
||||
if(stat.isDirectory()) return 1;
|
||||
} catch(e) {
|
||||
return -e.errno || -1;
|
||||
}
|
||||
}
|
||||
|
||||
const statSupportsThrowIfNoEntry = versionGteLt(process.versions.node, '15.3.0') ||
|
||||
versionGteLt(process.versions.node, '14.17.0', '15.0.0');
|
||||
|
||||
module.exports = {
|
||||
internalModuleReadJSON,
|
||||
internalModuleStat: statSupportsThrowIfNoEntry ? internalModuleStat : internalModuleStatInefficient
|
||||
};
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
|
||||
// Node imports this from 'internal/bootstrap/loaders'
|
||||
const Module = require('module');
|
||||
const NativeModule = {
|
||||
canBeRequiredByUsers(specifier) {
|
||||
return Module.builtinModules.includes(specifier)
|
||||
}
|
||||
};
|
||||
exports.NativeModule = NativeModule;
|
||||
+103
@@ -0,0 +1,103 @@
|
||||
// Replacement for node's internal 'internal/options' module
|
||||
|
||||
exports.getOptionValue = getOptionValue;
|
||||
function getOptionValue(opt) {
|
||||
parseOptions();
|
||||
return options[opt];
|
||||
}
|
||||
|
||||
let options;
|
||||
function parseOptions() {
|
||||
if (!options) {
|
||||
options = {
|
||||
'--preserve-symlinks': false,
|
||||
'--preserve-symlinks-main': false,
|
||||
'--input-type': undefined,
|
||||
'--experimental-specifier-resolution': 'explicit',
|
||||
'--experimental-policy': undefined,
|
||||
'--conditions': [],
|
||||
'--pending-deprecation': false,
|
||||
...parseArgv(getNodeOptionsEnvArgv()),
|
||||
...parseArgv(process.execArgv),
|
||||
...getOptionValuesFromOtherEnvVars()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function parseArgv(argv) {
|
||||
return require('arg')({
|
||||
'--preserve-symlinks': Boolean,
|
||||
'--preserve-symlinks-main': Boolean,
|
||||
'--input-type': String,
|
||||
'--experimental-specifier-resolution': String,
|
||||
// Legacy alias for node versions prior to 12.16
|
||||
'--es-module-specifier-resolution': '--experimental-specifier-resolution',
|
||||
'--experimental-policy': String,
|
||||
'--conditions': [String],
|
||||
'--pending-deprecation': Boolean,
|
||||
'--experimental-json-modules': Boolean,
|
||||
'--experimental-wasm-modules': Boolean,
|
||||
}, {
|
||||
argv,
|
||||
permissive: true
|
||||
});
|
||||
}
|
||||
|
||||
function getNodeOptionsEnvArgv() {
|
||||
const errors = [];
|
||||
const envArgv = ParseNodeOptionsEnvVar(process.env.NODE_OPTIONS || '', errors);
|
||||
if (errors.length !== 0) {
|
||||
// TODO: handle errors somehow
|
||||
}
|
||||
return envArgv;
|
||||
}
|
||||
|
||||
// Direct JS port of C implementation: https://github.com/nodejs/node/blob/67ba825037b4082d5d16f922fb9ce54516b4a869/src/node_options.cc#L1024-L1063
|
||||
function ParseNodeOptionsEnvVar(node_options, errors) {
|
||||
const env_argv = [];
|
||||
|
||||
let is_in_string = false;
|
||||
let will_start_new_arg = true;
|
||||
for (let index = 0; index < node_options.length; ++index) {
|
||||
let c = node_options[index];
|
||||
|
||||
// Backslashes escape the following character
|
||||
if (c === '\\' && is_in_string) {
|
||||
if (index + 1 === node_options.length) {
|
||||
errors.push("invalid value for NODE_OPTIONS " +
|
||||
"(invalid escape)\n");
|
||||
return env_argv;
|
||||
} else {
|
||||
c = node_options[++index];
|
||||
}
|
||||
} else if (c === ' ' && !is_in_string) {
|
||||
will_start_new_arg = true;
|
||||
continue;
|
||||
} else if (c === '"') {
|
||||
is_in_string = !is_in_string;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (will_start_new_arg) {
|
||||
env_argv.push(c);
|
||||
will_start_new_arg = false;
|
||||
} else {
|
||||
env_argv[env_argv.length - 1] += c;
|
||||
}
|
||||
}
|
||||
|
||||
if (is_in_string) {
|
||||
errors.push("invalid value for NODE_OPTIONS " +
|
||||
"(unterminated string)\n");
|
||||
}
|
||||
return env_argv;
|
||||
}
|
||||
|
||||
// Get option values that can be specified via env vars besides NODE_OPTIONS
|
||||
function getOptionValuesFromOtherEnvVars() {
|
||||
const options = {};
|
||||
if(process.env.NODE_PENDING_DEPRECATION === '1') {
|
||||
options['--pending-deprecation'] = true;
|
||||
}
|
||||
return options;
|
||||
}
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
module.exports = {
|
||||
ArrayFrom: Array.from,
|
||||
ArrayIsArray: Array.isArray,
|
||||
ArrayPrototypeShift: (obj) => Array.prototype.shift.call(obj),
|
||||
ArrayPrototypeForEach: (arr, ...rest) => Array.prototype.forEach.apply(arr, rest),
|
||||
ArrayPrototypeIncludes: (arr, ...rest) => Array.prototype.includes.apply(arr, rest),
|
||||
ArrayPrototypeJoin: (arr, ...rest) => Array.prototype.join.apply(arr, rest),
|
||||
ArrayPrototypePop: (arr, ...rest) => Array.prototype.pop.apply(arr, rest),
|
||||
ArrayPrototypePush: (arr, ...rest) => Array.prototype.push.apply(arr, rest),
|
||||
FunctionPrototype: Function.prototype,
|
||||
JSONParse: JSON.parse,
|
||||
JSONStringify: JSON.stringify,
|
||||
ObjectFreeze: Object.freeze,
|
||||
ObjectKeys: Object.keys,
|
||||
ObjectGetOwnPropertyNames: Object.getOwnPropertyNames,
|
||||
ObjectDefineProperty: Object.defineProperty,
|
||||
ObjectPrototypeHasOwnProperty: (obj, prop) => Object.prototype.hasOwnProperty.call(obj, prop),
|
||||
RegExpPrototypeExec: (obj, string) => RegExp.prototype.exec.call(obj, string),
|
||||
RegExpPrototypeTest: (obj, string) => RegExp.prototype.test.call(obj, string),
|
||||
RegExpPrototypeSymbolReplace: (obj, ...rest) => RegExp.prototype[Symbol.replace].apply(obj, rest),
|
||||
SafeMap: Map,
|
||||
SafeSet: Set,
|
||||
SafeWeakMap: WeakMap,
|
||||
StringPrototypeEndsWith: (str, ...rest) => String.prototype.endsWith.apply(str, rest),
|
||||
StringPrototypeIncludes: (str, ...rest) => String.prototype.includes.apply(str, rest),
|
||||
StringPrototypeLastIndexOf: (str, ...rest) => String.prototype.lastIndexOf.apply(str, rest),
|
||||
StringPrototypeIndexOf: (str, ...rest) => String.prototype.indexOf.apply(str, rest),
|
||||
StringPrototypeRepeat: (str, ...rest) => String.prototype.repeat.apply(str, rest),
|
||||
StringPrototypeReplace: (str, ...rest) => String.prototype.replace.apply(str, rest),
|
||||
StringPrototypeSlice: (str, ...rest) => String.prototype.slice.apply(str, rest),
|
||||
StringPrototypeSplit: (str, ...rest) => String.prototype.split.apply(str, rest),
|
||||
StringPrototypeStartsWith: (str, ...rest) => String.prototype.startsWith.apply(str, rest),
|
||||
StringPrototypeSubstr: (str, ...rest) => String.prototype.substr.apply(str, rest),
|
||||
StringPrototypeCharCodeAt: (str, ...rest) => String.prototype.charCodeAt.apply(str, rest),
|
||||
StringPrototypeMatch: (str, ...rest) => String.prototype.match.apply(str, rest),
|
||||
SyntaxError: SyntaxError
|
||||
};
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
const {pathToFileURL} = require('url');
|
||||
|
||||
// Hack to avoid Module.runMain on node 18.6.0
|
||||
// Keeping it simple for now, isolated in this file.
|
||||
// Could theoretically probe `getFormat` impl to determine if `import()` or `Module._load()` is best
|
||||
// Note that I attempted a try-catch around `Module._load`, but it poisons some sort of cache such that subsequent `import()` is impossible.
|
||||
exports.run = function(entryPointPath) {
|
||||
import(pathToFileURL(entryPointPath));
|
||||
}
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
#!/usr/bin/env node
|
||||
export {};
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
#!/usr/bin/env node
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const bin_1 = require("./bin");
|
||||
(0, bin_1.main)(undefined, { '--cwdMode': true });
|
||||
//# sourceMappingURL=bin-cwd.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"bin-cwd.js","sourceRoot":"","sources":["../src/bin-cwd.ts"],"names":[],"mappings":";;;AAEA,+BAA6B;AAE7B,IAAA,UAAI,EAAC,SAAS,EAAE,EAAE,WAAW,EAAE,IAAI,EAAE,CAAC,CAAC","sourcesContent":["#!/usr/bin/env node\n\nimport { main } from './bin';\n\nmain(undefined, { '--cwdMode': true });\n"]}
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
#!/usr/bin/env node
|
||||
export {};
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
#!/usr/bin/env node
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const bin_1 = require("./bin");
|
||||
(0, bin_1.main)(undefined, { '--esm': true });
|
||||
//# sourceMappingURL=bin-esm.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"bin-esm.js","sourceRoot":"","sources":["../src/bin-esm.ts"],"names":[],"mappings":";;;AAEA,+BAA6B;AAE7B,IAAA,UAAI,EAAC,SAAS,EAAE,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC,CAAC","sourcesContent":["#!/usr/bin/env node\n\nimport { main } from './bin';\n\nmain(undefined, { '--esm': true });\n"]}
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
#!/usr/bin/env node
|
||||
export {};
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
#!/usr/bin/env node
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const bin_1 = require("./bin");
|
||||
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, { '--scriptMode': true });
|
||||
//# sourceMappingURL=bin-script-deprecated.js.map
|
||||
+1
File diff suppressed because one or more lines are too long
+2
@@ -0,0 +1,2 @@
|
||||
#!/usr/bin/env node
|
||||
export {};
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
#!/usr/bin/env node
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const bin_1 = require("./bin");
|
||||
(0, bin_1.main)(undefined, { '--scriptMode': true });
|
||||
//# sourceMappingURL=bin-script.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"bin-script.js","sourceRoot":"","sources":["../src/bin-script.ts"],"names":[],"mappings":";;;AAEA,+BAA6B;AAE7B,IAAA,UAAI,EAAC,SAAS,EAAE,EAAE,cAAc,EAAE,IAAI,EAAE,CAAC,CAAC","sourcesContent":["#!/usr/bin/env node\n\nimport { main } from './bin';\n\nmain(undefined, { '--scriptMode': true });\n"]}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user