@wyw-in-js/transform 1.0.6 → 1.0.8

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.
Files changed (98) hide show
  1. package/esm/cache.js +160 -12
  2. package/esm/cache.js.map +1 -1
  3. package/esm/debug/fileReporter.js.map +1 -1
  4. package/esm/module.js +59 -5
  5. package/esm/module.js.map +1 -1
  6. package/esm/plugins/shaker.js +152 -13
  7. package/esm/plugins/shaker.js.map +1 -1
  8. package/esm/shaker.js +51 -23
  9. package/esm/shaker.js.map +1 -1
  10. package/esm/transform/BaseEntrypoint.js +3 -1
  11. package/esm/transform/BaseEntrypoint.js.map +1 -1
  12. package/esm/transform/Entrypoint.js +68 -20
  13. package/esm/transform/Entrypoint.js.map +1 -1
  14. package/esm/transform/EvaluatedEntrypoint.js.map +1 -1
  15. package/esm/transform/actions/BaseAction.js +2 -1
  16. package/esm/transform/actions/BaseAction.js.map +1 -1
  17. package/esm/transform/actions/actionRunner.js +2 -2
  18. package/esm/transform/actions/actionRunner.js.map +1 -1
  19. package/esm/transform/barrelManifest.js +291 -0
  20. package/esm/transform/barrelManifest.js.map +1 -0
  21. package/esm/transform/generators/getExports.js +5 -0
  22. package/esm/transform/generators/getExports.js.map +1 -1
  23. package/esm/transform/generators/processEntrypoint.js +31 -1
  24. package/esm/transform/generators/processEntrypoint.js.map +1 -1
  25. package/esm/transform/generators/resolveImports.js +29 -5
  26. package/esm/transform/generators/resolveImports.js.map +1 -1
  27. package/esm/transform/generators/rewriteBarrelImports.js +733 -0
  28. package/esm/transform/generators/rewriteBarrelImports.js.map +1 -0
  29. package/esm/transform/generators/transform.js +154 -21
  30. package/esm/transform/generators/transform.js.map +1 -1
  31. package/esm/transform/types.js.map +1 -1
  32. package/esm/transform.js +45 -23
  33. package/esm/transform.js.map +1 -1
  34. package/esm/utils/collectTemplateDependencies.js +9 -0
  35. package/esm/utils/collectTemplateDependencies.js.map +1 -1
  36. package/lib/cache.js +163 -12
  37. package/lib/cache.js.map +1 -1
  38. package/lib/debug/fileReporter.js.map +1 -1
  39. package/lib/module.js +61 -7
  40. package/lib/module.js.map +1 -1
  41. package/lib/plugins/shaker.js +152 -13
  42. package/lib/plugins/shaker.js.map +1 -1
  43. package/lib/shaker.js +58 -26
  44. package/lib/shaker.js.map +1 -1
  45. package/lib/transform/BaseEntrypoint.js +3 -1
  46. package/lib/transform/BaseEntrypoint.js.map +1 -1
  47. package/lib/transform/Entrypoint.js +69 -20
  48. package/lib/transform/Entrypoint.js.map +1 -1
  49. package/lib/transform/EvaluatedEntrypoint.js.map +1 -1
  50. package/lib/transform/actions/BaseAction.js +2 -1
  51. package/lib/transform/actions/BaseAction.js.map +1 -1
  52. package/lib/transform/actions/actionRunner.js +2 -2
  53. package/lib/transform/actions/actionRunner.js.map +1 -1
  54. package/lib/transform/barrelManifest.js +300 -0
  55. package/lib/transform/barrelManifest.js.map +1 -0
  56. package/lib/transform/generators/getExports.js +5 -0
  57. package/lib/transform/generators/getExports.js.map +1 -1
  58. package/lib/transform/generators/processEntrypoint.js +31 -1
  59. package/lib/transform/generators/processEntrypoint.js.map +1 -1
  60. package/lib/transform/generators/resolveImports.js +29 -5
  61. package/lib/transform/generators/resolveImports.js.map +1 -1
  62. package/lib/transform/generators/rewriteBarrelImports.js +743 -0
  63. package/lib/transform/generators/rewriteBarrelImports.js.map +1 -0
  64. package/lib/transform/generators/transform.js +158 -22
  65. package/lib/transform/generators/transform.js.map +1 -1
  66. package/lib/transform/types.js.map +1 -1
  67. package/lib/transform.js +45 -23
  68. package/lib/transform.js.map +1 -1
  69. package/lib/utils/collectTemplateDependencies.js +9 -0
  70. package/lib/utils/collectTemplateDependencies.js.map +1 -1
  71. package/package.json +8 -4
  72. package/types/cache.d.ts +23 -2
  73. package/types/cache.js +170 -10
  74. package/types/debug/fileReporter.d.ts +1 -0
  75. package/types/module.d.ts +3 -0
  76. package/types/module.js +65 -5
  77. package/types/plugins/shaker.js +161 -16
  78. package/types/shaker.d.ts +10 -1
  79. package/types/shaker.js +56 -28
  80. package/types/transform/BaseEntrypoint.d.ts +3 -1
  81. package/types/transform/BaseEntrypoint.js +5 -1
  82. package/types/transform/Entrypoint.d.ts +10 -1
  83. package/types/transform/Entrypoint.js +81 -23
  84. package/types/transform/EvaluatedEntrypoint.d.ts +2 -0
  85. package/types/transform/actions/BaseAction.d.ts +2 -1
  86. package/types/transform/actions/BaseAction.js +3 -1
  87. package/types/transform/actions/actionRunner.js +2 -2
  88. package/types/transform/barrelManifest.d.ts +42 -0
  89. package/types/transform/barrelManifest.js +300 -0
  90. package/types/transform/generators/getExports.js +5 -0
  91. package/types/transform/generators/processEntrypoint.js +29 -1
  92. package/types/transform/generators/resolveImports.js +29 -5
  93. package/types/transform/generators/rewriteBarrelImports.d.ts +15 -0
  94. package/types/transform/generators/rewriteBarrelImports.js +815 -0
  95. package/types/transform/generators/transform.js +148 -19
  96. package/types/transform/types.d.ts +3 -0
  97. package/types/transform.js +47 -23
  98. package/types/utils/collectTemplateDependencies.js +9 -0
