nitro-nightly 4.0.0-20251010-091516-7cafddba → 4.0.0-20251030-091344-d4418b98

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 (195) hide show
  1. package/dist/{_chunks/build2.mjs → _build/build.mjs} +108 -58
  2. package/dist/_build/build2.mjs +556 -0
  3. package/dist/_build/info.mjs +1002 -0
  4. package/dist/_build/prepare.mjs +1511 -0
  5. package/dist/_build/snapshot.mjs +185 -0
  6. package/dist/{_chunks/plugin.mjs → _build/vite.mjs} +295 -296
  7. package/dist/_build/vite2.mjs +149 -0
  8. package/dist/_chunks/_deps/@jridgewell/gen-mapping.mjs +189 -0
  9. package/dist/_chunks/_deps/@jridgewell/remapping.mjs +137 -0
  10. package/dist/_chunks/_deps/@jridgewell/resolve-uri.mjs +231 -0
  11. package/dist/_chunks/_deps/@jridgewell/sourcemap-codec.mjs +173 -0
  12. package/dist/_chunks/_deps/@jridgewell/trace-mapping.mjs +170 -0
  13. package/dist/_chunks/_deps/@pi0/vite-plugin-fullstack.mjs +575 -0
  14. package/dist/_chunks/_deps/@rollup/plugin-alias.mjs +89 -0
  15. package/dist/_chunks/_deps/@rollup/plugin-commonjs.mjs +2376 -0
  16. package/dist/_chunks/{index2.mjs → _deps/@rollup/plugin-inject.mjs} +5 -90
  17. package/dist/_chunks/_deps/@rollup/plugin-json.mjs +37 -0
  18. package/dist/_chunks/_deps/@rollup/plugin-node-resolve.mjs +1386 -0
  19. package/dist/_chunks/_deps/@rollup/plugin-replace.mjs +133 -0
  20. package/dist/_chunks/_deps/@rollup/pluginutils.mjs +346 -0
  21. package/dist/_chunks/_deps/acorn.mjs +6225 -0
  22. package/dist/_chunks/_deps/c12.mjs +510 -0
  23. package/dist/_chunks/_deps/chokidar.mjs +1428 -0
  24. package/dist/_chunks/_deps/citty.mjs +460 -0
  25. package/dist/_chunks/_deps/commondir.mjs +77 -0
  26. package/dist/_chunks/_deps/compatx.mjs +76 -0
  27. package/dist/_chunks/_deps/confbox.mjs +300 -0
  28. package/dist/_chunks/_deps/debug.mjs +885 -0
  29. package/dist/_chunks/_deps/deepmerge.mjs +147 -0
  30. package/dist/_chunks/_deps/depd.mjs +550 -0
  31. package/dist/_chunks/_deps/dot-prop.mjs +282 -0
  32. package/dist/_chunks/_deps/dotenv.mjs +555 -0
  33. package/dist/_chunks/_deps/duplexer.mjs +1 -0
  34. package/dist/_chunks/_deps/ee-first.mjs +104 -0
  35. package/dist/_chunks/_deps/encodeurl.mjs +69 -0
  36. package/dist/_chunks/_deps/escape-html.mjs +87 -0
  37. package/dist/_chunks/_deps/escape-string-regexp.mjs +13 -0
  38. package/dist/_chunks/_deps/estree-walker.mjs +433 -0
  39. package/dist/_chunks/_deps/etag.mjs +147 -0
  40. package/dist/_chunks/_deps/exsolve.mjs +1416 -0
  41. package/dist/_chunks/_deps/fdir.mjs +569 -0
  42. package/dist/_chunks/_deps/fresh.mjs +145 -0
  43. package/dist/_chunks/_deps/function-bind.mjs +106 -0
  44. package/dist/_chunks/{index4.mjs → _deps/giget.mjs} +21 -776
  45. package/dist/_chunks/_deps/gzip-size.mjs +19 -0
  46. package/dist/_chunks/_deps/hasown.mjs +19 -0
  47. package/dist/_chunks/_deps/http-errors.mjs +307 -0
  48. package/dist/_chunks/_deps/httpxy.mjs +580 -0
  49. package/dist/_chunks/_deps/inherits.mjs +57 -0
  50. package/dist/_chunks/_deps/is-core-module.mjs +596 -0
  51. package/dist/_chunks/_deps/is-module.mjs +25 -0
  52. package/dist/_chunks/_deps/is-reference.mjs +31 -0
  53. package/dist/_chunks/_deps/js-tokens.mjs +411 -0
  54. package/dist/_chunks/_deps/klona.mjs +137 -0
  55. package/dist/_chunks/_deps/knitwork.mjs +172 -0
  56. package/dist/_chunks/_deps/local-pkg.mjs +163 -0
  57. package/dist/_chunks/_deps/magic-string.mjs +1296 -0
  58. package/dist/_chunks/_deps/mime-db.mjs +11685 -0
  59. package/dist/_chunks/_deps/mime-types.mjs +287 -0
  60. package/dist/_chunks/_deps/mime.mjs +1172 -0
  61. package/dist/_chunks/_deps/mlly.mjs +2413 -0
  62. package/dist/_chunks/_deps/ms.mjs +172 -0
  63. package/dist/_chunks/_deps/node-fetch-native.mjs +3 -0
  64. package/dist/_chunks/_deps/nypm.mjs +219 -0
  65. package/dist/_chunks/_deps/on-finished.mjs +246 -0
  66. package/dist/_chunks/_deps/parseurl.mjs +168 -0
  67. package/dist/_chunks/_deps/path-parse.mjs +85 -0
  68. package/dist/_chunks/{pathe.M-eThtNZ.mjs → _deps/pathe.mjs} +48 -1
  69. package/dist/_chunks/_deps/perfect-debounce.mjs +88 -0
  70. package/dist/_chunks/_deps/picomatch.mjs +2144 -0
  71. package/dist/_chunks/_deps/pkg-types.mjs +247 -0
  72. package/dist/_chunks/{snapshot.mjs → _deps/pretty-bytes.mjs} +1 -105
  73. package/dist/_chunks/_deps/quansync.mjs +99 -0
  74. package/dist/_chunks/_deps/range-parser.mjs +171 -0
  75. package/dist/_chunks/_deps/rc9.mjs +219 -0
  76. package/dist/_chunks/_deps/readdirp.mjs +245 -0
  77. package/dist/_chunks/_deps/resolve.mjs +1260 -0
  78. package/dist/_chunks/_deps/rou3.mjs +326 -0
  79. package/dist/_chunks/_deps/send.mjs +1022 -0
  80. package/dist/_chunks/_deps/serve-static.mjs +228 -0
  81. package/dist/_chunks/_deps/setprototypeof.mjs +26 -0
  82. package/dist/_chunks/_deps/statuses.mjs +457 -0
  83. package/dist/_chunks/_deps/std-env.mjs +3 -0
  84. package/dist/_chunks/_deps/strip-literal.mjs +67 -0
  85. package/dist/_chunks/_deps/supports-color.mjs +44 -0
  86. package/dist/_chunks/_deps/tinyexec.mjs +552 -0
  87. package/dist/_chunks/_deps/tinyglobby.mjs +293 -0
  88. package/dist/_chunks/_deps/toidentifier.mjs +41 -0
  89. package/dist/_chunks/_deps/ultrahtml.mjs +3 -0
  90. package/dist/_chunks/_deps/unimport.mjs +2267 -0
  91. package/dist/_chunks/_deps/unplugin-utils.mjs +65 -0
  92. package/dist/_chunks/_deps/unplugin.mjs +1294 -0
  93. package/dist/_chunks/_deps/untyped.mjs +375 -0
  94. package/dist/_chunks/{info.mjs → _deps/unwasm.mjs} +8 -4206
  95. package/dist/_chunks/_deps/webpack-virtual-modules.mjs +360 -0
  96. package/dist/_chunks/_presets/_all.mjs +59 -0
  97. package/dist/_chunks/_presets/_nitro.mjs +74 -0
  98. package/dist/_chunks/_presets/_resolve.mjs +64 -0
  99. package/dist/_chunks/_presets/_static.mjs +69 -0
  100. package/dist/_chunks/_presets/_types.mjs +3 -0
  101. package/dist/_chunks/_presets/_utils.mjs +31 -0
  102. package/dist/_chunks/_presets/alwaysdata.mjs +17 -0
  103. package/dist/_chunks/_presets/aws-amplify.mjs +111 -0
  104. package/dist/_chunks/_presets/aws-lambda.mjs +23 -0
  105. package/dist/_chunks/_presets/azure.mjs +162 -0
  106. package/dist/_chunks/_presets/bun.mjs +19 -0
  107. package/dist/_chunks/_presets/cleavr.mjs +15 -0
  108. package/dist/_chunks/_presets/cloudflare.mjs +608 -0
  109. package/dist/_chunks/_presets/deno.mjs +196 -0
  110. package/dist/_chunks/_presets/digitalocean.mjs +14 -0
  111. package/dist/_chunks/_presets/firebase.mjs +47 -0
  112. package/dist/_chunks/_presets/flightcontrol.mjs +14 -0
  113. package/dist/_chunks/_presets/genezio.mjs +13 -0
  114. package/dist/_chunks/_presets/heroku.mjs +14 -0
  115. package/dist/_chunks/_presets/iis.mjs +194 -0
  116. package/dist/_chunks/_presets/index.mjs +62 -0
  117. package/dist/_chunks/_presets/koyeb.mjs +14 -0
  118. package/dist/_chunks/_presets/netlify.mjs +241 -0
  119. package/dist/_chunks/_presets/node.mjs +54 -0
  120. package/dist/_chunks/_presets/platform.mjs +14 -0
  121. package/dist/_chunks/_presets/render.mjs +14 -0
  122. package/dist/_chunks/_presets/standard.mjs +23 -0
  123. package/dist/_chunks/_presets/stormkit.mjs +18 -0
  124. package/dist/_chunks/_presets/vercel.mjs +375 -0
  125. package/dist/_chunks/_presets/winterjs.mjs +22 -0
  126. package/dist/_chunks/_presets/zeabur.mjs +69 -0
  127. package/dist/_chunks/_presets/zerops.mjs +27 -0
  128. package/dist/_chunks/app.mjs +9 -19206
  129. package/dist/_chunks/{index3.mjs → builder.mjs} +560 -970
  130. package/dist/_chunks/server.mjs +6 -4
  131. package/dist/{cli → _cli}/build.mjs +3 -8
  132. package/dist/{cli → _cli}/dev.mjs +38 -12
  133. package/dist/{cli/index2.mjs → _cli/index.mjs} +1 -2
  134. package/dist/{cli → _cli}/list.mjs +3 -4
  135. package/dist/{cli → _cli}/prepare.mjs +3 -4
  136. package/dist/{cli → _cli}/run.mjs +3 -4
  137. package/dist/{index.d.mts → builder.d.mts} +11 -11
  138. package/dist/builder.mjs +117 -0
  139. package/dist/cli/index.mjs +7 -464
  140. package/dist/node_modules/@speed-highlight/core/dist/index.js +1 -1
  141. package/dist/node_modules/@speed-highlight/core/dist/terminal.js +1 -1
  142. package/dist/node_modules/@speed-highlight/core/package.json +7 -3
  143. package/dist/node_modules/cookie-es/dist/index.mjs +262 -0
  144. package/dist/node_modules/cookie-es/package.json +37 -0
  145. package/dist/node_modules/hookable/dist/index.mjs +243 -266
  146. package/dist/node_modules/hookable/package.json +29 -26
  147. package/dist/node_modules/rendu/dist/index.mjs +380 -0
  148. package/dist/node_modules/rendu/package.json +47 -0
  149. package/dist/presets/_nitro/runtime/nitro-dev.mjs +4 -7
  150. package/dist/presets/_nitro/runtime/nitro-prerenderer.mjs +5 -4
  151. package/dist/presets/azure/runtime/azure-swa.mjs +1 -1
  152. package/dist/presets/cloudflare/runtime/_module-handler.mjs +7 -6
  153. package/dist/presets/cloudflare/runtime/cloudflare-durable.mjs +4 -5
  154. package/dist/presets/cloudflare/runtime/plugin.dev.mjs +7 -10
  155. package/dist/presets/cloudflare/runtime/shims/workers.dev.d.mts +21 -0
  156. package/dist/presets/cloudflare/runtime/shims/workers.dev.mjs +27 -0
  157. package/dist/presets/node/runtime/node-server.mjs +1 -1
  158. package/dist/runtime/index.d.mts +1 -1
  159. package/dist/runtime/index.mjs +1 -1
  160. package/dist/runtime/internal/app.d.mts +3 -1
  161. package/dist/runtime/internal/app.mjs +90 -64
  162. package/dist/runtime/internal/error/prod.d.mts +3 -2
  163. package/dist/runtime/internal/error/prod.mjs +9 -13
  164. package/dist/runtime/internal/renderer.mjs +4 -4
  165. package/dist/runtime/internal/routes/dev-tasks.d.mts +30 -2
  166. package/dist/runtime/internal/shutdown.d.mts +1 -2
  167. package/dist/runtime/internal/shutdown.mjs +3 -2
  168. package/dist/runtime/internal/task.mjs +1 -2
  169. package/dist/types/index.d.mts +1603 -10
  170. package/dist/vite.d.mts +5 -0
  171. package/dist/vite.mjs +94 -30
  172. package/lib/index.mjs +1 -0
  173. package/lib/indexd.mts +1 -0
  174. package/lib/runtime/meta.mjs +35 -0
  175. package/package.json +40 -41
  176. package/dist/_chunks/build.mjs +0 -84
  177. package/dist/_chunks/build3.mjs +0 -6452
  178. package/dist/_chunks/detect-acorn.mjs +0 -503
  179. package/dist/_chunks/index.mjs +0 -22242
  180. package/dist/_chunks/json5.mjs +0 -68
  181. package/dist/_chunks/jsonc.mjs +0 -51
  182. package/dist/_chunks/toml.mjs +0 -259
  183. package/dist/_chunks/yaml.mjs +0 -86
  184. package/dist/index.mjs +0 -55
  185. package/dist/node_modules/klona/dist/index.mjs +0 -81
  186. package/dist/node_modules/klona/full/index.mjs +0 -53
  187. package/dist/node_modules/klona/package.json +0 -74
  188. package/dist/node_modules/std-env/dist/index.mjs +0 -1
  189. package/dist/node_modules/std-env/package.json +0 -46
  190. package/dist/presets.mjs +0 -2460
  191. package/dist/runtime/internal/debug.d.mts +0 -2
  192. package/dist/runtime/internal/debug.mjs +0 -5
  193. package/lib/runtime-meta.mjs +0 -38
  194. /package/dist/{cli → _cli}/common.mjs +0 -0
  195. /package/lib/{runtime-meta.d.mts → runtime/meta.d.mts} +0 -0
