'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); const crypto = require('crypto'); const module$1 = require('module'); const path = require('path'); const url = require('url'); const browserslist = require('browserslist'); const MagicString = require('magic-string'); const require$$0 = require('tty'); const vite = require('vite'); var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null; function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e.default : e; } const path__default = /*#__PURE__*/_interopDefaultCompat(path); const browserslist__default = /*#__PURE__*/_interopDefaultCompat(browserslist); const MagicString__default = /*#__PURE__*/_interopDefaultCompat(MagicString); const require$$0__default = /*#__PURE__*/_interopDefaultCompat(require$$0); function getDefaultExportFromCjs (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } function commonjsRequire(path) { 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.'); } var picocolors = {exports: {}}; let argv = process.argv || [], env = process.env; let isColorSupported = !("NO_COLOR" in env || argv.includes("--no-color")) && ("FORCE_COLOR" in env || argv.includes("--color") || process.platform === "win32" || (commonjsRequire != null && require$$0__default.isatty(1) && env.TERM !== "dumb") || "CI" in env); let formatter = (open, close, replace = open) => input => { let string = "" + input; let index = string.indexOf(close, open.length); return ~index ? open + replaceClose(string, close, replace, index) + close : open + string + close }; let replaceClose = (string, close, replace, index) => { let result = ""; let cursor = 0; do { result += string.substring(cursor, index) + replace; cursor = index + close.length; index = string.indexOf(close, cursor); } while (~index) return result + string.substring(cursor) }; let createColors = (enabled = isColorSupported) => { let init = enabled ? formatter : () => String; return { isColorSupported: enabled, reset: init("\x1b[0m", "\x1b[0m"), bold: init("\x1b[1m", "\x1b[22m", "\x1b[22m\x1b[1m"), dim: init("\x1b[2m", "\x1b[22m", "\x1b[22m\x1b[2m"), italic: init("\x1b[3m", "\x1b[23m"), underline: init("\x1b[4m", "\x1b[24m"), inverse: init("\x1b[7m", "\x1b[27m"), hidden: init("\x1b[8m", "\x1b[28m"), strikethrough: init("\x1b[9m", "\x1b[29m"), black: init("\x1b[30m", "\x1b[39m"), red: init("\x1b[31m", "\x1b[39m"), green: init("\x1b[32m", "\x1b[39m"), yellow: init("\x1b[33m", "\x1b[39m"), blue: init("\x1b[34m", "\x1b[39m"), magenta: init("\x1b[35m", "\x1b[39m"), cyan: init("\x1b[36m", "\x1b[39m"), white: init("\x1b[37m", "\x1b[39m"), gray: init("\x1b[90m", "\x1b[39m"), bgBlack: init("\x1b[40m", "\x1b[49m"), bgRed: init("\x1b[41m", "\x1b[49m"), bgGreen: init("\x1b[42m", "\x1b[49m"), bgYellow: init("\x1b[43m", "\x1b[49m"), bgBlue: init("\x1b[44m", "\x1b[49m"), bgMagenta: init("\x1b[45m", "\x1b[49m"), bgCyan: init("\x1b[46m", "\x1b[49m"), bgWhite: init("\x1b[47m", "\x1b[49m"), } }; picocolors.exports = createColors(); picocolors.exports.createColors = createColors; var picocolorsExports = picocolors.exports; const colors = /*@__PURE__*/getDefaultExportFromCjs(picocolorsExports); 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()}}();`; const legacyPolyfillId = "vite-legacy-polyfill"; const legacyEntryId = "vite-legacy-entry"; const systemJSInlineCode = `System.import(document.getElementById('${legacyEntryId}').getAttribute('data-src'))`; const detectModernBrowserVarName = "__vite_is_modern_browser"; const detectModernBrowserDetector = `import.meta.url;import("_").catch(()=>1);(async function*(){})().next()`; const detectModernBrowserCode = `${detectModernBrowserDetector};if(location.protocol!="file:"){window.${detectModernBrowserVarName}=true}`; 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)}();`; const modernChunkLegacyGuard = `export function __vite_legacy_guard(){${detectModernBrowserDetector}};`; let loadedSwc; async function loadSwc() { if (!loadedSwc) { loadedSwc = await import('@swc/core'); } return loadedSwc; } const { loadConfig: browserslistLoadConfig } = browserslist__default; function toOutputFilePathInHtml({ filename, type, hostId, hostType, config, toRelative }) { const { renderBuiltUrl } = config.experimental; let relative = config.base === "" || config.base === "./"; if (renderBuiltUrl) { const result = renderBuiltUrl(filename, { hostId, hostType, type, ssr: Boolean(config.build.ssr) }); if (typeof result === "object") { if (result.runtime) { throw new Error( `{ runtime: "${result.runtime}" } is not supported for assets in ${hostType} files: ${filename}` ); } if (typeof result.relative === "boolean") { relative = result.relative; } } else if (result) { return result; } } if (relative && !config.build.ssr) { return toRelative(filename, hostId); } else { return joinUrlSegments(config["decodedBase"] ?? config.base, filename); } } function getBaseInHTML(urlRelativePath, config) { return config.base === "./" || config.base === "" ? path__default.posix.join( path__default.posix.relative(urlRelativePath, "").slice(0, -2), "./" ) : config.base; } function joinUrlSegments(a, b) { if (!a || !b) { return a || b || ""; } if (a[a.length - 1] === "/") { a = a.slice(0, Math.max(0, a.length - 1)); } if (b[0] !== "/") { b = "/" + b; } return a + b; } function toAssetPathFromHtml(filename, htmlPath, config) { const relativeUrlPath = vite.normalizePath(path__default.relative(config.root, htmlPath)); const toRelative = (filePath, hostId) => getBaseInHTML(relativeUrlPath, config) + filePath; return toOutputFilePathInHtml({ filename, type: "asset", hostId: htmlPath, hostType: "html", config, toRelative }); } const legacyEnvVarMarker = `__VITE_IS_LEGACY__`; const $require = module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href))); const nonLeadingHashInFileNameRE = /[^/]+\[hash(?::\d+)?\]/; const prefixedHashInFileNameRE = /\W?\[hash(?::\d+)?\]/; function viteLegacyPlugin(options = {}) { let resolvedConfig; let targets; let modernTargets; const modernTargetsEsbuild = [ "es2020", "edge79", "firefox67", "chrome64", "safari12" ]; const modernTargetsSwc = "edge>=79, firefox>=67, chrome>=64, safari>=12, chromeAndroid>=64, iOS>=12"; const genLegacy = options.renderLegacyChunks !== false; const genModern = options.renderModernChunks !== false; if (!genLegacy && !genModern) { throw new Error( "`renderLegacyChunks` and `renderModernChunks` cannot be both false" ); } const debugFlags = (process.env.DEBUG || "").split(","); const isDebug = debugFlags.includes("vite:*") || debugFlags.includes("vite:legacy"); const facadeToLegacyChunkMap = /* @__PURE__ */ new Map(); const facadeToLegacyPolyfillMap = /* @__PURE__ */ new Map(); const facadeToModernPolyfillMap = /* @__PURE__ */ new Map(); const modernPolyfills = /* @__PURE__ */ new Set(); const legacyPolyfills = /* @__PURE__ */ new Set(); const outputToChunkFileNameToPolyfills = /* @__PURE__ */ new WeakMap(); if (Array.isArray(options.modernPolyfills) && genModern) { options.modernPolyfills.forEach((i) => { modernPolyfills.add( i.includes("/") ? `core-js/${i}` : `core-js/modules/${i}.js` ); }); } if (Array.isArray(options.additionalModernPolyfills)) { options.additionalModernPolyfills.forEach((i) => { modernPolyfills.add(i); }); } if (Array.isArray(options.polyfills)) { options.polyfills.forEach((i) => { if (i.startsWith(`regenerator`)) { legacyPolyfills.add(`regenerator-runtime/runtime.js`); } else { legacyPolyfills.add( i.includes("/") ? `core-js/${i}` : `core-js/modules/${i}.js` ); } }); } if (Array.isArray(options.additionalLegacyPolyfills)) { options.additionalLegacyPolyfills.forEach((i) => { legacyPolyfills.add(i); }); } let overriddenBuildTarget = false; let overriddenDefaultModernTargets = false; const legacyConfigPlugin = { name: "vite:legacy-config", async config(config, env) { if (env.command === "build" && !config.build?.ssr) { if (!config.build) { config.build = {}; } if (!config.build.cssTarget) { config.build.cssTarget = "chrome61"; } if (genLegacy) { overriddenBuildTarget = config.build.target !== void 0; overriddenDefaultModernTargets = options.modernTargets !== void 0; if (options.modernTargets) { const { default: browserslistToEsbuild } = await import('browserslist-to-esbuild'); config.build.target = browserslistToEsbuild(options.modernTargets); } else { config.build.target = modernTargetsEsbuild; } } } return { define: { "import.meta.env.LEGACY": env.command === "serve" || config.build?.ssr ? false : legacyEnvVarMarker } }; }, configResolved(config) { if (overriddenBuildTarget) { config.logger.warn( colors.yellow( `plugin-legacy-swc overrode 'build.target'. You should pass 'targets' as an option to this plugin with the list of legacy browsers to support instead.` ) ); } if (overriddenDefaultModernTargets) { config.logger.warn( colors.yellow( `plugin-legacy-swc 'modernTargets' option overrode the builtin targets of modern chunks. Some versions of browsers between legacy and modern may not be supported.` ) ); } } }; const legacyGenerateBundlePlugin = { name: "vite:legacy-generate-polyfill-chunk", apply: "build", async generateBundle(opts, bundle) { if (resolvedConfig.build.ssr) { return; } const chunkFileNameToPolyfills = outputToChunkFileNameToPolyfills.get(opts); if (!chunkFileNameToPolyfills) { throw new Error( "Internal vite-plugin-legacy-swc error: discovered polyfills should exist" ); } if (!isLegacyBundle(bundle, opts)) { for (const { modern } of chunkFileNameToPolyfills.values()) { modern.forEach((p) => modernPolyfills.add(p)); } if (!modernPolyfills.size) { return; } if (isDebug) { console.log( `[vite-plugin-legacy-swc] modern polyfills:`, modernPolyfills ); } const polyfillChunk = await buildPolyfillChunk({ mode: resolvedConfig.mode, imports: modernPolyfills, bundle, facadeToChunkMap: facadeToModernPolyfillMap, buildOptions: resolvedConfig.build, format: "es", rollupOutputOptions: opts, excludeSystemJS: true }); if (genLegacy && polyfillChunk) { polyfillChunk.code = modernChunkLegacyGuard + polyfillChunk.code; } return; } if (!genLegacy) { return; } for (const { legacy } of chunkFileNameToPolyfills.values()) { legacy.forEach((p) => legacyPolyfills.add(p)); } if (options.polyfills !== false) { await detectPolyfills( `Promise.resolve(); Promise.all();`, targets, legacyPolyfills ); } if (legacyPolyfills.size || !options.externalSystemJS) { if (isDebug) { console.log( `[vite-plugin-legacy-swc] legacy polyfills:`, legacyPolyfills ); } await buildPolyfillChunk({ mode: resolvedConfig.mode, imports: legacyPolyfills, bundle, facadeToChunkMap: facadeToLegacyPolyfillMap, // force using swc for legacy polyfill minification, since esbuild // isn't legacy-safe buildOptions: resolvedConfig.build, format: "iife", rollupOutputOptions: opts, excludeSystemJS: options.externalSystemJS }); } } }; const legacyPostPlugin = { name: "vite:legacy-post-process", enforce: "post", apply: "build", renderStart(opts) { outputToChunkFileNameToPolyfills.set(opts, null); }, configResolved(config) { if (config.build.lib) { throw new Error("vite-plugin-legacy-swc does not support library mode."); } resolvedConfig = config; modernTargets = options.modernTargets || modernTargetsSwc; if (isDebug) { console.log(`[@vitejs/plugin-legacy-swc] modernTargets:`, modernTargets); } if (!genLegacy || resolvedConfig.build.ssr) { return; } targets = options.targets || browserslistLoadConfig({ path: resolvedConfig.root }) || "last 2 versions and not dead, > 0.3%, Firefox ESR"; if (isDebug) { console.log(`[vite-plugin-legacy-swc] targets:`, targets); } const getLegacyOutputFileName = (fileNames, defaultFileName = "[name]-legacy-[hash].js") => { if (!fileNames) { return path__default.posix.join(resolvedConfig.build.assetsDir, defaultFileName); } return (chunkInfo) => { let fileName = typeof fileNames === "function" ? fileNames(chunkInfo) : fileNames; if (fileName.includes("[name]")) { fileName = fileName.replace("[name]", "[name]-legacy"); } else if (nonLeadingHashInFileNameRE.test(fileName)) { fileName = fileName.replace(prefixedHashInFileNameRE, "-legacy$&"); } else { fileName = fileName.replace(/(.+?)\.(.+)/, "$1-legacy.$2"); } return fileName; }; }; const createLegacyOutput = (outputOptions = {}) => { return { ...outputOptions, format: "system", entryFileNames: getLegacyOutputFileName(outputOptions.entryFileNames), chunkFileNames: getLegacyOutputFileName(outputOptions.chunkFileNames) }; }; const { rollupOptions } = resolvedConfig.build; const { output } = rollupOptions; if (Array.isArray(output)) { rollupOptions.output = [ ...output.map(createLegacyOutput), ...genModern ? output : [] ]; } else { rollupOptions.output = [ createLegacyOutput(output), ...genModern ? [output ?? {}] : [] ]; } }, async renderChunk(raw, chunk, opts, { chunks }) { if (resolvedConfig.build.ssr) { return null; } let chunkFileNameToPolyfills = outputToChunkFileNameToPolyfills.get(opts); if (!chunkFileNameToPolyfills) { chunkFileNameToPolyfills = /* @__PURE__ */ new Map(); Object.keys(chunks).forEach((fileName) => { chunkFileNameToPolyfills.set(fileName, { modern: /* @__PURE__ */ new Set(), legacy: /* @__PURE__ */ new Set() }); }); outputToChunkFileNameToPolyfills.set(opts, chunkFileNameToPolyfills); } const polyfillsDiscovered = chunkFileNameToPolyfills.get(chunk.fileName); if (!polyfillsDiscovered) { throw new Error( `Internal vite-plugin-legacy-swc error: discovered polyfills for ${chunk.fileName} should exist` ); } if (!isLegacyChunk(chunk, opts)) { if (options.modernPolyfills && !Array.isArray(options.modernPolyfills) && genModern) { await detectPolyfills(raw, modernTargets, polyfillsDiscovered.modern); } const ms = new MagicString__default(raw); if (genLegacy && chunk.isEntry) { ms.prepend(modernChunkLegacyGuard); } if (raw.includes(legacyEnvVarMarker)) { const re = new RegExp(legacyEnvVarMarker, "g"); let match; while (match = re.exec(raw)) { ms.overwrite( match.index, match.index + legacyEnvVarMarker.length, `false` ); } } if (resolvedConfig.build.sourcemap) { return { code: ms.toString(), map: ms.generateMap({ hires: "boundary" }) }; } return { code: ms.toString() }; } if (!genLegacy) { return null; } opts.__vite_skip_esbuild__ = true; opts.__vite_force_terser__ = true; opts.__vite_skip_asset_emit__ = true; const needPolyfills = options.polyfills !== false && !Array.isArray(options.polyfills); const sourceMaps = Boolean(resolvedConfig.build.sourcemap); const swc = await loadSwc(); const swcOptions = { swcrc: false, configFile: false, sourceMaps, env: createSwcEnvOptions(targets, { needPolyfills }) }; const minifyOptions = { compress: { // Different defaults between terser and swc dead_code: true, keep_fargs: true, passes: 1 }, mangle: true, safari10: true, ...resolvedConfig.build.terserOptions, sourceMap: Boolean(opts.sourcemap), module: opts.format.startsWith("es"), toplevel: opts.format === "cjs" }; const transformResult = await swc.transform(raw, { ...swcOptions, inputSourceMap: void 0, // sourceMaps ? chunk.map : undefined, `.map` TODO: moved to OutputChunk? minify: Boolean(resolvedConfig.build.minify && minifyOptions.mangle), jsc: { // mangle only minify: { ...minifyOptions, compress: false }, transform: { optimizer: { globals: { vars: { [legacyEnvVarMarker]: "true" } } } } } }); const plugin = swc.plugins([ recordAndRemovePolyfillSwcPlugin(polyfillsDiscovered.legacy), wrapIIFESwcPlugin() ]); const ast = await swc.parse(transformResult.code); const result = await swc.print(plugin(ast), { ...swcOptions, inputSourceMap: transformResult.map, minify: Boolean(resolvedConfig.build.minify && minifyOptions.compress), jsc: { // compress only minify: { ...minifyOptions, mangle: false } } }); return result; }, transformIndexHtml(html, { chunk }) { if (resolvedConfig.build.ssr) return; if (!chunk) return; if (chunk.fileName.includes("-legacy")) { facadeToLegacyChunkMap.set(chunk.facadeModuleId, chunk.fileName); if (genModern) { return; } } if (!genModern) { html = html.replace(/