@vitejs/plugin-legacy 7.0.0 → 7.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -2,6 +2,7 @@ import { createRequire } from "node:module";
2
2
  import path from "node:path";
3
3
  import crypto from "node:crypto";
4
4
  import { fileURLToPath } from "node:url";
5
+ import * as vite from "vite";
5
6
  import { build, normalizePath } from "vite";
6
7
  import MagicString from "magic-string";
7
8
  import browserslist from "browserslist";
@@ -157,6 +158,10 @@ const _require = createRequire(import.meta.url);
157
158
  const nonLeadingHashInFileNameRE = /[^/]+\[hash(?::\d+)?\]/;
158
159
  const prefixedHashInFileNameRE = /\W?\[hash(?::\d+)?\]/;
159
160
  function viteLegacyPlugin(options = {}) {
161
+ if ("rolldownVersion" in vite) {
162
+ const { default: viteLegacyPluginForRolldownVite } = _require("#legacy-for-rolldown-vite");
163
+ return viteLegacyPluginForRolldownVite(options);
164
+ }
160
165
  let config;
161
166
  let targets;
162
167
  let modernTargets;
@@ -200,7 +205,7 @@ function viteLegacyPlugin(options = {}) {
200
205
  async config(config$1, env$1) {
201
206
  if (env$1.command === "build" && !config$1.build?.ssr) {
202
207
  if (!config$1.build) config$1.build = {};
203
- if (!config$1.build.cssTarget) config$1.build.cssTarget = "chrome61";
208
+ if (genLegacy && !config$1.build.cssTarget) config$1.build.cssTarget = "chrome61";
204
209
  if (genLegacy) {
205
210
  overriddenBuildTarget = config$1.build.target !== void 0;
206
211
  overriddenDefaultModernTargets = options.modernTargets !== void 0;
@@ -320,12 +325,23 @@ function viteLegacyPlugin(options = {}) {
320
325
  compact: !!config.build.minify,
321
326
  sourceMaps,
322
327
  inputSourceMap: void 0,
328
+ targets,
323
329
  assumptions,
330
+ browserslistConfigFile: false,
324
331
  presets: [[() => ({ plugins: [
325
332
  recordAndRemovePolyfillBabelPlugin(polyfillsDiscovered.legacy),
326
333
  replaceLegacyEnvBabelPlugin(),
327
334
  wrapIIFEBabelPlugin()
328
- ] })], [(await import("@babel/preset-env")).default, createBabelPresetEnvOptions(targets, { needPolyfills })]]
335
+ ] })], [(await import("@babel/preset-env")).default, {
336
+ bugfixes: true,
337
+ modules: false,
338
+ useBuiltIns: needPolyfills ? "usage" : false,
339
+ corejs: needPolyfills ? {
340
+ version: _require("core-js/package.json").version,
341
+ proposals: false
342
+ } : void 0,
343
+ shippedProposals: true
344
+ }]]
329
345
  });