@@ -0,0 +1,2376 @@
1
+ import { resolve, relative, join, dirname, extname, basename, sep } from 'path';
2
+ import { c as createFilter, m as makeLegalIdentifier, a as attachScopes, e as extractAssignedNames } from './pluginutils.mjs';
3
+ import { statSync, existsSync, readFileSync } from 'fs';
4
+ import { g as getCommonDir } from '../commondir.mjs';
5
+ import { B as Builder } from '../fdir.mjs';
6
+ import { w as walk } from '../estree-walker.mjs';
7
+ import { M as MagicString } from '../magic-string.mjs';
8
+ import { i as isReference } from '../is-reference.mjs';
9
+
10
+ var version = "28.0.9";
11
+ var peerDependencies = {
12
+ rollup: "^2.68.0||^3.0.0||^4.0.0"
13
+ };
14
+
15
+ function tryParse(parse, code, id) {
16
+ try {
17
+ return parse(code, { allowReturnOutsideFunction: true });
18
+ } catch (err) {
19
+ err.message += ` in ${id}`;
20
+ throw err;
21
+ }
22
+ }
23
+
24
+ const firstpassGlobal = /\b(?:require|module|exports|global)\b/;
25
+
26
+ const firstpassNoGlobal = /\b(?:require|module|exports)\b/;
27
+
28
+ function hasCjsKeywords(code, ignoreGlobal) {
29
+ const firstpass = ignoreGlobal ? firstpassNoGlobal : firstpassGlobal;
30
+ return firstpass.test(code);
31
+ }
32
+
33
+ /* eslint-disable no-underscore-dangle */
34
+
35
+
36
+ function analyzeTopLevelStatements(parse, code, id) {
37
+ const ast = tryParse(parse, code, id);
38
+
39
+ let isEsModule = false;
40
+ let hasDefaultExport = false;
41
+ let hasNamedExports = false;
42
+
43
+ for (const node of ast.body) {
44
+ switch (node.type) {
45
+ case 'ExportDefaultDeclaration':
46
+ isEsModule = true;
47
+ hasDefaultExport = true;
48
+ break;
49
+ case 'ExportNamedDeclaration':
50
+ isEsModule = true;
51
+ if (node.declaration) {
52
+ hasNamedExports = true;
53
+ } else {
54
+ for (const specifier of node.specifiers) {
55
+ if (specifier.exported.name === 'default') {
56
+ hasDefaultExport = true;
57
+ } else {
58
+ hasNamedExports = true;
59
+ }
60
+ }
61
+ }
62
+ break;
63
+ case 'ExportAllDeclaration':
64
+ isEsModule = true;
65
+ if (node.exported && node.exported.name === 'default') {
66
+ hasDefaultExport = true;
67
+ } else {
68
+ hasNamedExports = true;
69
+ }
70
+ break;
71
+ case 'ImportDeclaration':
72
+ isEsModule = true;
73
+ break;
74
+ }
75
+ }
76
+
77
+ return { isEsModule, hasDefaultExport, hasNamedExports, ast };
78
+ }
79
+
80
+ /* eslint-disable import/prefer-default-export */
81
+
82
+
83
+ function deconflict(scopes, globals, identifier) {
84
+ let i = 1;
85
+ let deconflicted = makeLegalIdentifier(identifier);
86
+ const hasConflicts = () =>
87
+ scopes.some((scope) => scope.contains(deconflicted)) || globals.has(deconflicted);
88
+
89
+ while (hasConflicts()) {
90
+ deconflicted = makeLegalIdentifier(`${identifier}_${i}`);
91
+ i += 1;
92
+ }
93
+
94
+ for (const scope of scopes) {
95
+ scope.declarations[deconflicted] = true;
96
+ }
97
+
98
+ return deconflicted;
99
+ }
100
+
101
+ function getName(id) {
102
+ const name = makeLegalIdentifier(basename(id, extname(id)));
103
+ if (name !== 'index') {
104
+ return name;
105
+ }
106
+ return makeLegalIdentifier(basename(dirname(id)));
107
+ }
108
+
109
+ function normalizePathSlashes(path) {
110
+ return path.replace(/\\/g, '/');
111
+ }
112
+
113
+ const getVirtualPathForDynamicRequirePath = (path, commonDir) =>
114
+ `/${normalizePathSlashes(relative(commonDir, path))}`;
115
+
116
+ function capitalize(name) {
117
+ return name[0].toUpperCase() + name.slice(1);
118
+ }
119
+
120
+ function getStrictRequiresFilter({ strictRequires }) {
121
+ switch (strictRequires) {
122
+ // eslint-disable-next-line no-undefined
123
+ case undefined:
124
+ case true:
125
+ return { strictRequiresFilter: () => true, detectCyclesAndConditional: false };
126
+ case 'auto':
127
+ case 'debug':
128
+ case null:
129
+ return { strictRequiresFilter: () => false, detectCyclesAndConditional: true };
130
+ case false:
131
+ return { strictRequiresFilter: () => false, detectCyclesAndConditional: false };
132
+ default:
133
+ if (typeof strictRequires === 'string' || Array.isArray(strictRequires)) {
134
+ return {
135
+ strictRequiresFilter: createFilter(strictRequires),
136
+ detectCyclesAndConditional: false
137
+ };
138
+ }
139
+ throw new Error('Unexpected value for "strictRequires" option.');
140
+ }
141
+ }
142
+
143
+ function getPackageEntryPoint(dirPath) {
144
+ let entryPoint = 'index.js';
145
+
146
+ try {
147
+ if (existsSync(join(dirPath, 'package.json'))) {
148
+ entryPoint =
149
+ JSON.parse(readFileSync(join(dirPath, 'package.json'), { encoding: 'utf8' })).main ||
150
+ entryPoint;
151
+ }
152
+ } catch (ignored) {
153
+ // ignored
154
+ }
155
+
156
+ return entryPoint;
157
+ }
158
+
159
+ function isDirectory(path) {
160
+ try {
161
+ if (statSync(path).isDirectory()) return true;
162
+ } catch (ignored) {
163
+ // Nothing to do here
164
+ }
165
+ return false;
166
+ }
167
+
168
+ function getDynamicRequireModules(patterns, dynamicRequireRoot) {
169
+ const dynamicRequireModules = new Map();
170
+ const dirNames = new Set();
171
+ for (const pattern of !patterns || Array.isArray(patterns) ? patterns || [] : [patterns]) {
172
+ const isNegated = pattern.startsWith('!');
173
+ const modifyMap = (targetPath, resolvedPath) =>
174
+ isNegated
175
+ ? dynamicRequireModules.delete(targetPath)
176
+ : dynamicRequireModules.set(targetPath, resolvedPath);
177
+ // eslint-disable-next-line new-cap
178
+ for (const path of new Builder()
179
+ .withBasePath()
180
+ .withDirs()
181
+ .glob(isNegated ? pattern.substr(1) : pattern)
182
+ .crawl(relative('.', dynamicRequireRoot))
183
+ .sync()
184
+ .sort((a, b) => a.localeCompare(b, 'en'))) {
185
+ const resolvedPath = resolve(path);
186
+ const requirePath = normalizePathSlashes(resolvedPath);
187
+ if (isDirectory(resolvedPath)) {
188
+ dirNames.add(resolvedPath);
189
+ const modulePath = resolve(join(resolvedPath, getPackageEntryPoint(path)));
190
+ modifyMap(requirePath, modulePath);
191
+ modifyMap(normalizePathSlashes(modulePath), modulePath);
192
+ } else {
193
+ dirNames.add(dirname(resolvedPath));
194
+ modifyMap(requirePath, resolvedPath);
195
+ }
196
+ }
197
+ }
198
+ return {
199
+ commonDir: dirNames.size ? getCommonDir([...dirNames, dynamicRequireRoot]) : null,
200
+ dynamicRequireModules
201
+ };
202
+ }
203
+
204
+ const FAILED_REQUIRE_ERROR = `throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.');`;
205
+
206
+ const COMMONJS_REQUIRE_EXPORT = 'commonjsRequire';
207
+ const CREATE_COMMONJS_REQUIRE_EXPORT = 'createCommonjsRequire';
208
+
209
+ function getDynamicModuleRegistry(
210
+ isDynamicRequireModulesEnabled,
211
+ dynamicRequireModules,
212
+ commonDir,
213
+ ignoreDynamicRequires
214
+ ) {
215
+ if (!isDynamicRequireModulesEnabled) {
216
+ return `export function ${COMMONJS_REQUIRE_EXPORT}(path) {
217
+ ${FAILED_REQUIRE_ERROR}
218
+ }`;
219
+ }
220
+ const dynamicModuleImports = [...dynamicRequireModules.values()]
221
+ .map(
222
+ (id, index) =>
223
+ `import ${
224
+ id.endsWith('.json') ? `json${index}` : `{ __require as require${index} }`
225
+ } from ${JSON.stringify(id)};`
226
+ )
227
+ .join('\n');
228
+ const dynamicModuleProps = [...dynamicRequireModules.keys()]
229
+ .map(
230
+ (id, index) =>
231
+ `\t\t${JSON.stringify(getVirtualPathForDynamicRequirePath(id, commonDir))}: ${
232
+ id.endsWith('.json') ? `function () { return json${index}; }` : `require${index}`
233
+ }`
234
+ )
235
+ .join(',\n');
236
+ return `${dynamicModuleImports}
237
+
238
+ var dynamicModules;
239
+
240
+ function getDynamicModules() {
241
+ return dynamicModules || (dynamicModules = {
242
+ ${dynamicModuleProps}
243
+ });
244
+ }
245
+
246
+ export function ${CREATE_COMMONJS_REQUIRE_EXPORT}(originalModuleDir) {
247
+ function handleRequire(path) {
248
+ var resolvedPath = commonjsResolve(path, originalModuleDir);
249
+ if (resolvedPath !== null) {
250
+ return getDynamicModules()[resolvedPath]();
251
+ }
252
+ ${ignoreDynamicRequires ? 'return require(path);' : FAILED_REQUIRE_ERROR}
253
+ }
254
+ handleRequire.resolve = function (path) {
255
+ var resolvedPath = commonjsResolve(path, originalModuleDir);
256
+ if (resolvedPath !== null) {
257
+ return resolvedPath;
258
+ }
259
+ return require.resolve(path);
260
+ }
261
+ return handleRequire;
262
+ }
263
+
264
+ function commonjsResolve (path, originalModuleDir) {
265
+ var shouldTryNodeModules = isPossibleNodeModulesPath(path);
266
+ path = normalize(path);
267
+ var relPath;
268
+ if (path[0] === '/') {
269
+ originalModuleDir = '';
270
+ }
271
+ var modules = getDynamicModules();
272
+ var checkedExtensions = ['', '.js', '.json'];
273
+ while (true) {
274
+ if (!shouldTryNodeModules) {
275
+ relPath = normalize(originalModuleDir + '/' + path);
276
+ } else {
277
+ relPath = normalize(originalModuleDir + '/node_modules/' + path);
278
+ }
279
+
280
+ if (relPath.endsWith('/..')) {
281
+ break; // Travelled too far up, avoid infinite loop
282
+ }
283
+
284
+ for (var extensionIndex = 0; extensionIndex < checkedExtensions.length; extensionIndex++) {
285
+ var resolvedPath = relPath + checkedExtensions[extensionIndex];
286
+ if (modules[resolvedPath]) {
287
+ return resolvedPath;
288
+ }
289
+ }
290
+ if (!shouldTryNodeModules) break;
291
+ var nextDir = normalize(originalModuleDir + '/..');
292
+ if (nextDir === originalModuleDir) break;
293
+ originalModuleDir = nextDir;
294
+ }
295
+ return null;
296
+ }
297
+
298
+ function isPossibleNodeModulesPath (modulePath) {
299
+ var c0 = modulePath[0];
300
+ if (c0 === '/' || c0 === '\\\\') return false;
301
+ var c1 = modulePath[1], c2 = modulePath[2];
302
+ if ((c0 === '.' && (!c1 || c1 === '/' || c1 === '\\\\')) ||
303
+ (c0 === '.' && c1 === '.' && (!c2 || c2 === '/' || c2 === '\\\\'))) return false;
304
+ if (c1 === ':' && (c2 === '/' || c2 === '\\\\')) return false;
305
+ return true;
306
+ }
307
+
308
+ function normalize (path) {
309
+ path = path.replace(/\\\\/g, '/');
310
+ var parts = path.split('/');
311
+ var slashed = parts[0] === '';
312
+ for (var i = 1; i < parts.length; i++) {
313
+ if (parts[i] === '.' || parts[i] === '') {
314
+ parts.splice(i--, 1);
315
+ }
316
+ }
317
+ for (var i = 1; i < parts.length; i++) {
318
+ if (parts[i] !== '..') continue;
319
+ if (i > 0 && parts[i - 1] !== '..' && parts[i - 1] !== '.') {
320
+ parts.splice(--i, 2);
321
+ i--;
322
+ }
323
+ }
324
+ path = parts.join('/');
325
+ if (slashed && path[0] !== '/') path = '/' + path;
326
+ else if (path.length === 0) path = '.';
327
+ return path;
328
+ }`;
329
+ }
330
+
331
+ const isWrappedId = (id, suffix) => id.endsWith(suffix);
332
+ const wrapId = (id, suffix) => `\0${id}${suffix}`;
333
+ const unwrapId = (wrappedId, suffix) => wrappedId.slice(1, -suffix.length);
334
+
335
+ // A proxy module when a module is required from non-wrapped CommonJS. Is different for ESM and CommonJS requires.
336
+ const PROXY_SUFFIX = '?commonjs-proxy';
337
+ // Indicates that a required module is wrapped commonjs and needs special handling.
338
+ const WRAPPED_SUFFIX = '?commonjs-wrapped';
339
+ // Indicates that a required module is external
340
+ const EXTERNAL_SUFFIX = '?commonjs-external';
341
+ // A helper module that contains the exports object of a module
342
+ const EXPORTS_SUFFIX = '?commonjs-exports';
343
+ // A helper module that contains the module object of a module, e.g. when module.exports is reassigned
344
+ const MODULE_SUFFIX = '?commonjs-module';
345
+ // A special proxy for CommonJS entry points
346
+ const ENTRY_SUFFIX = '?commonjs-entry';
347
+ // A proxy when wrapped ESM is required from CommonJS
348
+ const ES_IMPORT_SUFFIX = '?commonjs-es-import';
349
+
350
+ const DYNAMIC_MODULES_ID = '\0commonjs-dynamic-modules';
351
+ const HELPERS_ID = '\0commonjsHelpers.js';
352
+
353
+ const IS_WRAPPED_COMMONJS = 'withRequireFunction';
354
+
355
+ // `x['default']` is used instead of `x.default` for backward compatibility with ES3 browsers.
356
+ // Minifiers like uglify will usually transpile it back if compatibility with ES3 is not enabled.
357
+ // This could be improved by inspecting Rollup's "generatedCode" option
358
+
359
+ const HELPERS = `
360
+ export var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
361
+
362
+ export function getDefaultExportFromCjs (x) {
363
+ return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
364
+ }
365
+
366
+ export function getDefaultExportFromNamespaceIfPresent (n) {
367
+ return n && Object.prototype.hasOwnProperty.call(n, 'default') ? n['default'] : n;
368
+ }
369
+
370
+ export function getDefaultExportFromNamespaceIfNotNamed (n) {
371
+ return n && Object.prototype.hasOwnProperty.call(n, 'default') && Object.keys(n).length === 1 ? n['default'] : n;
372
+ }
373
+
374
+ export function getAugmentedNamespace(n) {
375
+ if (Object.prototype.hasOwnProperty.call(n, '__esModule')) return n;
376
+ var f = n.default;
377
+ if (typeof f == "function") {
378
+ var a = function a () {
379
+ var isInstance = false;
380
+ try {
381
+ isInstance = this instanceof a;
382
+ } catch {}
383
+ if (isInstance) {
384
+ return Reflect.construct(f, arguments, this.constructor);
385
+ }
386
+ return f.apply(this, arguments);
387
+ };
388
+ a.prototype = f.prototype;
389
+ } else a = {};
390
+ Object.defineProperty(a, '__esModule', {value: true});
391
+ Object.keys(n).forEach(function (k) {
392
+ var d = Object.getOwnPropertyDescriptor(n, k);
393
+ Object.defineProperty(a, k, d.get ? d : {
394
+ enumerable: true,
395
+ get: function () {
396
+ return n[k];
397
+ }
398
+ });
399
+ });
400
+ return a;
401
+ }
402
+ `;
403
+
404
+ function getHelpersModule() {
405
+ return HELPERS;
406
+ }
407
+
408
+ function getUnknownRequireProxy(id, requireReturnsDefault) {
409
+ if (requireReturnsDefault === true || id.endsWith('.json')) {
410
+ return `export { default } from ${JSON.stringify(id)};`;
411
+ }
412
+ const name = getName(id);
413
+ const exported =
414
+ requireReturnsDefault === 'auto'
415
+ ? `import { getDefaultExportFromNamespaceIfNotNamed } from "${HELPERS_ID}"; export default /*@__PURE__*/getDefaultExportFromNamespaceIfNotNamed(${name});`
416
+ : requireReturnsDefault === 'preferred'
417
+ ? `import { getDefaultExportFromNamespaceIfPresent } from "${HELPERS_ID}"; export default /*@__PURE__*/getDefaultExportFromNamespaceIfPresent(${name});`
418
+ : !requireReturnsDefault
419
+ ? `import { getAugmentedNamespace } from "${HELPERS_ID}"; export default /*@__PURE__*/getAugmentedNamespace(${name});`
420
+ : `export default ${name};`;
421
+ return `import * as ${name} from ${JSON.stringify(id)}; ${exported}`;
422
+ }
423
+
424
+ async function getStaticRequireProxy(id, requireReturnsDefault, loadModule) {
425
+ const name = getName(id);
426
+ const {
427
+ meta: { commonjs: commonjsMeta }
428
+ } = await loadModule({ id });
429
+ if (!commonjsMeta) {
430
+ return getUnknownRequireProxy(id, requireReturnsDefault);
431
+ }
432
+ if (commonjsMeta.isCommonJS) {
433
+ return `export { __moduleExports as default } from ${JSON.stringify(id)};`;
434
+ }
435
+ if (!requireReturnsDefault) {
436
+ return `import { getAugmentedNamespace } from "${HELPERS_ID}"; import * as ${name} from ${JSON.stringify(
437
+ id
438
+ )}; export default /*@__PURE__*/getAugmentedNamespace(${name});`;
439
+ }
440
+ if (
441
+ requireReturnsDefault !== true &&
442
+ (requireReturnsDefault === 'namespace' ||
443
+ !commonjsMeta.hasDefaultExport ||
444
+ (requireReturnsDefault === 'auto' && commonjsMeta.hasNamedExports))
445
+ ) {
446
+ return `import * as ${name} from ${JSON.stringify(id)}; export default ${name};`;
447
+ }
448
+ return `export { default } from ${JSON.stringify(id)};`;
449
+ }
450
+
451
+ function getEntryProxy(id, defaultIsModuleExports, getModuleInfo, shebang) {
452
+ const {
453
+ meta: { commonjs: commonjsMeta },
454
+ hasDefaultExport
455
+ } = getModuleInfo(id);
456
+ if (!commonjsMeta || commonjsMeta.isCommonJS !== IS_WRAPPED_COMMONJS) {
457
+ const stringifiedId = JSON.stringify(id);
458
+ let code = `export * from ${stringifiedId};`;
459
+ if (hasDefaultExport) {
460
+ code += `export { default } from ${stringifiedId};`;
461
+ }
462
+ return shebang + code;
463
+ }
464
+ const result = getEsImportProxy(id, defaultIsModuleExports, true);
465
+ return {
466
+ ...result,
467
+ code: shebang + result.code
468
+ };
469
+ }
470
+
471
+ function getEsImportProxy(id, defaultIsModuleExports, moduleSideEffects) {
472
+ const name = getName(id);
473
+ const exportsName = `${name}Exports`;
474
+ const requireModule = `require${capitalize(name)}`;
475
+ let code =
476
+ `import { getDefaultExportFromCjs } from "${HELPERS_ID}";\n` +
477
+ `import { __require as ${requireModule} } from ${JSON.stringify(id)};\n` +
478
+ `var ${exportsName} = ${moduleSideEffects ? '' : '/*@__PURE__*/ '}${requireModule}();\n` +
479
+ `export { ${exportsName} as __moduleExports };`;
480
+ if (defaultIsModuleExports === true) {
481
+ code += `\nexport { ${exportsName} as default };`;
482
+ } else if (defaultIsModuleExports === false) {
483
+ code += `\nexport default ${exportsName}.default;`;
484
+ } else {
485
+ code += `\nexport default /*@__PURE__*/getDefaultExportFromCjs(${exportsName});`;
486
+ }
487
+ return {
488
+ code,
489
+ syntheticNamedExports: '__moduleExports'
490
+ };
491
+ }
492
+
493
+ // For external Node built-ins required from wrapped CommonJS modules, we must not
494
+ // hoist an ESM import of the built-in (which would eagerly load it). Instead,
495
+ // expose a lazy `__require()` that resolves the built-in at runtime via
496
+ // `createRequire(import.meta.url)`.
497
+ function getExternalBuiltinRequireProxy(id) {
498
+ const stringifiedId = JSON.stringify(id);
499
+ return (
500
+ `import { createRequire } from 'node:module';\n` +
501
+ `const require = createRequire(import.meta.url);\n` +
502
+ `export function __require() { return require(${stringifiedId}); }`
503
+ );
504
+ }
505
+
506
+ /* eslint-disable no-param-reassign, no-undefined */
507
+
508
+
509
+ function getCandidatesForExtension(resolved, extension) {
510
+ return [resolved + extension, `${resolved}${sep}index${extension}`];
511
+ }
512
+
513
+ function getCandidates(resolved, extensions) {
514
+ return extensions.reduce(
515
+ (paths, extension) => paths.concat(getCandidatesForExtension(resolved, extension)),
516
+ [resolved]
517
+ );
518
+ }
519
+
520
+ function resolveExtensions(importee, importer, extensions) {
521
+ // not our problem
522
+ if (importee[0] !== '.' || !importer) return undefined;
523
+
524
+ const resolved = resolve(dirname(importer), importee);
525
+ const candidates = getCandidates(resolved, extensions);
526
+
527
+ for (let i = 0; i < candidates.length; i += 1) {
528
+ try {
529
+ const stats = statSync(candidates[i]);
530
+ if (stats.isFile()) return { id: candidates[i] };
531
+ } catch (err) {
532
+ /* noop */
533
+ }
534
+ }
535
+
536
+ return undefined;
537
+ }
538
+
539
+ function getResolveId(extensions, isPossibleCjsId) {
540
+ const currentlyResolving = new Map();
541
+
542
+ return {
543
+ /**
544
+ * This is a Maps of importers to Sets of require sources being resolved at
545
+ * the moment by resolveRequireSourcesAndUpdateMeta
546
+ */
547
+ currentlyResolving,
548
+ async resolveId(importee, importer, resolveOptions) {
549
+ const customOptions = resolveOptions.custom;
550
+ // All logic below is specific to ES imports.
551
+ // Also, if we do not skip this logic for requires that are resolved while
552
+ // transforming a commonjs file, it can easily lead to deadlocks.
553
+ if (customOptions?.['node-resolve']?.isRequire) {
554
+ return null;
555
+ }
556
+ const currentlyResolvingForParent = currentlyResolving.get(importer);
557
+ if (currentlyResolvingForParent && currentlyResolvingForParent.has(importee)) {
558
+ this.warn({
559
+ code: 'THIS_RESOLVE_WITHOUT_OPTIONS',
560
+ message:
561
+ 'It appears a plugin has implemented a "resolveId" hook that uses "this.resolve" without forwarding the third "options" parameter of "resolveId". This is problematic as it can lead to wrong module resolutions especially for the node-resolve plugin and in certain cases cause early exit errors for the commonjs plugin.\nIn rare cases, this warning can appear if the same file is both imported and required from the same mixed ES/CommonJS module, in which case it can be ignored.',
562
+ url: 'https://rollupjs.org/guide/en/#resolveid'
563
+ });
564
+ return null;
565
+ }
566
+
567
+ if (isWrappedId(importee, WRAPPED_SUFFIX)) {
568
+ return unwrapId(importee, WRAPPED_SUFFIX);
569
+ }
570
+
571
+ if (
572
+ importee.endsWith(ENTRY_SUFFIX) ||
573
+ isWrappedId(importee, MODULE_SUFFIX) ||
574
+ isWrappedId(importee, EXPORTS_SUFFIX) ||
575
+ isWrappedId(importee, PROXY_SUFFIX) ||
576
+ isWrappedId(importee, ES_IMPORT_SUFFIX) ||
577
+ isWrappedId(importee, EXTERNAL_SUFFIX) ||
578
+ importee.startsWith(HELPERS_ID) ||
579
+ importee === DYNAMIC_MODULES_ID
580
+ ) {
581
+ return importee;
582
+ }
583
+
584
+ if (importer) {
585
+ if (
586
+ importer === DYNAMIC_MODULES_ID ||
587
+ // Proxies are only importing resolved ids, no need to resolve again
588
+ isWrappedId(importer, PROXY_SUFFIX) ||
589
+ isWrappedId(importer, ES_IMPORT_SUFFIX) ||
590
+ importer.endsWith(ENTRY_SUFFIX)
591
+ ) {
592
+ return importee;
593
+ }
594
+ if (isWrappedId(importer, EXTERNAL_SUFFIX)) {
595
+ // We need to return null for unresolved imports so that the proper warning is shown
596
+ if (
597
+ !(await this.resolve(
598
+ importee,
599
+ importer,
600
+ Object.assign({ skipSelf: true }, resolveOptions)
601
+ ))
602
+ ) {
603
+ return null;
604
+ }
605
+ // For other external imports, we need to make sure they are handled as external
606
+ return { id: importee, external: true };
607
+ }
608
+ }
609
+
610
+ if (importee.startsWith('\0')) {
611
+ return null;
612
+ }
613
+
614
+ // If this is an entry point or ESM import, we need to figure out if the importee is wrapped and
615
+ // if that is the case, we need to add a proxy.
616
+ const resolved =
617
+ (await this.resolve(
618
+ importee,
619
+ importer,
620
+ Object.assign({ skipSelf: true }, resolveOptions)
621
+ )) || resolveExtensions(importee, importer, extensions);
622
+ // Make sure that even if other plugins resolve again, we ignore our own proxies
623
+ if (
624
+ !resolved ||
625
+ resolved.external ||
626
+ resolved.id.endsWith(ENTRY_SUFFIX) ||
627
+ isWrappedId(resolved.id, ES_IMPORT_SUFFIX) ||
628
+ !isPossibleCjsId(resolved.id)
629
+ ) {
630
+ return resolved;
631
+ }
632
+ const moduleInfo = await this.load(resolved);
633
+ const {
634
+ meta: { commonjs: commonjsMeta }
635
+ } = moduleInfo;
636
+ if (commonjsMeta) {
637
+ const { isCommonJS } = commonjsMeta;
638
+ if (isCommonJS) {
639
+ if (resolveOptions.isEntry) {
640
+ moduleInfo.moduleSideEffects = true;
641
+ // We must not precede entry proxies with a `\0` as that will mess up relative external resolution
642
+ return resolved.id + ENTRY_SUFFIX;
643
+ }
644
+ if (isCommonJS === IS_WRAPPED_COMMONJS) {
645
+ return { id: wrapId(resolved.id, ES_IMPORT_SUFFIX), meta: { commonjs: { resolved } } };
646
+ }
647
+ }
648
+ }
649
+ return resolved;
650
+ }
651
+ };
652
+ }
653
+
654
+ function getRequireResolver(extensions, detectCyclesAndConditional, currentlyResolving) {
655
+ const knownCjsModuleTypes = Object.create(null);
656
+ const requiredIds = Object.create(null);
657
+ const unconditionallyRequiredIds = Object.create(null);
658
+ const dependencies = Object.create(null);
659
+ const getDependencies = (id) => dependencies[id] || (dependencies[id] = new Set());
660
+
661
+ const isCyclic = (id) => {
662
+ const dependenciesToCheck = new Set(getDependencies(id));
663
+ for (const dependency of dependenciesToCheck) {
664
+ if (dependency === id) {
665
+ return true;
666
+ }
667
+ for (const childDependency of getDependencies(dependency)) {
668
+ dependenciesToCheck.add(childDependency);
669
+ }
670
+ }
671
+ return false;
672
+ };
673
+
674
+ // Once a module is listed here, its type (wrapped or not) is fixed and may
675
+ // not change for the rest of the current build, to not break already
676
+ // transformed modules.
677
+ const fullyAnalyzedModules = Object.create(null);
678
+
679
+ const getTypeForFullyAnalyzedModule = (id) => {
680
+ const knownType = knownCjsModuleTypes[id];
681
+ if (knownType !== true || !detectCyclesAndConditional || fullyAnalyzedModules[id]) {
682
+ return knownType;
683
+ }
684
+ if (isCyclic(id)) {
685
+ return (knownCjsModuleTypes[id] = IS_WRAPPED_COMMONJS);
686
+ }
687
+ return knownType;
688
+ };
689
+
690
+ const setInitialParentType = (id, initialCommonJSType) => {
691
+ // Fully analyzed modules may never change type
692
+ if (fullyAnalyzedModules[id]) {
693
+ return;
694
+ }
695
+ knownCjsModuleTypes[id] = initialCommonJSType;
696
+ if (
697
+ detectCyclesAndConditional &&
698
+ knownCjsModuleTypes[id] === true &&
699
+ requiredIds[id] &&
700
+ !unconditionallyRequiredIds[id]
701
+ ) {
702
+ knownCjsModuleTypes[id] = IS_WRAPPED_COMMONJS;
703
+ }
704
+ };
705
+
706
+ const analyzeRequiredModule = async (parentId, resolved, isConditional, loadModule) => {
707
+ const childId = resolved.id;
708
+ requiredIds[childId] = true;
709
+ if (!(isConditional || knownCjsModuleTypes[parentId] === IS_WRAPPED_COMMONJS)) {
710
+ unconditionallyRequiredIds[childId] = true;
711
+ }
712
+
713
+ getDependencies(parentId).add(childId);
714
+ if (!isCyclic(childId)) {
715
+ // This makes sure the current transform handler waits for all direct
716
+ // dependencies to be loaded and transformed and therefore for all
717
+ // transitive CommonJS dependencies to be loaded as well so that all
718
+ // cycles have been found and knownCjsModuleTypes is reliable.
719
+ await loadModule(resolved);
720
+ }
721
+ };
722
+
723
+ const getTypeForImportedModule = async (resolved, loadModule) => {
724
+ if (resolved.id in knownCjsModuleTypes) {
725
+ // This handles cyclic ES dependencies
726
+ return knownCjsModuleTypes[resolved.id];
727
+ }
728
+ const {
729
+ meta: { commonjs }
730
+ } = await loadModule(resolved);
731
+ return (commonjs && commonjs.isCommonJS) || false;
732
+ };
733
+
734
+ return {
735
+ getWrappedIds: () =>
736
+ Object.keys(knownCjsModuleTypes).filter(
737
+ (id) => knownCjsModuleTypes[id] === IS_WRAPPED_COMMONJS
738
+ ),
739
+ isRequiredId: (id) => requiredIds[id],
740
+ async shouldTransformCachedModule({
741
+ id: parentId,
742
+ resolvedSources,
743
+ meta: { commonjs: parentMeta }
744
+ }) {
745
+ // We explicitly track ES modules to handle circular imports
746
+ if (!(parentMeta && parentMeta.isCommonJS)) knownCjsModuleTypes[parentId] = false;
747
+ if (isWrappedId(parentId, ES_IMPORT_SUFFIX)) return false;
748
+ const parentRequires = parentMeta && parentMeta.requires;
749
+ if (parentRequires) {
750
+ setInitialParentType(parentId, parentMeta.initialCommonJSType);
751
+ await Promise.all(
752
+ parentRequires.map(({ resolved, isConditional }) =>
753
+ analyzeRequiredModule(parentId, resolved, isConditional, this.load)
754
+ )
755
+ );
756
+ if (getTypeForFullyAnalyzedModule(parentId) !== parentMeta.isCommonJS) {
757
+ return true;
758
+ }
759
+ for (const {
760
+ resolved: { id }
761
+ } of parentRequires) {
762
+ if (getTypeForFullyAnalyzedModule(id) !== parentMeta.isRequiredCommonJS[id]) {
763
+ return true;
764
+ }
765
+ }
766
+ // Now that we decided to go with the cached copy, neither the parent
767
+ // module nor any of its children may change types anymore
768
+ fullyAnalyzedModules[parentId] = true;
769
+ for (const {
770
+ resolved: { id }
771
+ } of parentRequires) {
772
+ fullyAnalyzedModules[id] = true;
773
+ }
774
+ }
775
+ const parentRequireSet = new Set((parentRequires || []).map(({ resolved: { id } }) => id));
776
+ return (
777
+ await Promise.all(
778
+ Object.keys(resolvedSources)
779
+ .map((source) => resolvedSources[source])
780
+ .filter(({ id, external }) => !(external || parentRequireSet.has(id)))
781
+ .map(async (resolved) => {
782
+ if (isWrappedId(resolved.id, ES_IMPORT_SUFFIX)) {
783
+ return (
784
+ (await getTypeForImportedModule(
785
+ (
786
+ await this.load(resolved)
787
+ ).meta.commonjs.resolved,
788
+ this.load
789
+ )) !== IS_WRAPPED_COMMONJS
790
+ );
791
+ }
792
+ return (await getTypeForImportedModule(resolved, this.load)) === IS_WRAPPED_COMMONJS;
793
+ })
794
+ )
795
+ ).some((shouldTransform) => shouldTransform);
796
+ },
797
+ /* eslint-disable no-param-reassign */
798
+ resolveRequireSourcesAndUpdateMeta:
799
+ (rollupContext) => async (parentId, isParentCommonJS, parentMeta, sources) => {
800
+ parentMeta.initialCommonJSType = isParentCommonJS;
801
+ parentMeta.requires = [];
802
+ parentMeta.isRequiredCommonJS = Object.create(null);
803
+ setInitialParentType(parentId, isParentCommonJS);
804
+ const currentlyResolvingForParent = currentlyResolving.get(parentId) || new Set();
805
+ currentlyResolving.set(parentId, currentlyResolvingForParent);
806
+ const requireTargets = await Promise.all(
807
+ sources.map(async ({ source, isConditional }) => {
808
+ // Never analyze or proxy internal modules
809
+ if (source.startsWith('\0')) {
810
+ return { id: source, allowProxy: false };
811
+ }
812
+ currentlyResolvingForParent.add(source);
813
+ const resolved =
814
+ (await rollupContext.resolve(source, parentId, {
815
+ skipSelf: false,
816
+ custom: { 'node-resolve': { isRequire: true } }
817
+ })) || resolveExtensions(source, parentId, extensions);
818
+ currentlyResolvingForParent.delete(source);
819
+ if (!resolved) {
820
+ return { id: wrapId(source, EXTERNAL_SUFFIX), allowProxy: false };
821
+ }
822
+ const childId = resolved.id;
823
+ if (resolved.external) {
824
+ return { id: wrapId(childId, EXTERNAL_SUFFIX), allowProxy: false };
825
+ }
826
+ parentMeta.requires.push({ resolved, isConditional });
827
+ await analyzeRequiredModule(parentId, resolved, isConditional, rollupContext.load);
828
+ return { id: childId, allowProxy: true };
829
+ })
830
+ );
831
+ parentMeta.isCommonJS = getTypeForFullyAnalyzedModule(parentId);
832
+ fullyAnalyzedModules[parentId] = true;
833
+ return requireTargets.map(({ id: dependencyId, allowProxy }, index) => {
834
+ // eslint-disable-next-line no-multi-assign
835
+ let isCommonJS = (parentMeta.isRequiredCommonJS[dependencyId] =
836
+ getTypeForFullyAnalyzedModule(dependencyId));
837
+ // Special-case external Node built-ins to be handled via a lazy __require
838
+ // helper instead of hoisted ESM imports when strict wrapping is used.
839
+ const isExternalWrapped = isWrappedId(dependencyId, EXTERNAL_SUFFIX);
840
+ let resolvedDependencyId = dependencyId;
841
+ if (parentMeta.isCommonJS === IS_WRAPPED_COMMONJS && !allowProxy && isExternalWrapped) {
842
+ const actualExternalId = unwrapId(dependencyId, EXTERNAL_SUFFIX);
843
+ if (actualExternalId.startsWith('node:')) {
844
+ isCommonJS = IS_WRAPPED_COMMONJS;
845
+ parentMeta.isRequiredCommonJS[dependencyId] = isCommonJS;
846
+ }
847
+ } else if (isExternalWrapped && !allowProxy) {
848
+ // If the parent is not wrapped but the dependency is a node: builtin external,
849
+ // unwrap the EXTERNAL_SUFFIX so it's treated as a normal external.
850
+ // This avoids trying to load the lazy __require proxy for non-wrapped contexts.
851
+ const actualExternalId = unwrapId(dependencyId, EXTERNAL_SUFFIX);
852
+ if (actualExternalId.startsWith('node:')) {
853
+ resolvedDependencyId = actualExternalId;
854
+ }
855
+ }
856
+ const isWrappedCommonJS = isCommonJS === IS_WRAPPED_COMMONJS;
857
+ fullyAnalyzedModules[dependencyId] = true;
858
+ const moduleInfo =
859
+ isWrappedCommonJS && !isExternalWrapped
860
+ ? rollupContext.getModuleInfo(dependencyId)
861
+ : null;
862
+ // For wrapped dependencies, annotate the generated require call as pure only
863
+ // when Rollup has module info and it explicitly reports no side effects.
864
+ // Note: For external Node built-ins (handled via EXTERNAL_SUFFIX), the module
865
+ // has not been loaded yet at this point and getModuleInfo returns null.
866
+ // Default to side effects = true in that case to be safe.
867
+ // Preserve Rollup's tri-state semantics (true | false | 'no-treeshake') when available.
868
+ const wrappedModuleSideEffects = !isWrappedCommonJS
869
+ ? false
870
+ : moduleInfo?.moduleSideEffects ?? true;
871
+ return {
872
+ wrappedModuleSideEffects,
873
+ source: sources[index].source,
874
+ id: allowProxy
875
+ ? wrapId(resolvedDependencyId, isWrappedCommonJS ? WRAPPED_SUFFIX : PROXY_SUFFIX)
876
+ : resolvedDependencyId,
877
+ isCommonJS
878
+ };
879
+ });
880
+ },
881
+ isCurrentlyResolving(source, parentId) {
882
+ const currentlyResolvingForParent = currentlyResolving.get(parentId);
883
+ return currentlyResolvingForParent && currentlyResolvingForParent.has(source);
884
+ }
885
+ };
886
+ }
887
+
888
+ function validateVersion(actualVersion, peerDependencyVersion, name) {
889
+ const versionRegexp = /\^(\d+\.\d+\.\d+)/g;
890
+ let minMajor = Infinity;
891
+ let minMinor = Infinity;
892
+ let minPatch = Infinity;
893
+ let foundVersion;
894
+ // eslint-disable-next-line no-cond-assign
895
+ while ((foundVersion = versionRegexp.exec(peerDependencyVersion))) {
896
+ const [foundMajor, foundMinor, foundPatch] = foundVersion[1].split('.').map(Number);
897
+ if (foundMajor < minMajor) {
898
+ minMajor = foundMajor;
899
+ minMinor = foundMinor;
900
+ minPatch = foundPatch;
901
+ }
902
+ }
903
+ if (!actualVersion) {
904
+ throw new Error(
905
+ `Insufficient ${name} version: "@rollup/plugin-commonjs" requires at least ${name}@${minMajor}.${minMinor}.${minPatch}.`
906
+ );
907
+ }
908
+ const [major, minor, patch] = actualVersion.split('.').map(Number);
909
+ if (
910
+ major < minMajor ||
911
+ (major === minMajor && (minor < minMinor || (minor === minMinor && patch < minPatch)))
912
+ ) {
913
+ throw new Error(
914
+ `Insufficient ${name} version: "@rollup/plugin-commonjs" requires at least ${name}@${minMajor}.${minMinor}.${minPatch} but found ${name}@${actualVersion}.`
915
+ );
916
+ }
917
+ }
918
+
919
+ const operators = {
920
+ '==': (x) => equals(x.left, x.right, false),
921
+
922
+ '!=': (x) => not(operators['=='](x)),
923
+
924
+ '===': (x) => equals(x.left, x.right, true),
925
+
926
+ '!==': (x) => not(operators['==='](x)),
927
+
928
+ '!': (x) => isFalsy(x.argument),
929
+
930
+ '&&': (x) => isTruthy(x.left) && isTruthy(x.right),
931
+
932
+ '||': (x) => isTruthy(x.left) || isTruthy(x.right)
933
+ };
934
+
935
+ function not(value) {
936
+ return value === null ? value : !value;
937
+ }
938
+
939
+ function equals(a, b, strict) {
940
+ if (a.type !== b.type) return null;
941
+ // eslint-disable-next-line eqeqeq
942
+ if (a.type === 'Literal') return strict ? a.value === b.value : a.value == b.value;
943
+ return null;
944
+ }
945
+
946
+ function isTruthy(node) {
947
+ if (!node) return false;
948
+ if (node.type === 'Literal') return !!node.value;
949
+ if (node.type === 'ParenthesizedExpression') return isTruthy(node.expression);
950
+ if (node.operator in operators) return operators[node.operator](node);
951
+ return null;
952
+ }
953
+
954
+ function isFalsy(node) {
955
+ return not(isTruthy(node));
956
+ }
957
+
958
+ function getKeypath(node) {
959
+ const parts = [];
960
+
961
+ while (node.type === 'MemberExpression') {
962
+ if (node.computed) return null;
963
+
964
+ parts.unshift(node.property.name);
965
+ // eslint-disable-next-line no-param-reassign
966
+ node = node.object;
967
+ }
968
+
969
+ if (node.type !== 'Identifier') return null;
970
+
971
+ const { name } = node;
972
+ parts.unshift(name);
973
+
974
+ return { name, keypath: parts.join('.') };
975
+ }
976
+
977
+ const KEY_COMPILED_ESM = '__esModule';
978
+
979
+ function getDefineCompiledEsmType(node) {
980
+ const definedPropertyWithExports = getDefinePropertyCallName(node, 'exports');
981
+ const definedProperty =
982
+ definedPropertyWithExports || getDefinePropertyCallName(node, 'module.exports');
983
+ if (definedProperty && definedProperty.key === KEY_COMPILED_ESM) {
984
+ return isTruthy(definedProperty.value)
985
+ ? definedPropertyWithExports
986
+ ? 'exports'
987
+ : 'module'
988
+ : false;
989
+ }
990
+ return false;
991
+ }
992
+
993
+ function getDefinePropertyCallName(node, targetName) {
994
+ const {
995
+ callee: { object, property }
996
+ } = node;
997
+ if (!object || object.type !== 'Identifier' || object.name !== 'Object') return;
998
+ if (!property || property.type !== 'Identifier' || property.name !== 'defineProperty') return;
999
+ if (node.arguments.length !== 3) return;
1000
+
1001
+ const targetNames = targetName.split('.');
1002
+ const [target, key, value] = node.arguments;
1003
+ if (targetNames.length === 1) {
1004
+ if (target.type !== 'Identifier' || target.name !== targetNames[0]) {
1005
+ return;
1006
+ }
1007
+ }
1008
+
1009
+ if (targetNames.length === 2) {
1010
+ if (
1011
+ target.type !== 'MemberExpression' ||
1012
+ target.object.name !== targetNames[0] ||
1013
+ target.property.name !== targetNames[1]
1014
+ ) {
1015
+ return;
1016
+ }
1017
+ }
1018
+
1019
+ if (value.type !== 'ObjectExpression' || !value.properties) return;
1020
+
1021
+ const valueProperty = value.properties.find((p) => p.key && p.key.name === 'value');
1022
+ if (!valueProperty || !valueProperty.value) return;
1023
+
1024
+ // eslint-disable-next-line consistent-return
1025
+ return { key: key.value, value: valueProperty.value };
1026
+ }
1027
+
1028
+ function isShorthandProperty(parent) {
1029
+ return parent && parent.type === 'Property' && parent.shorthand;
1030
+ }
1031
+
1032
+ function wrapCode(magicString, uses, moduleName, exportsName, indentExclusionRanges) {
1033
+ const args = [];
1034
+ const passedArgs = [];
1035
+ if (uses.module) {
1036
+ args.push('module');
1037
+ passedArgs.push(moduleName);
1038
+ }
1039
+ if (uses.exports) {
1040
+ args.push('exports');
1041
+ passedArgs.push(uses.module ? `${moduleName}.exports` : exportsName);
1042
+ }
1043
+ magicString
1044
+ .trim()
1045
+ .indent('\t', { exclude: indentExclusionRanges })
1046
+ .prepend(`(function (${args.join(', ')}) {\n`)
1047
+ // For some reason, this line is only indented correctly when using a
1048
+ // require-wrapper if we have this leading space
1049
+ .append(` \n} (${passedArgs.join(', ')}));`);
1050
+ }
1051
+
1052
+ function rewriteExportsAndGetExportsBlock(
1053
+ magicString,
1054
+ moduleName,
1055
+ exportsName,
1056
+ exportedExportsName,
1057
+ wrapped,
1058
+ moduleExportsAssignments,
1059
+ firstTopLevelModuleExportsAssignment,
1060
+ exportsAssignmentsByName,
1061
+ topLevelAssignments,
1062
+ defineCompiledEsmExpressions,
1063
+ deconflictedExportNames,
1064
+ code,
1065
+ HELPERS_NAME,
1066
+ exportMode,
1067
+ defaultIsModuleExports,
1068
+ usesRequireWrapper,
1069
+ requireName
1070
+ ) {
1071
+ const exports = [];
1072
+ const exportDeclarations = [];
1073
+
1074
+ if (usesRequireWrapper) {
1075
+ getExportsWhenUsingRequireWrapper(
1076
+ magicString,
1077
+ wrapped,
1078
+ exportMode,
1079
+ exports,
1080
+ moduleExportsAssignments,
1081
+ exportsAssignmentsByName,
1082
+ moduleName,
1083
+ exportsName,
1084
+ requireName,
1085
+ defineCompiledEsmExpressions
1086
+ );
1087
+ } else if (exportMode === 'replace') {
1088
+ getExportsForReplacedModuleExports(
1089
+ magicString,
1090
+ exports,
1091
+ exportDeclarations,
1092
+ moduleExportsAssignments,
1093
+ firstTopLevelModuleExportsAssignment,
1094
+ exportsName,
1095
+ defaultIsModuleExports,
1096
+ HELPERS_NAME
1097
+ );
1098
+ } else {
1099
+ if (exportMode === 'module') {
1100
+ exportDeclarations.push(`var ${exportedExportsName} = ${moduleName}.exports`);
1101
+ exports.push(`${exportedExportsName} as __moduleExports`);
1102
+ } else {
1103
+ exports.push(`${exportsName} as __moduleExports`);
1104
+ }
1105
+ if (wrapped) {
1106
+ exportDeclarations.push(
1107
+ getDefaultExportDeclaration(exportedExportsName, defaultIsModuleExports, HELPERS_NAME)
1108
+ );
1109
+ } else {
1110
+ getExports(
1111
+ magicString,
1112
+ exports,
1113
+ exportDeclarations,
1114
+ moduleExportsAssignments,
1115
+ exportsAssignmentsByName,
1116
+ deconflictedExportNames,
1117
+ topLevelAssignments,
1118
+ moduleName,
1119
+ exportsName,
1120
+ exportedExportsName,
1121
+ defineCompiledEsmExpressions,
1122
+ HELPERS_NAME,
1123
+ defaultIsModuleExports,
1124
+ exportMode
1125
+ );
1126
+ }
1127
+ }
1128
+ if (exports.length) {
1129
+ exportDeclarations.push(`export { ${exports.join(', ')} }`);
1130
+ }
1131
+
1132
+ return `\n\n${exportDeclarations.join(';\n')};`;
1133
+ }
1134
+
1135
+ function getExportsWhenUsingRequireWrapper(
1136
+ magicString,
1137
+ wrapped,
1138
+ exportMode,
1139
+ exports,
1140
+ moduleExportsAssignments,
1141
+ exportsAssignmentsByName,
1142
+ moduleName,
1143
+ exportsName,
1144
+ requireName,
1145
+ defineCompiledEsmExpressions
1146
+ ) {
1147
+ exports.push(`${requireName} as __require`);
1148
+ if (wrapped) return;
1149
+ if (exportMode === 'replace') {
1150
+ rewriteModuleExportsAssignments(magicString, moduleExportsAssignments, exportsName);
1151
+ } else {
1152
+ rewriteModuleExportsAssignments(magicString, moduleExportsAssignments, `${moduleName}.exports`);
1153
+ // Collect and rewrite named exports
1154
+ for (const [exportName, { nodes }] of exportsAssignmentsByName) {
1155
+ for (const { node, type } of nodes) {
1156
+ magicString.overwrite(
1157
+ node.start,
1158
+ node.left.end,
1159
+ `${
1160
+ exportMode === 'module' && type === 'module' ? `${moduleName}.exports` : exportsName
1161
+ }.${exportName}`
1162
+ );
1163
+ }
1164
+ }
1165
+ replaceDefineCompiledEsmExpressionsAndGetIfRestorable(
1166
+ defineCompiledEsmExpressions,
1167
+ magicString,
1168
+ exportMode,
1169
+ moduleName,
1170
+ exportsName
1171
+ );
1172
+ }
1173
+ }
1174
+
1175
+ function getExportsForReplacedModuleExports(
1176
+ magicString,
1177
+ exports,
1178
+ exportDeclarations,
1179
+ moduleExportsAssignments,
1180
+ firstTopLevelModuleExportsAssignment,
1181
+ exportsName,
1182
+ defaultIsModuleExports,
1183
+ HELPERS_NAME
1184
+ ) {
1185
+ for (const { left } of moduleExportsAssignments) {
1186
+ magicString.overwrite(left.start, left.end, exportsName);
1187
+ }
1188
+ magicString.prependRight(firstTopLevelModuleExportsAssignment.left.start, 'var ');
1189
+ exports.push(`${exportsName} as __moduleExports`);
1190
+ exportDeclarations.push(
1191
+ getDefaultExportDeclaration(exportsName, defaultIsModuleExports, HELPERS_NAME)
1192
+ );
1193
+ }
1194
+
1195
+ function getDefaultExportDeclaration(exportedExportsName, defaultIsModuleExports, HELPERS_NAME) {
1196
+ return `export default ${
1197
+ defaultIsModuleExports === true
1198
+ ? exportedExportsName
1199
+ : defaultIsModuleExports === false
1200
+ ? `${exportedExportsName}.default`
1201
+ : `/*@__PURE__*/${HELPERS_NAME}.getDefaultExportFromCjs(${exportedExportsName})`
1202
+ }`;
1203
+ }
1204
+
1205
+ function getExports(
1206
+ magicString,
1207
+ exports,
1208
+ exportDeclarations,
1209
+ moduleExportsAssignments,
1210
+ exportsAssignmentsByName,
1211
+ deconflictedExportNames,
1212
+ topLevelAssignments,
1213
+ moduleName,
1214
+ exportsName,
1215
+ exportedExportsName,
1216
+ defineCompiledEsmExpressions,
1217
+ HELPERS_NAME,
1218
+ defaultIsModuleExports,
1219
+ exportMode
1220
+ ) {
1221
+ let deconflictedDefaultExportName;
1222
+ // Collect and rewrite module.exports assignments
1223
+ for (const { left } of moduleExportsAssignments) {
1224
+ magicString.overwrite(left.start, left.end, `${moduleName}.exports`);
1225
+ }
1226
+
1227
+ // Collect and rewrite named exports
1228
+ for (const [exportName, { nodes }] of exportsAssignmentsByName) {
1229
+ const deconflicted = deconflictedExportNames[exportName];
1230
+ let needsDeclaration = true;
1231
+ for (const { node, type } of nodes) {
1232
+ let replacement = `${deconflicted} = ${
1233
+ exportMode === 'module' && type === 'module' ? `${moduleName}.exports` : exportsName
1234
+ }.${exportName}`;
1235
+ if (needsDeclaration && topLevelAssignments.has(node)) {
1236
+ replacement = `var ${replacement}`;
1237
+ needsDeclaration = false;
1238
+ }
1239
+ magicString.overwrite(node.start, node.left.end, replacement);
1240
+ }
1241
+ if (needsDeclaration) {
1242
+ magicString.prepend(`var ${deconflicted};\n`);
1243
+ }
1244
+
1245
+ if (exportName === 'default') {
1246
+ deconflictedDefaultExportName = deconflicted;
1247
+ } else {
1248
+ exports.push(exportName === deconflicted ? exportName : `${deconflicted} as ${exportName}`);
1249
+ }
1250
+ }
1251
+
1252
+ const isRestorableCompiledEsm = replaceDefineCompiledEsmExpressionsAndGetIfRestorable(
1253
+ defineCompiledEsmExpressions,
1254
+ magicString,
1255
+ exportMode,
1256
+ moduleName,
1257
+ exportsName
1258
+ );
1259
+
1260
+ if (
1261
+ defaultIsModuleExports === false ||
1262
+ (defaultIsModuleExports === 'auto' &&
1263
+ isRestorableCompiledEsm &&
1264
+ moduleExportsAssignments.length === 0)
1265
+ ) {
1266
+ // If there is no deconflictedDefaultExportName, then we use the namespace as
1267
+ // fallback because there can be no "default" property on the namespace
1268
+ exports.push(`${deconflictedDefaultExportName || exportedExportsName} as default`);
1269
+ } else if (
1270
+ defaultIsModuleExports === true ||
1271
+ (!isRestorableCompiledEsm && moduleExportsAssignments.length === 0)
1272
+ ) {
1273
+ exports.push(`${exportedExportsName} as default`);
1274
+ } else {
1275
+ exportDeclarations.push(
1276
+ getDefaultExportDeclaration(exportedExportsName, defaultIsModuleExports, HELPERS_NAME)
1277
+ );
1278
+ }
1279
+ }
1280
+
1281
+ function rewriteModuleExportsAssignments(magicString, moduleExportsAssignments, exportsName) {
1282
+ for (const { left } of moduleExportsAssignments) {
1283
+ magicString.overwrite(left.start, left.end, exportsName);
1284
+ }
1285
+ }
1286
+
1287
+ function replaceDefineCompiledEsmExpressionsAndGetIfRestorable(
1288
+ defineCompiledEsmExpressions,
1289
+ magicString,
1290
+ exportMode,
1291
+ moduleName,
1292
+ exportsName
1293
+ ) {
1294
+ let isRestorableCompiledEsm = false;
1295
+ for (const { node, type } of defineCompiledEsmExpressions) {
1296
+ isRestorableCompiledEsm = true;
1297
+ const moduleExportsExpression =
1298
+ node.type === 'CallExpression' ? node.arguments[0] : node.left.object;
1299
+ magicString.overwrite(
1300
+ moduleExportsExpression.start,
1301
+ moduleExportsExpression.end,
1302
+ exportMode === 'module' && type === 'module' ? `${moduleName}.exports` : exportsName
1303
+ );
1304
+ }
1305
+ return isRestorableCompiledEsm;
1306
+ }
1307
+
1308
+ function isRequireExpression(node, scope) {
1309
+ if (!node) return false;
1310
+ if (node.type !== 'CallExpression') return false;
1311
+
1312
+ // Weird case of `require()` or `module.require()` without arguments
1313
+ if (node.arguments.length === 0) return false;
1314
+
1315
+ return isRequire(node.callee, scope);
1316
+ }
1317
+
1318
+ function isRequire(node, scope) {
1319
+ return (
1320
+ (node.type === 'Identifier' && node.name === 'require' && !scope.contains('require')) ||
1321
+ (node.type === 'MemberExpression' && isModuleRequire(node, scope))
1322
+ );
1323
+ }
1324
+
1325
+ function isModuleRequire({ object, property }, scope) {
1326
+ return (
1327
+ object.type === 'Identifier' &&
1328
+ object.name === 'module' &&
1329
+ property.type === 'Identifier' &&
1330
+ property.name === 'require' &&
1331
+ !scope.contains('module')
1332
+ );
1333
+ }
1334
+
1335
+ function hasDynamicArguments(node) {
1336
+ return (
1337
+ node.arguments.length > 1 ||
1338
+ (node.arguments[0].type !== 'Literal' &&
1339
+ (node.arguments[0].type !== 'TemplateLiteral' || node.arguments[0].expressions.length > 0))
1340
+ );
1341
+ }
1342
+
1343
+ const reservedMethod = { resolve: true, cache: true, main: true };
1344
+
1345
+ function isNodeRequirePropertyAccess(parent) {
1346
+ return parent && parent.property && reservedMethod[parent.property.name];
1347
+ }
1348
+
1349
+ function getRequireStringArg(node) {
1350
+ return node.arguments[0].type === 'Literal'
1351
+ ? node.arguments[0].value
1352
+ : node.arguments[0].quasis[0].value.cooked;
1353
+ }
1354
+
1355
+ function getRequireHandlers() {
1356
+ const requireExpressions = [];
1357
+
1358
+ function addRequireExpression(
1359
+ sourceId,
1360
+ node,
1361
+ scope,
1362
+ usesReturnValue,
1363
+ isInsideTryBlock,
1364
+ isInsideConditional,
1365
+ toBeRemoved
1366
+ ) {
1367
+ requireExpressions.push({
1368
+ sourceId,
1369
+ node,
1370
+ scope,
1371
+ usesReturnValue,
1372
+ isInsideTryBlock,
1373
+ isInsideConditional,
1374
+ toBeRemoved
1375
+ });
1376
+ }
1377
+
1378
+ async function rewriteRequireExpressionsAndGetImportBlock(
1379
+ magicString,
1380
+ topLevelDeclarations,
1381
+ reassignedNames,
1382
+ helpersName,
1383
+ dynamicRequireName,
1384
+ moduleName,
1385
+ exportsName,
1386
+ id,
1387
+ exportMode,
1388
+ resolveRequireSourcesAndUpdateMeta,
1389
+ needsRequireWrapper,
1390
+ isEsModule,
1391
+ isDynamicRequireModulesEnabled,
1392
+ getIgnoreTryCatchRequireStatementMode,
1393
+ commonjsMeta
1394
+ ) {
1395
+ const imports = [];
1396
+ imports.push(`import * as ${helpersName} from "${HELPERS_ID}"`);
1397
+ if (dynamicRequireName) {
1398
+ imports.push(
1399
+ `import { ${
1400
+ isDynamicRequireModulesEnabled ? CREATE_COMMONJS_REQUIRE_EXPORT : COMMONJS_REQUIRE_EXPORT
1401
+ } as ${dynamicRequireName} } from "${DYNAMIC_MODULES_ID}"`
1402
+ );
1403
+ }
1404
+ if (exportMode === 'module') {
1405
+ imports.push(
1406
+ `import { __module as ${moduleName} } from ${JSON.stringify(wrapId(id, MODULE_SUFFIX))}`,
1407
+ `var ${exportsName} = ${moduleName}.exports`
1408
+ );
1409
+ } else if (exportMode === 'exports') {
1410
+ imports.push(
1411
+ `import { __exports as ${exportsName} } from ${JSON.stringify(wrapId(id, EXPORTS_SUFFIX))}`
1412
+ );
1413
+ }
1414
+ const requiresBySource = collectSources(requireExpressions);
1415
+ const requireTargets = await resolveRequireSourcesAndUpdateMeta(
1416
+ id,
1417
+ needsRequireWrapper ? IS_WRAPPED_COMMONJS : !isEsModule,
1418
+ commonjsMeta,
1419
+ Object.keys(requiresBySource).map((source) => {
1420
+ return {
1421
+ source,
1422
+ isConditional: requiresBySource[source].every((require) => require.isInsideConditional)
1423
+ };
1424
+ })
1425
+ );
1426
+ processRequireExpressions(
1427
+ imports,
1428
+ requireTargets,
1429
+ requiresBySource,
1430
+ getIgnoreTryCatchRequireStatementMode,
1431
+ magicString
1432
+ );
1433
+ return imports.length ? `${imports.join(';\n')};\n\n` : '';
1434
+ }
1435
+
1436
+ return {
1437
+ addRequireExpression,
1438
+ rewriteRequireExpressionsAndGetImportBlock
1439
+ };
1440
+ }
1441
+
1442
+ function collectSources(requireExpressions) {
1443
+ const requiresBySource = Object.create(null);
1444
+ for (const requireExpression of requireExpressions) {
1445
+ const { sourceId } = requireExpression;
1446
+ if (!requiresBySource[sourceId]) {
1447
+ requiresBySource[sourceId] = [];
1448
+ }
1449
+ const requires = requiresBySource[sourceId];
1450
+ requires.push(requireExpression);
1451
+ }
1452
+ return requiresBySource;
1453
+ }
1454
+
1455
+ function processRequireExpressions(
1456
+ imports,
1457
+ requireTargets,
1458
+ requiresBySource,
1459
+ getIgnoreTryCatchRequireStatementMode,
1460
+ magicString
1461
+ ) {
1462
+ const generateRequireName = getGenerateRequireName();
1463
+ for (const { source, id: resolvedId, isCommonJS, wrappedModuleSideEffects } of requireTargets) {
1464
+ const requires = requiresBySource[source];
1465
+ const name = generateRequireName(requires);
1466
+ let usesRequired = false;
1467
+ let needsImport = false;
1468
+ for (const { node, usesReturnValue, toBeRemoved, isInsideTryBlock } of requires) {
1469
+ const { canConvertRequire, shouldRemoveRequire } =
1470
+ isInsideTryBlock && isWrappedId(resolvedId, EXTERNAL_SUFFIX)
1471
+ ? getIgnoreTryCatchRequireStatementMode(source)
1472
+ : { canConvertRequire: true, shouldRemoveRequire: false };
1473
+ if (shouldRemoveRequire) {
1474
+ if (usesReturnValue) {
1475
+ magicString.overwrite(node.start, node.end, 'undefined');
1476
+ } else {
1477
+ magicString.remove(toBeRemoved.start, toBeRemoved.end);
1478
+ }
1479
+ } else if (canConvertRequire) {
1480
+ needsImport = true;
1481
+ if (isCommonJS === IS_WRAPPED_COMMONJS) {
1482
+ magicString.overwrite(
1483
+ node.start,
1484
+ node.end,
1485
+ `${wrappedModuleSideEffects ? '' : '/*@__PURE__*/ '}${name}()`
1486
+ );
1487
+ } else if (usesReturnValue) {
1488
+ usesRequired = true;
1489
+ magicString.overwrite(node.start, node.end, name);
1490
+ } else {
1491
+ magicString.remove(toBeRemoved.start, toBeRemoved.end);
1492
+ }
1493
+ }
1494
+ }
1495
+ if (needsImport) {
1496
+ if (isCommonJS === IS_WRAPPED_COMMONJS) {
1497
+ imports.push(`import { __require as ${name} } from ${JSON.stringify(resolvedId)}`);
1498
+ } else {
1499
+ imports.push(`import ${usesRequired ? `${name} from ` : ''}${JSON.stringify(resolvedId)}`);
1500
+ }
1501
+ }
1502
+ }
1503
+ }
1504
+
1505
+ function getGenerateRequireName() {
1506
+ let uid = 0;
1507
+ return (requires) => {
1508
+ let name;
1509
+ const hasNameConflict = ({ scope }) => scope.contains(name);
1510
+ do {
1511
+ name = `require$$${uid}`;
1512
+ uid += 1;
1513
+ } while (requires.some(hasNameConflict));
1514
+ return name;
1515
+ };
1516
+ }
1517
+
1518
+ /* eslint-disable no-param-reassign, no-shadow, no-underscore-dangle, no-continue */
1519
+
1520
+
1521
+ const exportsPattern = /^(?:module\.)?exports(?:\.([a-zA-Z_$][a-zA-Z_$0-9]*))?$/;
1522
+
1523
+ const functionType = /^(?:FunctionDeclaration|FunctionExpression|ArrowFunctionExpression)$/;
1524
+
1525
+ // There are three different types of CommonJS modules, described by their
1526
+ // "exportMode":
1527
+ // - exports: Only assignments to (module.)exports properties
1528
+ // - replace: A single assignment to module.exports itself
1529
+ // - module: Anything else
1530
+ // Special cases:
1531
+ // - usesRequireWrapper
1532
+ // - isWrapped
1533
+ async function transformCommonjs(
1534
+ parse,
1535
+ code,
1536
+ id,
1537
+ isEsModule,
1538
+ ignoreGlobal,
1539
+ ignoreRequire,
1540
+ ignoreDynamicRequires,
1541
+ getIgnoreTryCatchRequireStatementMode,
1542
+ sourceMap,
1543
+ isDynamicRequireModulesEnabled,
1544
+ dynamicRequireModules,
1545
+ commonDir,
1546
+ astCache,
1547
+ defaultIsModuleExports,
1548
+ needsRequireWrapper,
1549
+ resolveRequireSourcesAndUpdateMeta,
1550
+ isRequired,
1551
+ checkDynamicRequire,
1552
+ commonjsMeta
1553
+ ) {
1554
+ const ast = astCache || tryParse(parse, code, id);
1555
+ const magicString = new MagicString(code);
1556
+ const uses = {
1557
+ module: false,
1558
+ exports: false,
1559
+ global: false,
1560
+ require: false
1561
+ };
1562
+ const virtualDynamicRequirePath =
1563
+ isDynamicRequireModulesEnabled && getVirtualPathForDynamicRequirePath(dirname(id), commonDir);
1564
+ let scope = attachScopes(ast, 'scope');
1565
+ let lexicalDepth = 0;
1566
+ let programDepth = 0;
1567
+ let classBodyDepth = 0;
1568
+ let currentTryBlockEnd = null;
1569
+ let shouldWrap = false;
1570
+
1571
+ const globals = new Set();
1572
+ // A conditionalNode is a node for which execution is not guaranteed. If such a node is a require
1573
+ // or contains nested requires, those should be handled as function calls unless there is an
1574
+ // unconditional require elsewhere.
1575
+ let currentConditionalNodeEnd = null;
1576
+ const conditionalNodes = new Set();
1577
+ const { addRequireExpression, rewriteRequireExpressionsAndGetImportBlock } = getRequireHandlers();
1578
+
1579
+ // See which names are assigned to. This is necessary to prevent
1580
+ // illegally replacing `var foo = require('foo')` with `import foo from 'foo'`,
1581
+ // where `foo` is later reassigned. (This happens in the wild. CommonJS, sigh)
1582
+ const reassignedNames = new Set();
1583
+ const topLevelDeclarations = [];
1584
+ const skippedNodes = new Set();
1585
+ const moduleAccessScopes = new Set([scope]);
1586
+ const exportsAccessScopes = new Set([scope]);
1587
+ const moduleExportsAssignments = [];
1588
+ let firstTopLevelModuleExportsAssignment = null;
1589
+ const exportsAssignmentsByName = new Map();
1590
+ const topLevelAssignments = new Set();
1591
+ const topLevelDefineCompiledEsmExpressions = [];
1592
+ const replacedGlobal = [];
1593
+ const replacedThis = [];
1594
+ const replacedDynamicRequires = [];
1595
+ const importedVariables = new Set();
1596
+ const indentExclusionRanges = [];
1597
+
1598
+ walk(ast, {
1599
+ enter(node, parent) {
1600
+ if (skippedNodes.has(node)) {
1601
+ this.skip();
1602
+ return;
1603
+ }
1604
+
1605
+ if (currentTryBlockEnd !== null && node.start > currentTryBlockEnd) {
1606
+ currentTryBlockEnd = null;
1607
+ }
1608
+ if (currentConditionalNodeEnd !== null && node.start > currentConditionalNodeEnd) {
1609
+ currentConditionalNodeEnd = null;
1610
+ }
1611
+ if (currentConditionalNodeEnd === null && conditionalNodes.has(node)) {
1612
+ currentConditionalNodeEnd = node.end;
1613
+ }
1614
+
1615
+ programDepth += 1;
1616
+ if (node.scope) ({ scope } = node);
1617
+ if (functionType.test(node.type)) lexicalDepth += 1;
1618
+ if (sourceMap) {
1619
+ magicString.addSourcemapLocation(node.start);
1620
+ magicString.addSourcemapLocation(node.end);
1621
+ }
1622
+
1623
+ // eslint-disable-next-line default-case
1624
+ switch (node.type) {
1625
+ case 'AssignmentExpression':
1626
+ if (node.left.type === 'MemberExpression') {
1627
+ const flattened = getKeypath(node.left);
1628
+ if (!flattened || scope.contains(flattened.name)) return;
1629
+
1630
+ const exportsPatternMatch = exportsPattern.exec(flattened.keypath);
1631
+ if (!exportsPatternMatch || flattened.keypath === 'exports') return;
1632
+
1633
+ const [, exportName] = exportsPatternMatch;
1634
+ uses[flattened.name] = true;
1635
+
1636
+ // we're dealing with `module.exports = ...` or `[module.]exports.foo = ...` –
1637
+ if (flattened.keypath === 'module.exports') {
1638
+ moduleExportsAssignments.push(node);
1639
+ if (programDepth > 3) {
1640
+ moduleAccessScopes.add(scope);
1641
+ } else if (!firstTopLevelModuleExportsAssignment) {
1642
+ firstTopLevelModuleExportsAssignment = node;
1643
+ }
1644
+ } else if (exportName === KEY_COMPILED_ESM) {
1645
+ if (programDepth > 3) {
1646
+ shouldWrap = true;
1647
+ } else {
1648
+ // The "type" is either "module" or "exports" to discern
1649
+ // assignments to module.exports vs exports if needed
1650
+ topLevelDefineCompiledEsmExpressions.push({ node, type: flattened.name });
1651
+ }
1652
+ } else {
1653
+ const exportsAssignments = exportsAssignmentsByName.get(exportName) || {
1654
+ nodes: [],
1655
+ scopes: new Set()
1656
+ };
1657
+ exportsAssignments.nodes.push({ node, type: flattened.name });
1658
+ exportsAssignments.scopes.add(scope);
1659
+ exportsAccessScopes.add(scope);
1660
+ exportsAssignmentsByName.set(exportName, exportsAssignments);
1661
+ if (programDepth <= 3) {
1662
+ topLevelAssignments.add(node);
1663
+ }
1664
+ }
1665
+
1666
+ skippedNodes.add(node.left);
1667
+ } else {
1668
+ for (const name of extractAssignedNames(node.left)) {
1669
+ reassignedNames.add(name);
1670
+ }
1671
+ }
1672
+ return;
1673
+ case 'CallExpression': {
1674
+ const defineCompiledEsmType = getDefineCompiledEsmType(node);
1675
+ if (defineCompiledEsmType) {
1676
+ if (programDepth === 3 && parent.type === 'ExpressionStatement') {
1677
+ // skip special handling for [module.]exports until we know we render this
1678
+ skippedNodes.add(node.arguments[0]);
1679
+ topLevelDefineCompiledEsmExpressions.push({ node, type: defineCompiledEsmType });
1680
+ } else {
1681
+ shouldWrap = true;
1682
+ }
1683
+ return;
1684
+ }
1685
+
1686
+ // Transform require.resolve
1687
+ if (
1688
+ isDynamicRequireModulesEnabled &&
1689
+ node.callee.object &&
1690
+ isRequire(node.callee.object, scope) &&
1691
+ node.callee.property.name === 'resolve'
1692
+ ) {
1693
+ checkDynamicRequire(node.start);
1694
+ uses.require = true;
1695
+ const requireNode = node.callee.object;
1696
+ replacedDynamicRequires.push(requireNode);
1697
+ skippedNodes.add(node.callee);
1698
+ return;
1699
+ }
1700
+
1701
+ if (!isRequireExpression(node, scope)) {
1702
+ const keypath = getKeypath(node.callee);
1703
+ if (keypath && importedVariables.has(keypath.name)) {
1704
+ // Heuristic to deoptimize requires after a required function has been called
1705
+ currentConditionalNodeEnd = Infinity;
1706
+ }
1707
+ return;
1708
+ }
1709
+
1710
+ skippedNodes.add(node.callee);
1711
+ uses.require = true;
1712
+
1713
+ if (hasDynamicArguments(node)) {
1714
+ if (isDynamicRequireModulesEnabled) {
1715
+ checkDynamicRequire(node.start);
1716
+ }
1717
+ if (!ignoreDynamicRequires) {
1718
+ replacedDynamicRequires.push(node.callee);
1719
+ }
1720
+ return;
1721
+ }
1722
+
1723
+ const requireStringArg = getRequireStringArg(node);
1724
+ if (!ignoreRequire(requireStringArg)) {
1725
+ const usesReturnValue = parent.type !== 'ExpressionStatement';
1726
+ const toBeRemoved =
1727
+ parent.type === 'ExpressionStatement' &&
1728
+ (!currentConditionalNodeEnd ||
1729
+ // We should completely remove requires directly in a try-catch
1730
+ // so that Rollup can remove up the try-catch
1731
+ (currentTryBlockEnd !== null && currentTryBlockEnd < currentConditionalNodeEnd))
1732
+ ? parent
1733
+ : node;
1734
+ addRequireExpression(
1735
+ requireStringArg,
1736
+ node,
1737
+ scope,
1738
+ usesReturnValue,
1739
+ currentTryBlockEnd !== null,
1740
+ currentConditionalNodeEnd !== null,
1741
+ toBeRemoved
1742
+ );
1743
+ if (parent.type === 'VariableDeclarator' && parent.id.type === 'Identifier') {
1744
+ for (const name of extractAssignedNames(parent.id)) {
1745
+ importedVariables.add(name);
1746
+ }
1747
+ }
1748
+ }
1749
+ return;
1750
+ }
1751
+ case 'ClassBody':
1752
+ classBodyDepth += 1;
1753
+ return;
1754
+ case 'ConditionalExpression':
1755
+ case 'IfStatement':
1756
+ // skip dead branches
1757
+ if (isFalsy(node.test)) {
1758
+ skippedNodes.add(node.consequent);
1759
+ } else if (isTruthy(node.test)) {
1760
+ if (node.alternate) {
1761
+ skippedNodes.add(node.alternate);
1762
+ }
1763
+ } else {
1764
+ conditionalNodes.add(node.consequent);
1765
+ if (node.alternate) {
1766
+ conditionalNodes.add(node.alternate);
1767
+ }
1768
+ }
1769
+ return;
1770
+ case 'ArrowFunctionExpression':
1771
+ case 'FunctionDeclaration':
1772
+ case 'FunctionExpression':
1773
+ // requires in functions should be conditional unless it is an IIFE
1774
+ if (
1775
+ currentConditionalNodeEnd === null &&
1776
+ !(parent.type === 'CallExpression' && parent.callee === node)
1777
+ ) {
1778
+ currentConditionalNodeEnd = node.end;
1779
+ }
1780
+ return;
1781
+ case 'Identifier': {
1782
+ const { name } = node;
1783
+ if (
1784
+ !isReference(node, parent) ||
1785
+ scope.contains(name) ||
1786
+ (parent.type === 'PropertyDefinition' && parent.key === node)
1787
+ )
1788
+ return;
1789
+ switch (name) {
1790
+ case 'require':
1791
+ uses.require = true;
1792
+ if (isNodeRequirePropertyAccess(parent)) {
1793
+ return;
1794
+ }
1795
+ if (!ignoreDynamicRequires) {
1796
+ if (isShorthandProperty(parent)) {
1797
+ // as key and value are the same object, isReference regards
1798
+ // both as references, so we need to skip now
1799
+ skippedNodes.add(parent.value);
1800
+ magicString.prependRight(node.start, 'require: ');
1801
+ }
1802
+ replacedDynamicRequires.push(node);
1803
+ }
1804
+ return;
1805
+ case 'module':
1806
+ case 'exports':
1807
+ shouldWrap = true;
1808
+ uses[name] = true;
1809
+ return;
1810
+ case 'global':
1811
+ uses.global = true;
1812
+ if (!ignoreGlobal) {
1813
+ replacedGlobal.push(node);
1814
+ }
1815
+ return;
1816
+ case 'define':
1817
+ magicString.overwrite(node.start, node.end, 'undefined', {
1818
+ storeName: true
1819
+ });
1820
+ return;
1821
+ default:
1822
+ globals.add(name);
1823
+ return;
1824
+ }
1825
+ }
1826
+ case 'LogicalExpression':
1827
+ // skip dead branches
1828
+ if (node.operator === '&&') {
1829
+ if (isFalsy(node.left)) {
1830
+ skippedNodes.add(node.right);
1831
+ } else if (!isTruthy(node.left)) {
1832
+ conditionalNodes.add(node.right);
1833
+ }
1834
+ } else if (node.operator === '||') {
1835
+ if (isTruthy(node.left)) {
1836
+ skippedNodes.add(node.right);
1837
+ } else if (!isFalsy(node.left)) {
1838
+ conditionalNodes.add(node.right);
1839
+ }
1840
+ }
1841
+ return;
1842
+ case 'MemberExpression':
1843
+ if (!isDynamicRequireModulesEnabled && isModuleRequire(node, scope)) {
1844
+ uses.require = true;
1845
+ replacedDynamicRequires.push(node);
1846
+ skippedNodes.add(node.object);
1847
+ skippedNodes.add(node.property);
1848
+ }
1849
+ return;
1850
+ case 'ReturnStatement':
1851
+ // if top-level return, we need to wrap it
1852
+ if (lexicalDepth === 0) {
1853
+ shouldWrap = true;
1854
+ }
1855
+ return;
1856
+ case 'ThisExpression':
1857
+ // rewrite top-level `this` as `exportsName`
1858
+ if (lexicalDepth === 0 && !classBodyDepth) {
1859
+ uses.global = true;
1860
+ if (!ignoreGlobal) {
1861
+ replacedThis.push(node);
1862
+ }
1863
+ }
1864
+ return;
1865
+ case 'TryStatement':
1866
+ if (currentTryBlockEnd === null) {
1867
+ currentTryBlockEnd = node.block.end;
1868
+ }
1869
+ if (currentConditionalNodeEnd === null) {
1870
+ currentConditionalNodeEnd = node.end;
1871
+ }
1872
+ return;
1873
+ case 'UnaryExpression':
1874
+ // rewrite `typeof module`, `typeof module.exports` and `typeof exports` (https://github.com/rollup/rollup-plugin-commonjs/issues/151)
1875
+ if (node.operator === 'typeof') {
1876
+ const flattened = getKeypath(node.argument);
1877
+ if (!flattened) return;
1878
+
1879
+ if (scope.contains(flattened.name)) return;
1880
+
1881
+ if (
1882
+ !isEsModule &&
1883
+ (flattened.keypath === 'module.exports' ||
1884
+ flattened.keypath === 'module' ||
1885
+ flattened.keypath === 'exports')
1886
+ ) {
1887
+ magicString.overwrite(node.start, node.end, `'object'`, {
1888
+ storeName: false
1889
+ });
1890
+ }
1891
+ }
1892
+ return;
1893
+ case 'VariableDeclaration':
1894
+ if (!scope.parent) {
1895
+ topLevelDeclarations.push(node);
1896
+ }
1897
+ return;
1898
+ case 'TemplateElement':
1899
+ if (node.value.raw.includes('\n')) {
1900
+ indentExclusionRanges.push([node.start, node.end]);
1901
+ }
1902
+ }
1903
+ },
1904
+
1905
+ leave(node) {
1906
+ programDepth -= 1;
1907
+ if (node.scope) scope = scope.parent;
1908
+ if (functionType.test(node.type)) lexicalDepth -= 1;
1909
+ if (node.type === 'ClassBody') classBodyDepth -= 1;
1910
+ }
1911
+ });
1912
+
1913
+ const nameBase = getName(id);
1914
+ const exportsName = deconflict([...exportsAccessScopes], globals, nameBase);
1915
+ const moduleName = deconflict([...moduleAccessScopes], globals, `${nameBase}Module`);
1916
+ const requireName = deconflict([scope], globals, `require${capitalize(nameBase)}`);
1917
+ const isRequiredName = deconflict([scope], globals, `hasRequired${capitalize(nameBase)}`);
1918
+ const helpersName = deconflict([scope], globals, 'commonjsHelpers');
1919
+ const dynamicRequireName =
1920
+ replacedDynamicRequires.length > 0 &&
1921
+ deconflict(
1922
+ [scope],
1923
+ globals,
1924
+ isDynamicRequireModulesEnabled ? CREATE_COMMONJS_REQUIRE_EXPORT : COMMONJS_REQUIRE_EXPORT
1925
+ );
1926
+ const deconflictedExportNames = Object.create(null);
1927
+ for (const [exportName, { scopes }] of exportsAssignmentsByName) {
1928
+ deconflictedExportNames[exportName] = deconflict([...scopes], globals, exportName);
1929
+ }
1930
+
1931
+ for (const node of replacedGlobal) {
1932
+ magicString.overwrite(node.start, node.end, `${helpersName}.commonjsGlobal`, {
1933
+ storeName: true
1934
+ });
1935
+ }
1936
+ for (const node of replacedThis) {
1937
+ magicString.overwrite(node.start, node.end, exportsName, {
1938
+ storeName: true
1939
+ });
1940
+ }
1941
+ for (const node of replacedDynamicRequires) {
1942
+ magicString.overwrite(
1943
+ node.start,
1944
+ node.end,
1945
+ isDynamicRequireModulesEnabled
1946
+ ? `${dynamicRequireName}(${JSON.stringify(virtualDynamicRequirePath)})`
1947
+ : dynamicRequireName,
1948
+ {
1949
+ contentOnly: true,
1950
+ storeName: true
1951
+ }
1952
+ );
1953
+ }
1954
+
1955
+ // We cannot wrap ES/mixed modules
1956
+ shouldWrap = !isEsModule && (shouldWrap || (uses.exports && moduleExportsAssignments.length > 0));
1957
+
1958
+ if (
1959
+ !(
1960
+ shouldWrap ||
1961
+ isRequired ||
1962
+ needsRequireWrapper ||
1963
+ uses.module ||
1964
+ uses.exports ||
1965
+ uses.require ||
1966
+ topLevelDefineCompiledEsmExpressions.length > 0
1967
+ ) &&
1968
+ (ignoreGlobal || !uses.global)
1969
+ ) {
1970
+ return { meta: { commonjs: { isCommonJS: false } } };
1971
+ }
1972
+
1973
+ let leadingComment = '';
1974
+ if (code.startsWith('/*')) {
1975
+ const commentEnd = code.indexOf('*/', 2) + 2;
1976
+ leadingComment = `${code.slice(0, commentEnd)}\n`;
1977
+ magicString.remove(0, commentEnd).trim();
1978
+ }
1979
+
1980
+ let shebang = '';
1981
+ if (code.startsWith('#!')) {
1982
+ const shebangEndPosition = code.indexOf('\n') + 1;
1983
+ shebang = code.slice(0, shebangEndPosition);
1984
+ magicString.remove(0, shebangEndPosition).trim();
1985
+ }
1986
+
1987
+ const exportMode = isEsModule
1988
+ ? 'none'
1989
+ : shouldWrap
1990
+ ? uses.module
1991
+ ? 'module'
1992
+ : 'exports'
1993
+ : firstTopLevelModuleExportsAssignment
1994
+ ? exportsAssignmentsByName.size === 0 && topLevelDefineCompiledEsmExpressions.length === 0
1995
+ ? 'replace'
1996
+ : 'module'
1997
+ : moduleExportsAssignments.length === 0
1998
+ ? 'exports'
1999
+ : 'module';
2000
+
2001
+ const exportedExportsName =
2002
+ exportMode === 'module' ? deconflict([], globals, `${nameBase}Exports`) : exportsName;
2003
+
2004
+ const importBlock = await rewriteRequireExpressionsAndGetImportBlock(
2005
+ magicString,
2006
+ topLevelDeclarations,
2007
+ reassignedNames,
2008
+ helpersName,
2009
+ dynamicRequireName,
2010
+ moduleName,
2011
+ exportsName,
2012
+ id,
2013
+ exportMode,
2014
+ resolveRequireSourcesAndUpdateMeta,
2015
+ needsRequireWrapper,
2016
+ isEsModule,
2017
+ isDynamicRequireModulesEnabled,
2018
+ getIgnoreTryCatchRequireStatementMode,
2019
+ commonjsMeta
2020
+ );
2021
+ const usesRequireWrapper = commonjsMeta.isCommonJS === IS_WRAPPED_COMMONJS;
2022
+ const exportBlock = isEsModule
2023
+ ? ''
2024
+ : rewriteExportsAndGetExportsBlock(
2025
+ magicString,
2026
+ moduleName,
2027
+ exportsName,
2028
+ exportedExportsName,
2029
+ shouldWrap,
2030
+ moduleExportsAssignments,
2031
+ firstTopLevelModuleExportsAssignment,
2032
+ exportsAssignmentsByName,
2033
+ topLevelAssignments,
2034
+ topLevelDefineCompiledEsmExpressions,
2035
+ deconflictedExportNames,
2036
+ code,
2037
+ helpersName,
2038
+ exportMode,
2039
+ defaultIsModuleExports,
2040
+ usesRequireWrapper,
2041
+ requireName
2042
+ );
2043
+
2044
+ if (shouldWrap) {
2045
+ wrapCode(magicString, uses, moduleName, exportsName, indentExclusionRanges);
2046
+ }
2047
+
2048
+ if (usesRequireWrapper) {
2049
+ magicString.trim().indent('\t', {
2050
+ exclude: indentExclusionRanges
2051
+ });
2052
+ const exported = exportMode === 'module' ? `${moduleName}.exports` : exportsName;
2053
+ magicString.prepend(
2054
+ `var ${isRequiredName};
2055
+
2056
+ function ${requireName} () {
2057
+ \tif (${isRequiredName}) return ${exported};
2058
+ \t${isRequiredName} = 1;
2059
+ `
2060
+ ).append(`
2061
+ \treturn ${exported};
2062
+ }`);
2063
+ if (exportMode === 'replace') {
2064
+ magicString.prepend(`var ${exportsName};\n`);
2065
+ }
2066
+ }
2067
+
2068
+ magicString
2069
+ .trim()
2070
+ .prepend(shebang + leadingComment + importBlock)
2071
+ .append(exportBlock);
2072
+
2073
+ return {
2074
+ code: magicString.toString(),
2075
+ map: sourceMap ? magicString.generateMap() : null,
2076
+ syntheticNamedExports: isEsModule || usesRequireWrapper ? false : '__moduleExports',
2077
+ meta: { commonjs: { ...commonjsMeta, shebang } }
2078
+ };
2079
+ }
2080
+
2081
+ const PLUGIN_NAME = 'commonjs';
2082
+
2083
+ function commonjs(options = {}) {
2084
+ const {
2085
+ ignoreGlobal,
2086
+ ignoreDynamicRequires,
2087
+ requireReturnsDefault: requireReturnsDefaultOption,
2088
+ defaultIsModuleExports: defaultIsModuleExportsOption,
2089
+ esmExternals
2090
+ } = options;
2091
+ const extensions = options.extensions || ['.js'];
2092
+ const filter = createFilter(options.include, options.exclude);
2093
+ const isPossibleCjsId = (id) => {
2094
+ const extName = extname(id);
2095
+ return extName === '.cjs' || (extensions.includes(extName) && filter(id));
2096
+ };
2097
+
2098
+ const { strictRequiresFilter, detectCyclesAndConditional } = getStrictRequiresFilter(options);
2099
+
2100
+ const getRequireReturnsDefault =
2101
+ typeof requireReturnsDefaultOption === 'function'
2102
+ ? requireReturnsDefaultOption
2103
+ : () => requireReturnsDefaultOption;
2104
+
2105
+ let esmExternalIds;
2106
+ const isEsmExternal =
2107
+ typeof esmExternals === 'function'
2108
+ ? esmExternals
2109
+ : Array.isArray(esmExternals)
2110
+ ? ((esmExternalIds = new Set(esmExternals)), (id) => esmExternalIds.has(id))
2111
+ : () => esmExternals;
2112
+
2113
+ const getDefaultIsModuleExports =
2114
+ typeof defaultIsModuleExportsOption === 'function'
2115
+ ? defaultIsModuleExportsOption
2116
+ : () =>
2117
+ typeof defaultIsModuleExportsOption === 'boolean' ? defaultIsModuleExportsOption : 'auto';
2118
+
2119
+ const dynamicRequireRoot =
2120
+ typeof options.dynamicRequireRoot === 'string'
2121
+ ? resolve(options.dynamicRequireRoot)
2122
+ : process.cwd();
2123
+ const { commonDir, dynamicRequireModules } = getDynamicRequireModules(
2124
+ options.dynamicRequireTargets,
2125
+ dynamicRequireRoot
2126
+ );
2127
+ const isDynamicRequireModulesEnabled = dynamicRequireModules.size > 0;
2128
+
2129
+ const ignoreRequire =
2130
+ typeof options.ignore === 'function'
2131
+ ? options.ignore
2132
+ : Array.isArray(options.ignore)
2133
+ ? (id) => options.ignore.includes(id)
2134
+ : () => false;
2135
+
2136
+ const getIgnoreTryCatchRequireStatementMode = (id) => {
2137
+ const mode =
2138
+ typeof options.ignoreTryCatch === 'function'
2139
+ ? options.ignoreTryCatch(id)
2140
+ : Array.isArray(options.ignoreTryCatch)
2141
+ ? options.ignoreTryCatch.includes(id)
2142
+ : typeof options.ignoreTryCatch !== 'undefined'
2143
+ ? options.ignoreTryCatch
2144
+ : true;
2145
+
2146
+ return {
2147
+ canConvertRequire: mode !== 'remove' && mode !== true,
2148
+ shouldRemoveRequire: mode === 'remove'
2149
+ };
2150
+ };
2151
+
2152
+ const { currentlyResolving, resolveId } = getResolveId(extensions, isPossibleCjsId);
2153
+
2154
+ const sourceMap = options.sourceMap !== false;
2155
+
2156
+ // Initialized in buildStart
2157
+ let requireResolver;
2158
+
2159
+ function transformAndCheckExports(code, id) {
2160
+ const normalizedId = normalizePathSlashes(id);
2161
+ const { isEsModule, hasDefaultExport, hasNamedExports, ast } = analyzeTopLevelStatements(
2162
+ this.parse,
2163
+ code,
2164
+ id
2165
+ );
2166
+
2167
+ const commonjsMeta = this.getModuleInfo(id).meta.commonjs || {};
2168
+ if (hasDefaultExport) {
2169
+ commonjsMeta.hasDefaultExport = true;
2170
+ }
2171
+ if (hasNamedExports) {
2172
+ commonjsMeta.hasNamedExports = true;
2173
+ }
2174
+
2175
+ if (
2176
+ !dynamicRequireModules.has(normalizedId) &&
2177
+ (!(hasCjsKeywords(code, ignoreGlobal) || requireResolver.isRequiredId(id)) ||
2178
+ (isEsModule && !options.transformMixedEsModules))
2179
+ ) {
2180
+ commonjsMeta.isCommonJS = false;
2181
+ return { meta: { commonjs: commonjsMeta } };
2182
+ }
2183
+
2184
+ const needsRequireWrapper =
2185
+ !isEsModule && (dynamicRequireModules.has(normalizedId) || strictRequiresFilter(id));
2186
+
2187
+ const checkDynamicRequire = (position) => {
2188
+ const normalizedDynamicRequireRoot = normalizePathSlashes(dynamicRequireRoot);
2189
+
2190
+ if (normalizedId.indexOf(normalizedDynamicRequireRoot) !== 0) {
2191
+ this.error(
2192
+ {
2193
+ code: 'DYNAMIC_REQUIRE_OUTSIDE_ROOT',
2194
+ normalizedId,
2195
+ normalizedDynamicRequireRoot,
2196
+ message: `"${normalizedId}" contains dynamic require statements but it is not within the current dynamicRequireRoot "${normalizedDynamicRequireRoot}". You should set dynamicRequireRoot to "${dirname(
2197
+ normalizedId
2198
+ )}" or one of its parent directories.`
2199
+ },
2200
+ position
2201
+ );
2202
+ }
2203
+ };
2204
+
2205
+ return transformCommonjs(
2206
+ this.parse,
2207
+ code,
2208
+ id,
2209
+ isEsModule,
2210
+ ignoreGlobal || isEsModule,
2211
+ ignoreRequire,
2212
+ ignoreDynamicRequires && !isDynamicRequireModulesEnabled,
2213
+ getIgnoreTryCatchRequireStatementMode,
2214
+ sourceMap,
2215
+ isDynamicRequireModulesEnabled,
2216
+ dynamicRequireModules,
2217
+ commonDir,
2218
+ ast,
2219
+ getDefaultIsModuleExports(id),
2220
+ needsRequireWrapper,
2221
+ requireResolver.resolveRequireSourcesAndUpdateMeta(this),
2222
+ requireResolver.isRequiredId(id),
2223
+ checkDynamicRequire,
2224
+ commonjsMeta
2225
+ );
2226
+ }
2227
+
2228
+ return {
2229
+ name: PLUGIN_NAME,
2230
+
2231
+ version,
2232
+
2233
+ options(rawOptions) {
2234
+ // We inject the resolver in the beginning so that "catch-all-resolver" like node-resolver
2235
+ // do not prevent our plugin from resolving entry points ot proxies.
2236
+ const plugins = Array.isArray(rawOptions.plugins)
2237
+ ? [...rawOptions.plugins]
2238
+ : rawOptions.plugins
2239
+ ? [rawOptions.plugins]
2240
+ : [];
2241
+ plugins.unshift({
2242
+ name: 'commonjs--resolver',
2243
+ resolveId
2244
+ });
2245
+ return { ...rawOptions, plugins };
2246
+ },
2247
+
2248
+ buildStart({ plugins }) {
2249
+ validateVersion(this.meta.rollupVersion, peerDependencies.rollup, 'rollup');
2250
+ const nodeResolve = plugins.find(({ name }) => name === 'node-resolve');
2251
+ if (nodeResolve) {
2252
+ validateVersion(nodeResolve.version, '^13.0.6', '@rollup/plugin-node-resolve');
2253
+ }
2254
+ if (options.namedExports != null) {
2255
+ this.warn(
2256
+ 'The namedExports option from "@rollup/plugin-commonjs" is deprecated. Named exports are now handled automatically.'
2257
+ );
2258
+ }
2259
+ requireResolver = getRequireResolver(
2260
+ extensions,
2261
+ detectCyclesAndConditional,
2262
+ currentlyResolving
2263
+ );
2264
+ },
2265
+
2266
+ buildEnd() {
2267
+ if (options.strictRequires === 'debug') {
2268
+ const wrappedIds = requireResolver.getWrappedIds();
2269
+ if (wrappedIds.length) {
2270
+ this.warn({
2271
+ code: 'WRAPPED_IDS',
2272
+ ids: wrappedIds,
2273
+ message: `The commonjs plugin automatically wrapped the following files:\n[\n${wrappedIds
2274
+ .map((id) => `\t${JSON.stringify(relative(process.cwd(), id))}`)
2275
+ .join(',\n')}\n]`
2276
+ });
2277
+ } else {
2278
+ this.warn({
2279
+ code: 'WRAPPED_IDS',
2280
+ ids: wrappedIds,
2281
+ message: 'The commonjs plugin did not wrap any files.'
2282
+ });
2283
+ }
2284
+ }
2285
+ },
2286
+
2287
+ async load(id) {
2288
+ if (id === HELPERS_ID) {
2289
+ return getHelpersModule();
2290
+ }
2291
+
2292
+ if (isWrappedId(id, MODULE_SUFFIX)) {
2293
+ const name = getName(unwrapId(id, MODULE_SUFFIX));
2294
+ return {
2295
+ code: `var ${name} = {exports: {}}; export {${name} as __module}`,
2296
+ meta: { commonjs: { isCommonJS: false } }
2297
+ };
2298
+ }
2299
+
2300
+ if (isWrappedId(id, EXPORTS_SUFFIX)) {
2301
+ const name = getName(unwrapId(id, EXPORTS_SUFFIX));
2302
+ return {
2303
+ code: `var ${name} = {}; export {${name} as __exports}`,
2304
+ meta: { commonjs: { isCommonJS: false } }
2305
+ };
2306
+ }
2307
+
2308
+ if (isWrappedId(id, EXTERNAL_SUFFIX)) {
2309
+ const actualId = unwrapId(id, EXTERNAL_SUFFIX);
2310
+ if (actualId.startsWith('node:')) {
2311
+ return getExternalBuiltinRequireProxy(actualId);
2312
+ }
2313
+ return getUnknownRequireProxy(
2314
+ actualId,
2315
+ isEsmExternal(actualId) ? getRequireReturnsDefault(actualId) : true
2316
+ );
2317
+ }
2318
+
2319
+ // entry suffix is just appended to not mess up relative external resolution
2320
+ if (id.endsWith(ENTRY_SUFFIX)) {
2321
+ const acutalId = id.slice(0, -ENTRY_SUFFIX.length);
2322
+ const {
2323
+ meta: { commonjs: commonjsMeta }
2324
+ } = this.getModuleInfo(acutalId);
2325
+ const shebang = commonjsMeta?.shebang ?? '';
2326
+ return getEntryProxy(
2327
+ acutalId,
2328
+ getDefaultIsModuleExports(acutalId),
2329
+ this.getModuleInfo,
2330
+ shebang
2331
+ );
2332
+ }
2333
+
2334
+ if (isWrappedId(id, ES_IMPORT_SUFFIX)) {
2335
+ const actualId = unwrapId(id, ES_IMPORT_SUFFIX);
2336
+ return getEsImportProxy(
2337
+ actualId,
2338
+ getDefaultIsModuleExports(actualId),
2339
+ (await this.load({ id: actualId })).moduleSideEffects
2340
+ );
2341
+ }
2342
+
2343
+ if (id === DYNAMIC_MODULES_ID) {
2344
+ return getDynamicModuleRegistry(
2345
+ isDynamicRequireModulesEnabled,
2346
+ dynamicRequireModules,
2347
+ commonDir,
2348
+ ignoreDynamicRequires
2349
+ );
2350
+ }
2351
+
2352
+ if (isWrappedId(id, PROXY_SUFFIX)) {
2353
+ const actualId = unwrapId(id, PROXY_SUFFIX);
2354
+ return getStaticRequireProxy(actualId, getRequireReturnsDefault(actualId), this.load);
2355
+ }
2356
+
2357
+ return null;
2358
+ },
2359
+
2360
+ shouldTransformCachedModule(...args) {
2361
+ return requireResolver.shouldTransformCachedModule.call(this, ...args);
2362
+ },
2363
+
2364
+ transform(code, id) {
2365
+ if (!isPossibleCjsId(id)) return null;
2366
+
2367
+ try {
2368
+ return transformAndCheckExports.call(this, code, id);
2369
+ } catch (err) {
2370
+ return this.error(err, err.pos);
2371
+ }
2372
+ }
2373
+ };
2374
+ }
2375
+
2376
+ export { commonjs as c };