@ms-cloudpack/esm-stub-utilities 0.6.24 → 0.6.26
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.js +2 -2
- package/lib/runInSandbox.js.map +1 -1
- package/package.json +4 -4
package/lib/runInSandbox.js
CHANGED
|
@@ -99,7 +99,7 @@ function logMissingModule(params) {
|
|
|
99
99
|
const depName = moduleName.match(/^(@[\w.-]+\/)?[\w.-]+/)?.[0];
|
|
100
100
|
const parentPkgRoot = depName ? findPackageRoot(parentDir) : undefined;
|
|
101
101
|
if (depName && parentPkgRoot) {
|
|
102
|
-
// eslint-disable-next-line no-
|
|
102
|
+
// eslint-disable-next-line @ms-cloudpack/internal/no-sync-filesystem
|
|
103
103
|
const packageJson = readJsonSync(path.join(parentPkgRoot, 'package.json'));
|
|
104
104
|
isOptionalPeerDep = !!(packageJson?.peerDependencies?.[depName] && packageJson.peerDependenciesMeta?.[depName]?.optional);
|
|
105
105
|
}
|
|
@@ -150,7 +150,7 @@ export async function runInSandbox(entryPath) {
|
|
|
150
150
|
import: [browserEnvSetup],
|
|
151
151
|
// fallback resolver if vm2's algorithm fails
|
|
152
152
|
resolve: (moduleName, parentDir) => {
|
|
153
|
-
// eslint-disable-next-line no-
|
|
153
|
+
// eslint-disable-next-line @ms-cloudpack/internal/no-sync-filesystem
|
|
154
154
|
const realParentDir = fs.realpathSync(parentDir);
|
|
155
155
|
if (realParentDir === parentDir) {
|
|
156
156
|
// Log a more informative error if this isn't a realpath issue (explained below).
|
package/lib/runInSandbox.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"runInSandbox.js","sourceRoot":"","sources":["../src/runInSandbox.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,IAAI,CAAC;AACpB,OAAO,UAAU,MAAM,aAAa,CAAC;AACrC,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,EAAE,cAAc,EAAE,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C,CAAC;IACpF,CAAC,CAAC;IACF,OAAO,CAAC,EAAE,CAAC,mBAAmB,EAAE,OAAO,CAAC,CAAC;IAEzC,IAAI;QACF,MAAM,OAAO,GAAG,MAAM,UAAU,CAAC,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC,CAAC;QAC7D,OAAO,GAAG,CAAC,WAAW,CAAC,CAAC,GAAG,CAAC,OAAO,EAAE,EAAE,QAAQ,EAAE,SAAS,EAAE,CAAY,CAAC;KAC1E;IAAC,OAAO,GAAG,EAAE;QACZ,OAAO,CAAC,GAAG,CAAC,CAAC;KACd;YAAS;QACR,OAAO,CAAC,GAAG,CAAC,mBAAmB,EAAE,OAAO,CAAC,CAAC;KAC3C;AACH,CAAC","sourcesContent":["import fs from 'fs';\nimport fsPromises from 'fs/promises';\nimport path from 'path';\nimport { builtinModules, createRequire } from 'module';\nimport { fileURLToPath } from 'url';\nimport { NodeVM, VMError } from 'vm2';\nimport type { PackageJson } from '@ms-cloudpack/bundler-types';\nimport { findPackageRoot } from '@ms-cloudpack/path-utilities';\nimport { readJsonSync } from '@ms-cloudpack/json-utilities';\n\nconst require = createRequire(import.meta.url);\nconst filename = fileURLToPath(import.meta.url);\nconst dirname = path.dirname(filename);\nconst browserEnvSetup = path.join(path.dirname(dirname), 'browserEnvironment/index.cjs');\n\n/** Allow the sandbox to load these built-in modules */\n// ('events' and 'stream' export classes which other things extend and can't be proxied)\nconst allowedBuiltins = ['buffer', 'events', 'path', 'stream', 'url', 'util'];\n/** Empty mocks of all built-in modules that aren't allowed (to ensure that requires succeed) */\nconst mockBuiltins = Object.fromEntries(builtinModules.filter((m) => !allowedBuiltins.includes(m)).map((m) => [m, {}]));\n\n/** Mapping from sandbox root to VM */\nconst vms: Record<string, NodeVM> = {};\n\n/** Mapping from directory to sandbox root */\nconst sandboxRoots: Record<string, string> = {};\n/** Sandbox root for this file and other cloudpack-related files */\nlet cloudpackSandboxRoot = '';\n\n/** Reset `vms` and `sandboxRoots` for testing */\nexport function _clearSandboxCaches() {\n Object.keys(vms).forEach((k) => delete vms[k]);\n Object.keys(sandboxRoots).forEach((k) => delete sandboxRoots[k]);\n}\n\n/** Get `vms` state for testing */\nexport function _getSandboxVms() {\n return vms;\n}\n\n/**\n * Try to figure out a root directory where the sandbox should be allowed to require files from.\n * This prefers the git root if found, falling back to package root or parent directory.\n *\n * (This is very likely overly permissive and might be good to restrict in the future.)\n */\nfunction findSandboxRoot(filePath: string) {\n const root = path.parse(filePath).root;\n let dir: string | undefined = path.dirname(filePath);\n\n if (!sandboxRoots[dir]) {\n // Try to find a git root first\n while (dir !== root && !fs.existsSync(path.join(dir, '.git'))) {\n dir = path.dirname(dir);\n }\n\n if (dir === root) {\n // If there's a node_modules segment in the path, take the part before that. This covers two cases:\n // - The entry file's sandbox when running cloudpack in a dependency package folder within node_modules\n // - The cloudpack browser environment sandbox when using globally installed cloudpack\n const nodeModulesMatch = filePath.match(/^(.*?)[\\\\/]node_modules[\\\\/]/);\n if (nodeModulesMatch) {\n dir = nodeModulesMatch[1];\n } else {\n // Try to find a package root, or fall back to parent directory\n dir = findPackageRoot(filePath) || path.dirname(filePath);\n }\n }\n\n sandboxRoots[dir] = dir;\n }\n\n return sandboxRoots[dir];\n}\n\nfunction handleError(action: string, err: unknown, sandboxRoot: string) {\n const message = (err as Error).message || String(err);\n const stack = (err as Error).stack?.split(/\\r?\\n/g) || [];\n // instanceof checks don't work with errors from code run within the sandbox, but name is preserved\n const errorName = (err as Error).name;\n\n const newMessage = [`Error ${action}:`, message];\n\n if (stack.length && err instanceof VMError && err.message.includes('Cannot find module')) {\n newMessage.push(\n '',\n 'Ensure that this file exists on disk. If it exists, this may be a bug with the choice of `root` ' +\n '(allowed parent directories) settings in @ms-cloudpack/esm-stub-utilities runInSandbox.',\n `- Root for file being stubbed: ${sandboxRoot}`,\n `- Root for cloudpack files: ${cloudpackSandboxRoot}`,\n );\n\n // Find the actual line which caused the error\n const errorLines = stack.filter((line) => line.trim().startsWith('at') && !line.includes('vm2'));\n if (errorLines.length) {\n newMessage.push('', 'Code that may have required this module:', ...errorLines);\n }\n } else if (errorName === 'TypeError') {\n newMessage.push(\n '',\n 'If the code was referencing a built-in global or a property of a Node built-in module, ' +\n 'this error may be caused by a missing mock or other issue with the sandbox environment ' +\n 'configured in @ms-cloudpack/esm-stub-utilities runInSandbox.',\n );\n } else if (\n errorName === 'SyntaxError' &&\n (/Unexpected token '(import|export)'/.test(message) ||\n message.includes(`'import' and 'export' may appear only with`))\n ) {\n newMessage.push(\n '',\n \"It appears you're trying to load an ES module, which is not currently supported in the sandbox. \" +\n 'If this module is loaded at startup within a CommonJS file, please file an issue with cloudpack. ',\n );\n }\n\n if (stack.length) {\n newMessage.push('', 'Original stack:', ...stack.slice(1));\n }\n\n throw new Error(newMessage.join('\\n'));\n}\n\nfunction logMissingModule(params: { moduleName: string; parentDir: string; error: string; realParentDir?: string }) {\n const { moduleName, parentDir, error, realParentDir } = params;\n\n // First determine if moduleName is from an optional peer dependency\n let isOptionalPeerDep = false;\n const depName = moduleName.match(/^(@[\\w.-]+\\/)?[\\w.-]+/)?.[0];\n const parentPkgRoot = depName ? findPackageRoot(parentDir) : undefined;\n if (depName && parentPkgRoot) {\n // eslint-disable-next-line no-restricted-syntax -- must be synchronous\n const packageJson = readJsonSync<PackageJson>(path.join(parentPkgRoot, 'package.json'));\n isOptionalPeerDep = !!(\n packageJson?.peerDependencies?.[depName] && packageJson.peerDependenciesMeta?.[depName]?.optional\n );\n }\n\n // If the module is from an optional dep, it's not useful to warn\n if (!isOptionalPeerDep) {\n const realPathMsg = realParentDir ? ` (real path: ${realParentDir})` : '';\n console.warn(`runInSandbox failed to resolve \"${moduleName}\" from \"${parentDir}\"${realPathMsg}: ${error}`);\n }\n}\n\n/**\n * Run a CommonJS file within a sandboxed environment.\n * @param entryPath - Path to a CommonJS file to run in a sandbox (does not work with ESM files)\n * @returns The module's exports\n */\nexport async function runInSandbox(entryPath: string) {\n if (!path.isAbsolute(entryPath)) {\n throw new Error('Entry path must be absolute. Received: ' + entryPath);\n }\n\n if (!fs.existsSync(entryPath)) {\n throw new Error('Entry path does not exist: ' + entryPath);\n }\n\n // Allow code in the sandbox to require files under the requested file's package root,\n // or under its directory if it's not in a package.\n const sandboxRoot = findSandboxRoot(entryPath);\n\n if (!vms[sandboxRoot]) {\n if (!cloudpackSandboxRoot) {\n cloudpackSandboxRoot = findSandboxRoot(filename);\n }\n\n console.debug('esm-stub-utilities: Creating sandbox for ' + sandboxRoot);\n\n try {\n vms[sandboxRoot] = new NodeVM({\n // disable console logging instead of passing through to the host console\n console: 'off',\n // look for these import extensions (mjs is not included because this doesn't support loading ESM)\n sourceExtensions: ['js', 'cjs'],\n // use a commonjs module wrapper\n wrapper: 'commonjs',\n require: {\n // allow local and dependency modules to be required under here\n root: [cloudpackSandboxRoot, sandboxRoot],\n // load, compile, and require modules in the sandbox (instead of requiring in the host)\n context: 'sandbox',\n // allowed built-in modules\n builtin: allowedBuiltins,\n // allow loading \"external\" modules under the given roots\n external: true,\n // simulate the browser at startup (can throw errors)\n import: [browserEnvSetup],\n // fallback resolver if vm2's algorithm fails\n resolve: (moduleName: string, parentDir: string) => {\n // eslint-disable-next-line no-restricted-syntax\n const realParentDir = fs.realpathSync(parentDir);\n if (realParentDir === parentDir) {\n // Log a more informative error if this isn't a realpath issue (explained below).\n // This is clearer than the error message vm2 provides if the file isn't found.\n logMissingModule({ moduleName, parentDir, error: 'module not found' });\n return undefined;\n }\n\n try {\n // vm2 doesn't get the realpath of the parent directory before resolving,\n // which causes issues with certain install layouts (pnpm, yarn strict).\n // Try again using actual require.resolve with the realpath.\n return require.resolve(moduleName, { paths: [realParentDir] });\n } catch (err) {\n logMissingModule({ moduleName, parentDir, error: String(err), realParentDir });\n return undefined;\n }\n },\n // mock these modules so they can be successfully required\n mock: {\n ...mockBuiltins,\n // some modules reference these built-ins during their setup\n perf_hooks: {\n performance: { now: () => Date.now() },\n },\n tty: {\n isatty: () => false,\n },\n vm: {\n isContext: () => false,\n },\n },\n },\n env: {\n // prevent debug from accessing process.stderr\n DEBUG_COLORS: 0,\n },\n });\n } catch (err) {\n handleError(`initializing sandbox for ${sandboxRoot} (to create stub of ${entryPath})`, err, sandboxRoot);\n }\n }\n\n const onError = (err: unknown) => {\n handleError(`running ${entryPath} in sandbox (to create stub)`, err, sandboxRoot);\n };\n process.on('uncaughtException', onError);\n\n try {\n const cjsFile = await fsPromises.readFile(entryPath, 'utf8');\n return vms[sandboxRoot].run(cjsFile, { filename: entryPath }) as unknown;\n } catch (err) {\n onError(err);\n } finally {\n process.off('uncaughtException', onError);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"runInSandbox.js","sourceRoot":"","sources":["../src/runInSandbox.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,IAAI,CAAC;AACpB,OAAO,UAAU,MAAM,aAAa,CAAC;AACrC,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,EAAE,cAAc,EAAE,aAAa,EAAE,MAAM,QAAQ,CAAC;AACvD,OAAO,EAAE,aAAa,EAAE,MAAM,KAAK,CAAC;AACpC,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,KAAK,CAAC;AAEtC,OAAO,EAAE,eAAe,EAAE,MAAM,8BAA8B,CAAC;AAC/D,OAAO,EAAE,YAAY,EAAE,MAAM,8BAA8B,CAAC;AAE5D,MAAM,OAAO,GAAG,aAAa,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AAC/C,MAAM,QAAQ,GAAG,aAAa,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AAChD,MAAM,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC;AACvC,MAAM,eAAe,GAAG,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE,8BAA8B,CAAC,CAAC;AAEzF,uDAAuD;AACvD,wFAAwF;AACxF,MAAM,eAA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AY;wBACf,4DAA4D;wBAC5D,UAAU,EAAE;4BACV,WAAW,EAAE,EAAE,GAAG,EAAE,GAAG,EAAE,CAAC,IAAI,CAAC,GAAG,EAAE,EAAE;yBACvC;wBACD,GAAG,EAAE;4BACH,MAAM,EAAE,GAAG,EAAE,CAAC,KAAK;yBACpB;wBACD,EAAE,EAAE;4BACF,SAAS,EAAE,GAAG,EAAE,CAAC,KAAK;yBACvB;qBACF;iBACF;gBACD,GAAG,EAAE;oBACH,8CAA8C;oBAC9C,YAAY,EAAE,CAAC;iBAChB;aACF,CAAC,CAAC;SACJ;QAAC,OAAO,GAAG,EAAE;YACZ,WAAW,CAAC,4BAA4B,WAAW,uBAAuB,SAAS,GAAG,EAAE,GAAG,EAAE,WAAW,CAAC,CAAC;SAC3G;KACF;IAED,MAAM,OAAO,GAAG,CAAC,GAAY,EAAE,EAAE;QAC/B,WAAW,CAAC,WAAW,SAAS,8BAA8B,EAAE,GAAG,EAAE,WAAW,CAAC,CAAC;IACpF,CAAC,CAAC;IACF,OAAO,CAAC,EAAE,CAAC,mBAAmB,EAAE,OAAO,CAAC,CAAC;IAEzC,IAAI;QACF,MAAM,OAAO,GAAG,MAAM,UAAU,CAAC,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC,CAAC;QAC7D,OAAO,GAAG,CAAC,WAAW,CAAC,CAAC,GAAG,CAAC,OAAO,EAAE,EAAE,QAAQ,EAAE,SAAS,EAAE,CAAY,CAAC;KAC1E;IAAC,OAAO,GAAG,EAAE;QACZ,OAAO,CAAC,GAAG,CAAC,CAAC;KACd;YAAS;QACR,OAAO,CAAC,GAAG,CAAC,mBAAmB,EAAE,OAAO,CAAC,CAAC;KAC3C;AACH,CAAC","sourcesContent":["import fs from 'fs';\nimport fsPromises from 'fs/promises';\nimport path from 'path';\nimport { builtinModules, createRequire } from 'module';\nimport { fileURLToPath } from 'url';\nimport { NodeVM, VMError } from 'vm2';\nimport type { PackageJson } from '@ms-cloudpack/bundler-types';\nimport { findPackageRoot } from '@ms-cloudpack/path-utilities';\nimport { readJsonSync } from '@ms-cloudpack/json-utilities';\n\nconst require = createRequire(import.meta.url);\nconst filename = fileURLToPath(import.meta.url);\nconst dirname = path.dirname(filename);\nconst browserEnvSetup = path.join(path.dirname(dirname), 'browserEnvironment/index.cjs');\n\n/** Allow the sandbox to load these built-in modules */\n// ('events' and 'stream' export classes which other things extend and can't be proxied)\nconst allowedBuiltins = ['buffer', 'events', 'path', 'stream', 'url', 'util'];\n/** Empty mocks of all built-in modules that aren't allowed (to ensure that requires succeed) */\nconst mockBuiltins = Object.fromEntries(builtinModules.filter((m) => !allowedBuiltins.includes(m)).map((m) => [m, {}]));\n\n/** Mapping from sandbox root to VM */\nconst vms: Record<string, NodeVM> = {};\n\n/** Mapping from directory to sandbox root */\nconst sandboxRoots: Record<string, string> = {};\n/** Sandbox root for this file and other cloudpack-related files */\nlet cloudpackSandboxRoot = '';\n\n/** Reset `vms` and `sandboxRoots` for testing */\nexport function _clearSandboxCaches() {\n Object.keys(vms).forEach((k) => delete vms[k]);\n Object.keys(sandboxRoots).forEach((k) => delete sandboxRoots[k]);\n}\n\n/** Get `vms` state for testing */\nexport function _getSandboxVms() {\n return vms;\n}\n\n/**\n * Try to figure out a root directory where the sandbox should be allowed to require files from.\n * This prefers the git root if found, falling back to package root or parent directory.\n *\n * (This is very likely overly permissive and might be good to restrict in the future.)\n */\nfunction findSandboxRoot(filePath: string) {\n const root = path.parse(filePath).root;\n let dir: string | undefined = path.dirname(filePath);\n\n if (!sandboxRoots[dir]) {\n // Try to find a git root first\n while (dir !== root && !fs.existsSync(path.join(dir, '.git'))) {\n dir = path.dirname(dir);\n }\n\n if (dir === root) {\n // If there's a node_modules segment in the path, take the part before that. This covers two cases:\n // - The entry file's sandbox when running cloudpack in a dependency package folder within node_modules\n // - The cloudpack browser environment sandbox when using globally installed cloudpack\n const nodeModulesMatch = filePath.match(/^(.*?)[\\\\/]node_modules[\\\\/]/);\n if (nodeModulesMatch) {\n dir = nodeModulesMatch[1];\n } else {\n // Try to find a package root, or fall back to parent directory\n dir = findPackageRoot(filePath) || path.dirname(filePath);\n }\n }\n\n sandboxRoots[dir] = dir;\n }\n\n return sandboxRoots[dir];\n}\n\nfunction handleError(action: string, err: unknown, sandboxRoot: string) {\n const message = (err as Error).message || String(err);\n const stack = (err as Error).stack?.split(/\\r?\\n/g) || [];\n // instanceof checks don't work with errors from code run within the sandbox, but name is preserved\n const errorName = (err as Error).name;\n\n const newMessage = [`Error ${action}:`, message];\n\n if (stack.length && err instanceof VMError && err.message.includes('Cannot find module')) {\n newMessage.push(\n '',\n 'Ensure that this file exists on disk. If it exists, this may be a bug with the choice of `root` ' +\n '(allowed parent directories) settings in @ms-cloudpack/esm-stub-utilities runInSandbox.',\n `- Root for file being stubbed: ${sandboxRoot}`,\n `- Root for cloudpack files: ${cloudpackSandboxRoot}`,\n );\n\n // Find the actual line which caused the error\n const errorLines = stack.filter((line) => line.trim().startsWith('at') && !line.includes('vm2'));\n if (errorLines.length) {\n newMessage.push('', 'Code that may have required this module:', ...errorLines);\n }\n } else if (errorName === 'TypeError') {\n newMessage.push(\n '',\n 'If the code was referencing a built-in global or a property of a Node built-in module, ' +\n 'this error may be caused by a missing mock or other issue with the sandbox environment ' +\n 'configured in @ms-cloudpack/esm-stub-utilities runInSandbox.',\n );\n } else if (\n errorName === 'SyntaxError' &&\n (/Unexpected token '(import|export)'/.test(message) ||\n message.includes(`'import' and 'export' may appear only with`))\n ) {\n newMessage.push(\n '',\n \"It appears you're trying to load an ES module, which is not currently supported in the sandbox. \" +\n 'If this module is loaded at startup within a CommonJS file, please file an issue with cloudpack. ',\n );\n }\n\n if (stack.length) {\n newMessage.push('', 'Original stack:', ...stack.slice(1));\n }\n\n throw new Error(newMessage.join('\\n'));\n}\n\nfunction logMissingModule(params: { moduleName: string; parentDir: string; error: string; realParentDir?: string }) {\n const { moduleName, parentDir, error, realParentDir } = params;\n\n // First determine if moduleName is from an optional peer dependency\n let isOptionalPeerDep = false;\n const depName = moduleName.match(/^(@[\\w.-]+\\/)?[\\w.-]+/)?.[0];\n const parentPkgRoot = depName ? findPackageRoot(parentDir) : undefined;\n if (depName && parentPkgRoot) {\n // eslint-disable-next-line @ms-cloudpack/internal/no-sync-filesystem\n const packageJson = readJsonSync<PackageJson>(path.join(parentPkgRoot, 'package.json'));\n isOptionalPeerDep = !!(\n packageJson?.peerDependencies?.[depName] && packageJson.peerDependenciesMeta?.[depName]?.optional\n );\n }\n\n // If the module is from an optional dep, it's not useful to warn\n if (!isOptionalPeerDep) {\n const realPathMsg = realParentDir ? ` (real path: ${realParentDir})` : '';\n console.warn(`runInSandbox failed to resolve \"${moduleName}\" from \"${parentDir}\"${realPathMsg}: ${error}`);\n }\n}\n\n/**\n * Run a CommonJS file within a sandboxed environment.\n * @param entryPath - Path to a CommonJS file to run in a sandbox (does not work with ESM files)\n * @returns The module's exports\n */\nexport async function runInSandbox(entryPath: string) {\n if (!path.isAbsolute(entryPath)) {\n throw new Error('Entry path must be absolute. Received: ' + entryPath);\n }\n\n if (!fs.existsSync(entryPath)) {\n throw new Error('Entry path does not exist: ' + entryPath);\n }\n\n // Allow code in the sandbox to require files under the requested file's package root,\n // or under its directory if it's not in a package.\n const sandboxRoot = findSandboxRoot(entryPath);\n\n if (!vms[sandboxRoot]) {\n if (!cloudpackSandboxRoot) {\n cloudpackSandboxRoot = findSandboxRoot(filename);\n }\n\n console.debug('esm-stub-utilities: Creating sandbox for ' + sandboxRoot);\n\n try {\n vms[sandboxRoot] = new NodeVM({\n // disable console logging instead of passing through to the host console\n console: 'off',\n // look for these import extensions (mjs is not included because this doesn't support loading ESM)\n sourceExtensions: ['js', 'cjs'],\n // use a commonjs module wrapper\n wrapper: 'commonjs',\n require: {\n // allow local and dependency modules to be required under here\n root: [cloudpackSandboxRoot, sandboxRoot],\n // load, compile, and require modules in the sandbox (instead of requiring in the host)\n context: 'sandbox',\n // allowed built-in modules\n builtin: allowedBuiltins,\n // allow loading \"external\" modules under the given roots\n external: true,\n // simulate the browser at startup (can throw errors)\n import: [browserEnvSetup],\n // fallback resolver if vm2's algorithm fails\n resolve: (moduleName: string, parentDir: string) => {\n // eslint-disable-next-line @ms-cloudpack/internal/no-sync-filesystem\n const realParentDir = fs.realpathSync(parentDir);\n if (realParentDir === parentDir) {\n // Log a more informative error if this isn't a realpath issue (explained below).\n // This is clearer than the error message vm2 provides if the file isn't found.\n logMissingModule({ moduleName, parentDir, error: 'module not found' });\n return undefined;\n }\n\n try {\n // vm2 doesn't get the realpath of the parent directory before resolving,\n // which causes issues with certain install layouts (pnpm, yarn strict).\n // Try again using actual require.resolve with the realpath.\n return require.resolve(moduleName, { paths: [realParentDir] });\n } catch (err) {\n logMissingModule({ moduleName, parentDir, error: String(err), realParentDir });\n return undefined;\n }\n },\n // mock these modules so they can be successfully required\n mock: {\n ...mockBuiltins,\n // some modules reference these built-ins during their setup\n perf_hooks: {\n performance: { now: () => Date.now() },\n },\n tty: {\n isatty: () => false,\n },\n vm: {\n isContext: () => false,\n },\n },\n },\n env: {\n // prevent debug from accessing process.stderr\n DEBUG_COLORS: 0,\n },\n });\n } catch (err) {\n handleError(`initializing sandbox for ${sandboxRoot} (to create stub of ${entryPath})`, err, sandboxRoot);\n }\n }\n\n const onError = (err: unknown) => {\n handleError(`running ${entryPath} in sandbox (to create stub)`, err, sandboxRoot);\n };\n process.on('uncaughtException', onError);\n\n try {\n const cjsFile = await fsPromises.readFile(entryPath, 'utf8');\n return vms[sandboxRoot].run(cjsFile, { filename: entryPath }) as unknown;\n } catch (err) {\n onError(err);\n } finally {\n process.off('uncaughtException', onError);\n }\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ms-cloudpack/esm-stub-utilities",
|
|
3
|
-
"version": "0.6.
|
|
3
|
+
"version": "0.6.26",
|
|
4
4
|
"description": "Generates ESM stubs for CommonJS entry files.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -14,13 +14,13 @@
|
|
|
14
14
|
},
|
|
15
15
|
"dependencies": {
|
|
16
16
|
"@ms-cloudpack/json-utilities": "^0.0.7",
|
|
17
|
-
"@ms-cloudpack/path-utilities": "^2.3.
|
|
18
|
-
"@ms-cloudpack/path-string-parsing": "^1.0
|
|
17
|
+
"@ms-cloudpack/path-utilities": "^2.3.4",
|
|
18
|
+
"@ms-cloudpack/path-string-parsing": "^1.1.0",
|
|
19
19
|
"atob": "^2.1.2",
|
|
20
20
|
"btoa": "^1.2.1",
|
|
21
21
|
"jsdom-global": "^3.0.2",
|
|
22
22
|
"jsdom": "^22.0.0",
|
|
23
|
-
"regenerator-runtime": "^0.
|
|
23
|
+
"regenerator-runtime": "^0.14.0",
|
|
24
24
|
"vm2": "^3.9.13"
|
|
25
25
|
},
|
|
26
26
|
"devDependencies": {
|