package/esm/module.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"module.js","names":["fs","NativeModule","path","vm","invariant","isFeatureEnabled","Entrypoint","getStack","isSuperSet","mergeOnly","isUnprocessedEntrypointError","applyImportOverrideToOnly","getImportOverride","resolveMockSpecifier","toImportKey","parseRequest","stripQueryAndHash","createVmContext","DefaultModuleImplementation","builtins","assert","buffer","child_process","cluster","console","constants","crypto","dgram","dns","domain","events","http","https","module","net","os","punycode","process","querystring","readline","repl","stream","string_decoder","sys","timers","tls","tty","url","util","zlib","VITE_VIRTUAL_PREFIX","REACT_REFRESH_VIRTUAL_ID","reactRefreshRuntime","createSignatureFunctionForTransform","NOOP","browserOnlyEvalHintTriggers","getBrowserOnlyEvalHint","error","message","Error","String","looksLikeBrowserOnly","some","trigger","includes","join","warnedUnknownImportsByServices","WeakMap","emitWarning","services","warn","getWarnedUnknownImports","cached","get","created","Set","set","getUncached","test","cachedSet","split","has","filter","t","resolve","id","resolved","resolveDependency","defaultImportLoaders","raw","Module","callstack","isEvaluated","require","Object","assign","dependencies","push","debug","startsWith","dependency","isAbsolute","source","loaded","loadByImportLoaders","handled","value","entrypoint","getEntrypoint","only","evaluated","evaluatedOnly","exports","m","createChild","evaluate","ensure","bind","entrypointRef","constructor","parentModule","moduleImpl","cache","options","pluginOptions","features","name","WeakRef","idx","filename","log","extend","parentIsIgnored","ignored","extensions","deref","assertTransformed","evaluatedCreated","supersededWith","add","createEvaluated","transformedCode","JSON","parse","context","teardown","__wyw_dynamic_import","__dirname","dirname","overrideContext","script","Script","runInContext","e","EvalError","baseMessage","hint","strippedFilename","extension","extname","newEntrypoint","readFileSync","stack","uncachedExports","reprocessOnly","evaluatedExports","length","code","createRoot","getDependency","Promise","_extensions","added","forEach","ext","strippedId","_resolveFilename","paths","_nodeModulePaths","isFileSpecifier","endsWith","existsSync","slice","root","keyInfo","override","importOverrides","key","policy","unknown","mock","shouldWarn","finalResolved","importer","errorMessage","map","item","Boolean","warnedUnknownImports","stringify","request","importLoaders","undefined","query","hash","params","URLSearchParams","matchedKey","Array","from","keys","find","loader","importerDir","toUrl","relative","replace","posix","sep","readFile"],"sources":["../src/module.ts"],"sourcesContent":["/**\n * This is a custom implementation for the module system for evaluating code,\n * used for resolving values for dependencies interpolated in `css` or `styled`.\n *\n * This serves 2 purposes:\n * - Avoid leakage from evaluated code to module cache in current context, e.g. `babel-register`\n * - Allow us to invalidate the module cache without affecting other stuff, necessary for rebuilds\n *\n * We also use it to transpile the code with Babel by default.\n * We also store source maps for it to provide correct error stacktraces.\n *\n */\n\nimport fs from 'fs';\nimport NativeModule from 'module';\nimport path from 'path';\nimport vm from 'vm';\n\nimport { invariant } from 'ts-invariant';\n\nimport {\n isFeatureEnabled,\n type Debugger,\n type ImportLoaderContext,\n type ImportLoaders,\n} from '@wyw-in-js/shared';\n\nimport './utils/dispose-polyfill';\nimport type { TransformCacheCollection } from './cache';\nimport { Entrypoint } from './transform/Entrypoint';\nimport {\n getStack,\n isSuperSet,\n mergeOnly,\n} from './transform/Entrypoint.helpers';\nimport type { IEntrypointDependency } from './transform/Entrypoint.types';\nimport type { IEvaluatedEntrypoint } from './transform/EvaluatedEntrypoint';\nimport { isUnprocessedEntrypointError } from './transform/actions/UnprocessedEntrypointError';\nimport type { Services } from './transform/types';\nimport {\n applyImportOverrideToOnly,\n getImportOverride,\n resolveMockSpecifier,\n toImportKey,\n} from './utils/importOverrides';\nimport { parseRequest, stripQueryAndHash } from './utils/parseRequest';\nimport { createVmContext } from './vm/createVmContext';\n\ntype HiddenModuleMembers = {\n _extensions: Record<string, () => void>;\n _resolveFilename: (\n id: string,\n options: { filename: string; id: string; paths: string[] }\n ) => string;\n _nodeModulePaths(filename: string): string[];\n};\n\nexport const DefaultModuleImplementation = NativeModule as typeof NativeModule &\n HiddenModuleMembers;\n\n// Supported node builtins based on the modules polyfilled by webpack\n// `true` means module is polyfilled, `false` means module is empty\nconst builtins = {\n assert: true,\n buffer: true,\n child_process: false,\n cluster: false,\n console: true,\n constants: true,\n crypto: true,\n dgram: false,\n dns: false,\n domain: true,\n events: true,\n fs: false,\n http: true,\n https: true,\n module: false,\n net: false,\n os: true,\n path: true,\n punycode: true,\n process: true,\n querystring: true,\n readline: false,\n repl: false,\n stream: true,\n string_decoder: true,\n sys: true,\n timers: true,\n tls: false,\n tty: true,\n url: true,\n util: true,\n vm: true,\n zlib: true,\n};\n\nconst VITE_VIRTUAL_PREFIX = '/@';\nconst REACT_REFRESH_VIRTUAL_ID = '/@react-refresh';\nconst reactRefreshRuntime = {\n createSignatureFunctionForTransform: () => () => {},\n};\n\nconst NOOP = () => {};\n\nconst browserOnlyEvalHintTriggers = [\n 'window is not defined',\n \"evaluating 'window\",\n 'document is not defined',\n \"evaluating 'document\",\n 'navigator is not defined',\n \"evaluating 'navigator\",\n 'self is not defined',\n \"evaluating 'self\",\n];\n\nconst getBrowserOnlyEvalHint = (error: unknown): string | null => {\n const message = error instanceof Error ? error.message : String(error);\n const looksLikeBrowserOnly = browserOnlyEvalHintTriggers.some((trigger) =>\n message.includes(trigger)\n );\n if (!looksLikeBrowserOnly) return null;\n\n return [\n '',\n '[wyw-in-js] Evaluation hint:',\n 'This usually means browser-only code ran during build-time evaluation.',\n 'Move browser-only initialization out of evaluated modules, or mock the import via `importOverrides`.',\n \"Example: importOverrides: { 'msw/browser': { mock: './src/__mocks__/msw-browser.js' } }\",\n ].join('\\n');\n};\n\nconst warnedUnknownImportsByServices = new WeakMap<Services, Set<string>>();\n\nfunction emitWarning(services: Services, message: string) {\n if (services.emitWarning) {\n services.emitWarning(message);\n return;\n }\n\n // eslint-disable-next-line no-console\n console.warn(message);\n}\n\nfunction getWarnedUnknownImports(services: Services): Set<string> {\n const cached = warnedUnknownImportsByServices.get(services);\n if (cached) {\n return cached;\n }\n\n const created = new Set<string>();\n warnedUnknownImportsByServices.set(services, created);\n return created;\n}\n\nfunction getUncached(cached: string | string[], test: string[]): string[] {\n const cachedSet = new Set(\n typeof cached === 'string' ? cached.split(',') : cached\n );\n\n if (cachedSet.has('*')) {\n return [];\n }\n\n return test.filter((t) => !cachedSet.has(t));\n}\n\nfunction resolve(\n this: { resolveDependency: (id: string) => IEntrypointDependency },\n id: string\n): string {\n const { resolved } = this.resolveDependency(id);\n invariant(resolved, `Unable to resolve \"${id}\"`);\n return resolved;\n}\n\nconst defaultImportLoaders: ImportLoaders = {\n raw: 'raw',\n url: 'url',\n};\n\nexport class Module {\n public readonly callstack: string[] = [];\n\n public readonly debug: Debugger;\n\n public readonly dependencies: string[];\n\n public readonly extensions: string[];\n\n public readonly filename: string;\n\n public id: string;\n\n public readonly idx: string;\n\n public readonly ignored: boolean;\n\n public isEvaluated: boolean = false;\n\n public readonly parentIsIgnored: boolean;\n\n public require: {\n (id: string): unknown;\n ensure: () => void;\n resolve: (id: string) => string;\n } = Object.assign(\n (id: string) => {\n if (id === REACT_REFRESH_VIRTUAL_ID) {\n this.dependencies.push(id);\n this.debug('require', `vite virtual '${id}'`);\n return reactRefreshRuntime;\n }\n\n if (id.startsWith(VITE_VIRTUAL_PREFIX)) {\n this.dependencies.push(id);\n this.debug('require', `vite virtual '${id}'`);\n return {};\n }\n\n if (id in builtins) {\n // The module is in the allowed list of builtin node modules\n // Ideally we should prevent importing them, but webpack polyfills some\n // So we check for the list of polyfills to determine which ones to support\n if (builtins[id as keyof typeof builtins]) {\n this.debug('require', `builtin '${id}'`);\n return require(id);\n }\n\n return null;\n }\n\n // Resolve module id (and filename) relatively to parent module\n const dependency = this.resolveDependency(id);\n if (dependency.resolved === id && !path.isAbsolute(id)) {\n // The module is a builtin node modules, but not in the allowed list\n throw new Error(\n `Unable to import \"${id}\". Importing Node builtins is not supported in the sandbox.`\n );\n }\n\n invariant(\n dependency.resolved,\n `Dependency ${dependency.source} cannot be resolved`\n );\n\n const loaded = this.loadByImportLoaders(id, dependency.resolved);\n if (loaded.handled) {\n this.dependencies.push(id);\n this.debug('require', `${id} -> ${dependency.resolved} (loader)`);\n return loaded.value;\n }\n\n this.dependencies.push(id);\n\n this.debug('require', `${id} -> ${dependency.resolved}`);\n\n const entrypoint = this.getEntrypoint(\n dependency.resolved,\n dependency.only,\n this.debug\n );\n\n if (entrypoint === null) {\n return dependency.resolved;\n }\n\n if (\n entrypoint.evaluated ||\n isSuperSet(entrypoint.evaluatedOnly, dependency.only)\n ) {\n return entrypoint.exports;\n }\n\n const m = this.createChild(entrypoint);\n m.evaluate();\n\n return entrypoint.exports;\n },\n {\n ensure: NOOP,\n resolve: resolve.bind(this),\n }\n );\n\n public resolve = resolve.bind(this);\n\n private cache: TransformCacheCollection;\n\n #entrypointRef: WeakRef<Entrypoint> | Entrypoint;\n\n constructor(\n private services: Services,\n entrypoint: Entrypoint,\n parentModule?: Module,\n private moduleImpl: HiddenModuleMembers = DefaultModuleImplementation\n ) {\n this.cache = services.cache;\n this.#entrypointRef = isFeatureEnabled(\n services.options.pluginOptions.features,\n 'useWeakRefInEval',\n entrypoint.name\n )\n ? new WeakRef(entrypoint)\n : entrypoint;\n this.idx = entrypoint.idx;\n this.id = entrypoint.name;\n this.filename = entrypoint.name;\n this.dependencies = [];\n this.debug = entrypoint.log.extend('module');\n this.parentIsIgnored = parentModule?.ignored ?? false;\n this.ignored = entrypoint.ignored ?? this.parentIsIgnored;\n\n if (parentModule) {\n this.callstack = [entrypoint.name, ...parentModule.callstack];\n } else {\n this.callstack = [entrypoint.name];\n }\n\n this.extensions = services.options.pluginOptions.extensions;\n\n this.debug('init', entrypoint.name);\n }\n\n public get exports() {\n return this.entrypoint.exports;\n }\n\n public set exports(value) {\n this.entrypoint.exports = value;\n\n this.debug('the whole exports was overridden with %O', value);\n }\n\n protected get entrypoint(): Entrypoint {\n const entrypoint =\n this.#entrypointRef instanceof WeakRef\n ? this.#entrypointRef.deref()\n : this.#entrypointRef;\n invariant(entrypoint, `Module ${this.idx} is disposed`);\n return entrypoint;\n }\n\n evaluate(): void {\n const { entrypoint } = this;\n entrypoint.assertTransformed();\n\n const cached = this.cache.get('entrypoints', entrypoint.name)!;\n let evaluatedCreated = false;\n if (!entrypoint.supersededWith) {\n this.cache.add(\n 'entrypoints',\n entrypoint.name,\n entrypoint.createEvaluated()\n );\n evaluatedCreated = true;\n }\n\n const { transformedCode: source } = entrypoint;\n const { pluginOptions } = this.services.options;\n\n if (!source) {\n this.debug(`evaluate`, 'there is nothing to evaluate');\n return;\n }\n\n if (this.isEvaluated) {\n this.debug('evaluate', `is already evaluated`);\n return;\n }\n\n this.debug('evaluate');\n this.debug.extend('source')('%s', source);\n\n this.isEvaluated = true;\n\n const filename = stripQueryAndHash(this.filename);\n\n if (/\\.json$/.test(filename)) {\n // For JSON files, parse it to a JS object similar to Node\n this.exports = JSON.parse(source);\n return;\n }\n\n const { context, teardown } = createVmContext(\n filename,\n pluginOptions.features,\n {\n module: this,\n exports: entrypoint.exports,\n require: this.require,\n __wyw_dynamic_import: async (id: unknown) => this.require(String(id)),\n __dirname: path.dirname(filename),\n },\n pluginOptions.overrideContext\n );\n\n try {\n const script = new vm.Script(\n `(function (exports) { ${source}\\n})(exports);`,\n {\n filename,\n }\n );\n\n script.runInContext(context);\n } catch (e) {\n this.isEvaluated = false;\n if (evaluatedCreated) {\n this.cache.add('entrypoints', entrypoint.name, cached);\n }\n\n if (isUnprocessedEntrypointError(e)) {\n // It will be handled by evalFile scenario\n throw e;\n }\n\n if (e instanceof EvalError) {\n this.debug('%O', e);\n\n throw e;\n }\n\n this.debug('%O\\n%O', e, this.callstack);\n const baseMessage = `${(e as Error).message} in${this.callstack.join(\n '\\n| '\n )}\\n`;\n const hint = getBrowserOnlyEvalHint(e);\n\n throw new EvalError(hint ? `${baseMessage}${hint}\\n` : baseMessage);\n } finally {\n teardown();\n }\n }\n\n getEntrypoint(\n filename: string,\n only: string[],\n log: Debugger\n ): Entrypoint | IEvaluatedEntrypoint | null {\n const strippedFilename = stripQueryAndHash(filename);\n const extension = path.extname(strippedFilename);\n if (extension !== '.json' && !this.extensions.includes(extension)) {\n return null;\n }\n\n const entrypoint = this.cache.get('entrypoints', filename);\n if (entrypoint && isSuperSet(entrypoint.evaluatedOnly ?? [], only)) {\n log('✅ file has been already evaluated');\n return entrypoint;\n }\n\n if (entrypoint?.ignored) {\n log(\n '✅ file has been ignored during prepare stage. Original code will be used'\n );\n return entrypoint;\n }\n\n if (this.ignored) {\n log(\n '✅ one of the parent files has been ignored during prepare stage. Original code will be used'\n );\n\n const newEntrypoint = this.entrypoint.createChild(\n filename,\n ['*'],\n fs.readFileSync(strippedFilename, 'utf-8')\n );\n\n if (newEntrypoint === 'loop') {\n const stack = getStack(this.entrypoint);\n throw new Error(\n `Circular dependency detected: ${stack.join(' -> ')} -> ${filename}`\n );\n }\n\n return newEntrypoint;\n }\n\n let uncachedExports: string[] | null = null;\n let reprocessOnly: string[] = only;\n // Requested file can be already prepared for evaluation on the stage 1\n if (only && entrypoint) {\n const evaluatedExports =\n entrypoint.evaluatedOnly?.length !== 0\n ? entrypoint.evaluatedOnly\n : entrypoint.only ?? [];\n uncachedExports = getUncached(evaluatedExports, only);\n if (uncachedExports.length === 0) {\n log('✅ ready for evaluation');\n return entrypoint;\n }\n\n if (entrypoint.evaluatedOnly?.length) {\n reprocessOnly = mergeOnly(evaluatedExports, only);\n }\n\n log(\n '❌ file has been processed during prepare stage but %o is not evaluated yet (evaluated: %o)',\n uncachedExports,\n evaluatedExports\n );\n } else {\n log('❌ file has not been processed during prepare stage');\n }\n\n // If code wasn't extracted from cache, it indicates that we were unable\n // to process some of the imports on stage1. Let's try to reprocess.\n const code = fs.readFileSync(strippedFilename, 'utf-8');\n const newEntrypoint = Entrypoint.createRoot(\n this.services,\n filename,\n reprocessOnly,\n code\n );\n\n if (newEntrypoint.evaluated) {\n log('✅ file has been already evaluated');\n return newEntrypoint;\n }\n\n if (newEntrypoint.ignored) {\n log(\n '✅ file has been ignored during prepare stage. Original code will be used'\n );\n return newEntrypoint;\n }\n\n return newEntrypoint;\n }\n\n resolveDependency = (id: string): IEntrypointDependency => {\n const cached = this.entrypoint.getDependency(id);\n invariant(!(cached instanceof Promise), 'Dependency is not resolved yet');\n\n if (cached) {\n return cached;\n }\n\n if (!this.ignored) {\n this.debug(\n '❌ import has not been resolved during prepare stage. Fallback to Node.js resolver'\n );\n }\n\n const extensions = this.moduleImpl._extensions;\n const added: string[] = [];\n\n try {\n // Check for supported extensions\n this.extensions.forEach((ext) => {\n if (ext in extensions) {\n return;\n }\n\n // When an extension is not supported, add it\n // And keep track of it to clean it up after resolving\n // Use noop for the transform function since we handle it\n extensions[ext] = NOOP;\n added.push(ext);\n });\n\n const { filename } = this;\n const strippedId = stripQueryAndHash(id);\n\n let resolved = this.moduleImpl._resolveFilename(strippedId, {\n id: filename,\n filename,\n paths: this.moduleImpl._nodeModulePaths(path.dirname(filename)),\n });\n\n const isFileSpecifier =\n strippedId.startsWith('.') || path.isAbsolute(strippedId);\n\n if (\n isFileSpecifier &&\n path.extname(strippedId) === '' &&\n resolved.endsWith('.cjs') &&\n fs.existsSync(`${resolved.slice(0, -4)}.js`)\n ) {\n // When both `.cjs` and `.js` exist for an extensionless specifier, the\n // resolver may pick `.cjs` depending on the environment/extensions.\n // Prefer `.js` to keep resolved paths stable (e.g. importOverrides keys).\n resolved = `${resolved.slice(0, -4)}.js`;\n }\n\n const { root } = this.services.options;\n const keyInfo = toImportKey({\n source: id,\n resolved,\n root,\n });\n\n const override = getImportOverride(\n this.services.options.pluginOptions.importOverrides,\n keyInfo.key\n );\n\n const policy = override?.unknown ?? (override?.mock ? 'allow' : 'warn');\n const shouldWarn = !this.ignored && policy === 'warn';\n\n let finalResolved = resolved;\n if (override?.mock) {\n try {\n finalResolved = resolveMockSpecifier({\n mock: override.mock,\n importer: filename,\n root,\n stack: this.callstack,\n });\n } catch (e) {\n const errorMessage = String((e as Error)?.message ?? e);\n throw new Error(\n `[wyw-in-js] Failed to resolve import mock for \"${keyInfo.key}\" (${id} from ${filename}): ${errorMessage}`\n );\n }\n }\n\n if (policy === 'error') {\n throw new Error(\n [\n `[wyw-in-js] Unknown import reached during eval (Node resolver fallback)`,\n ``,\n `importer: ${filename}`,\n `source: ${id}`,\n `resolved: ${resolved}`,\n override?.mock\n ? `mock: ${override.mock} -> ${finalResolved}`\n : ``,\n ``,\n `callstack:`,\n ...this.callstack.map((item) => ` ${item}`),\n ``,\n `config key: ${keyInfo.key}`,\n ]\n .filter(Boolean)\n .join('\\n')\n );\n }\n\n const warnedUnknownImports = getWarnedUnknownImports(this.services);\n\n if (shouldWarn && !warnedUnknownImports.has(keyInfo.key)) {\n warnedUnknownImports.add(keyInfo.key);\n emitWarning(\n this.services,\n [\n `[wyw-in-js] Unknown import reached during eval (Node resolver fallback)`,\n ``,\n `importer: ${filename}`,\n `source: ${id}`,\n `resolved: ${resolved}`,\n override?.mock\n ? `mock: ${override.mock} -> ${finalResolved}`\n : ``,\n ``,\n `callstack:`,\n ...this.callstack.map((item) => ` ${item}`),\n ``,\n `config key: ${keyInfo.key}`,\n `hint: add { importOverrides: { ${JSON.stringify(\n keyInfo.key\n )}: { unknown: 'allow' } } } to silence warnings, or use { mock } / { noShake: true } overrides.`,\n ]\n .filter(Boolean)\n .join('\\n')\n );\n }\n\n return {\n source: id,\n only: applyImportOverrideToOnly(['*'], override),\n resolved: finalResolved,\n };\n } finally {\n // Cleanup the extensions we added to restore previous behaviour\n added.forEach((ext) => delete extensions[ext]);\n }\n };\n\n protected createChild(entrypoint: Entrypoint): Module {\n return new Module(this.services, entrypoint, this, this.moduleImpl);\n }\n\n private loadByImportLoaders(\n request: string,\n resolved: string\n ): { handled: boolean; value: unknown } {\n const { pluginOptions } = this.services.options;\n const importLoaders =\n pluginOptions.importLoaders === undefined\n ? defaultImportLoaders\n : { ...defaultImportLoaders, ...pluginOptions.importLoaders };\n\n const { query, hash } = parseRequest(request);\n if (!query) return { handled: false, value: undefined };\n\n const params = new URLSearchParams(query);\n const matchedKey = Array.from(params.keys()).find(\n (key) => importLoaders[key] !== undefined && importLoaders[key] !== false\n );\n\n if (!matchedKey) return { handled: false, value: undefined };\n\n const loader = importLoaders[matchedKey];\n\n const filename = stripQueryAndHash(resolved);\n const importer = stripQueryAndHash(this.filename);\n const importerDir = path.dirname(importer);\n\n const toUrl = () => {\n const relative = path\n .relative(importerDir, filename)\n .replace(/\\\\/g, path.posix.sep);\n\n if (relative.startsWith('.') || path.isAbsolute(relative)) {\n return relative;\n }\n\n return `./${relative}`;\n };\n\n const readFile = () => fs.readFileSync(filename, 'utf-8');\n\n const context: ImportLoaderContext = {\n importer,\n request,\n resolved,\n filename,\n query,\n hash,\n emitWarning: (message) => emitWarning(this.services, message),\n readFile,\n toUrl,\n };\n\n if (loader === 'raw') {\n return { handled: true, value: context.readFile() };\n }\n\n if (loader === 'url') {\n return { handled: true, value: context.toUrl() };\n }\n\n if (typeof loader === 'function') {\n return { handled: true, value: loader(context) };\n }\n\n return { handled: false, value: undefined };\n }\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A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AAC;IAClD;IAEA,IAAI,OAAOF,MAAM,KAAK,UAAU,EAAE;MAChC,OAAO;QAAE3G,OAAO,EAAE,IAAI;QAAEC,KAAK,EAAE0G,MAAM,CAACpE,OAAO;MAAE,CAAC;IAClD;IAEA,OAAO;MAAEvC,OAAO,EAAE,KAAK;MAAEC,KAAK,EAAEgG;IAAU,CAAC;EAC7C;AACF","ignoreList":[]}
1
+ {"version":3,"file":"module.js","names":["fs","NativeModule","path","vm","invariant","isFeatureEnabled","Entrypoint","getStack","isSuperSet","mergeOnly","isUnprocessedEntrypointError","applyImportOverrideToOnly","getImportOverride","resolveMockSpecifier","toImportKey","parseRequest","stripQueryAndHash","createVmContext","CJS_DEFAULT_CONDITIONS","expandConditions","conditionNames","result","Set","name","d","add","isBarePackageSubpath","id","startsWith","isAbsolute","split","length","includes","DefaultModuleImplementation","builtins","assert","buffer","child_process","cluster","console","constants","crypto","dgram","dns","domain","events","http","https","module","net","os","punycode","process","querystring","readline","repl","stream","string_decoder","sys","timers","tls","tty","url","util","zlib","VITE_VIRTUAL_PREFIX","REACT_REFRESH_VIRTUAL_ID","reactRefreshRuntime","createSignatureFunctionForTransform","NOOP","browserOnlyEvalHintTriggers","getBrowserOnlyEvalHint","error","message","Error","String","looksLikeBrowserOnly","some","trigger","join","warnedUnknownImportsByServices","WeakMap","emitWarning","services","warn","getWarnedUnknownImports","cached","get","created","set","getUncached","test","cachedSet","has","filter","t","resolve","resolved","resolveDependency","defaultImportLoaders","raw","Module","callstack","isEvaluated","require","Object","assign","dependencies","push","debug","dependency","source","loaded","loadByImportLoaders","handled","value","entrypoint","getEntrypoint","only","evaluated","evaluatedOnly","exports","m","createChild","evaluate","ensure","bind","entrypointRef","constructor","parentModule","moduleImpl","cache","options","pluginOptions","features","WeakRef","idx","filename","log","extend","parentIsIgnored","ignored","extensions","deref","assertTransformed","evaluatedCreated","supersededWith","createEvaluated","transformedCode","JSON","parse","context","teardown","__wyw_dynamic_import","__dirname","dirname","overrideContext","script","Script","runInContext","e","EvalError","baseMessage","hint","strippedFilename","extension","extname","checkFreshness","undefined","newEntrypoint","readFileSync","stack","uncachedExports","reprocessOnly","evaluatedExports","code","createRoot","resolveWithConditions","parent","conditions","resolveOptions","shouldRetryWithExtensions","_resolveFilename","ext","getDependency","Promise","_extensions","added","forEach","strippedId","paths","_nodeModulePaths","isFileSpecifier","endsWith","existsSync","slice","root","keyInfo","override","importOverrides","key","policy","unknown","mock","shouldWarn","finalResolved","importer","errorMessage","map","item","Boolean","warnedUnknownImports","stringify","request","importLoaders","query","hash","params","URLSearchParams","matchedKey","Array","from","keys","find","loader","importerDir","toUrl","relative","replace","posix","sep","readFile"],"sources":["../src/module.ts"],"sourcesContent":["/**\n * This is a custom implementation for the module system for evaluating code,\n * used for resolving values for dependencies interpolated in `css` or `styled`.\n *\n * This serves 2 purposes:\n * - Avoid leakage from evaluated code to module cache in current context, e.g. `babel-register`\n * - Allow us to invalidate the module cache without affecting other stuff, necessary for rebuilds\n *\n * We also use it to transpile the code with Babel by default.\n * We also store source maps for it to provide correct error stacktraces.\n *\n */\n\nimport fs from 'fs';\nimport NativeModule from 'module';\nimport path from 'path';\nimport vm from 'vm';\n\nimport { invariant } from 'ts-invariant';\n\nimport {\n isFeatureEnabled,\n type Debugger,\n type ImportLoaderContext,\n type ImportLoaders,\n} from '@wyw-in-js/shared';\n\nimport './utils/dispose-polyfill';\nimport type { TransformCacheCollection } from './cache';\nimport { Entrypoint } from './transform/Entrypoint';\nimport {\n getStack,\n isSuperSet,\n mergeOnly,\n} from './transform/Entrypoint.helpers';\nimport type { IEntrypointDependency } from './transform/Entrypoint.types';\nimport type { IEvaluatedEntrypoint } from './transform/EvaluatedEntrypoint';\nimport { isUnprocessedEntrypointError } from './transform/actions/UnprocessedEntrypointError';\nimport type { Services } from './transform/types';\nimport {\n applyImportOverrideToOnly,\n getImportOverride,\n resolveMockSpecifier,\n toImportKey,\n} from './utils/importOverrides';\nimport { parseRequest, stripQueryAndHash } from './utils/parseRequest';\nimport { createVmContext } from './vm/createVmContext';\n\ntype HiddenModuleMembers = {\n _extensions: Record<string, () => void>;\n _resolveFilename: (\n id: string,\n options: { filename: string; id: string; paths: string[] },\n isMain?: boolean,\n resolveOptions?: { conditions?: Set<string> }\n ) => string;\n _nodeModulePaths(filename: string): string[];\n};\n\nconst CJS_DEFAULT_CONDITIONS = ['require', 'node', 'default'] as const;\n\nfunction expandConditions(conditionNames: string[]): Set<string> {\n const result = new Set<string>();\n for (const name of conditionNames) {\n if (name === '...') {\n for (const d of CJS_DEFAULT_CONDITIONS) result.add(d);\n } else {\n result.add(name);\n }\n }\n return result;\n}\n\nfunction isBarePackageSubpath(id: string): boolean {\n if (id.startsWith('.') || path.isAbsolute(id)) {\n return false;\n }\n\n if (id.startsWith('@')) {\n return id.split('/').length > 2;\n }\n\n return id.includes('/');\n}\n\nexport const DefaultModuleImplementation = NativeModule as typeof NativeModule &\n HiddenModuleMembers;\n\n// Supported node builtins based on the modules polyfilled by webpack\n// `true` means module is polyfilled, `false` means module is empty\nconst builtins = {\n assert: true,\n buffer: true,\n child_process: false,\n cluster: false,\n console: true,\n constants: true,\n crypto: true,\n dgram: false,\n dns: false,\n domain: true,\n events: true,\n fs: false,\n http: true,\n https: true,\n module: false,\n net: false,\n os: true,\n path: true,\n punycode: true,\n process: true,\n querystring: true,\n readline: false,\n repl: false,\n stream: true,\n string_decoder: true,\n sys: true,\n timers: true,\n tls: false,\n tty: true,\n url: true,\n util: true,\n vm: true,\n zlib: true,\n};\n\nconst VITE_VIRTUAL_PREFIX = '/@';\nconst REACT_REFRESH_VIRTUAL_ID = '/@react-refresh';\nconst reactRefreshRuntime = {\n createSignatureFunctionForTransform: () => () => {},\n};\n\nconst NOOP = () => {};\n\nconst browserOnlyEvalHintTriggers = [\n 'window is not defined',\n \"evaluating 'window\",\n 'document is not defined',\n \"evaluating 'document\",\n 'navigator is not defined',\n \"evaluating 'navigator\",\n 'self is not defined',\n \"evaluating 'self\",\n];\n\nconst getBrowserOnlyEvalHint = (error: unknown): string | null => {\n const message = error instanceof Error ? error.message : String(error);\n const looksLikeBrowserOnly = browserOnlyEvalHintTriggers.some((trigger) =>\n message.includes(trigger)\n );\n if (!looksLikeBrowserOnly) return null;\n\n return [\n '',\n '[wyw-in-js] Evaluation hint:',\n 'This usually means browser-only code ran during build-time evaluation.',\n 'Move browser-only initialization out of evaluated modules, or mock the import via `importOverrides`.',\n \"Example: importOverrides: { 'msw/browser': { mock: './src/__mocks__/msw-browser.js' } }\",\n ].join('\\n');\n};\n\nconst warnedUnknownImportsByServices = new WeakMap<Services, Set<string>>();\n\nfunction emitWarning(services: Services, message: string) {\n if (services.emitWarning) {\n services.emitWarning(message);\n return;\n }\n\n // eslint-disable-next-line no-console\n console.warn(message);\n}\n\nfunction getWarnedUnknownImports(services: Services): Set<string> {\n const cached = warnedUnknownImportsByServices.get(services);\n if (cached) {\n return cached;\n }\n\n const created = new Set<string>();\n warnedUnknownImportsByServices.set(services, created);\n return created;\n}\n\nfunction getUncached(cached: string | string[], test: string[]): string[] {\n const cachedSet = new Set(\n typeof cached === 'string' ? cached.split(',') : cached\n );\n\n if (cachedSet.has('*')) {\n return [];\n }\n\n return test.filter((t) => !cachedSet.has(t));\n}\n\nfunction resolve(\n this: { resolveDependency: (id: string) => IEntrypointDependency },\n id: string\n): string {\n const { resolved } = this.resolveDependency(id);\n invariant(resolved, `Unable to resolve \"${id}\"`);\n return resolved;\n}\n\nconst defaultImportLoaders: ImportLoaders = {\n raw: 'raw',\n url: 'url',\n};\n\nexport class Module {\n public readonly callstack: string[] = [];\n\n public readonly debug: Debugger;\n\n public readonly dependencies: string[];\n\n public readonly extensions: string[];\n\n public readonly filename: string;\n\n public id: string;\n\n public readonly idx: string;\n\n public readonly ignored: boolean;\n\n public isEvaluated: boolean = false;\n\n public readonly parentIsIgnored: boolean;\n\n public require: {\n (id: string): unknown;\n ensure: () => void;\n resolve: (id: string) => string;\n } = Object.assign(\n (id: string) => {\n if (id === REACT_REFRESH_VIRTUAL_ID) {\n this.dependencies.push(id);\n this.debug('require', `vite virtual '${id}'`);\n return reactRefreshRuntime;\n }\n\n if (id.startsWith(VITE_VIRTUAL_PREFIX)) {\n this.dependencies.push(id);\n this.debug('require', `vite virtual '${id}'`);\n return {};\n }\n\n if (id in builtins) {\n // The module is in the allowed list of builtin node modules\n // Ideally we should prevent importing them, but webpack polyfills some\n // So we check for the list of polyfills to determine which ones to support\n if (builtins[id as keyof typeof builtins]) {\n this.debug('require', `builtin '${id}'`);\n return require(id);\n }\n\n return null;\n }\n\n // Resolve module id (and filename) relatively to parent module\n const dependency = this.resolveDependency(id);\n if (dependency.resolved === id && !path.isAbsolute(id)) {\n // The module is a builtin node modules, but not in the allowed list\n throw new Error(\n `Unable to import \"${id}\". Importing Node builtins is not supported in the sandbox.`\n );\n }\n\n invariant(\n dependency.resolved,\n `Dependency ${dependency.source} cannot be resolved`\n );\n\n const loaded = this.loadByImportLoaders(id, dependency.resolved);\n if (loaded.handled) {\n this.dependencies.push(id);\n this.debug('require', `${id} -> ${dependency.resolved} (loader)`);\n return loaded.value;\n }\n\n this.dependencies.push(id);\n\n this.debug('require', `${id} -> ${dependency.resolved}`);\n\n const entrypoint = this.getEntrypoint(\n dependency.resolved,\n dependency.only,\n this.debug\n );\n\n if (entrypoint === null) {\n return dependency.resolved;\n }\n\n if (\n entrypoint.evaluated ||\n isSuperSet(entrypoint.evaluatedOnly, dependency.only)\n ) {\n return entrypoint.exports;\n }\n\n const m = this.createChild(entrypoint);\n m.evaluate();\n\n return entrypoint.exports;\n },\n {\n ensure: NOOP,\n resolve: resolve.bind(this),\n }\n );\n\n public resolve = resolve.bind(this);\n\n private cache: TransformCacheCollection;\n\n #entrypointRef: WeakRef<Entrypoint> | Entrypoint;\n\n constructor(\n private services: Services,\n entrypoint: Entrypoint,\n parentModule?: Module,\n private moduleImpl: HiddenModuleMembers = DefaultModuleImplementation\n ) {\n this.cache = services.cache;\n this.#entrypointRef = isFeatureEnabled(\n services.options.pluginOptions.features,\n 'useWeakRefInEval',\n entrypoint.name\n )\n ? new WeakRef(entrypoint)\n : entrypoint;\n this.idx = entrypoint.idx;\n this.id = entrypoint.name;\n this.filename = entrypoint.name;\n this.dependencies = [];\n this.debug = entrypoint.log.extend('module');\n this.parentIsIgnored = parentModule?.ignored ?? false;\n this.ignored = entrypoint.ignored ?? this.parentIsIgnored;\n\n if (parentModule) {\n this.callstack = [entrypoint.name, ...parentModule.callstack];\n } else {\n this.callstack = [entrypoint.name];\n }\n\n this.extensions = services.options.pluginOptions.extensions;\n\n this.debug('init', entrypoint.name);\n }\n\n public get exports() {\n return this.entrypoint.exports;\n }\n\n public set exports(value) {\n this.entrypoint.exports = value;\n\n this.debug('the whole exports was overridden with %O', value);\n }\n\n protected get entrypoint(): Entrypoint {\n const entrypoint =\n this.#entrypointRef instanceof WeakRef\n ? this.#entrypointRef.deref()\n : this.#entrypointRef;\n invariant(entrypoint, `Module ${this.idx} is disposed`);\n return entrypoint;\n }\n\n evaluate(): void {\n const { entrypoint } = this;\n entrypoint.assertTransformed();\n\n const cached = this.cache.get('entrypoints', entrypoint.name)!;\n let evaluatedCreated = false;\n if (!entrypoint.supersededWith) {\n this.cache.add(\n 'entrypoints',\n entrypoint.name,\n entrypoint.createEvaluated()\n );\n evaluatedCreated = true;\n }\n\n const { transformedCode: source } = entrypoint;\n const { pluginOptions } = this.services.options;\n\n if (!source) {\n this.debug(`evaluate`, 'there is nothing to evaluate');\n return;\n }\n\n if (this.isEvaluated) {\n this.debug('evaluate', `is already evaluated`);\n return;\n }\n\n this.debug('evaluate');\n this.debug.extend('source')('%s', source);\n\n this.isEvaluated = true;\n\n const filename = stripQueryAndHash(this.filename);\n\n if (/\\.json$/.test(filename)) {\n // For JSON files, parse it to a JS object similar to Node\n this.exports = JSON.parse(source);\n return;\n }\n\n const { context, teardown } = createVmContext(\n filename,\n pluginOptions.features,\n {\n module: this,\n exports: entrypoint.exports,\n require: this.require,\n __wyw_dynamic_import: async (id: unknown) => this.require(String(id)),\n __dirname: path.dirname(filename),\n },\n pluginOptions.overrideContext\n );\n\n try {\n const script = new vm.Script(\n `(function (exports) { ${source}\\n})(exports);`,\n {\n filename,\n }\n );\n\n script.runInContext(context);\n } catch (e) {\n this.isEvaluated = false;\n if (evaluatedCreated) {\n this.cache.add('entrypoints', entrypoint.name, cached);\n }\n\n if (isUnprocessedEntrypointError(e)) {\n // It will be handled by evalFile scenario\n throw e;\n }\n\n if (e instanceof EvalError) {\n this.debug('%O', e);\n\n throw e;\n }\n\n this.debug('%O\\n%O', e, this.callstack);\n const baseMessage = `${(e as Error).message} in${this.callstack.join(\n '\\n| '\n )}\\n`;\n const hint = getBrowserOnlyEvalHint(e);\n\n throw new EvalError(hint ? `${baseMessage}${hint}\\n` : baseMessage);\n } finally {\n teardown();\n }\n }\n\n getEntrypoint(\n filename: string,\n only: string[],\n log: Debugger\n ): Entrypoint | IEvaluatedEntrypoint | null {\n const strippedFilename = stripQueryAndHash(filename);\n const extension = path.extname(strippedFilename);\n if (extension !== '.json' && !this.extensions.includes(extension)) {\n return null;\n }\n\n let entrypoint = this.cache.get('entrypoints', filename);\n if (entrypoint && isSuperSet(entrypoint.evaluatedOnly ?? [], only)) {\n if (this.cache.checkFreshness(filename, strippedFilename)) {\n entrypoint = undefined;\n }\n\n if (entrypoint) {\n log('✅ file has been already evaluated');\n return entrypoint;\n }\n }\n\n if (entrypoint?.ignored) {\n log(\n '✅ file has been ignored during prepare stage. Original code will be used'\n );\n return entrypoint;\n }\n\n if (this.ignored) {\n log(\n '✅ one of the parent files has been ignored during prepare stage. Original code will be used'\n );\n\n const newEntrypoint = this.entrypoint.createChild(\n filename,\n ['*'],\n fs.readFileSync(strippedFilename, 'utf-8')\n );\n\n if (newEntrypoint === 'loop') {\n const stack = getStack(this.entrypoint);\n throw new Error(\n `Circular dependency detected: ${stack.join(' -> ')} -> ${filename}`\n );\n }\n\n return newEntrypoint;\n }\n\n let uncachedExports: string[] | null = null;\n let reprocessOnly: string[] = only;\n // Requested file can be already prepared for evaluation on the stage 1\n if (only && entrypoint) {\n const evaluatedExports =\n entrypoint.evaluatedOnly?.length !== 0\n ? entrypoint.evaluatedOnly\n : entrypoint.only ?? [];\n uncachedExports = getUncached(evaluatedExports, only);\n if (uncachedExports.length === 0) {\n log('✅ ready for evaluation');\n return entrypoint;\n }\n\n if (entrypoint.evaluatedOnly?.length) {\n reprocessOnly = mergeOnly(evaluatedExports, only);\n }\n\n log(\n '❌ file has been processed during prepare stage but %o is not evaluated yet (evaluated: %o)',\n uncachedExports,\n evaluatedExports\n );\n } else {\n log('❌ file has not been processed during prepare stage');\n }\n\n // If code wasn't extracted from cache, it indicates that we were unable\n // to process some of the imports on stage1. Let's try to reprocess.\n const code = fs.readFileSync(strippedFilename, 'utf-8');\n const newEntrypoint = Entrypoint.createRoot(\n this.services,\n filename,\n reprocessOnly,\n code\n );\n\n if (newEntrypoint.evaluated) {\n log('✅ file has been already evaluated');\n return newEntrypoint;\n }\n\n if (newEntrypoint.ignored) {\n log(\n '✅ file has been ignored during prepare stage. Original code will be used'\n );\n return newEntrypoint;\n }\n\n return newEntrypoint;\n }\n\n private resolveWithConditions(\n id: string,\n parent: { id: string; filename: string; paths: string[] },\n conditions?: Set<string>\n ): string {\n const resolveOptions = conditions ? { conditions } : undefined;\n const shouldRetryWithExtensions =\n conditions &&\n path.extname(id) === '' &&\n (id.startsWith('.') || path.isAbsolute(id) || isBarePackageSubpath(id));\n try {\n return this.moduleImpl._resolveFilename(\n id,\n parent,\n false,\n resolveOptions\n );\n } catch (e: unknown) {\n if (\n shouldRetryWithExtensions &&\n e instanceof Error &&\n (e as NodeJS.ErrnoException).code === 'MODULE_NOT_FOUND'\n ) {\n // Extensionless subpath requests (e.g. \"pkg/src/*\" or \"./src/*\") may\n // resolve to extensionless targets via conditional exports. Retry with\n // each known extension, but never rewrite already explicit specifiers.\n for (const ext of this.extensions) {\n try {\n return this.moduleImpl._resolveFilename(\n id + ext,\n parent,\n false,\n resolveOptions\n );\n } catch {\n // try next extension\n }\n }\n }\n throw e;\n }\n }\n\n resolveDependency = (id: string): IEntrypointDependency => {\n const cached = this.entrypoint.getDependency(id);\n invariant(!(cached instanceof Promise), 'Dependency is not resolved yet');\n\n if (cached) {\n return cached;\n }\n\n if (!this.ignored) {\n this.debug(\n '❌ import has not been resolved during prepare stage. Fallback to Node.js resolver'\n );\n }\n\n const extensions = this.moduleImpl._extensions;\n const added: string[] = [];\n\n try {\n // Check for supported extensions\n this.extensions.forEach((ext) => {\n if (ext in extensions) {\n return;\n }\n\n // When an extension is not supported, add it\n // And keep track of it to clean it up after resolving\n // Use noop for the transform function since we handle it\n extensions[ext] = NOOP;\n added.push(ext);\n });\n\n const { filename } = this;\n const strippedId = stripQueryAndHash(id);\n\n const parent = {\n id: filename,\n filename,\n paths: this.moduleImpl._nodeModulePaths(path.dirname(filename)),\n };\n const { conditionNames } = this.services.options.pluginOptions;\n const conditions = conditionNames?.length\n ? expandConditions(conditionNames)\n : undefined;\n\n let resolved = this.resolveWithConditions(strippedId, parent, conditions);\n\n const isFileSpecifier =\n strippedId.startsWith('.') || path.isAbsolute(strippedId);\n\n if (\n isFileSpecifier &&\n path.extname(strippedId) === '' &&\n resolved.endsWith('.cjs') &&\n fs.existsSync(`${resolved.slice(0, -4)}.js`)\n ) {\n // When both `.cjs` and `.js` exist for an extensionless specifier, the\n // resolver may pick `.cjs` depending on the environment/extensions.\n // Prefer `.js` to keep resolved paths stable (e.g. importOverrides keys).\n resolved = `${resolved.slice(0, -4)}.js`;\n }\n\n const { root } = this.services.options;\n const keyInfo = toImportKey({\n source: id,\n resolved,\n root,\n });\n\n const override = getImportOverride(\n this.services.options.pluginOptions.importOverrides,\n keyInfo.key\n );\n\n const policy = override?.unknown ?? (override?.mock ? 'allow' : 'warn');\n const shouldWarn = !this.ignored && policy === 'warn';\n\n let finalResolved = resolved;\n if (override?.mock) {\n try {\n finalResolved = resolveMockSpecifier({\n mock: override.mock,\n importer: filename,\n root,\n stack: this.callstack,\n });\n } catch (e) {\n const errorMessage = String((e as Error)?.message ?? e);\n throw new Error(\n `[wyw-in-js] Failed to resolve import mock for \"${keyInfo.key}\" (${id} from ${filename}): ${errorMessage}`\n );\n }\n }\n\n if (policy === 'error') {\n throw new Error(\n [\n `[wyw-in-js] Unknown import reached during eval (Node resolver fallback)`,\n ``,\n `importer: ${filename}`,\n `source: ${id}`,\n `resolved: ${resolved}`,\n override?.mock\n ? `mock: ${override.mock} -> ${finalResolved}`\n : ``,\n ``,\n `callstack:`,\n ...this.callstack.map((item) => ` ${item}`),\n ``,\n `config key: ${keyInfo.key}`,\n ]\n .filter(Boolean)\n .join('\\n')\n );\n }\n\n const warnedUnknownImports = getWarnedUnknownImports(this.services);\n\n if (shouldWarn && !warnedUnknownImports.has(keyInfo.key)) {\n warnedUnknownImports.add(keyInfo.key);\n emitWarning(\n this.services,\n [\n `[wyw-in-js] Unknown import reached during eval (Node resolver fallback)`,\n ``,\n `importer: ${filename}`,\n `source: ${id}`,\n `resolved: ${resolved}`,\n override?.mock\n ? `mock: ${override.mock} -> ${finalResolved}`\n : ``,\n ``,\n `callstack:`,\n ...this.callstack.map((item) => ` ${item}`),\n ``,\n `config key: ${keyInfo.key}`,\n `hint: add { importOverrides: { ${JSON.stringify(\n keyInfo.key\n )}: { unknown: 'allow' } } } to silence warnings, or use { mock } / { noShake: true } overrides.`,\n ]\n .filter(Boolean)\n .join('\\n')\n );\n }\n\n return {\n source: id,\n only: applyImportOverrideToOnly(['*'], override),\n resolved: finalResolved,\n };\n } finally {\n // Cleanup the extensions we added to restore previous behaviour\n added.forEach((ext) => delete extensions[ext]);\n }\n };\n\n protected createChild(entrypoint: Entrypoint): Module {\n return new Module(this.services, entrypoint, this, this.moduleImpl);\n }\n\n private loadByImportLoaders(\n request: string,\n resolved: string\n ): { handled: boolean; value: unknown } {\n const { pluginOptions } = this.services.options;\n const importLoaders =\n pluginOptions.importLoaders === undefined\n ? defaultImportLoaders\n : { ...defaultImportLoaders, ...pluginOptions.importLoaders };\n\n const { query, hash } = parseRequest(request);\n if (!query) return { handled: false, value: undefined };\n\n const params = new URLSearchParams(query);\n const matchedKey = Array.from(params.keys()).find(\n (key) => importLoaders[key] !== undefined && importLoaders[key] !== false\n );\n\n if (!matchedKey) return { handled: false, value: undefined };\n\n const loader = importLoaders[matchedKey];\n\n const filename = stripQueryAndHash(resolved);\n const importer = stripQueryAndHash(this.filename);\n const importerDir = path.dirname(importer);\n\n const toUrl = () => {\n const relative = path\n .relative(importerDir, filename)\n .replace(/\\\\/g, path.posix.sep);\n\n if (relative.startsWith('.') || path.isAbsolute(relative)) {\n return relative;\n }\n\n return `./${relative}`;\n };\n\n const readFile = () => fs.readFileSync(filename, 'utf-8');\n\n const context: ImportLoaderContext = {\n importer,\n request,\n resolved,\n filename,\n query,\n hash,\n emitWarning: (message) => emitWarning(this.services, message),\n readFile,\n toUrl,\n };\n\n if (loader === 'raw') {\n return { handled: true, value: context.readFile() };\n }\n\n if (loader === 'url') {\n return { handled: true, value: context.toUrl() };\n }\n\n if (typeof loader === 'function') {\n return { handled: true, value: loader(context) };\n }\n\n return { handled: false, value: undefined };\n }\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,OAAOA,EAAE,MAAM,IAAI;AACnB,OAAOC,YAAY,MAAM,QAAQ;AACjC,OAAOC,IAAI,MAAM,MAAM;AACvB,OAAOC,EAAE,MAAM,IAAI;AAEnB,SAASC,SAAS,QAAQ,cAAc;AAExC,SACEC,gBAAgB,QAIX,mBAAmB;AAE1B,OAAO,0BAA0B;AAEjC,SAASC,UAAU,QAAQ,wBAAwB;AACnD,SACEC,QAAQ,EACRC,UAAU,EACVC,SAAS,QACJ,gCAAgC;AAGvC,SAASC,4BAA4B,QAAQ,gDAAgD;AAE7F,SACEC,yBAAyB,EACzBC,iBAAiB,EACjBC,oBAAoB,EACpBC,WAAW,QACN,yBAAyB;AAChC,SAASC,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;MACRwC,QAAQ;MACR8E,KAAK;MACLC,IAAI;MACJtI,WAAW,EAAGT,OAAO,IAAKS,WAAW,CAAC,IAAI,CAACC,QAAQ,EAAEV,OAAO,CAAC;MAC7D8J,QAAQ;MACRL;IACF,CAAC;IAED,IAAIF,MAAM,KAAK,KAAK,EAAE;MACpB,OAAO;QAAE9G,OAAO,EAAE,IAAI;QAAEC,KAAK,EAAEoC,OAAO,CAACgF,QAAQ,CAAC;MAAE,CAAC;IACrD;IAEA,IAAIP,MAAM,KAAK,KAAK,EAAE;MACpB,OAAO;QAAE9G,OAAO,EAAE,IAAI;QAAEC,KAAK,EAAEoC,OAAO,CAAC2E,KAAK,CAAC;MAAE,CAAC;IAClD;IAEA,IAAI,OAAOF,MAAM,KAAK,UAAU,EAAE;MAChC,OAAO;QAAE9G,OAAO,EAAE,IAAI;QAAEC,KAAK,EAAE6G,MAAM,CAACzE,OAAO;MAAE,CAAC;IAClD;IAEA,OAAO;MAAErC,OAAO,EAAE,KAAK;MAAEC,KAAK,EAAEqD;IAAU,CAAC;EAC7C;AACF","ignoreList":[]}
@@ -46,6 +46,9 @@ function getBindingForExport(exportPath) {
46
46
  }
47
47
  return getNonParamBinding(exportPath, id.name);
48
48
  }
