This commit is contained in:
root
2025-11-25 09:56:15 +03:00
commit 68c8f0e80d
23717 changed files with 3200521 additions and 0 deletions

420
mc_test/node_modules/@vitejs/plugin-react/dist/index.cjs generated vendored Executable file
View File

@ -0,0 +1,420 @@
'use strict';
const node_path = require('node:path');
const node_url = require('node:url');
const node_fs = require('node:fs');
const vite = require('vite');
const pluginutils = require('@rolldown/pluginutils');
var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
function _interopNamespaceCompat(e) {
if (e && typeof e === 'object' && 'default' in e) return e;
const n = Object.create(null);
if (e) {
for (const k in e) {
n[k] = e[k];
}
}
n.default = e;
return n;
}
const vite__namespace = /*#__PURE__*/_interopNamespaceCompat(vite);
const runtimePublicPath = "/@react-refresh";
const reactCompRE = /extends\s+(?:React\.)?(?:Pure)?Component/;
const refreshContentRE = /\$RefreshReg\$\(/;
const preambleCode = `import { injectIntoGlobalHook } from "__BASE__${runtimePublicPath.slice(
1
)}";
injectIntoGlobalHook(window);
window.$RefreshReg$ = () => {};
window.$RefreshSig$ = () => (type) => type;`;
const getPreambleCode = (base) => preambleCode.replace("__BASE__", base);
const avoidSourceMapOption = Symbol();
function addRefreshWrapper(code, map, pluginName, id, reactRefreshHost = "") {
const hasRefresh = refreshContentRE.test(code);
const onlyReactComp = !hasRefresh && reactCompRE.test(code);
const normalizedMap = map === avoidSourceMapOption ? null : map;
if (!hasRefresh && !onlyReactComp) return { code, map: normalizedMap };
const avoidSourceMap = map === avoidSourceMapOption;
const newMap = typeof normalizedMap === "string" ? JSON.parse(normalizedMap) : normalizedMap;
let newCode = code;
if (hasRefresh) {
const refreshHead = removeLineBreaksIfNeeded(
`let prevRefreshReg;
let prevRefreshSig;
if (import.meta.hot && !inWebWorker) {
if (!window.$RefreshReg$) {
throw new Error(
"${pluginName} can't detect preamble. Something is wrong."
);
}
prevRefreshReg = window.$RefreshReg$;
prevRefreshSig = window.$RefreshSig$;
window.$RefreshReg$ = RefreshRuntime.getRefreshReg(${JSON.stringify(id)});
window.$RefreshSig$ = RefreshRuntime.createSignatureFunctionForTransform;
}
`,
avoidSourceMap
);
newCode = `${refreshHead}${newCode}
if (import.meta.hot && !inWebWorker) {
window.$RefreshReg$ = prevRefreshReg;
window.$RefreshSig$ = prevRefreshSig;
}
`;
if (newMap) {
newMap.mappings = ";".repeat(16) + newMap.mappings;
}
}
const sharedHead = removeLineBreaksIfNeeded(
`import * as RefreshRuntime from "${reactRefreshHost}${runtimePublicPath}";
const inWebWorker = typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope;
`,
avoidSourceMap
);
newCode = `${sharedHead}${newCode}
if (import.meta.hot && !inWebWorker) {
RefreshRuntime.__hmr_import(import.meta.url).then((currentExports) => {
RefreshRuntime.registerExportsForReactRefresh(${JSON.stringify(
id
)}, currentExports);
import.meta.hot.accept((nextExports) => {
if (!nextExports) return;
const invalidateMessage = RefreshRuntime.validateRefreshBoundaryAndEnqueueUpdate(${JSON.stringify(
id
)}, currentExports, nextExports);
if (invalidateMessage) import.meta.hot.invalidate(invalidateMessage);
});
});
}
`;
if (newMap) {
newMap.mappings = ";;;" + newMap.mappings;
}
return { code: newCode, map: newMap };
}
function removeLineBreaksIfNeeded(code, enabled) {
return enabled ? code.replace(/\n/g, "") : code;
}
const silenceUseClientWarning = (userConfig) => ({
rollupOptions: {
onwarn(warning, defaultHandler) {
if (warning.code === "MODULE_LEVEL_DIRECTIVE" && (warning.message.includes("use client") || warning.message.includes("use server"))) {
return;
}
if (warning.code === "SOURCEMAP_ERROR" && warning.message.includes("resolve original location") && warning.pos === 0) {
return;
}
if (userConfig.build?.rollupOptions?.onwarn) {
userConfig.build.rollupOptions.onwarn(warning, defaultHandler);
} else {
defaultHandler(warning);
}
}
}
});
const _dirname = node_path.dirname(node_url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href))));
const refreshRuntimePath = node_path.join(_dirname, "refresh-runtime.js") ;
let babel;
async function loadBabel() {
if (!babel) {
babel = await import('@babel/core');
}
return babel;
}
const defaultIncludeRE = /\.[tj]sx?$/;
const tsRE = /\.tsx?$/;
function viteReact(opts = {}) {
const include = opts.include ?? defaultIncludeRE;
const exclude = opts.exclude;
const filter = vite.createFilter(include, exclude);
const jsxImportSource = opts.jsxImportSource ?? "react";
const jsxImportRuntime = `${jsxImportSource}/jsx-runtime`;
const jsxImportDevRuntime = `${jsxImportSource}/jsx-dev-runtime`;
let runningInVite = false;
let isProduction = true;
let projectRoot = process.cwd();
let skipFastRefresh = true;
let runPluginOverrides;
let staticBabelOptions;
const importReactRE = /\bimport\s+(?:\*\s+as\s+)?React\b/;
const viteBabel = {
name: "vite:react-babel",
enforce: "pre",
config() {
if (opts.jsxRuntime === "classic") {
if ("rolldownVersion" in vite__namespace) {
return {
oxc: {
jsx: {
runtime: "classic",
// disable __self and __source injection even in dev
// as this plugin injects them by babel and oxc will throw
// if development is enabled and those properties are already present
development: false
}
}
};
} else {
return {
esbuild: {
jsx: "transform"
}
};
}
} else {
return {
esbuild: {
jsx: "automatic",
jsxImportSource: opts.jsxImportSource
},
optimizeDeps: "rolldownVersion" in vite__namespace ? { rollupOptions: { jsx: { mode: "automatic" } } } : { esbuildOptions: { jsx: "automatic" } }
};
}
},
configResolved(config) {
runningInVite = true;
projectRoot = config.root;
isProduction = config.isProduction;
skipFastRefresh = isProduction || config.command === "build" || config.server.hmr === false;
if ("jsxPure" in opts) {
config.logger.warnOnce(
"[@vitejs/plugin-react] jsxPure was removed. You can configure esbuild.jsxSideEffects directly."
);
}
const hooks = config.plugins.map((plugin) => plugin.api?.reactBabel).filter(defined);
if ("rolldownVersion" in vite__namespace && !opts.babel && !hooks.length && !opts.disableOxcRecommendation) {
config.logger.warn(
"[vite:react-babel] We recommend switching to `@vitejs/plugin-react-oxc` for improved performance. More information at https://vite.dev/rolldown"
);
}
if (hooks.length > 0) {
runPluginOverrides = (babelOptions, context) => {
hooks.forEach((hook) => hook(babelOptions, context, config));
};
} else if (typeof opts.babel !== "function") {
staticBabelOptions = createBabelOptions(opts.babel);
if (canSkipBabel(staticBabelOptions.plugins, staticBabelOptions) && skipFastRefresh && (opts.jsxRuntime === "classic" ? isProduction : true)) {
delete viteBabel.transform;
}
}
},
options(options) {
if (!runningInVite) {
options.jsx = {
mode: opts.jsxRuntime,
importSource: opts.jsxImportSource
};
return options;
}
},
transform: {
filter: {
id: {
include: pluginutils.makeIdFiltersToMatchWithQuery(include),
exclude: [
...exclude ? pluginutils.makeIdFiltersToMatchWithQuery(ensureArray(exclude)) : [],
/\/node_modules\//
]
}
},
async handler(code, id, options) {
if (id.includes("/node_modules/")) return;
const [filepath] = id.split("?");
if (!filter(filepath)) return;
const ssr = options?.ssr === true;
const babelOptions = (() => {
if (staticBabelOptions) return staticBabelOptions;
const newBabelOptions = createBabelOptions(
typeof opts.babel === "function" ? opts.babel(id, { ssr }) : opts.babel
);
runPluginOverrides?.(newBabelOptions, { id, ssr });
return newBabelOptions;
})();
const plugins = [...babelOptions.plugins];
const isJSX = filepath.endsWith("x");
const useFastRefresh = !skipFastRefresh && !ssr && (isJSX || (opts.jsxRuntime === "classic" ? importReactRE.test(code) : code.includes(jsxImportDevRuntime) || code.includes(jsxImportRuntime)));
if (useFastRefresh) {
plugins.push([
await loadPlugin("react-refresh/babel"),
{ skipEnvCheck: true }
]);
}
if (opts.jsxRuntime === "classic" && isJSX) {
if (!isProduction) {
plugins.push(
await loadPlugin("@babel/plugin-transform-react-jsx-self"),
await loadPlugin("@babel/plugin-transform-react-jsx-source")
);
}
}
if (canSkipBabel(plugins, babelOptions)) {
return;
}
const parserPlugins = [...babelOptions.parserOpts.plugins];
if (!filepath.endsWith(".ts")) {
parserPlugins.push("jsx");
}
if (tsRE.test(filepath)) {
parserPlugins.push("typescript");
}
const babel2 = await loadBabel();
const result = await babel2.transformAsync(code, {
...babelOptions,
root: projectRoot,
filename: id,
sourceFileName: filepath,
// Required for esbuild.jsxDev to provide correct line numbers
// This creates issues the react compiler because the re-order is too important
// People should use @babel/plugin-transform-react-jsx-development to get back good line numbers
retainLines: getReactCompilerPlugin(plugins) != null ? false : !isProduction && isJSX && opts.jsxRuntime !== "classic",
parserOpts: {
...babelOptions.parserOpts,
sourceType: "module",
allowAwaitOutsideFunction: true,
plugins: parserPlugins
},
generatorOpts: {
...babelOptions.generatorOpts,
// import attributes parsing available without plugin since 7.26
importAttributesKeyword: "with",
decoratorsBeforeExport: true
},
plugins,
sourceMaps: true
});
if (result) {
if (!useFastRefresh) {
return { code: result.code, map: result.map };
}
return addRefreshWrapper(
result.code,
result.map,
"@vitejs/plugin-react",
id,
opts.reactRefreshHost
);
}
}
}
};
const dependencies = [
"react",
"react-dom",
jsxImportDevRuntime,
jsxImportRuntime
];
const staticBabelPlugins = typeof opts.babel === "object" ? opts.babel?.plugins ?? [] : [];
const reactCompilerPlugin = getReactCompilerPlugin(staticBabelPlugins);
if (reactCompilerPlugin != null) {
const reactCompilerRuntimeModule = getReactCompilerRuntimeModule(reactCompilerPlugin);
dependencies.push(reactCompilerRuntimeModule);
}
const viteReactRefresh = {
name: "vite:react-refresh",
enforce: "pre",
config: (userConfig) => ({
build: silenceUseClientWarning(userConfig),
optimizeDeps: {
include: dependencies
},
resolve: {
dedupe: ["react", "react-dom"]
}
}),
resolveId: {
filter: { id: pluginutils.exactRegex(runtimePublicPath) },
handler(id) {
if (id === runtimePublicPath) {
return id;
}
}
},
load: {
filter: { id: pluginutils.exactRegex(runtimePublicPath) },
handler(id) {
if (id === runtimePublicPath) {
return node_fs.readFileSync(refreshRuntimePath, "utf-8").replace(
/__README_URL__/g,
"https://github.com/vitejs/vite-plugin-react/tree/main/packages/plugin-react"
);
}
}
},
transformIndexHtml(_, config) {
if (!skipFastRefresh)
return [
{
tag: "script",
attrs: { type: "module" },
children: getPreambleCode(config.server.config.base)
}
];
}
};
return [viteBabel, viteReactRefresh];
}
viteReact.preambleCode = preambleCode;
function canSkipBabel(plugins, babelOptions) {
return !(plugins.length || babelOptions.presets.length || babelOptions.configFile || babelOptions.babelrc);
}
const loadedPlugin = /* @__PURE__ */ new Map();
function loadPlugin(path) {
const cached = loadedPlugin.get(path);
if (cached) return cached;
const promise = import(path).then((module) => {
const value = module.default || module;
loadedPlugin.set(path, value);
return value;
});
loadedPlugin.set(path, promise);
return promise;
}
function createBabelOptions(rawOptions) {
const babelOptions = {
babelrc: false,
configFile: false,
...rawOptions
};
babelOptions.plugins ||= [];
babelOptions.presets ||= [];
babelOptions.overrides ||= [];
babelOptions.parserOpts ||= {};
babelOptions.parserOpts.plugins ||= [];
return babelOptions;
}
function defined(value) {
return value !== void 0;
}
function getReactCompilerPlugin(plugins) {
return plugins.find(
(p) => p === "babel-plugin-react-compiler" || Array.isArray(p) && p[0] === "babel-plugin-react-compiler"
);
}
function getReactCompilerRuntimeModule(plugin) {
let moduleName = "react/compiler-runtime";
if (Array.isArray(plugin)) {
if (plugin[1]?.target === "17" || plugin[1]?.target === "18") {
moduleName = "react-compiler-runtime";
} else if (typeof plugin[1]?.runtimeModule === "string") {
moduleName = plugin[1]?.runtimeModule;
}
}
return moduleName;
}
function ensureArray(value) {
return Array.isArray(value) ? value : [value];
}
module.exports = viteReact;
module.exports.default = viteReact;

