@vitejs/plugin-legacy 1.8.1 → 2.0.0-alpha.1

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