@vitejs/plugin-legacy 1.8.2 → 2.0.0-alpha.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs ADDED
@@ -0,0 +1,475 @@
1
+ import path from 'path';
2
+ import { createHash } from 'crypto';
3
+ import { createRequire } from 'module';
4
+ import { fileURLToPath } from 'url';
5
+ import { build } from 'vite';
6
+ import MagicString from 'magic-string';
7
+
8
+ let babel;
9
+ async function loadBabel() {
10
+ if (!babel) {
11
+ babel = await import('@babel/standalone');
12
+ }
13
+ return babel;
14
+ }
15
+ 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()}}();`;
16
+ const legacyPolyfillId = "vite-legacy-polyfill";
17
+ const legacyEntryId = "vite-legacy-entry";
18
+ const systemJSInlineCode = `System.import(document.getElementById('${legacyEntryId}').getAttribute('data-src'))`;
19
+ const detectModernBrowserVarName = "__vite_is_modern_browser";
20
+ const detectModernBrowserCode = `try{import.meta.url;import("_").catch(()=>1);}catch(e){}window.${detectModernBrowserVarName}=true;`;
21
+ const dynamicFallbackInlineCode = `!function(){if(window.${detectModernBrowserVarName})return;console.warn("vite: loading legacy build because dynamic import or import.meta.url is unsupported, syntax error above should be ignored");var e=document.getElementById("${legacyPolyfillId}"),n=document.createElement("script");n.src=e.src,n.onload=function(){${systemJSInlineCode}},document.body.appendChild(n)}();`;
22
+ const forceDynamicImportUsage = `export function __vite_legacy_guard(){import('data:text/javascript,')};`;
23
+ const legacyEnvVarMarker = `__VITE_IS_LEGACY__`;
24
+ const _require = createRequire(import.meta.url);
25
+ function viteLegacyPlugin(options = {}) {
26
+ let config;
27
+ const targets = options.targets || "defaults";
28
+ const genLegacy = options.renderLegacyChunks !== false;
29
+ const genDynamicFallback = genLegacy;
30
+ const debugFlags = (process.env.DEBUG || "").split(",");
31
+ const isDebug = debugFlags.includes("vite:*") || debugFlags.includes("vite:legacy");
32
+ const facadeToLegacyChunkMap = /* @__PURE__ */ new Map();
33
+ const facadeToLegacyPolyfillMap = /* @__PURE__ */ new Map();
34
+ const facadeToModernPolyfillMap = /* @__PURE__ */ new Map();
35
+ const modernPolyfills = /* @__PURE__ */ new Set();
36
+ const legacyPolyfills = /* @__PURE__ */ new Set();
37
+ if (Array.isArray(options.modernPolyfills)) {
38
+ options.modernPolyfills.forEach((i) => {
39
+ modernPolyfills.add(i.includes("/") ? `core-js/${i}` : `core-js/modules/${i}.js`);
40
+ });
41
+ }
42
+ if (Array.isArray(options.polyfills)) {
43
+ options.polyfills.forEach((i) => {
44
+ if (i.startsWith(`regenerator`)) {
45
+ legacyPolyfills.add(`regenerator-runtime/runtime.js`);
46
+ } else {
47
+ legacyPolyfills.add(i.includes("/") ? `core-js/${i}` : `core-js/modules/${i}.js`);
48
+ }
49
+ });
50
+ }
51
+ if (Array.isArray(options.additionalLegacyPolyfills)) {
52
+ options.additionalLegacyPolyfills.forEach((i) => {
53
+ legacyPolyfills.add(i);
54
+ });
55
+ }
56
+ const legacyConfigPlugin = {
57
+ name: "vite:legacy-config",
58
+ apply: "build",
59
+ config(config2) {
60
+ if (!config2.build) {
61
+ config2.build = {};
62
+ }
63
+ if (!config2.build.cssTarget) {
64
+ config2.build.cssTarget = "chrome61";
65
+ }
66
+ }
67
+ };
68
+ const legacyGenerateBundlePlugin = {
69
+ name: "vite:legacy-generate-polyfill-chunk",
70
+ apply: "build",
71
+ async generateBundle(opts, bundle) {
72
+ if (config.build.ssr) {
73
+ return;
74
+ }
75
+ if (!isLegacyBundle(bundle, opts)) {
76
+ if (!modernPolyfills.size) {
77
+ return;
78
+ }
79
+ isDebug && console.log(`[@vitejs/plugin-legacy] modern polyfills:`, modernPolyfills);
80
+ await buildPolyfillChunk(modernPolyfills, bundle, facadeToModernPolyfillMap, config.build, "es", opts, true);
81
+ return;
82
+ }
83
+ if (!genLegacy) {
84
+ return;
85
+ }
86
+ if (legacyPolyfills.size || genDynamicFallback) {
87
+ await detectPolyfills(`Promise.resolve(); Promise.all();`, targets, legacyPolyfills);
88
+ isDebug && console.log(`[@vitejs/plugin-legacy] legacy polyfills:`, legacyPolyfills);
89
+ await buildPolyfillChunk(legacyPolyfills, bundle, facadeToLegacyPolyfillMap, config.build, "iife", opts, options.externalSystemJS);
90
+ }
91
+ }
92
+ };
93
+ const legacyPostPlugin = {
94
+ name: "vite:legacy-post-process",
95
+ enforce: "post",
96
+ apply: "build",
97
+ configResolved(_config) {
98
+ if (_config.build.lib) {
99
+ throw new Error("@vitejs/plugin-legacy does not support library mode.");
100
+ }
101
+ config = _config;
102
+ if (!genLegacy || config.build.ssr) {
103
+ return;
104
+ }
105
+ const getLegacyOutputFileName = (fileNames, defaultFileName = "[name]-legacy.[hash].js") => {
106
+ if (!fileNames) {
107
+ return path.posix.join(config.build.assetsDir, defaultFileName);
108
+ }
109
+ return (chunkInfo) => {
110
+ let fileName = typeof fileNames === "function" ? fileNames(chunkInfo) : fileNames;
111
+ if (fileName.includes("[name]")) {
112
+ fileName = fileName.replace("[name]", "[name]-legacy");
113
+ } else {
114
+ fileName = fileName.replace(/(.+)\.(.+)/, "$1-legacy.$2");
115
+ }
116
+ return fileName;
117
+ };
118
+ };
119
+ const createLegacyOutput = (options2 = {}) => {
120
+ return {
121
+ ...options2,
122
+ format: "system",
123
+ entryFileNames: getLegacyOutputFileName(options2.entryFileNames),
124
+ chunkFileNames: getLegacyOutputFileName(options2.chunkFileNames)
125
+ };
126
+ };
127
+ const { rollupOptions } = config.build;
128
+ const { output } = rollupOptions;
129
+ if (Array.isArray(output)) {
130
+ rollupOptions.output = [...output.map(createLegacyOutput), ...output];
131
+ } else {
132
+ rollupOptions.output = [createLegacyOutput(output), output || {}];
133
+ }
134
+ },
135
+ async renderChunk(raw, chunk, opts) {
136
+ if (config.build.ssr) {
137
+ return null;
138
+ }
139
+ if (!isLegacyChunk(chunk, opts)) {
140
+ if (options.modernPolyfills && !Array.isArray(options.modernPolyfills)) {
141
+ await detectPolyfills(raw, { esmodules: true }, modernPolyfills);
142
+ }
143
+ const ms = new MagicString(raw);
144
+ if (genDynamicFallback && chunk.isEntry) {
145
+ ms.prepend(forceDynamicImportUsage);
146
+ }
147
+ if (raw.includes(legacyEnvVarMarker)) {
148
+ const re = new RegExp(legacyEnvVarMarker, "g");
149
+ let match;
150
+ while (match = re.exec(raw)) {
151
+ ms.overwrite(match.index, match.index + legacyEnvVarMarker.length, `false`);
152
+ }
153
+ }
154
+ if (config.build.sourcemap) {
155
+ return {
156
+ code: ms.toString(),
157
+ map: ms.generateMap({ hires: true })
158
+ };
159
+ }
160
+ return {
161
+ code: ms.toString()
162
+ };
163
+ }
164
+ if (!genLegacy) {
165
+ return null;
166
+ }
167
+ opts.__vite_skip_esbuild__ = true;
168
+ opts.__vite_force_terser__ = true;
169
+ opts.__vite_skip_asset_emit__ = true;
170
+ const needPolyfills = options.polyfills !== false && !Array.isArray(options.polyfills);
171
+ const sourceMaps = !!config.build.sourcemap;
172
+ const babel2 = await loadBabel();
173
+ const { code, map } = babel2.transform(raw, {
174
+ babelrc: false,
175
+ configFile: false,
176
+ compact: !!config.build.minify,
177
+ sourceMaps,
178
+ inputSourceMap: sourceMaps ? chunk.map : void 0,
179
+ presets: [
180
+ [
181
+ () => ({
182
+ plugins: [
183
+ recordAndRemovePolyfillBabelPlugin(legacyPolyfills),
184
+ replaceLegacyEnvBabelPlugin(),
185
+ wrapIIFEBabelPlugin()
186
+ ]
187
+ })
188
+ ],
189
+ [
190
+ "env",
191
+ createBabelPresetEnvOptions(targets, {
192
+ needPolyfills,
193
+ ignoreBrowserslistConfig: options.ignoreBrowserslistConfig
194
+ })
195
+ ]
196
+ ]
197
+ });
198
+ if (code)
199
+ return { code, map };
200
+ return null;
201
+ },
202
+ transformIndexHtml(html, { chunk }) {
203
+ if (config.build.ssr)
204
+ return;
205
+ if (!chunk)
206
+ return;
207
+ if (chunk.fileName.includes("-legacy")) {
208
+ facadeToLegacyChunkMap.set(chunk.facadeModuleId, chunk.fileName);
209
+ return;
210
+ }
211
+ const tags = [];
212
+ const htmlFilename = chunk.facadeModuleId?.replace(/\?.*$/, "");
213
+ const modernPolyfillFilename = facadeToModernPolyfillMap.get(chunk.facadeModuleId);
214
+ if (modernPolyfillFilename) {
215
+ tags.push({
216
+ tag: "script",
217
+ attrs: {
218
+ type: "module",
219
+ crossorigin: true,
220
+ src: `${config.base}${modernPolyfillFilename}`
221
+ }
222
+ });
223
+ } else if (modernPolyfills.size) {
224
+ throw new Error(`No corresponding modern polyfill chunk found for ${htmlFilename}`);
225
+ }
226
+ if (!genLegacy) {
227
+ return { html, tags };
228
+ }
229
+ tags.push({
230
+ tag: "script",
231
+ attrs: { nomodule: true },
232
+ children: safari10NoModuleFix,
233
+ injectTo: "body"
234
+ });
235
+ const legacyPolyfillFilename = facadeToLegacyPolyfillMap.get(chunk.facadeModuleId);
236
+ if (legacyPolyfillFilename) {
237
+ tags.push({
238
+ tag: "script",
239
+ attrs: {
240
+ nomodule: true,
241
+ crossorigin: true,
242
+ id: legacyPolyfillId,
243
+ src: `${config.base}${legacyPolyfillFilename}`
244
+ },
245
+ injectTo: "body"
246
+ });
247
+ } else if (legacyPolyfills.size) {
248
+ throw new Error(`No corresponding legacy polyfill chunk found for ${htmlFilename}`);
249
+ }
250
+ const legacyEntryFilename = facadeToLegacyChunkMap.get(chunk.facadeModuleId);
251
+ if (legacyEntryFilename) {
252
+ const nonBareBase = config.base === "" ? "./" : config.base;
253
+ tags.push({
254
+ tag: "script",
255
+ attrs: {
256
+ nomodule: true,
257
+ crossorigin: true,
258
+ id: legacyEntryId,
259
+ "data-src": nonBareBase + legacyEntryFilename
260
+ },
261
+ children: systemJSInlineCode,
262
+ injectTo: "body"
263
+ });
264
+ } else {
265
+ throw new Error(`No corresponding legacy entry chunk found for ${htmlFilename}`);
266
+ }
267
+ if (genDynamicFallback && legacyPolyfillFilename && legacyEntryFilename) {
268
+ tags.push({
269
+ tag: "script",
270
+ attrs: { type: "module" },
271
+ children: detectModernBrowserCode,
272
+ injectTo: "head"
273
+ });
274
+ tags.push({
275
+ tag: "script",
276
+ attrs: { type: "module" },
277
+ children: dynamicFallbackInlineCode,
278
+ injectTo: "head"
279
+ });
280
+ }
281
+ return {
282
+ html,
283
+ tags
284
+ };
285
+ },
286
+ generateBundle(opts, bundle) {
287
+ if (config.build.ssr) {
288
+ return;
289
+ }
290
+ if (isLegacyBundle(bundle, opts)) {
291
+ for (const name in bundle) {
292
+ if (bundle[name].type === "asset") {
293
+ delete bundle[name];
294
+ }
295
+ }
296
+ }
297
+ }
298
+ };
299
+ let envInjectionFailed = false;
300
+ const legacyEnvPlugin = {
301
+ name: "vite:legacy-env",
302
+ config(config2, env) {
303
+ if (env) {
304
+ return {
305
+ define: {
306
+ "import.meta.env.LEGACY": env.command === "serve" || config2.build?.ssr ? false : legacyEnvVarMarker
307
+ }
308
+ };
309
+ } else {
310
+ envInjectionFailed = true;
311
+ }
312
+ },
313
+ configResolved(config2) {
314
+ if (envInjectionFailed) {
315
+ config2.logger.warn(`[@vitejs/plugin-legacy] import.meta.env.LEGACY was not injected due to incompatible vite version (requires vite@^2.0.0-beta.69).`);
316
+ }
317
+ }
318
+ };
319
+ return [
320
+ legacyConfigPlugin,
321
+ legacyGenerateBundlePlugin,
322
+ legacyPostPlugin,
323
+ legacyEnvPlugin
324
+ ];
325
+ }
326
+ async function detectPolyfills(code, targets, list) {
327
+ const babel2 = await loadBabel();
328
+ const { ast } = babel2.transform(code, {
329
+ ast: true,
330
+ babelrc: false,
331
+ configFile: false,
332
+ presets: [
333
+ [
334
+ "env",
335
+ createBabelPresetEnvOptions(targets, { ignoreBrowserslistConfig: true })
336
+ ]
337
+ ]
338
+ });
339
+ for (const node of ast.program.body) {
340
+ if (node.type === "ImportDeclaration") {
341
+ const source = node.source.value;
342
+ if (source.startsWith("core-js/") || source.startsWith("regenerator-runtime/")) {
343
+ list.add(source);
344
+ }
345
+ }
346
+ }
347
+ }
348
+ function createBabelPresetEnvOptions(targets, {
349
+ needPolyfills = true,
350
+ ignoreBrowserslistConfig
351
+ }) {
352
+ return {
353
+ targets,
354
+ bugfixes: true,
355
+ loose: false,
356
+ modules: false,
357
+ useBuiltIns: needPolyfills ? "usage" : false,
358
+ corejs: needPolyfills ? {
359
+ version: _require("core-js/package.json").version,
360
+ proposals: false
361
+ } : void 0,
362
+ shippedProposals: true,
363
+ ignoreBrowserslistConfig
364
+ };
365
+ }
366
+ async function buildPolyfillChunk(imports, bundle, facadeToChunkMap, buildOptions, format, rollupOutputOptions, excludeSystemJS) {
367
+ let { minify, assetsDir } = buildOptions;
368
+ minify = minify ? "terser" : false;
369
+ const res = await build({
370
+ root: path.dirname(fileURLToPath(import.meta.url)),
371
+ configFile: false,
372
+ logLevel: "error",
373
+ plugins: [polyfillsPlugin(imports, excludeSystemJS)],
374
+ build: {
375
+ write: false,
376
+ target: false,
377
+ minify,
378
+ assetsDir,
379
+ rollupOptions: {
380
+ input: {
381
+ polyfills: polyfillId
382
+ },
383
+ output: {
384
+ format,
385
+ entryFileNames: rollupOutputOptions.entryFileNames,
386
+ manualChunks: void 0
387
+ }
388
+ }
389
+ }
390
+ });
391
+ const _polyfillChunk = Array.isArray(res) ? res[0] : res;
392
+ if (!("output" in _polyfillChunk))
393
+ return;
394
+ const polyfillChunk = _polyfillChunk.output[0];
395
+ for (const key in bundle) {
396
+ const chunk = bundle[key];
397
+ if (chunk.type === "chunk" && chunk.facadeModuleId) {
398
+ facadeToChunkMap.set(chunk.facadeModuleId, polyfillChunk.fileName);
399
+ }
400
+ }
401
+ bundle[polyfillChunk.fileName] = polyfillChunk;
402
+ }
403
+ const polyfillId = "\0vite/legacy-polyfills";
404
+ function polyfillsPlugin(imports, excludeSystemJS) {
405
+ return {
406
+ name: "vite:legacy-polyfills",
407
+ resolveId(id) {
408
+ if (id === polyfillId) {
409
+ return id;
410
+ }
411
+ },
412
+ load(id) {
413
+ if (id === polyfillId) {
414
+ return [...imports].map((i) => `import "${i}";`).join("") + (excludeSystemJS ? "" : `import "systemjs/dist/s.min.js";`);
415
+ }
416
+ }
417
+ };
418
+ }
419
+ function isLegacyChunk(chunk, options) {
420
+ return options.format === "system" && chunk.fileName.includes("-legacy");
421
+ }
422
+ function isLegacyBundle(bundle, options) {
423
+ if (options.format === "system") {
424
+ const entryChunk = Object.values(bundle).find((output) => output.type === "chunk" && output.isEntry);
425
+ return !!entryChunk && entryChunk.fileName.includes("-legacy");
426
+ }
427
+ return false;
428
+ }
429
+ function recordAndRemovePolyfillBabelPlugin(polyfills) {
430
+ return ({ types: t }) => ({
431
+ name: "vite-remove-polyfill-import",
432
+ post({ path: path2 }) {
433
+ path2.get("body").forEach((p) => {
434
+ if (t.isImportDeclaration(p)) {
435
+ polyfills.add(p.node.source.value);
436
+ p.remove();
437
+ }
438
+ });
439
+ }
440
+ });
441
+ }
442
+ function replaceLegacyEnvBabelPlugin() {
443
+ return ({ types: t }) => ({
444
+ name: "vite-replace-env-legacy",
445
+ visitor: {
446
+ Identifier(path2) {
447
+ if (path2.node.name === legacyEnvVarMarker) {
448
+ path2.replaceWith(t.booleanLiteral(true));
449
+ }
450
+ }
451
+ }
452
+ });
453
+ }
454
+ function wrapIIFEBabelPlugin() {
455
+ return ({ types: t, template }) => {
456
+ const buildIIFE = template(";(function(){%%body%%})();");
457
+ return {
458
+ name: "vite-wrap-iife",
459
+ post({ path: path2 }) {
460
+ if (!this.isWrapped) {
461
+ this.isWrapped = true;
462
+ path2.replaceWith(t.program(buildIIFE({ body: path2.node.body })));
463
+ }
464
+ }
465
+ };
466
+ };
467
+ }
468
+ const cspHashes = [
469
+ createHash("sha256").update(safari10NoModuleFix).digest("base64"),
470
+ createHash("sha256").update(systemJSInlineCode).digest("base64"),
471
+ createHash("sha256").update(detectModernBrowserCode).digest("base64"),
472
+ createHash("sha256").update(dynamicFallbackInlineCode).digest("base64")
473
+ ];
474
+
475
+ export { cspHashes, viteLegacyPlugin as default, detectPolyfills };
package/package.json CHANGED
@@ -1,16 +1,29 @@
1
1
  {
2
2
  "name": "@vitejs/plugin-legacy",
3
- "version": "1.8.2",
3
+ "version": "2.0.0-alpha.2",
4
4
  "license": "MIT",
5
5
  "author": "Evan You",
6
6
  "files": [
7
- "index.js",
8
- "index.d.ts"
7
+ "dist"
9
8
  ],
10
- "main": "index.js",
11
- "types": "index.d.ts",
9
+ "main": "./dist/index.cjs",
10
+ "module": "./dist/index.mjs",
11
+ "types": "./dist/index.d.ts",
12
+ "exports": {
13
+ ".": {
14
+ "types": "./dist/index.d.ts",
15
+ "import": "./dist/index.mjs",
16
+ "require": "./dist/index.cjs"
17
+ }
18
+ },
19
+ "scripts": {
20
+ "dev": "unbuild --stub",
21
+ "build": "unbuild && pnpm run patch-cjs",
22
+ "patch-cjs": "esno ../../scripts/patchCJS.ts",
23
+ "prepublishOnly": "npm run build"
24
+ },
12
25
  "engines": {
13
- "node": ">=12.0.0"
26
+ "node": ">=14.6.0"
14
27
  },
15
28
  "repository": {
16
29
  "type": "git",
@@ -22,13 +35,18 @@
22
35
  },
23
36
  "homepage": "https://github.com/vitejs/vite/tree/main/packages/plugin-legacy#readme",
24
37
  "dependencies": {
25
- "@babel/standalone": "^7.17.11",
26
- "core-js": "^3.22.3",
27
- "magic-string": "^0.26.1",
38
+ "@babel/standalone": "^7.18.5",
39
+ "core-js": "^3.22.8",
40
+ "magic-string": "^0.26.2",
28
41
  "regenerator-runtime": "^0.13.9",
29
42
  "systemjs": "^6.12.1"
30
43
  },
31
44
  "peerDependencies": {
32
- "vite": "^2.8.0"
45
+ "terser": "^5.4.0",
46
+ "vite": "^3.0.0-alpha"
47
+ },
48
+ "devDependencies": {
49
+ "@babel/core": "^7.18.5",
50
+ "vite": "workspace:*"
33
51
  }
34
52
  }
package/index.d.ts DELETED
@@ -1,35 +0,0 @@
1
- import type { Plugin } from 'vite'
2
-
3
- export interface Options {
4
- /**
5
- * default: 'defaults'
6
- */
7
- targets?: string | string[] | { [key: string]: string }
8
- /**
9
- * default: false
10
- */
11
- ignoreBrowserslistConfig?: boolean
12
- /**
13
- * default: true
14
- */
15
- polyfills?: boolean | string[]
16
- additionalLegacyPolyfills?: string[]
17
- /**
18
- * default: false
19
- */
20
- modernPolyfills?: boolean | string[]
21
- /**
22
- * default: true
23
- */
24
- renderLegacyChunks?: boolean
25
- /**
26
- * default: false
27
- */
28
- externalSystemJS?: boolean
29
- }
30
-
31
- declare function createPlugin(options?: Options): Plugin
32
-
33
- export default createPlugin
34
-
35
- export const cspHashes: string[]