67
mc_test/node_modules/@vitejs/plugin-react/dist/index.d.cts generated vendored Executable file
View File

@ -0,0 +1,67 @@
import { TransformOptions, ParserOptions } from '@babel/core';
import { PluginOption, ResolvedConfig } from 'vite';
interface Options {
include?: string | RegExp | Array<string | RegExp>;
exclude?: string | RegExp | Array<string | RegExp>;
/**
* Control where the JSX factory is imported from.
* https://esbuild.github.io/api/#jsx-import-source
* @default 'react'
*/
jsxImportSource?: string;
/**
* Note: Skipping React import with classic runtime is not supported from v4
* @default "automatic"
*/
jsxRuntime?: 'classic' | 'automatic';
/**
* Babel configuration applied in both dev and prod.
*/
babel?: BabelOptions | ((id: string, options: {
ssr?: boolean;
}) => BabelOptions);
/**
* React Fast Refresh runtime URL prefix.
* Useful in a module federation context to enable HMR by specifying
* the host application URL in the Vite config of a remote application.
* @example
* reactRefreshHost: 'http://localhost:3000'
*/
reactRefreshHost?: string;
/**
* If set, disables the recommendation to use `@vitejs/plugin-react-oxc`
*/
disableOxcRecommendation?: boolean;
}
type BabelOptions = Omit<TransformOptions, 'ast' | 'filename' | 'root' | 'sourceFileName' | 'sourceMaps' | 'inputSourceMap'>;
/**
* The object type used by the `options` passed to plugins with
* an `api.reactBabel` method.
*/
interface ReactBabelOptions extends BabelOptions {
plugins: Extract<BabelOptions['plugins'], any[]>;
presets: Extract<BabelOptions['presets'], any[]>;
overrides: Extract<BabelOptions['overrides'], any[]>;
parserOpts: ParserOptions & {
plugins: Extract<ParserOptions['plugins'], any[]>;
};
}
type ReactBabelHook = (babelConfig: ReactBabelOptions, context: ReactBabelHookContext, config: ResolvedConfig) => void;
type ReactBabelHookContext = {
ssr: boolean;
id: string;
};
type ViteReactPluginApi = {
/**
* Manipulate the Babel options of `@vitejs/plugin-react`
*/
reactBabel?: ReactBabelHook;
};
declare function viteReact(opts?: Options): PluginOption[];
declare namespace viteReact {
var preambleCode: string;
}
export = viteReact;
export type { BabelOptions, Options, ReactBabelOptions, ViteReactPluginApi };

