@ms-cloudpack/esm-stub-utilities 0.6.0 → 0.6.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/runInSandbox.d.ts +10 -0
- package/lib/runInSandbox.js +48 -19
- package/lib/runInSandbox.js.map +1 -1
- package/lib/tsdoc-metadata.json +1 -1
- package/package.json +1 -1
package/lib/runInSandbox.d.ts
CHANGED
|
@@ -1 +1,11 @@
|
|
|
1
|
+
import { NodeVM } from 'vm2';
|
|
2
|
+
/** Reset `vms` and `sandboxRoots` for testing */
|
|
3
|
+
export declare function _clearSandboxCaches(): void;
|
|
4
|
+
/** Get `vms` state for testing */
|
|
5
|
+
export declare function _getSandboxVms(): Record<string, NodeVM>;
|
|
6
|
+
/**
|
|
7
|
+
* Run a CommonJS file within a sandboxed environment.
|
|
8
|
+
* @param entryPath - Path to a CommonJS file to run in a sandbox (does not work with ESM files)
|
|
9
|
+
* @returns The module's exports
|
|
10
|
+
*/
|
|
1
11
|
export declare function runInSandbox(entryPath: string): Promise<unknown>;
|
package/lib/runInSandbox.js
CHANGED
|
@@ -9,17 +9,24 @@ const dirname = path.dirname(filename);
|
|
|
9
9
|
const browserEnvSetup = path.join(dirname, 'browserEnvironment.cjs');
|
|
10
10
|
/** Allow the sandbox to load these built-in modules */
|
|
11
11
|
// ('events' and 'stream' export classes which other things extend and can't be proxied)
|
|
12
|
-
const allowedBuiltins = ['events', 'path', 'stream', 'url', 'util'];
|
|
13
|
-
/** Built-in modules provided by vm2 */
|
|
14
|
-
const includedBuiltins = ['buffer'];
|
|
12
|
+
const allowedBuiltins = ['events', 'path', 'stream', 'url', 'util', 'buffer'];
|
|
15
13
|
/** Empty mocks of all built-in modules that aren't allowed (to ensure that requires succeed) */
|
|
16
|
-
const mockBuiltins = Object.fromEntries(builtinModules.filter((m) => !allowedBuiltins.includes(m)
|
|
14
|
+
const mockBuiltins = Object.fromEntries(builtinModules.filter((m) => !allowedBuiltins.includes(m)).map((m) => [m, {}]));
|
|
17
15
|
/** Mapping from sandbox root to VM */
|
|
18
16
|
const vms = {};
|
|
19
17
|
/** Mapping from directory to sandbox root */
|
|
20
18
|
const sandboxRoots = {};
|
|
21
19
|
/** Sandbox root for this file and other cloudpack-related files */
|
|
22
20
|
let cloudpackSandboxRoot = '';
|
|
21
|
+
/** Reset `vms` and `sandboxRoots` for testing */
|
|
22
|
+
export function _clearSandboxCaches() {
|
|
23
|
+
Object.keys(vms).forEach((k) => delete vms[k]);
|
|
24
|
+
Object.keys(sandboxRoots).forEach((k) => delete sandboxRoots[k]);
|
|
25
|
+
}
|
|
26
|
+
/** Get `vms` state for testing */
|
|
27
|
+
export function _getSandboxVms() {
|
|
28
|
+
return vms;
|
|
29
|
+
}
|
|
23
30
|
/**
|
|
24
31
|
* Try to figure out a root directory where the sandbox should be allowed to require files from.
|
|
25
32
|
* This prefers the git root if found, falling back to package root or parent directory.
|
|
@@ -47,24 +54,49 @@ function findSandboxRoot(filePath) {
|
|
|
47
54
|
return sandboxRoots[dir];
|
|
48
55
|
}
|
|
49
56
|
function handleError(action, err, sandboxRoot) {
|
|
50
|
-
const message =
|
|
51
|
-
const stack = err.stack?.split(/\r?\n/g);
|
|
52
|
-
|
|
53
|
-
|
|
57
|
+
const message = err.message || String(err);
|
|
58
|
+
const stack = err.stack?.split(/\r?\n/g) || [];
|
|
59
|
+
// instanceof checks don't work with errors from code run within the sandbox, but name is preserved
|
|
60
|
+
const errorName = err.name;
|
|
61
|
+
const newMessage = [`Error ${action}:`, message];
|
|
62
|
+
if (stack.length && err instanceof VMError && err.message.includes('Cannot find module')) {
|
|
63
|
+
newMessage.push('', 'Ensure that this file exists on disk. If it exists, this may be a bug with the choice of `root` ' +
|
|
54
64
|
'(allowed parent directories) settings in @ms-cloudpack/esm-stub-utilities runInSandbox.', `- Root for file being stubbed: ${sandboxRoot}`, `- Root for cloudpack files: ${cloudpackSandboxRoot}`);
|
|
55
65
|
// Find the actual line which caused the error
|
|
56
66
|
const errorLines = stack.filter((line) => line.trim().startsWith('at') && !line.includes('vm2'));
|
|
57
67
|
if (errorLines.length) {
|
|
58
|
-
|
|
68
|
+
newMessage.push('', 'Code that may have required this module:', ...errorLines);
|
|
59
69
|
}
|
|
60
70
|
}
|
|
61
|
-
if (
|
|
62
|
-
|
|
71
|
+
else if (errorName === 'TypeError') {
|
|
72
|
+
newMessage.push('', 'If the code was referencing a built-in global or a property of a Node built-in module, ' +
|
|
73
|
+
'this error may be caused by a missing mock or other issue with the sandbox environment ' +
|
|
74
|
+
'configured in @ms-cloudpack/esm-stub-utilities runInSandbox.');
|
|
75
|
+
}
|
|
76
|
+
else if (errorName === 'SyntaxError' &&
|
|
77
|
+
(/Unexpected token '(import|export)'/.test(message) ||
|
|
78
|
+
message.includes(`'import' and 'export' may appear only with`))) {
|
|
79
|
+
newMessage.push('', "It appears you're trying to load an ES module, which is not currently supported in the sandbox. " +
|
|
80
|
+
'If this module is loaded at startup within a CommonJS file, please file an issue with cloudpack. ');
|
|
63
81
|
}
|
|
64
|
-
|
|
82
|
+
if (stack.length) {
|
|
83
|
+
newMessage.push('', 'Original stack:', ...stack.slice(1));
|
|
84
|
+
}
|
|
85
|
+
throw new Error(newMessage.join('\n'));
|
|
65
86
|
}
|
|
87
|
+
/**
|
|
88
|
+
* Run a CommonJS file within a sandboxed environment.
|
|
89
|
+
* @param entryPath - Path to a CommonJS file to run in a sandbox (does not work with ESM files)
|
|
90
|
+
* @returns The module's exports
|
|
91
|
+
*/
|
|
66
92
|
// eslint-disable-next-line @typescript-eslint/require-await -- using async to catch async errors
|
|
67
93
|
export async function runInSandbox(entryPath) {
|
|
94
|
+
if (!path.isAbsolute(entryPath)) {
|
|
95
|
+
throw new Error('Entry path must be absolute. Received: ' + entryPath);
|
|
96
|
+
}
|
|
97
|
+
if (!fs.existsSync(entryPath)) {
|
|
98
|
+
throw new Error('Entry path does not exist: ' + entryPath);
|
|
99
|
+
}
|
|
68
100
|
// Allow code in the sandbox to require files under the requested file's package root,
|
|
69
101
|
// or under its directory if it's not in a package.
|
|
70
102
|
const sandboxRoot = findSandboxRoot(entryPath);
|
|
@@ -77,8 +109,8 @@ export async function runInSandbox(entryPath) {
|
|
|
77
109
|
vms[sandboxRoot] = new NodeVM({
|
|
78
110
|
// disable console logging instead of passing through to the host console
|
|
79
111
|
console: 'off',
|
|
80
|
-
// look for these import extensions
|
|
81
|
-
sourceExtensions: ['js', 'cjs'
|
|
112
|
+
// look for these import extensions (mjs is not included because this doesn't support loading ESM)
|
|
113
|
+
sourceExtensions: ['js', 'cjs'],
|
|
82
114
|
// use a commonjs module wrapper
|
|
83
115
|
wrapper: 'commonjs',
|
|
84
116
|
require: {
|
|
@@ -99,9 +131,6 @@ export async function runInSandbox(entryPath) {
|
|
|
99
131
|
perf_hooks: {
|
|
100
132
|
performance: { now: () => Date.now() },
|
|
101
133
|
},
|
|
102
|
-
tty: {
|
|
103
|
-
isatty: () => false,
|
|
104
|
-
},
|
|
105
134
|
vm: {
|
|
106
135
|
isContext: () => false,
|
|
107
136
|
},
|
|
@@ -120,11 +149,11 @@ export async function runInSandbox(entryPath) {
|
|
|
120
149
|
});
|
|
121
150
|
}
|
|
122
151
|
catch (err) {
|
|
123
|
-
handleError(`initializing sandbox for ${sandboxRoot}`, err, sandboxRoot);
|
|
152
|
+
handleError(`initializing sandbox for ${sandboxRoot} (to create stub of ${entryPath})`, err, sandboxRoot);
|
|
124
153
|
}
|
|
125
154
|
}
|
|
126
155
|
const onError = (err) => {
|
|
127
|
-
handleError(`running ${entryPath} in sandbox`, err, sandboxRoot);
|
|
156
|
+
handleError(`running ${entryPath} in sandbox (to create stub)`, err, sandboxRoot);
|
|
128
157
|
};
|
|
129
158
|
process.on('uncaughtException', onError);
|
|
130
159
|
try {
|
package/lib/runInSandbox.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"runInSandbox.js","sourceRoot":"","sources":["../src/runInSandbox.ts"],"names":[],"mappings":"AA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