330
346
  if (result) return {
331
347
  code: result.code,
@@ -412,7 +428,7 @@ function viteLegacyPlugin(options = {}) {
412
428
  generateBundle(opts, bundle) {
413
429
  if (config.build.ssr) return;
414
430
  if (isLegacyBundle(bundle, opts) && genModern) {
415
- for (const name in bundle) if (bundle[name].type === "asset" && !/.+\.map$/.test(name)) delete bundle[name];
431
+ for (const name in bundle) if (bundle[name].type === "asset" && !name.endsWith(".map")) delete bundle[name];
416
432
  }
417
433
  }
418
434
  };
@@ -426,32 +442,24 @@ async function detectPolyfills(code, targets, assumptions, list) {
426
442
  const babel$1 = await loadBabel();
427
443
  const result = babel$1.transform(code, {
428
444
  ast: true,
445
+ code: false,
429
446
  babelrc: false,
430
447
  configFile: false,
431
448
  compact: false,
449
+ targets,
432
450
  assumptions,
433
- presets: [[(await import("@babel/preset-env")).default, createBabelPresetEnvOptions(targets, {})]]
451
+ browserslistConfigFile: false,
452
+ plugins: [[(await import("babel-plugin-polyfill-corejs3")).default, {
453
+ method: "usage-global",
454
+ version: _require("core-js/package.json").version,
455
+ shippedProposals: true
456
+ }], [(await import("babel-plugin-polyfill-regenerator")).default, { method: "usage-global" }]]
434
457
  });
435
458
  for (const node of result.ast.program.body) if (node.type === "ImportDeclaration") {
436
459
  const source = node.source.value;
437
460
  if (source.startsWith("core-js/") || source.startsWith("regenerator-runtime/")) list.add(source);
438
461
  }
439
462
  }
440
- function createBabelPresetEnvOptions(targets, { needPolyfills = true }) {
441
- return {
442
- targets,
443
- bugfixes: true,
444
- loose: false,
445
- modules: false,
446
- useBuiltIns: needPolyfills ? "usage" : false,
447
- corejs: needPolyfills ? {
448
- version: _require("core-js/package.json").version,
449
- proposals: false
450
- } : void 0,
451
- shippedProposals: true,
452
- ignoreBrowserslistConfig: true
453
- };
454
- }
455
463
  async function buildPolyfillChunk(mode, imports, bundle, facadeToChunkMap, buildOptions, format, rollupOutputOptions, excludeSystemJS, prependModenChunkLegacyGuard) {
456
464
  let { minify, assetsDir, sourcemap } = buildOptions;
457
465
  minify = minify ? "terser" : false;
@@ -0,0 +1,607 @@
1
+ import { createRequire } from "node:module";
2
+ import path from "node:path";
3
+ import crypto from "node:crypto";
4
+ import { fileURLToPath } from "node:url";
5
+ import { build, normalizePath } from "vite";
6
+ import MagicString from "magic-string";
7
+ import browserslist from "browserslist";
8
+
9
+ //#region rolldown:runtime
10
+ var __create = Object.create;
11
+ var __defProp = Object.defineProperty;
12
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
13
+ var __getOwnPropNames = Object.getOwnPropertyNames;
14
+ var __getProtoOf = Object.getPrototypeOf;
15
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
16
+ var __commonJS = (cb, mod) => function() {
17
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
18
+ };
19
+ var __copyProps = (to, from, except, desc) => {
20
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
21
+ key = keys[i];
22
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
23
+ get: ((k) => from[k]).bind(null, key),
24
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
25
+ });
26
+ }
27
+ return to;
28
+ };
29
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
30
+ value: mod,
31
+ enumerable: true
32
+ }) : target, mod));
33
+
34
+ //#endregion
35
+ //#region ../../node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/picocolors.js
36
+ var require_picocolors = __commonJS({ "../../node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/picocolors.js"(exports, module) {
37
+ let p = process || {}, argv = p.argv || [], env = p.env || {};
38
+ let isColorSupported = !(!!env.NO_COLOR || argv.includes("--no-color")) && (!!env.FORCE_COLOR || argv.includes("--color") || p.platform === "win32" || (p.stdout || {}).isTTY && env.TERM !== "dumb" || !!env.CI);
39
+ let formatter = (open, close, replace = open) => (input) => {
40
+ let string = "" + input, index = string.indexOf(close, open.length);
41
+ return ~index ? open + replaceClose(string, close, replace, index) + close : open + string + close;
42
+ };
43
+ let replaceClose = (string, close, replace, index) => {
44
+ let result = "", cursor = 0;
45
+ do {
46
+ result += string.substring(cursor, index) + replace;
47
+ cursor = index + close.length;
48
+ index = string.indexOf(close, cursor);
49
+ } while (~index);
50
+ return result + string.substring(cursor);
51
+ };
52
+ let createColors = (enabled = isColorSupported) => {
53
+ let f = enabled ? formatter : () => String;
54
+ return {
55
+ isColorSupported: enabled,
56
+ reset: f("\x1B[0m", "\x1B[0m"),
57
+ bold: f("\x1B[1m", "\x1B[22m", "\x1B[22m\x1B[1m"),
58
+ dim: f("\x1B[2m", "\x1B[22m", "\x1B[22m\x1B[2m"),
59
+ italic: f("\x1B[3m", "\x1B[23m"),
60
+ underline: f("\x1B[4m", "\x1B[24m"),
61
+ inverse: f("\x1B[7m", "\x1B[27m"),
62
+ hidden: f("\x1B[8m", "\x1B[28m"),
63
+ strikethrough: f("\x1B[9m", "\x1B[29m"),
64
+ black: f("\x1B[30m", "\x1B[39m"),
65
+ red: f("\x1B[31m", "\x1B[39m"),
66
+ green: f("\x1B[32m", "\x1B[39m"),
67
+ yellow: f("\x1B[33m", "\x1B[39m"),
68
+ blue: f("\x1B[34m", "\x1B[39m"),
69
+ magenta: f("\x1B[35m", "\x1B[39m"),
70
+ cyan: f("\x1B[36m", "\x1B[39m"),
71
+ white: f("\x1B[37m", "\x1B[39m"),
72
+ gray: f("\x1B[90m", "\x1B[39m"),
73
+ bgBlack: f("\x1B[40m", "\x1B[49m"),
74
+ bgRed: f("\x1B[41m", "\x1B[49m"),
75
+ bgGreen: f("\x1B[42m", "\x1B[49m"),
76
+ bgYellow: f("\x1B[43m", "\x1B[49m"),
77
+ bgBlue: f("\x1B[44m", "\x1B[49m"),
78
+ bgMagenta: f("\x1B[45m", "\x1B[49m"),
79
+ bgCyan: f("\x1B[46m", "\x1B[49m"),
80
+ bgWhite: f("\x1B[47m", "\x1B[49m"),
81
+ blackBright: f("\x1B[90m", "\x1B[39m"),
82
+ redBright: f("\x1B[91m", "\x1B[39m"),
83
+ greenBright: f("\x1B[92m", "\x1B[39m"),
84
+ yellowBright: f("\x1B[93m", "\x1B[39m"),
85
+ blueBright: f("\x1B[94m", "\x1B[39m"),
86
+ magentaBright: f("\x1B[95m", "\x1B[39m"),
87
+ cyanBright: f("\x1B[96m", "\x1B[39m"),
88
+ whiteBright: f("\x1B[97m", "\x1B[39m"),
89
+ bgBlackBright: f("\x1B[100m", "\x1B[49m"),
90
+ bgRedBright: f("\x1B[101m", "\x1B[49m"),
91
+ bgGreenBright: f("\x1B[102m", "\x1B[49m"),
92
+ bgYellowBright: f("\x1B[103m", "\x1B[49m"),
93
+ bgBlueBright: f("\x1B[104m", "\x1B[49m"),
94
+ bgMagentaBright: f("\x1B[105m", "\x1B[49m"),
95
+ bgCyanBright: f("\x1B[106m", "\x1B[49m"),
96
+ bgWhiteBright: f("\x1B[107m", "\x1B[49m")
97
+ };
98
+ };
99
+ module.exports = createColors();
100
+ module.exports.createColors = createColors;
101
+ } });
102
+
103
+ //#endregion
104
+ //#region src/snippets.ts
105
+ const safari10NoModuleFix = `!function(){var e=document,t=e.createElement("script");if(!("noModule"in t)&&"onbeforeload"in t){var n=!1;e.addEventListener("beforeload",(function(e){if(e.target===t)n=!0;else if(!e.target.hasAttribute("nomodule")||!n)return;e.preventDefault()}),!0),t.type="module",t.src=".",e.head.appendChild(t),t.remove()}}();`;
106
+ const legacyPolyfillId = "vite-legacy-polyfill";
107
+ const legacyEntryId = "vite-legacy-entry";
108
+ const systemJSInlineCode = `System.import(document.getElementById('${legacyEntryId}').getAttribute('data-src'))`;
109
+ const detectModernBrowserVarName = "__vite_is_modern_browser";
110
+ const detectModernBrowserDetector = `import.meta.url;import("_").catch(()=>1);(async function*(){})().next()`;
111
+ const detectModernBrowserCode = `${detectModernBrowserDetector};window.${detectModernBrowserVarName}=true`;
112
+ const dynamicFallbackInlineCode = `!function(){if(window.${detectModernBrowserVarName})return;console.warn("vite: loading legacy chunks, syntax error above and the same error below should be ignored");var e=document.getElementById("${legacyPolyfillId}"),n=document.createElement("script");n.src=e.src,n.onload=function(){${systemJSInlineCode}},document.body.appendChild(n)}();`;
113
+ const modernChunkLegacyGuard = `export function __vite_legacy_guard(){${detectModernBrowserDetector}};`;
114
+
115
+ //#endregion
116
+ //#region src/index.ts
117
+ var import_picocolors = __toESM(require_picocolors(), 1);
118
+ let babel;
119
+ async function loadBabel() {
120
+ return babel ??= import("@babel/core");
121
+ }
122
+ const { loadConfig: browserslistLoadConfig } = browserslist;
123
+ function toOutputFilePathInHtml(filename, type, hostId, hostType, config, toRelative) {
124
+ const { renderBuiltUrl } = config.experimental;
125
+ let relative = config.base === "" || config.base === "./";
126
+ if (renderBuiltUrl) {
127
+ const result = renderBuiltUrl(filename, {
128
+ hostId,
129
+ hostType,
130
+ type,
131
+ ssr: !!config.build.ssr
132
+ });
133
+ if (typeof result === "object") {
134
+ if (result.runtime) throw new Error(`{ runtime: "${result.runtime}" } is not supported for assets in ${hostType} files: ${filename}`);
135
+ if (typeof result.relative === "boolean") relative = result.relative;
136
+ } else if (result) return result;
137
+ }
138
+ if (relative && !config.build.ssr) return toRelative(filename, hostId);
139
+ else return joinUrlSegments(config.decodedBase, filename);
140
+ }
141
+ function getBaseInHTML(urlRelativePath, config) {
142
+ return config.base === "./" || config.base === "" ? path.posix.join(path.posix.relative(urlRelativePath, "").slice(0, -2), "./") : config.base;
143
+ }
144
+ function joinUrlSegments(a, b) {
145
+ if (!a || !b) return a || b || "";
146
+ if (a.endsWith("/")) a = a.substring(0, a.length - 1);
147
+ if (b[0] !== "/") b = "/" + b;
148
+ return a + b;
149
+ }
150
+ function toAssetPathFromHtml(filename, htmlPath, config) {
151
+ const relativeUrlPath = normalizePath(path.relative(config.root, htmlPath));
152
+ const toRelative = (filename$1, _hostId) => getBaseInHTML(relativeUrlPath, config) + filename$1;
153
+ return toOutputFilePathInHtml(filename, "asset", htmlPath, "html", config, toRelative);
154
+ }
155
+ const legacyEnvVarMarker = `__VITE_IS_LEGACY__`;
156
+ const _require = createRequire(import.meta.url);
157
+ const nonLeadingHashInFileNameRE = /[^/]+\[hash(?::\d+)?\]/;
158
+ const prefixedHashInFileNameRE = /\W?\[hash(?::\d+)?\]/;
159
+ const outputOptionsForLegacyChunks = /* @__PURE__ */ new WeakSet();
160
+ function viteLegacyPlugin(options = {}) {
161
+ let config;
162
+ let targets;
163
+ let modernTargets;
164
+ const modernTargetsEsbuild = [
165
+ "es2020",
166
+ "edge79",
167
+ "firefox67",
168
+ "chrome64",
169
+ "safari12"
170
+ ];
171
+ const modernTargetsBabel = "edge>=79, firefox>=67, chrome>=64, safari>=12, chromeAndroid>=64, iOS>=12";
172
+ const genLegacy = options.renderLegacyChunks !== false;
173
+ const genModern = options.renderModernChunks !== false;
174
+ if (!genLegacy && !genModern) throw new Error("`renderLegacyChunks` and `renderModernChunks` cannot be both false");
175
+ const debugFlags = (process.env.DEBUG || "").split(",");
176
+ const isDebug = debugFlags.includes("vite:*") || debugFlags.includes("vite:legacy");
177
+ const assumptions = options.assumptions || {};
178
+ const facadeToLegacyChunkMap = /* @__PURE__ */ new Map();
179
+ const facadeToLegacyPolyfillMap = /* @__PURE__ */ new Map();
180
+ const facadeToModernPolyfillMap = /* @__PURE__ */ new Map();
181
+ const modernPolyfills = /* @__PURE__ */ new Set();
182
+ const legacyPolyfills = /* @__PURE__ */ new Set();
183
+ const outputToChunkFileNameToPolyfills = /* @__PURE__ */ new WeakMap();
184
+ if (Array.isArray(options.modernPolyfills) && genModern) options.modernPolyfills.forEach((i) => {
185
+ modernPolyfills.add(i.includes("/") ? `core-js/${i}` : `core-js/modules/${i}.js`);
186
+ });
187
+ if (Array.isArray(options.additionalModernPolyfills)) options.additionalModernPolyfills.forEach((i) => {
188
+ modernPolyfills.add(i);
189
+ });
190
+ if (Array.isArray(options.polyfills)) options.polyfills.forEach((i) => {
191
+ if (i.startsWith(`regenerator`)) legacyPolyfills.add(`regenerator-runtime/runtime.js`);
192
+ else legacyPolyfills.add(i.includes("/") ? `core-js/${i}` : `core-js/modules/${i}.js`);
193
+ });
194
+ if (Array.isArray(options.additionalLegacyPolyfills)) options.additionalLegacyPolyfills.forEach((i) => {
195
+ legacyPolyfills.add(i);
196
+ });
197
+ let overriddenBuildTarget = false;
198
+ let overriddenDefaultModernTargets = false;
199
+ const legacyConfigPlugin = {
200
+ name: "vite:legacy-config",
201
+ async config(config$1, env$1) {
202
+ if (env$1.command === "build" && !config$1.build?.ssr) {
203
+ if (!config$1.build) config$1.build = {};
204
+ if (genLegacy && !config$1.build.cssTarget) config$1.build.cssTarget = "chrome61";
205
+ if (genLegacy) {
206
+ overriddenBuildTarget = config$1.build.target !== void 0;
207
+ overriddenDefaultModernTargets = options.modernTargets !== void 0;
208
+ if (options.modernTargets) {
209
+ const { default: browserslistToEsbuild } = await import("browserslist-to-esbuild");
210
+ config$1.build.target = browserslistToEsbuild(options.modernTargets);
211
+ } else config$1.build.target = modernTargetsEsbuild;
212
+ }
213
+ }
214
+ return { define: { "import.meta.env.LEGACY": env$1.command === "serve" || config$1.build?.ssr ? false : legacyEnvVarMarker } };
215
+ },
216
+ configResolved(config$1) {
217
+ if (overriddenBuildTarget) config$1.logger.warn(import_picocolors.default.yellow(`plugin-legacy overrode 'build.target'. You should pass 'targets' as an option to this plugin with the list of legacy browsers to support instead.`));
218
+ if (overriddenDefaultModernTargets) config$1.logger.warn(import_picocolors.default.yellow(`plugin-legacy 'modernTargets' option overrode the builtin targets of modern chunks. Some versions of browsers between legacy and modern may not be supported.`));
219
+ if (config$1.isWorker) config$1.logger.warn(import_picocolors.default.yellow(`plugin-legacy should not be passed to 'worker.plugins'. Pass to 'plugins' instead. Note that generating legacy chunks for workers are not supported by plugin-legacy.`));
220
+ }
221
+ };
222
+ const legacyGenerateBundlePlugin = {
223
+ name: "vite:legacy-generate-polyfill-chunk",
224
+ apply: "build",
225
+ async generateBundle(opts, bundle) {
226
+ if (config.build.ssr) return;
227
+ const chunkFileNameToPolyfills = outputToChunkFileNameToPolyfills.get(opts);
228
+ if (chunkFileNameToPolyfills == null) throw new Error("Internal @vitejs/plugin-legacy error: discovered polyfills should exist");
229
+ if (!isLegacyBundle(bundle)) {
230
+ for (const { modern } of chunkFileNameToPolyfills.values()) modern.forEach((p$1) => modernPolyfills.add(p$1));
231
+ if (!modernPolyfills.size) return;
232
+ if (isDebug) console.log(`[@vitejs/plugin-legacy] modern polyfills:`, modernPolyfills);
233
+ await buildPolyfillChunk(this, config.mode, modernPolyfills, bundle, facadeToModernPolyfillMap, config.build, "es", opts, true, genLegacy);
234
+ return;
235
+ }
236
+ if (!genLegacy) return;
237
+ for (const { legacy } of chunkFileNameToPolyfills.values()) legacy.forEach((p$1) => legacyPolyfills.add(p$1));
238
+ if (options.polyfills !== false) await detectPolyfills(`Promise.resolve(); Promise.all();`, targets, assumptions, legacyPolyfills);
239
+ if (legacyPolyfills.size || !options.externalSystemJS) {
240
+ if (isDebug) console.log(`[@vitejs/plugin-legacy] legacy polyfills:`, legacyPolyfills);
241
+ await buildPolyfillChunk(this, config.mode, legacyPolyfills, bundle, facadeToLegacyPolyfillMap, config.build, "iife", opts, options.externalSystemJS);
242
+ }
243
+ }
244
+ };
245
+ const legacyPostPlugin = {
246
+ name: "vite:legacy-post-process",
247
+ enforce: "post",
248
+ apply: "build",
249
+ renderStart(opts) {
250
+ outputToChunkFileNameToPolyfills.set(opts, null);
251
+ },
252
+ configResolved(_config) {
253
+ if (_config.build.lib) throw new Error("@vitejs/plugin-legacy does not support library mode.");
254
+ config = _config;
255
+ modernTargets = options.modernTargets || modernTargetsBabel;
256
+ if (isDebug) console.log(`[@vitejs/plugin-legacy] modernTargets:`, modernTargets);
257
+ if (!genLegacy || config.build.ssr) return;
258
+ targets = options.targets || browserslistLoadConfig({ path: config.root }) || "last 2 versions and not dead, > 0.3%, Firefox ESR";
259
+ if (isDebug) console.log(`[@vitejs/plugin-legacy] targets:`, targets);
260
+ const getLegacyOutputFileName = (fileNames, defaultFileName = "[name]-legacy-[hash].js") => {
261
+ if (!fileNames) return path.posix.join(config.build.assetsDir, defaultFileName);
262
+ return (chunkInfo) => {
263
+ let fileName = typeof fileNames === "function" ? fileNames(chunkInfo) : fileNames;
264
+ if (fileName.includes("[name]")) fileName = fileName.replace("[name]", "[name]-legacy");
265
+ else if (nonLeadingHashInFileNameRE.test(fileName)) fileName = fileName.replace(prefixedHashInFileNameRE, "-legacy$&");
266
+ else fileName = fileName.replace(/(.+?)\.(.+)/, "$1-legacy.$2");
267
+ return fileName;
268
+ };
269
+ };
270
+ const createLegacyOutput = (options$1 = {}) => {
271
+ return {
272
+ ...options$1,
273
+ format: "esm",
274
+ entryFileNames: getLegacyOutputFileName(options$1.entryFileNames),
275
+ chunkFileNames: getLegacyOutputFileName(options$1.chunkFileNames),
276
+ minify: false
277
+ };
278
+ };
279
+ const { rollupOptions } = config.build;
280
+ const { output } = rollupOptions;
281
+ if (Array.isArray(output)) rollupOptions.output = [...output.map(createLegacyOutput), ...genModern ? output : []];
282
+ else rollupOptions.output = [createLegacyOutput(output), ...genModern ? [output || {}] : []];
283
+ _config.isOutputOptionsForLegacyChunks = (opts) => outputOptionsForLegacyChunks.has(opts);
284
+ },
285
+ async renderChunk(raw, chunk, opts, { chunks }) {
286
+ if (config.build.ssr) return null;
287
+ let chunkFileNameToPolyfills = outputToChunkFileNameToPolyfills.get(opts);
288
+ if (chunkFileNameToPolyfills == null) {
289
+ chunkFileNameToPolyfills = /* @__PURE__ */ new Map();
290
+ for (const fileName in chunks) chunkFileNameToPolyfills.set(fileName, {
291
+ modern: /* @__PURE__ */ new Set(),
292
+ legacy: /* @__PURE__ */ new Set()
293
+ });
294
+ outputToChunkFileNameToPolyfills.set(opts, chunkFileNameToPolyfills);
295
+ }
296
+ const polyfillsDiscovered = chunkFileNameToPolyfills.get(chunk.fileName);
297
+ if (polyfillsDiscovered == null) throw new Error(`Internal @vitejs/plugin-legacy error: discovered polyfills for ${chunk.fileName} should exist`);
298
+ if (!isLegacyChunk(chunk)) {
299
+ if (options.modernPolyfills && !Array.isArray(options.modernPolyfills) && genModern) await detectPolyfills(raw, modernTargets, assumptions, polyfillsDiscovered.modern);
300
+ const ms = new MagicString(raw);
301
+ if (genLegacy && chunk.isEntry) ms.prepend(modernChunkLegacyGuard);
302
+ if (raw.includes(legacyEnvVarMarker)) {
303
+ const re = new RegExp(legacyEnvVarMarker, "g");
304
+ let match;
305
+ while (match = re.exec(raw)) ms.overwrite(match.index, match.index + legacyEnvVarMarker.length, `false`);
306
+ }
307
+ if (config.build.sourcemap) return {
308
+ code: ms.toString(),
309
+ map: ms.generateMap({ hires: "boundary" })
310
+ };
311
+ return { code: ms.toString() };
312
+ }
313
+ if (!genLegacy) return null;
314
+ outputOptionsForLegacyChunks.add(opts);
315
+ const needPolyfills = options.polyfills !== false && !Array.isArray(options.polyfills);
316
+ const sourceMaps = !!config.build.sourcemap;
317
+ const babel$1 = await loadBabel();
318
+ const resultSystem = babel$1.transform(raw, {
319
+ babelrc: false,
320
+ configFile: false,
321
+ ast: true,
322
+ code: false,
323
+ sourceMaps,
324
+ plugins: [(await import("@babel/plugin-transform-dynamic-import")).default, (await import("@babel/plugin-transform-modules-systemjs")).default]
325
+ });
326
+ const babelTransformOptions = {
327
+ babelrc: false,
328
+ configFile: false,
329
+ cloneInputAst: false,
330
+ compact: !!config.build.minify,
331
+ sourceMaps,
332
+ inputSourceMap: void 0,
333
+ targets,
334
+ assumptions,
335
+ browserslistConfigFile: false,
336
+ presets: [[() => ({ plugins: [
337
+ recordAndRemovePolyfillBabelPlugin(polyfillsDiscovered.legacy),
338
+ replaceLegacyEnvBabelPlugin(),
339
+ wrapIIFEBabelPlugin()
340
+ ] })], [(await import("@babel/preset-env")).default, {
341
+ bugfixes: true,
342
+ modules: false,
343
+ useBuiltIns: needPolyfills ? "usage" : false,
344
+ corejs: needPolyfills ? {
345
+ version: _require("core-js/package.json").version,
346
+ proposals: false
347
+ } : void 0,
348
+ shippedProposals: true
349
+ }]]
350
+ };
351
+ let result;
352
+ if (resultSystem) result = babel$1.transformFromAstSync(resultSystem.ast, void 0, babelTransformOptions);
353
+ else result = babel$1.transform(raw, babelTransformOptions);
354
+ if (result) return {
355
+ code: result.code,
356
+ map: result.map
357
+ };
358
+ return null;
359
+ },
360
+ transformIndexHtml(html, { chunk }) {
361
+ if (config.build.ssr) return;
362
+ if (!chunk) return;
363
+ if (chunk.fileName.includes("-legacy")) {
364
+ facadeToLegacyChunkMap.set(chunk.facadeModuleId, chunk.fileName);
365
+ if (genModern) return;
366
+ }
367
+ if (!genModern) html = html.replace(/<script type="module".*?<\/script>/g, "");
368
+ const tags = [];
369
+ const htmlFilename = chunk.facadeModuleId?.replace(/\?.*$/, "");
370
+ if (genModern) {
371
+ const modernPolyfillFilename = facadeToModernPolyfillMap.get(chunk.facadeModuleId);
372
+ if (modernPolyfillFilename) tags.push({
373
+ tag: "script",
374
+ attrs: {
375
+ type: "module",
376
+ crossorigin: true,
377
+ src: toAssetPathFromHtml(modernPolyfillFilename, chunk.facadeModuleId, config)
378
+ }
379
+ });
380
+ else if (modernPolyfills.size) throw new Error(`No corresponding modern polyfill chunk found for ${htmlFilename}`);
381
+ }
382
+ if (!genLegacy) return {
383
+ html,
384
+ tags
385
+ };
386
+ if (genModern) tags.push({
387
+ tag: "script",
388
+ attrs: { nomodule: genModern },
389
+ children: safari10NoModuleFix,
390
+ injectTo: "body"
391
+ });
392
+ const legacyPolyfillFilename = facadeToLegacyPolyfillMap.get(chunk.facadeModuleId);
393
+ if (legacyPolyfillFilename) tags.push({
394
+ tag: "script",
395
+ attrs: {
396
+ nomodule: genModern,
397
+ crossorigin: true,
398
+ id: legacyPolyfillId,
399
+ src: toAssetPathFromHtml(legacyPolyfillFilename, chunk.facadeModuleId, config)
400
+ },
401
+ injectTo: "body"
402
+ });
403
+ else if (legacyPolyfills.size) throw new Error(`No corresponding legacy polyfill chunk found for ${htmlFilename}`);
404
+ const legacyEntryFilename = facadeToLegacyChunkMap.get(chunk.facadeModuleId);
405
+ if (legacyEntryFilename) tags.push({
406
+ tag: "script",
407
+ attrs: {
408
+ nomodule: genModern,
409
+ crossorigin: true,
410
+ id: legacyEntryId,
411
+ "data-src": toAssetPathFromHtml(legacyEntryFilename, chunk.facadeModuleId, config)
412
+ },
413
+ children: systemJSInlineCode,
414
+ injectTo: "body"
415
+ });
416
+ else throw new Error(`No corresponding legacy entry chunk found for ${htmlFilename}`);
417
+ if (legacyPolyfillFilename && legacyEntryFilename && genModern) {
418
+ tags.push({
419
+ tag: "script",
420
+ attrs: { type: "module" },
421
+ children: detectModernBrowserCode,
422
+ injectTo: "head"
423
+ });
424
+ tags.push({
425
+ tag: "script",
426
+ attrs: { type: "module" },
427
+ children: dynamicFallbackInlineCode,
428
+ injectTo: "head"
429
+ });
430
+ }
431
+ return {
432
+ html,
433
+ tags
434
+ };
435
+ },
436
+ generateBundle(_opts, bundle) {
437
+ if (config.build.ssr) return;
438
+ if (isLegacyBundle(bundle) && genModern) {
439
+ for (const name in bundle) if (bundle[name].type === "asset" && !name.endsWith(".map") && !name.includes("-legacy")) delete bundle[name];
440
+ }
441
+ }
442
+ };
443
+ return [
444
+ legacyConfigPlugin,
445
+ legacyGenerateBundlePlugin,
446
+ legacyPostPlugin
447
+ ];
448
+ }
449
+ async function detectPolyfills(code, targets, assumptions, list) {
450
+ const babel$1 = await loadBabel();
451
+ const result = babel$1.transform(code, {
452
+ ast: true,
453
+ code: false,
454
+ babelrc: false,
455
+ configFile: false,
456
+ compact: false,
457
+ targets,
458
+ assumptions,
459
+ browserslistConfigFile: false,
460
+ plugins: [[(await import("babel-plugin-polyfill-corejs3")).default, {
461
+ method: "usage-global",
462
+ version: _require("core-js/package.json").version,
463
+ shippedProposals: true
464
+ }], [(await import("babel-plugin-polyfill-regenerator")).default, { method: "usage-global" }]]
465
+ });
466
+ for (const node of result.ast.program.body) if (node.type === "ImportDeclaration") {
467
+ const source = node.source.value;
468
+ if (source.startsWith("core-js/") || source.startsWith("regenerator-runtime/")) list.add(source);
469
+ }
470
+ }
471
+ async function buildPolyfillChunk(ctx, mode, imports, bundle, facadeToChunkMap, buildOptions, format, rollupOutputOptions, excludeSystemJS, prependModenChunkLegacyGuard) {
472
+ let { minify, assetsDir, sourcemap } = buildOptions;
473
+ minify = minify ? "terser" : false;
474
+ const res = await build({
475
+ mode,
476
+ root: path.dirname(fileURLToPath(import.meta.url)),
477
+ configFile: false,
478
+ logLevel: "error",
479
+ plugins: [polyfillsPlugin(imports, excludeSystemJS), prependModenChunkLegacyGuard && prependModenChunkLegacyGuardPlugin()],
480
+ build: {
481
+ write: false,
482
+ minify,
483
+ assetsDir,
484
+ sourcemap,
485
+ rollupOptions: {
486
+ input: { polyfills: polyfillId },
487
+ output: {
488
+ format,
489
+ hashCharacters: rollupOutputOptions.hashCharacters,
490
+ entryFileNames: rollupOutputOptions.entryFileNames
491
+ }
492
+ }
493
+ },
494
+ esbuild: false,
495
+ optimizeDeps: { esbuildOptions: { target: "es5" } }
496
+ });
497
+ const _polyfillChunk = Array.isArray(res) ? res[0] : res;
498
+ if (!("output" in _polyfillChunk)) return;
499
+ const polyfillChunk = _polyfillChunk.output.find((chunk) => chunk.type === "chunk" && chunk.isEntry);
500
+ for (const key in bundle) {
501
+ const chunk = bundle[key];
502
+ if (chunk.type === "chunk" && chunk.facadeModuleId) facadeToChunkMap.set(chunk.facadeModuleId, polyfillChunk.fileName);
503
+ }
504
+ ctx.emitFile({
505
+ type: "asset",
506
+ fileName: polyfillChunk.fileName,
507
+ source: polyfillChunk.code
508
+ });
509
+ if (polyfillChunk.sourcemapFileName) {
510
+ const polyfillChunkMapAsset = _polyfillChunk.output.find((chunk) => chunk.type === "asset" && chunk.fileName === polyfillChunk.sourcemapFileName);
511
+ if (polyfillChunkMapAsset) ctx.emitFile({
512
+ type: "asset",
513
+ fileName: polyfillChunkMapAsset.fileName,
514
+ source: polyfillChunkMapAsset.source
515
+ });
516
+ }
517
+ }
518
+ const polyfillId = "\0vite/legacy-polyfills";
519
+ function polyfillsPlugin(imports, excludeSystemJS) {
520
+ return {
521
+ name: "vite:legacy-polyfills",
522
+ resolveId(id) {
523
+ if (id === polyfillId) return id;
524
+ },
525
+ load(id) {
526
+ if (id === polyfillId) return [...imports].map((i) => `import ${JSON.stringify(i)};`).join("") + (excludeSystemJS ? "" : `import "systemjs/dist/s.min.js";`);
527
+ }
528
+ };
529
+ }
530
+ function prependModenChunkLegacyGuardPlugin() {
531
+ let sourceMapEnabled;
532
+ return {
533
+ name: "vite:legacy-prepend-moden-chunk-legacy-guard",
534
+ configResolved(config) {
535
+ sourceMapEnabled = !!config.build.sourcemap;
536
+ },
537
+ renderChunk(code) {
538
+ if (!sourceMapEnabled) return modernChunkLegacyGuard + code;
539
+ const ms = new MagicString(code);
540
+ ms.prepend(modernChunkLegacyGuard);
541
+ return {
542
+ code: ms.toString(),
543
+ map: ms.generateMap({ hires: "boundary" })
544
+ };
545
+ }
546
+ };
547
+ }
548
+ function isLegacyChunk(chunk) {
549
+ return chunk.fileName.includes("-legacy");
550
+ }
551
+ function isLegacyBundle(bundle) {
552
+ const entryChunk = Object.values(bundle).find((output) => output.type === "chunk" && output.isEntry);
553
+ return !!entryChunk && entryChunk.fileName.includes("-legacy");
554
+ }
555
+ function recordAndRemovePolyfillBabelPlugin(polyfills) {
556
+ return ({ types: t }) => ({
557
+ name: "vite-remove-polyfill-import",
558
+ post({ path: path$1 }) {
559
+ path$1.get("body").forEach((p$1) => {
560
+ if (t.isImportDeclaration(p$1.node)) {
561
+ polyfills.add(p$1.node.source.value);
562
+ p$1.remove();
563
+ }
564
+ });
565
+ }
566
+ });
567
+ }
568
+ function replaceLegacyEnvBabelPlugin() {
569
+ return ({ types: t }) => ({
570
+ name: "vite-replace-env-legacy",
571
+ visitor: { Identifier(path$1) {
572
+ if (path$1.node.name === legacyEnvVarMarker) path$1.replaceWith(t.booleanLiteral(true));
573
+ } }
574
+ });
575
+ }
576
+ function wrapIIFEBabelPlugin() {
577
+ return ({ types: t, template }) => {
578
+ const buildIIFE = template(";(function(){%%body%%})();");
579
+ return {
580
+ name: "vite-wrap-iife",
581
+ post({ path: path$1 }) {
582
+ if (!this.isWrapped) {
583
+ this.isWrapped = true;
584
+ path$1.replaceWith(t.program(buildIIFE({ body: path$1.node.body })));
585
+ }
586
+ }
587
+ };
588
+ };
589
+ }
590
+ const cspHashes = [
591
+ safari10NoModuleFix,
592
+ systemJSInlineCode,
593
+ detectModernBrowserCode,
594
+ dynamicFallbackInlineCode
595
+ ].map((i) => crypto.hash("sha256", i, "base64"));
596
+ var src_default = viteLegacyPlugin;
597
+ function viteLegacyPluginCjs(options) {
598
+ return viteLegacyPlugin.call(this, options);
599
+ }
600
+ Object.assign(viteLegacyPluginCjs, {
601
+ cspHashes,
602
+ default: viteLegacyPluginCjs,
603
+ detectPolyfills
604
+ });
605
+
606
+ //#endregion
607
+ export { cspHashes, src_default as default, detectPolyfills, viteLegacyPluginCjs as "module.exports" };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vitejs/plugin-legacy",
3
- "version": "7.0.0",
3
+ "version": "7.1.0",
4
4
  "type": "module",