67
mc_test/node_modules/@vitejs/plugin-react/dist/index.d.mts generated vendored Executable file
View File

@ -0,0 +1,67 @@
import { TransformOptions, ParserOptions } from '@babel/core';
import { PluginOption, ResolvedConfig } from 'vite';
interface Options {
include?: string | RegExp | Array<string | RegExp>;
exclude?: string | RegExp | Array<string | RegExp>;
/**
* Control where the JSX factory is imported from.
* https://esbuild.github.io/api/#jsx-import-source
* @default 'react'
*/
jsxImportSource?: string;
/**
* Note: Skipping React import with classic runtime is not supported from v4
* @default "automatic"
*/
jsxRuntime?: 'classic' | 'automatic';
/**
* Babel configuration applied in both dev and prod.
*/
babel?: BabelOptions | ((id: string, options: {
ssr?: boolean;
}) => BabelOptions);
/**
* React Fast Refresh runtime URL prefix.
* Useful in a module federation context to enable HMR by specifying
* the host application URL in the Vite config of a remote application.
* @example
* reactRefreshHost: 'http://localhost:3000'
*/
reactRefreshHost?: string;
/**
* If set, disables the recommendation to use `@vitejs/plugin-react-oxc`
*/
disableOxcRecommendation?: boolean;
}
type BabelOptions = Omit<TransformOptions, 'ast' | 'filename' | 'root' | 'sourceFileName' | 'sourceMaps' | 'inputSourceMap'>;
/**
* The object type used by the `options` passed to plugins with
* an `api.reactBabel` method.
*/
interface ReactBabelOptions extends BabelOptions {
plugins: Extract<BabelOptions['plugins'], any[]>;
presets: Extract<BabelOptions['presets'], any[]>;
overrides: Extract<BabelOptions['overrides'], any[]>;
parserOpts: ParserOptions & {
plugins: Extract<ParserOptions['plugins'], any[]>;
};
}
type ReactBabelHook = (babelConfig: ReactBabelOptions, context: ReactBabelHookContext, config: ResolvedConfig) => void;
type ReactBabelHookContext = {
ssr: boolean;
id: string;
};
type ViteReactPluginApi = {
/**
* Manipulate the Babel options of `@vitejs/plugin-react`
*/
reactBabel?: ReactBabelHook;
};
declare function viteReact(opts?: Options): PluginOption[];
declare namespace viteReact {
var preambleCode: string;
}
export { viteReact as default };
export type { BabelOptions, Options, ReactBabelOptions, ViteReactPluginApi };

67
mc_test/node_modules/@vitejs/plugin-react/dist/index.d.ts generated vendored Executable file
View File