49
+ if (exportPath.isTSEnumDeclaration()) {
50
+ return getNonParamBinding(exportPath, exportPath.node.id.name);
51
+ }
49
52
  return undefined;
50
53
  }
51
54
  const withoutRemoved = items => items.filter(({
@@ -113,24 +116,113 @@ const getPropertyAssignmentStatement = (ref, bindingName) => {
113
116
  return statement?.isExpressionStatement() ? statement : null;
114
117
  };
115
118
  const isWithinAliveExport = (ref, aliveExports) => [...aliveExports].some(alive => alive === ref || alive.isAncestor(ref));
116
- function stripExportKeepDeclaration(path) {
119
+ function getExportPathsForVariableDeclaration(declaration, exports) {
120
+ const exportPaths = [];
121
+ declaration.get('declarations').forEach(declarator => {
122
+ Object.keys(declarator.getOuterBindingIdentifiers()).forEach(name => {
123
+ const exportPath = exports[name];
124
+ if (exportPath && !exportPaths.includes(exportPath)) {
125
+ exportPaths.push(exportPath);
126
+ }
127
+ });
128
+ });
129
+ return exportPaths;
130
+ }
131
+ function getDeclaratorExportLiveness(declarator, exports, aliveExports) {
132
+ const bindingNames = Object.keys(declarator.getOuterBindingIdentifiers());
133
+ if (bindingNames.length === 0) {
134
+ return null;
135
+ }
136
+ let liveness = null;
137
+ for (const name of bindingNames) {
138
+ const exportPath = exports[name];
139
+ if (!exportPath) {
140
+ return null;
141
+ }
142
+ const isAlive = aliveExports.has(exportPath);
143
+ if (liveness === null) {
144
+ liveness = isAlive;
145
+ } else if (liveness !== isAlive) {
146
+ return null;
147
+ }
148
+ }
149
+ return liveness;
150
+ }
151
+ function hasRuntimeReferencesToEnum(path) {
152
+ if (!path.isTSEnumDeclaration()) {
153
+ return false;
154
+ }
155
+ const enumId = path.get('id');
156
+ const bindingName = enumId.node.name;
157
+ const program = path.scope.getProgramParent().path;
158
+ let hasReference = false;
159
+ program.traverse({
160
+ Identifier(identifier) {
161
+ if (hasReference || identifier.node.name !== bindingName) {
162
+ return;
163
+ }
164
+ if (identifier.findParent(ancestor => ancestor === path)) {
165
+ return;
166
+ }
167
+ if (identifier.find(ancestor => ancestor.isTSType() || ancestor.isFlowType())) {
168
+ return;
169
+ }
170
+ if (!identifier.isReferencedIdentifier()) {
171
+ return;
172
+ }
173
+ const localBinding = identifier.scope.getBinding(bindingName);
174
+ if (localBinding && localBinding.path !== enumId) {
175
+ return;
176
+ }
177
+ hasReference = true;
178
+ identifier.stop();
179
+ }
180
+ });
181
+ return hasReference;
182
+ }
183
+ function stripExportKeepDeclaration(path, exports, aliveExports, t) {
117
184
  const exportDeclaration = path.findParent(p => p.isExportNamedDeclaration());
118
- if (!exportDeclaration) return false;
185
+ if (!exportDeclaration) return null;
119
186
  const declaration = exportDeclaration.get('declaration');
120
- if (!declaration.node) return false;
187
+ if (!declaration.node) return null;
121
188
  if (declaration.isFunctionDeclaration() || declaration.isClassDeclaration() || declaration.isTSEnumDeclaration()) {
122
- exportDeclaration.replaceWith(declaration.node);
123
- return true;
189
+ exportDeclaration.replaceWith(t.cloneNode(declaration.node, true));
190
+ return [path];
124
191
  }
125
192
  if (declaration.isVariableDeclaration()) {
126
193
  const declarators = declaration.get('declarations');
127
- if (declarators.length !== 1) {
128
- return false;
194
+ const staleExportPaths = getExportPathsForVariableDeclaration(declaration, exports);
195
+ if (declarators.length === 1) {
196
+ exportDeclaration.replaceWith(t.cloneNode(declaration.node, true));
197
+ return staleExportPaths.length > 0 ? staleExportPaths : [path];
198
+ }
199
+ const segments = [];
200
+ for (const declarator of declarators) {
201
+ const isAlive = getDeclaratorExportLiveness(declarator, exports, aliveExports);
202
+ if (isAlive === null) {
203
+ return null;
204
+ }
205
+ const clonedDeclarator = t.cloneNode(declarator.node, true);
206
+ const currentSegment = segments[segments.length - 1];
207
+ if (currentSegment && currentSegment.alive === isAlive) {
208
+ currentSegment.declarators.push(clonedDeclarator);
209
+ } else {
210
+ segments.push({
211
+ alive: isAlive,
212
+ declarators: [clonedDeclarator]
213
+ });
214
+ }
129
215
  }
130
- exportDeclaration.replaceWith(declaration.node);
131
- return true;
216
+ exportDeclaration.replaceWithMultiple(segments.map(({
217
+ alive,
218
+ declarators: groupedDeclarators
219
+ }) => {
220
+ const groupedDeclaration = t.variableDeclaration(declaration.node.kind, groupedDeclarators);
221
+ return alive ? t.exportNamedDeclaration(groupedDeclaration, []) : groupedDeclaration;
222
+ }));
223
+ return staleExportPaths.length > 0 ? staleExportPaths : [path];
132
224
  }
133
- return false;
225
+ return null;
134
226
  }
135
227
  export default function shakerPlugin(babel, {
136
228
  keepSideEffects = false,
@@ -361,13 +453,51 @@ export default function shakerPlugin(babel, {
361
453
  dereference(path);
362
454
  dereferenced.push(path);
363
455
  }
364
- if (!deleted.has(path) && binding && blockingReferences.length > 0 && stripExportKeepDeclaration(path)) {
365
- deleted.add(path);
456
+ const strippedEnum = !deleted.has(path) && hasRuntimeReferencesToEnum(path) ? stripExportKeepDeclaration(path, exports, aliveExports, babel.types) : null;
457
+ if (strippedEnum) {
458
+ strippedEnum.forEach(stalePath => {
459
+ deleted.add(stalePath);
460
+ });
461
+ changed = true;
462
+ // eslint-disable-next-line no-continue
463
+ continue;
464
+ }
465
+ const strippedWithBlocking = !deleted.has(path) && binding && blockingReferences.length > 0 ? stripExportKeepDeclaration(path, exports, aliveExports, babel.types) : null;
466
+ if (strippedWithBlocking) {
467
+ strippedWithBlocking.forEach(stalePath => {
468
+ deleted.add(stalePath);
469
+ });
366
470
  changed = true;
367
471
  // eslint-disable-next-line no-continue
368
472
  continue;
369
473
  }
370
474
  if (!deleted.has(path) && (!binding || blockingReferences.length === 0)) {
475
+ // For variable declaration exports, `path` is the init expression
476
+ // (not the Identifier). Other forDeleting candidates whose init
477
+ // expressions are ancestors of references to this binding can
478
+ // incorrectly filter them out of outerReferences. Those candidates
479
+ // may later survive via stripExportKeepDeclaration, leaving a
480
+ // dangling reference. Strip the export keyword but keep the
481
+ // declaration so the unreferenced sweep removes it only when dead.
482
+ // This only applies to expression paths (variable init), not
483
+ // Identifiers (function/class declarations) which can't be
484
+ // ancestors of external references.
485
+ const strippedWithoutBlocking = binding && !path.isIdentifier() ? stripExportKeepDeclaration(path, exports, aliveExports, babel.types) : null;
486
+ if (strippedWithoutBlocking) {
487
+ strippedWithoutBlocking.forEach(stalePath => {
488
+ deleted.add(stalePath);
489
+ });
490
+ if (removableAssignmentStatements.size > 0) {
491
+ for (const statement of removableAssignmentStatements) {
492
+ if (queueForDeleting(statement)) {
493
+ changed = true;
494
+ }
495
+ }
496
+ }
497
+ changed = true;
498
+ // eslint-disable-next-line no-continue
499
+ continue;
500
+ }
371
501
  if (removableAssignmentStatements.size > 0) {
372
502
  for (const statement of removableAssignmentStatements) {
373
503
  if (queueForDeleting(statement)) {
@@ -392,12 +522,21 @@ export default function shakerPlugin(babel, {
392
522
  });
393
523
  dereferenced = [];
394
524
 
525
+ // stripExportKeepDeclaration replaces ExportNamedDeclaration with
526
+ // its declaration, creating new AST nodes. The old scope bindings
527
+ // become stale (pointing at disconnected paths). Recrawl so
528
+ // getAllBindings() returns fresh bindings with correct .referenced.
529
+ file.scope.crawl();
530
+
395
531
  // Find and mark for deleting all unreferenced variables
396
532
  const unreferenced = Object.values(file.scope.getAllBindings()).filter(i => !i.referenced);
397
533
  for (const binding of unreferenced) {
398
534
  if (binding.path.isVariableDeclarator()) {
399
535
  const id = binding.path.get('id');
400
- if (!isRemoved(id) && !forDeletingSet.has(id)) {
536
+ // Skip destructured patterns — removing the declarator would kill
537
+ // sibling bindings that may still be referenced (e.g. export {B}
538
+ // from `const [A, B] = createContext(...)` when only A is dead).
539
+ if (!id.isArrayPattern() && !id.isObjectPattern() && !isRemoved(id) && !forDeletingSet.has(id)) {
401
540
  // Drop dead variable declarations, e.g. `const foo = make();` when `foo` is no longer referenced.
402
541
  for (const violation of binding.constantViolations) {
403
542
  if (queueForDeleting(violation)) {