5
5
  "license": "MIT",
6
6
  "author": "Evan You",
@@ -27,12 +27,22 @@
27
27
  },
28
28
  "homepage": "https://github.com/vitejs/vite/tree/main/packages/plugin-legacy#readme",
29
29
  "funding": "https://github.com/vitejs/vite?sponsor=1",
30
+ "imports": {
31
+ "#legacy-for-rolldown-vite": {
32
+ "types": "./types/legacy-for-rolldown-vite.d.ts",
33
+ "default": "./dist/vendor/rolldown-vite/index.js"
34
+ }
35
+ },
30
36
  "dependencies": {
31
- "@babel/core": "^7.27.4",
32
- "@babel/preset-env": "^7.27.2",
33
- "browserslist": "^4.25.0",
37
+ "@babel/core": "^7.28.0",
38
+ "@babel/plugin-transform-dynamic-import": "^7.27.1",
39
+ "@babel/plugin-transform-modules-systemjs": "^7.27.1",
40
+ "@babel/preset-env": "^7.28.0",
41
+ "babel-plugin-polyfill-corejs3": "^0.13.0",
42
+ "babel-plugin-polyfill-regenerator": "^0.6.5",
43
+ "browserslist": "^4.25.1",
34
44
  "browserslist-to-esbuild": "^2.1.1",
35
- "core-js": "^3.43.0",
45
+ "core-js": "^3.44.0",
36
46
  "magic-string": "^0.30.17",
37
47
  "regenerator-runtime": "^0.14.1",
38
48
  "systemjs": "^6.15.1"
@@ -42,10 +52,12 @@
42
52
  "vite": "^7.0.0"
43
53
  },
44
54
  "devDependencies": {
55
+ "@vitejs/plugin-legacy-for-rolldown-vite": "https://pkg.pr.new/vitejs/rolldown-vite/@vitejs/plugin-legacy@b19b90a",
45
56
  "acorn": "^8.15.0",
57
+ "fdir": "^6.4.6",
46
58
  "picocolors": "^1.1.1",
47
- "tsdown": "^0.12.8",
48
- "vite": "7.0.0"
59
+ "tsdown": "^0.12.9",
60
+ "vite": "7.0.5"
49
61
  },
50
62
  "scripts": {
51
63
  "dev": "tsdown --watch",