@ -0,0 +1,67 @@
import { TransformOptions, ParserOptions } from '@babel/core';
import { PluginOption, ResolvedConfig } from 'vite';
interface Options {
include?: string | RegExp | Array<string | RegExp>;
exclude?: string | RegExp | Array<string | RegExp>;
/**
* Control where the JSX factory is imported from.
* https://esbuild.github.io/api/#jsx-import-source
* @default 'react'
*/
jsxImportSource?: string;
/**
* Note: Skipping React import with classic runtime is not supported from v4
* @default "automatic"
*/
jsxRuntime?: 'classic' | 'automatic';
/**
* Babel configuration applied in both dev and prod.
*/
babel?: BabelOptions | ((id: string, options: {
ssr?: boolean;
}) => BabelOptions);
/**
* React Fast Refresh runtime URL prefix.
* Useful in a module federation context to enable HMR by specifying
* the host application URL in the Vite config of a remote application.
* @example
* reactRefreshHost: 'http://localhost:3000'
*/
reactRefreshHost?: string;
/**
* If set, disables the recommendation to use `@vitejs/plugin-react-oxc`
*/
disableOxcRecommendation?: boolean;
}
type BabelOptions = Omit<TransformOptions, 'ast' | 'filename' | 'root' | 'sourceFileName' | 'sourceMaps' | 'inputSourceMap'>;
/**
* The object type used by the `options` passed to plugins with
* an `api.reactBabel` method.
*/
interface ReactBabelOptions extends BabelOptions {
plugins: Extract<BabelOptions['plugins'], any[]>;
presets: Extract<BabelOptions['presets'], any[]>;
overrides: Extract<BabelOptions['overrides'], any[]>;
parserOpts: ParserOptions & {
plugins: Extract<ParserOptions['plugins'], any[]>;
};
}
type ReactBabelHook = (babelConfig: ReactBabelOptions, context: ReactBabelHookContext, config: ResolvedConfig) => void;
type ReactBabelHookContext = {
ssr: boolean;
id: string;
};
type ViteReactPluginApi = {
/**
* Manipulate the Babel options of `@vitejs/plugin-react`
*/
reactBabel?: ReactBabelHook;
};
declare function viteReact(opts?: Options): PluginOption[];
declare namespace viteReact {
var preambleCode: string;
}
export = viteReact;
export type { BabelOptions, Options, ReactBabelOptions, ViteReactPluginApi };

403
mc_test/node_modules/@vitejs/plugin-react/dist/index.mjs generated vendored Executable file
View File

@ -0,0 +1,403 @@
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { readFileSync } from 'node:fs';
import * as vite from 'vite';
import { createFilter } from 'vite';
import { makeIdFiltersToMatchWithQuery, exactRegex } from '@rolldown/pluginutils';
const runtimePublicPath = "/@react-refresh";
const reactCompRE = /extends\s+(?:React\.)?(?:Pure)?Component/;
const refreshContentRE = /\$RefreshReg\$\(/;
const preambleCode = `import { injectIntoGlobalHook } from "__BASE__${runtimePublicPath.slice(
1
)}";
injectIntoGlobalHook(window);
window.$RefreshReg$ = () => {};
window.$RefreshSig$ = () => (type) => type;`;
const getPreambleCode = (base) => preambleCode.replace("__BASE__", base);
const avoidSourceMapOption = Symbol();
function addRefreshWrapper(code, map, pluginName, id, reactRefreshHost = "") {
const hasRefresh = refreshContentRE.test(code);
const onlyReactComp = !hasRefresh && reactCompRE.test(code);
const normalizedMap = map === avoidSourceMapOption ? null : map;
if (!hasRefresh && !onlyReactComp) return { code, map: normalizedMap };
const avoidSourceMap = map === avoidSourceMapOption;
const newMap = typeof normalizedMap === "string" ? JSON.parse(normalizedMap) : normalizedMap;
let newCode = code;
if (hasRefresh) {
const refreshHead = removeLineBreaksIfNeeded(
`let prevRefreshReg;
let prevRefreshSig;
if (import.meta.hot && !inWebWorker) {
if (!window.$RefreshReg$) {
throw new Error(
"${pluginName} can't detect preamble. Something is wrong."
);
}
prevRefreshReg = window.$RefreshReg$;
prevRefreshSig = window.$RefreshSig$;
window.$RefreshReg$ = RefreshRuntime.getRefreshReg(${JSON.stringify(id)});
window.$RefreshSig$ = RefreshRuntime.createSignatureFunctionForTransform;
}
`,
avoidSourceMap
);
newCode = `${refreshHead}${newCode}
if (import.meta.hot && !inWebWorker) {
window.$RefreshReg$ = prevRefreshReg;
window.$RefreshSig$ = prevRefreshSig;
}
`;
if (newMap) {
newMap.mappings = ";".repeat(16) + newMap.mappings;
}
}
const sharedHead = removeLineBreaksIfNeeded(
`import * as RefreshRuntime from "${reactRefreshHost}${runtimePublicPath}";
const inWebWorker = typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope;
`,
avoidSourceMap
);
newCode = `${sharedHead}${newCode}
if (import.meta.hot && !inWebWorker) {
RefreshRuntime.__hmr_import(import.meta.url).then((currentExports) => {
RefreshRuntime.registerExportsForReactRefresh(${JSON.stringify(
id
)}, currentExports);
import.meta.hot.accept((nextExports) => {
if (!nextExports) return;
const invalidateMessage = RefreshRuntime.validateRefreshBoundaryAndEnqueueUpdate(${JSON.stringify(
id
)}, currentExports, nextExports);
if (invalidateMessage) import.meta.hot.invalidate(invalidateMessage);
});
});
}
`;
if (newMap) {
newMap.mappings = ";;;" + newMap.mappings;
}
return { code: newCode, map: newMap };
}
function removeLineBreaksIfNeeded(code, enabled) {
return enabled ? code.replace(/\n/g, "") : code;
}
const silenceUseClientWarning = (userConfig) => ({
rollupOptions: {
onwarn(warning, defaultHandler) {
if (warning.code === "MODULE_LEVEL_DIRECTIVE" && (warning.message.includes("use client") || warning.message.includes("use server"))) {
return;
}
if (warning.code === "SOURCEMAP_ERROR" && warning.message.includes("resolve original location") && warning.pos === 0) {
return;
}
if (userConfig.build?.rollupOptions?.onwarn) {
userConfig.build.rollupOptions.onwarn(warning, defaultHandler);
} else {
defaultHandler(warning);
}
}
}
});
const _dirname = dirname(fileURLToPath(import.meta.url));
const refreshRuntimePath = join(_dirname, "refresh-runtime.js") ;
let babel;
async function loadBabel() {
if (!babel) {
babel = await import('@babel/core');
}
return babel;
}
const defaultIncludeRE = /\.[tj]sx?$/;
const tsRE = /\.tsx?$/;
function viteReact(opts = {}) {
const include = opts.include ?? defaultIncludeRE;
const exclude = opts.exclude;
const filter = createFilter(include, exclude);
const jsxImportSource = opts.jsxImportSource ?? "react";
const jsxImportRuntime = `${jsxImportSource}/jsx-runtime`;
const jsxImportDevRuntime = `${jsxImportSource}/jsx-dev-runtime`;
let runningInVite = false;
let isProduction = true;
let projectRoot = process.cwd();
let skipFastRefresh = true;
let runPluginOverrides;
let staticBabelOptions;
const importReactRE = /\bimport\s+(?:\*\s+as\s+)?React\b/;
const viteBabel = {
name: "vite:react-babel",
enforce: "pre",
config() {
if (opts.jsxRuntime === "classic") {
if ("rolldownVersion" in vite) {
return {
oxc: {
jsx: {
runtime: "classic",
// disable __self and __source injection even in dev
// as this plugin injects them by babel and oxc will throw
// if development is enabled and those properties are already present
development: false
}
}
};
} else {
return {
esbuild: {
jsx: "transform"
}
};
}
} else {
return {
esbuild: {
jsx: "automatic",
jsxImportSource: opts.jsxImportSource
},
optimizeDeps: "rolldownVersion" in vite ? { rollupOptions: { jsx: { mode: "automatic" } } } : { esbuildOptions: { jsx: "automatic" } }
};
}
},
configResolved(config) {
runningInVite = true;
projectRoot = config.root;
isProduction = config.isProduction;
skipFastRefresh = isProduction || config.command === "build" || config.server.hmr === false;
if ("jsxPure" in opts) {
config.logger.warnOnce(
"[@vitejs/plugin-react] jsxPure was removed. You can configure esbuild.jsxSideEffects directly."
);
}
const hooks = config.plugins.map((plugin) => plugin.api?.reactBabel).filter(defined);
if ("rolldownVersion" in vite && !opts.babel && !hooks.length && !opts.disableOxcRecommendation) {
config.logger.warn(
"[vite:react-babel] We recommend switching to `@vitejs/plugin-react-oxc` for improved performance. More information at https://vite.dev/rolldown"
);
}
if (hooks.length > 0) {
runPluginOverrides = (babelOptions, context) => {
hooks.forEach((hook) => hook(babelOptions, context, config));
};
} else if (typeof opts.babel !== "function") {
staticBabelOptions = createBabelOptions(opts.babel);
if (canSkipBabel(staticBabelOptions.plugins, staticBabelOptions) && skipFastRefresh && (opts.jsxRuntime === "classic" ? isProduction : true)) {
delete viteBabel.transform;
}
}
},
options(options) {
if (!runningInVite) {
options.jsx = {
mode: opts.jsxRuntime,
importSource: opts.jsxImportSource
};
return options;
}
},
transform: {
filter: {
id: {
include: makeIdFiltersToMatchWithQuery(include),
exclude: [
...exclude ? makeIdFiltersToMatchWithQuery(ensureArray(exclude)) : [],
/\/node_modules\//
]
}
},
async handler(code, id, options) {
if (id.includes("/node_modules/")) return;
const [filepath] = id.split("?");
if (!filter(filepath)) return;
const ssr = options?.ssr === true;
const babelOptions = (() => {
if (staticBabelOptions) return staticBabelOptions;
const newBabelOptions = createBabelOptions(
typeof opts.babel === "function" ? opts.babel(id, { ssr }) : opts.babel
);
runPluginOverrides?.(newBabelOptions, { id, ssr });
return newBabelOptions;
})();
const plugins = [...babelOptions.plugins];
const isJSX = filepath.endsWith("x");
const useFastRefresh = !skipFastRefresh && !ssr && (isJSX || (opts.jsxRuntime === "classic" ? importReactRE.test(code) : code.includes(jsxImportDevRuntime) || code.includes(jsxImportRuntime)));
if (useFastRefresh) {
plugins.push([
await loadPlugin("react-refresh/babel"),
{ skipEnvCheck: true }
]);
}
if (opts.jsxRuntime === "classic" && isJSX) {
if (!isProduction) {
plugins.push(
await loadPlugin("@babel/plugin-transform-react-jsx-self"),
await loadPlugin("@babel/plugin-transform-react-jsx-source")
);
}
}
if (canSkipBabel(plugins, babelOptions)) {
return;
}
const parserPlugins = [...babelOptions.parserOpts.plugins];
if (!filepath.endsWith(".ts")) {
parserPlugins.push("jsx");
}
if (tsRE.test(filepath)) {
parserPlugins.push("typescript");
}
const babel2 = await loadBabel();
const result = await babel2.transformAsync(code, {
...babelOptions,
root: projectRoot,
filename: id,
sourceFileName: filepath,
// Required for esbuild.jsxDev to provide correct line numbers
// This creates issues the react compiler because the re-order is too important
// People should use @babel/plugin-transform-react-jsx-development to get back good line numbers
retainLines: getReactCompilerPlugin(plugins) != null ? false : !isProduction && isJSX && opts.jsxRuntime !== "classic",
parserOpts: {
...babelOptions.parserOpts,
sourceType: "module",
allowAwaitOutsideFunction: true,
plugins: parserPlugins
},
generatorOpts: {
...babelOptions.generatorOpts,
// import attributes parsing available without plugin since 7.26
importAttributesKeyword: "with",
decoratorsBeforeExport: true
},
plugins,
sourceMaps: true
});
if (result) {
if (!useFastRefresh) {
return { code: result.code, map: result.map };
}
return addRefreshWrapper(
result.code,
result.map,
"@vitejs/plugin-react",
id,
opts.reactRefreshHost
);
}
}
}
};
const dependencies = [
"react",
"react-dom",
jsxImportDevRuntime,
jsxImportRuntime
];
const staticBabelPlugins = typeof opts.babel === "object" ? opts.babel?.plugins ?? [] : [];
const reactCompilerPlugin = getReactCompilerPlugin(staticBabelPlugins);
if (reactCompilerPlugin != null) {
const reactCompilerRuntimeModule = getReactCompilerRuntimeModule(reactCompilerPlugin);
dependencies.push(reactCompilerRuntimeModule);
}
const viteReactRefresh = {
name: "vite:react-refresh",
enforce: "pre",
config: (userConfig) => ({
build: silenceUseClientWarning(userConfig),
optimizeDeps: {
include: dependencies
},
resolve: {
dedupe: ["react", "react-dom"]
}
}),
resolveId: {
filter: { id: exactRegex(runtimePublicPath) },
handler(id) {
if (id === runtimePublicPath) {
return id;
}
}
},
load: {
filter: { id: exactRegex(runtimePublicPath) },
handler(id) {
if (id === runtimePublicPath) {
return readFileSync(refreshRuntimePath, "utf-8").replace(
/__README_URL__/g,
"https://github.com/vitejs/vite-plugin-react/tree/main/packages/plugin-react"
);
}
}
},
transformIndexHtml(_, config) {
if (!skipFastRefresh)
return [
{
tag: "script",
attrs: { type: "module" },
children: getPreambleCode(config.server.config.base)
}
];
}
};
return [viteBabel, viteReactRefresh];
}
viteReact.preambleCode = preambleCode;
function canSkipBabel(plugins, babelOptions) {
return !(plugins.length || babelOptions.presets.length || babelOptions.configFile || babelOptions.babelrc);
}
const loadedPlugin = /* @__PURE__ */ new Map();
function loadPlugin(path) {
const cached = loadedPlugin.get(path);
if (cached) return cached;
const promise = import(path).then((module) => {
const value = module.default || module;
loadedPlugin.set(path, value);
return value;
});
loadedPlugin.set(path, promise);
return promise;
}
function createBabelOptions(rawOptions) {
const babelOptions = {
babelrc: false,
configFile: false,
...rawOptions
};
babelOptions.plugins ||= [];
babelOptions.presets ||= [];
babelOptions.overrides ||= [];
babelOptions.parserOpts ||= {};
babelOptions.parserOpts.plugins ||= [];
return babelOptions;
}
function defined(value) {
return value !== void 0;
}
function getReactCompilerPlugin(plugins) {
return plugins.find(
(p) => p === "babel-plugin-react-compiler" || Array.isArray(p) && p[0] === "babel-plugin-react-compiler"
);
}
function getReactCompilerRuntimeModule(plugin) {
let moduleName = "react/compiler-runtime";
if (Array.isArray(plugin)) {
if (plugin[1]?.target === "17" || plugin[1]?.target === "18") {
moduleName = "react-compiler-runtime";
} else if (typeof plugin[1]?.runtimeModule === "string") {
moduleName = plugin[1]?.runtimeModule;
}
}
return moduleName;
}
function ensureArray(value) {
return Array.isArray(value) ? value : [value];
}
export { viteReact as default };

View File

@ -0,0 +1,647 @@
/* global window */
/* eslint-disable eqeqeq, prefer-const, @typescript-eslint/no-empty-function */
/*! Copyright (c) Meta Platforms, Inc. and affiliates. **/
/**
* This is simplified pure-js version of https://github.com/facebook/react/blob/main/packages/react-refresh/src/ReactFreshRuntime.js
* without IE11 compatibility and verbose isDev checks.
* Some utils are appended at the bottom for HMR integration.
*/
const REACT_FORWARD_REF_TYPE = Symbol.for('react.forward_ref')
const REACT_MEMO_TYPE = Symbol.for('react.memo')
// We never remove these associations.
// It's OK to reference families, but use WeakMap/Set for types.
let allFamiliesByID = new Map()
let allFamiliesByType = new WeakMap()
let allSignaturesByType = new WeakMap()
// This WeakMap is read by React, so we only put families
// that have actually been edited here. This keeps checks fast.
const updatedFamiliesByType = new WeakMap()
// This is cleared on every performReactRefresh() call.
// It is an array of [Family, NextType] tuples.
let pendingUpdates = []
// This is injected by the renderer via DevTools global hook.
const helpersByRendererID = new Map()
const helpersByRoot = new Map()
// We keep track of mounted roots so we can schedule updates.
const mountedRoots = new Set()
// If a root captures an error, we remember it so we can retry on edit.
const failedRoots = new Set()
// We also remember the last element for every root.
// It needs to be weak because we do this even for roots that failed to mount.
// If there is no WeakMap, we won't attempt to do retrying.
let rootElements = new WeakMap()
let isPerformingRefresh = false
function computeFullKey(signature) {
if (signature.fullKey !== null) {
return signature.fullKey
}
let fullKey = signature.ownKey
let hooks
try {
hooks = signature.getCustomHooks()
} catch (err) {
// This can happen in an edge case, e.g. if expression like Foo.useSomething
// depends on Foo which is lazily initialized during rendering.
// In that case just assume we'll have to remount.
signature.forceReset = true
signature.fullKey = fullKey
return fullKey
}
for (let i = 0; i < hooks.length; i++) {
const hook = hooks[i]
if (typeof hook !== 'function') {
// Something's wrong. Assume we need to remount.
signature.forceReset = true
signature.fullKey = fullKey
return fullKey
}
const nestedHookSignature = allSignaturesByType.get(hook)
if (nestedHookSignature === undefined) {
// No signature means Hook wasn't in the source code, e.g. in a library.
// We'll skip it because we can assume it won't change during this session.
continue
}
const nestedHookKey = computeFullKey(nestedHookSignature)
if (nestedHookSignature.forceReset) {
signature.forceReset = true
}
fullKey += '\n---\n' + nestedHookKey
}
signature.fullKey = fullKey
return fullKey
}
function haveEqualSignatures(prevType, nextType) {
const prevSignature = allSignaturesByType.get(prevType)
const nextSignature = allSignaturesByType.get(nextType)
if (prevSignature === undefined && nextSignature === undefined) {
return true
}
if (prevSignature === undefined || nextSignature === undefined) {
return false
}
if (computeFullKey(prevSignature) !== computeFullKey(nextSignature)) {
return false
}
if (nextSignature.forceReset) {
return false
}
return true
}
function isReactClass(type) {
return type.prototype && type.prototype.isReactComponent
}
function canPreserveStateBetween(prevType, nextType) {
if (isReactClass(prevType) || isReactClass(nextType)) {
return false
}
if (haveEqualSignatures(prevType, nextType)) {
return true
}
return false
}
function resolveFamily(type) {
// Only check updated types to keep lookups fast.
return updatedFamiliesByType.get(type)
}
// This is a safety mechanism to protect against rogue getters and Proxies.
function getProperty(object, property) {
try {
return object[property]
} catch (err) {
// Intentionally ignore.
return undefined
}
}
function performReactRefresh() {
if (pendingUpdates.length === 0) {
return null
}
if (isPerformingRefresh) {
return null
}
isPerformingRefresh = true
try {
const staleFamilies = new Set()
const updatedFamilies = new Set()
const updates = pendingUpdates
pendingUpdates = []
updates.forEach(([family, nextType]) => {
// Now that we got a real edit, we can create associations
// that will be read by the React reconciler.
const prevType = family.current
updatedFamiliesByType.set(prevType, family)
updatedFamiliesByType.set(nextType, family)
family.current = nextType
// Determine whether this should be a re-render or a re-mount.
if (canPreserveStateBetween(prevType, nextType)) {
updatedFamilies.add(family)
} else {
staleFamilies.add(family)
}
})
// TODO: rename these fields to something more meaningful.
const update = {
updatedFamilies, // Families that will re-render preserving state
staleFamilies, // Families that will be remounted
}
helpersByRendererID.forEach((helpers) => {
// Even if there are no roots, set the handler on first update.
// This ensures that if *new* roots are mounted, they'll use the resolve handler.
helpers.setRefreshHandler(resolveFamily)
})
let didError = false
let firstError = null
// We snapshot maps and sets that are mutated during commits.
// If we don't do this, there is a risk they will be mutated while
// we iterate over them. For example, trying to recover a failed root
// may cause another root to be added to the failed list -- an infinite loop.
const failedRootsSnapshot = new Set(failedRoots)
const mountedRootsSnapshot = new Set(mountedRoots)
const helpersByRootSnapshot = new Map(helpersByRoot)
failedRootsSnapshot.forEach((root) => {
const helpers = helpersByRootSnapshot.get(root)
if (helpers === undefined) {
throw new Error(
'Could not find helpers for a root. This is a bug in React Refresh.',
)
}
if (!failedRoots.has(root)) {
// No longer failed.
}
if (rootElements === null) {
return
}
if (!rootElements.has(root)) {
return
}
const element = rootElements.get(root)
try {
helpers.scheduleRoot(root, element)
} catch (err) {
if (!didError) {
didError = true
firstError = err
}
// Keep trying other roots.
}
})
mountedRootsSnapshot.forEach((root) => {
const helpers = helpersByRootSnapshot.get(root)
if (helpers === undefined) {
throw new Error(
'Could not find helpers for a root. This is a bug in React Refresh.',
)
}
if (!mountedRoots.has(root)) {
// No longer mounted.
}
try {
helpers.scheduleRefresh(root, update)
} catch (err) {
if (!didError) {
didError = true
firstError = err
}
// Keep trying other roots.
}
})
if (didError) {
throw firstError
}
return update
} finally {
isPerformingRefresh = false
}
}
function register(type, id) {
if (type === null) {
return
}
if (typeof type !== 'function' && typeof type !== 'object') {
return
}
// This can happen in an edge case, e.g. if we register
// return value of a HOC but it returns a cached component.
// Ignore anything but the first registration for each type.
if (allFamiliesByType.has(type)) {
return
}
// Create family or remember to update it.
// None of this bookkeeping affects reconciliation
// until the first performReactRefresh() call above.
let family = allFamiliesByID.get(id)
if (family === undefined) {
family = { current: type }
allFamiliesByID.set(id, family)
} else {
pendingUpdates.push([family, type])
}
allFamiliesByType.set(type, family)
// Visit inner types because we might not have registered them.
if (typeof type === 'object' && type !== null) {
switch (getProperty(type, '$$typeof')) {
case REACT_FORWARD_REF_TYPE:
register(type.render, id + '$render')
break
case REACT_MEMO_TYPE:
register(type.type, id + '$type')
break
}
}
}
function setSignature(type, key, forceReset, getCustomHooks) {
if (!allSignaturesByType.has(type)) {
allSignaturesByType.set(type, {
forceReset,
ownKey: key,
fullKey: null,
getCustomHooks: getCustomHooks || (() => []),
})
}
// Visit inner types because we might not have signed them.
if (typeof type === 'object' && type !== null) {
switch (getProperty(type, '$$typeof')) {
case REACT_FORWARD_REF_TYPE:
setSignature(type.render, key, forceReset, getCustomHooks)
break
case REACT_MEMO_TYPE:
setSignature(type.type, key, forceReset, getCustomHooks)
break
}
}
}
// This is lazily called during first render for a type.
// It captures Hook list at that time so inline requires don't break comparisons.
function collectCustomHooksForSignature(type) {
const signature = allSignaturesByType.get(type)
if (signature !== undefined) {
computeFullKey(signature)
}
}
export function injectIntoGlobalHook(globalObject) {
// For React Native, the global hook will be set up by require('react-devtools-core').
// That code will run before us. So we need to monkeypatch functions on existing hook.
// For React Web, the global hook will be set up by the extension.
// This will also run before us.
let hook = globalObject.__REACT_DEVTOOLS_GLOBAL_HOOK__
if (hook === undefined) {
// However, if there is no DevTools extension, we'll need to set up the global hook ourselves.
// Note that in this case it's important that renderer code runs *after* this method call.
// Otherwise, the renderer will think that there is no global hook, and won't do the injection.
let nextID = 0
globalObject.__REACT_DEVTOOLS_GLOBAL_HOOK__ = hook = {
renderers: new Map(),
supportsFiber: true,
inject: (injected) => nextID++,
onScheduleFiberRoot: (id, root, children) => {},
onCommitFiberRoot: (id, root, maybePriorityLevel, didError) => {},
onCommitFiberUnmount() {},
}
}
if (hook.isDisabled) {
// This isn't a real property on the hook, but it can be set to opt out
// of DevTools integration and associated warnings and logs.
// Using console['warn'] to evade Babel and ESLint
console['warn'](
'Something has shimmed the React DevTools global hook (__REACT_DEVTOOLS_GLOBAL_HOOK__). ' +
'Fast Refresh is not compatible with this shim and will be disabled.',
)
return
}
// Here, we just want to get a reference to scheduleRefresh.
const oldInject = hook.inject
hook.inject = function (injected) {
const id = oldInject.apply(this, arguments)
if (
typeof injected.scheduleRefresh === 'function' &&
typeof injected.setRefreshHandler === 'function'
) {
// This version supports React Refresh.
helpersByRendererID.set(id, injected)
}
return id
}
// Do the same for any already injected roots.
// This is useful if ReactDOM has already been initialized.
// https://github.com/facebook/react/issues/17626
hook.renderers.forEach((injected, id) => {
if (
typeof injected.scheduleRefresh === 'function' &&
typeof injected.setRefreshHandler === 'function'
) {
// This version supports React Refresh.
helpersByRendererID.set(id, injected)
}
})
// We also want to track currently mounted roots.
const oldOnCommitFiberRoot = hook.onCommitFiberRoot
const oldOnScheduleFiberRoot = hook.onScheduleFiberRoot || (() => {})
hook.onScheduleFiberRoot = function (id, root, children) {
if (!isPerformingRefresh) {
// If it was intentionally scheduled, don't attempt to restore.
// This includes intentionally scheduled unmounts.
failedRoots.delete(root)
if (rootElements !== null) {
rootElements.set(root, children)
}
}
return oldOnScheduleFiberRoot.apply(this, arguments)
}
hook.onCommitFiberRoot = function (id, root, maybePriorityLevel, didError) {
const helpers = helpersByRendererID.get(id)
if (helpers !== undefined) {
helpersByRoot.set(root, helpers)
const current = root.current
const alternate = current.alternate
// We need to determine whether this root has just (un)mounted.
// This logic is copy-pasted from similar logic in the DevTools backend.
// If this breaks with some refactoring, you'll want to update DevTools too.
if (alternate !== null) {
const wasMounted =
alternate.memoizedState != null &&
alternate.memoizedState.element != null &&
mountedRoots.has(root)
const isMounted =
current.memoizedState != null && current.memoizedState.element != null
if (!wasMounted && isMounted) {
// Mount a new root.
mountedRoots.add(root)
failedRoots.delete(root)
} else if (wasMounted && isMounted) {
// Update an existing root.
// This doesn't affect our mounted root Set.
} else if (wasMounted && !isMounted) {
// Unmount an existing root.
mountedRoots.delete(root)
if (didError) {
// We'll remount it on future edits.
failedRoots.add(root)
} else {
helpersByRoot.delete(root)
}
} else if (!wasMounted && !isMounted) {
if (didError) {
// We'll remount it on future edits.
failedRoots.add(root)
}
}
} else {
// Mount a new root.
mountedRoots.add(root)
}
}
// Always call the decorated DevTools hook.
return oldOnCommitFiberRoot.apply(this, arguments)
}
}
// This is a wrapper over more primitive functions for setting signature.
// Signatures let us decide whether the Hook order has changed on refresh.
//
// This function is intended to be used as a transform target, e.g.:
// var _s = createSignatureFunctionForTransform()
//
// function Hello() {
// const [foo, setFoo] = useState(0);
// const value = useCustomHook();
// _s(); /* Call without arguments triggers collecting the custom Hook list.
// * This doesn't happen during the module evaluation because we
// * don't want to change the module order with inline requires.
// * Next calls are noops. */
// return <h1>Hi</h1>;
// }
//
// /* Call with arguments attaches the signature to the type: */
// _s(
// Hello,
// 'useState{[foo, setFoo]}(0)',
// () => [useCustomHook], /* Lazy to avoid triggering inline requires */
// );
export function createSignatureFunctionForTransform() {
let savedType
let hasCustomHooks
let didCollectHooks = false
return function (type, key, forceReset, getCustomHooks) {
if (typeof key === 'string') {
// We're in the initial phase that associates signatures
// with the functions. Note this may be called multiple times
// in HOC chains like _s(hoc1(_s(hoc2(_s(actualFunction))))).
if (!savedType) {
// We're in the innermost call, so this is the actual type.
// $FlowFixMe[escaped-generic] discovered when updating Flow
savedType = type
hasCustomHooks = typeof getCustomHooks === 'function'
}
// Set the signature for all types (even wrappers!) in case
// they have no signatures of their own. This is to prevent
// problems like https://github.com/facebook/react/issues/20417.
if (
type != null &&
(typeof type === 'function' || typeof type === 'object')
) {
setSignature(type, key, forceReset, getCustomHooks)
}
return type
} else {
// We're in the _s() call without arguments, which means
// this is the time to collect custom Hook signatures.
// Only do this once. This path is hot and runs *inside* every render!
if (!didCollectHooks && hasCustomHooks) {
didCollectHooks = true
collectCustomHooksForSignature(savedType)
}
}
}
}
function isLikelyComponentType(type) {
switch (typeof type) {
case 'function': {
// First, deal with classes.
if (type.prototype != null) {
if (type.prototype.isReactComponent) {
// React class.
return true
}
const ownNames = Object.getOwnPropertyNames(type.prototype)
if (ownNames.length > 1 || ownNames[0] !== 'constructor') {
// This looks like a class.
return false
}
if (type.prototype.__proto__ !== Object.prototype) {
// It has a superclass.
return false
}
// Pass through.
// This looks like a regular function with empty prototype.
}
// For plain functions and arrows, use name as a heuristic.
const name = type.name || type.displayName
return typeof name === 'string' && /^[A-Z]/.test(name)
}
case 'object': {
if (type != null) {
switch (getProperty(type, '$$typeof')) {
case REACT_FORWARD_REF_TYPE:
case REACT_MEMO_TYPE:
// Definitely React components.
return true
default:
return false
}
}
return false
}
default: {
return false
}
}
}
/**
* Plugin utils
*/
export function getRefreshReg(filename) {
return (type, id) => register(type, filename + ' ' + id)
}
// Taken from https://github.com/pmmmwh/react-refresh-webpack-plugin/blob/main/lib/runtime/RefreshUtils.js#L141
// This allows to resister components not detected by SWC like styled component
export function registerExportsForReactRefresh(filename, moduleExports) {
for (const key in moduleExports) {
if (key === '__esModule') continue
const exportValue = moduleExports[key]
if (isLikelyComponentType(exportValue)) {
// 'export' is required to avoid key collision when renamed exports that
// shadow a local component name: https://github.com/vitejs/vite-plugin-react/issues/116
// The register function has an identity check to not register twice the same component,
// so this is safe to not used the same key here.
register(exportValue, filename + ' export ' + key)
}
}
}
function debounce(fn, delay) {
let handle
return () => {
clearTimeout(handle)
handle = setTimeout(fn, delay)
}
}
const hooks = []
window.__registerBeforePerformReactRefresh = (cb) => {
hooks.push(cb)
}
const enqueueUpdate = debounce(async () => {
if (hooks.length) await Promise.all(hooks.map((cb) => cb()))
performReactRefresh()
}, 16)
export function validateRefreshBoundaryAndEnqueueUpdate(
id,
prevExports,
nextExports,
) {
const ignoredExports = window.__getReactRefreshIgnoredExports?.({ id }) ?? []
if (
predicateOnExport(
ignoredExports,
prevExports,
(key) => key in nextExports,
) !== true
) {
return 'Could not Fast Refresh (export removed)'
}
if (
predicateOnExport(
ignoredExports,
nextExports,
(key) => key in prevExports,
) !== true
) {
return 'Could not Fast Refresh (new export)'
}
let hasExports = false
const allExportsAreComponentsOrUnchanged = predicateOnExport(
ignoredExports,
nextExports,
(key, value) => {
hasExports = true
if (isLikelyComponentType(value)) return true
return prevExports[key] === nextExports[key]
},
)
if (hasExports && allExportsAreComponentsOrUnchanged === true) {
enqueueUpdate()
} else {
return `Could not Fast Refresh ("${allExportsAreComponentsOrUnchanged}" export is incompatible). Learn more at __README_URL__#consistent-components-exports`
}
}
function predicateOnExport(ignoredExports, moduleExports, predicate) {
for (const key in moduleExports) {
if (key === '__esModule') continue
if (ignoredExports.includes(key)) continue
const desc = Object.getOwnPropertyDescriptor(moduleExports, key)
if (desc && desc.get) return key
if (!predicate(key, moduleExports[key])) return key
}
return true
}
// Hides vite-ignored dynamic import so that Vite can skip analysis if no other
// dynamic import is present (https://github.com/vitejs/vite/pull/12732)
export const __hmr_import = (module) => import(/* @vite-ignore */ module)
// For backwards compatibility with @vitejs/plugin-react.
export default { injectIntoGlobalHook }