index.cjs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  1. //#region rolldown:runtime
  2. var __create = Object.create;
  3. var __defProp = Object.defineProperty;
  4. var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
  5. var __getOwnPropNames = Object.getOwnPropertyNames;
  6. var __getProtoOf = Object.getPrototypeOf;
  7. var __hasOwnProp = Object.prototype.hasOwnProperty;
  8. var __copyProps = (to, from, except, desc) => {
  9. if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
  10. key = keys[i];
  11. if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
  12. get: ((k) => from[k]).bind(null, key),
  13. enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
  14. });
  15. }
  16. return to;
  17. };
  18. var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
  19. value: mod,
  20. enumerable: true
  21. }) : target, mod));
  22. //#endregion
  23. const node_path = __toESM(require("node:path"));
  24. const node_url = __toESM(require("node:url"));
  25. const node_fs = __toESM(require("node:fs"));
  26. const vite = __toESM(require("vite"));
  27. const __rolldown_pluginutils = __toESM(require("@rolldown/pluginutils"));
  28. //#region ../common/refresh-utils.ts
  29. const runtimePublicPath = "/@react-refresh";
  30. const reactCompRE = /extends\s+(?:React\.)?(?:Pure)?Component/;
  31. const refreshContentRE = /\$RefreshReg\$\(/;
  32. const preambleCode = `import { injectIntoGlobalHook } from "__BASE__${runtimePublicPath.slice(1)}";
  33. injectIntoGlobalHook(window);
  34. window.$RefreshReg$ = () => {};
  35. window.$RefreshSig$ = () => (type) => type;`;
  36. const getPreambleCode = (base) => preambleCode.replace("__BASE__", base);
  37. const avoidSourceMapOption = Symbol();
  38. function addRefreshWrapper(code, map, pluginName, id, reactRefreshHost = "") {
  39. const hasRefresh = refreshContentRE.test(code);
  40. const onlyReactComp = !hasRefresh && reactCompRE.test(code);
  41. const normalizedMap = map === avoidSourceMapOption ? null : map;
  42. if (!hasRefresh && !onlyReactComp) return {
  43. code,
  44. map: normalizedMap
  45. };
  46. const avoidSourceMap = map === avoidSourceMapOption;
  47. const newMap = typeof normalizedMap === "string" ? JSON.parse(normalizedMap) : normalizedMap;
  48. let newCode = code;
  49. if (hasRefresh) {
  50. const refreshHead = removeLineBreaksIfNeeded(`let prevRefreshReg;
  51. let prevRefreshSig;
  52. if (import.meta.hot && !inWebWorker) {
  53. if (!window.$RefreshReg$) {
  54. throw new Error(
  55. "${pluginName} can't detect preamble. Something is wrong."
  56. );
  57. }
  58. prevRefreshReg = window.$RefreshReg$;
  59. prevRefreshSig = window.$RefreshSig$;
  60. window.$RefreshReg$ = RefreshRuntime.getRefreshReg(${JSON.stringify(id)});
  61. window.$RefreshSig$ = RefreshRuntime.createSignatureFunctionForTransform;
  62. }
  63. `, avoidSourceMap);
  64. newCode = `${refreshHead}${newCode}
  65. if (import.meta.hot && !inWebWorker) {
  66. window.$RefreshReg$ = prevRefreshReg;
  67. window.$RefreshSig$ = prevRefreshSig;
  68. }
  69. `;
  70. if (newMap) newMap.mappings = ";".repeat(16) + newMap.mappings;
  71. }
  72. const sharedHead = removeLineBreaksIfNeeded(`import * as RefreshRuntime from "${reactRefreshHost}${runtimePublicPath}";
  73. const inWebWorker = typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope;
  74. `, avoidSourceMap);
  75. newCode = `${sharedHead}${newCode}
  76. if (import.meta.hot && !inWebWorker) {
  77. RefreshRuntime.__hmr_import(import.meta.url).then((currentExports) => {
  78. RefreshRuntime.registerExportsForReactRefresh(${JSON.stringify(id)}, currentExports);
  79. import.meta.hot.accept((nextExports) => {
  80. if (!nextExports) return;
  81. const invalidateMessage = RefreshRuntime.validateRefreshBoundaryAndEnqueueUpdate(${JSON.stringify(id)}, currentExports, nextExports);
  82. if (invalidateMessage) import.meta.hot.invalidate(invalidateMessage);
  83. });
  84. });
  85. }
  86. `;
  87. if (newMap) newMap.mappings = ";;;" + newMap.mappings;
  88. return {
  89. code: newCode,
  90. map: newMap
  91. };
  92. }
  93. function removeLineBreaksIfNeeded(code, enabled) {
  94. return enabled ? code.replace(/\n/g, "") : code;
  95. }
  96. //#endregion
  97. //#region ../common/warning.ts
  98. const silenceUseClientWarning = (userConfig) => ({ rollupOptions: { onwarn(warning, defaultHandler) {
  99. var _userConfig$build;
  100. if (warning.code === "MODULE_LEVEL_DIRECTIVE" && (warning.message.includes("use client") || warning.message.includes("use server"))) return;
  101. if (warning.code === "SOURCEMAP_ERROR" && warning.message.includes("resolve original location") && warning.pos === 0) return;
  102. if ((_userConfig$build = userConfig.build) === null || _userConfig$build === void 0 || (_userConfig$build = _userConfig$build.rollupOptions) === null || _userConfig$build === void 0 ? void 0 : _userConfig$build.onwarn) userConfig.build.rollupOptions.onwarn(warning, defaultHandler);
  103. else defaultHandler(warning);
  104. } } });
  105. //#endregion
  106. //#region src/index.ts
  107. const _dirname = (0, node_path.dirname)((0, node_url.fileURLToPath)(require("url").pathToFileURL(__filename).href));
  108. const refreshRuntimePath = (0, node_path.join)(_dirname, "refresh-runtime.js");
  109. let babel;
  110. async function loadBabel() {
  111. if (!babel) babel = await import("@babel/core");
  112. return babel;
  113. }
  114. const defaultIncludeRE = /\.[tj]sx?$/;
  115. const tsRE = /\.tsx?$/;
  116. function viteReact(opts = {}) {
  117. var _opts$babel;
  118. const include = opts.include ?? defaultIncludeRE;
  119. const exclude = opts.exclude;
  120. const filter = (0, vite.createFilter)(include, exclude);
  121. const jsxImportSource = opts.jsxImportSource ?? "react";
  122. const jsxImportRuntime = `${jsxImportSource}/jsx-runtime`;
  123. const jsxImportDevRuntime = `${jsxImportSource}/jsx-dev-runtime`;
  124. let runningInVite = false;
  125. let isProduction = true;
  126. let projectRoot = process.cwd();
  127. let skipFastRefresh = true;
  128. let runPluginOverrides;
  129. let staticBabelOptions;
  130. const importReactRE = /\bimport\s+(?:\*\s+as\s+)?React\b/;
  131. const viteBabel = {
  132. name: "vite:react-babel",
  133. enforce: "pre",
  134. config() {
  135. if (opts.jsxRuntime === "classic") if ("rolldownVersion" in vite) return { oxc: { jsx: {
  136. runtime: "classic",
  137. development: false
  138. } } };
  139. else return { esbuild: { jsx: "transform" } };
  140. else return {
  141. esbuild: {
  142. jsx: "automatic",
  143. jsxImportSource: opts.jsxImportSource
  144. },
  145. optimizeDeps: "rolldownVersion" in vite ? { rollupOptions: { jsx: { mode: "automatic" } } } : { esbuildOptions: { jsx: "automatic" } }
  146. };
  147. },
  148. configResolved(config) {
  149. runningInVite = true;
  150. projectRoot = config.root;
  151. isProduction = config.isProduction;
  152. skipFastRefresh = isProduction || config.command === "build" || config.server.hmr === false;
  153. if ("jsxPure" in opts) config.logger.warnOnce("[@vitejs/plugin-react] jsxPure was removed. You can configure esbuild.jsxSideEffects directly.");
  154. const hooks = config.plugins.map((plugin) => {
  155. var _plugin$api;
  156. return (_plugin$api = plugin.api) === null || _plugin$api === void 0 ? void 0 : _plugin$api.reactBabel;
  157. }).filter(defined);
  158. 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");
  159. if (hooks.length > 0) runPluginOverrides = (babelOptions, context) => {
  160. hooks.forEach((hook) => hook(babelOptions, context, config));
  161. };
  162. else if (typeof opts.babel !== "function") {
  163. staticBabelOptions = createBabelOptions(opts.babel);
  164. if (canSkipBabel(staticBabelOptions.plugins, staticBabelOptions) && skipFastRefresh && (opts.jsxRuntime === "classic" ? isProduction : true)) delete viteBabel.transform;
  165. }
  166. },
  167. options(options) {
  168. if (!runningInVite) {
  169. options.jsx = {
  170. mode: opts.jsxRuntime,
  171. importSource: opts.jsxImportSource
  172. };
  173. return options;
  174. }
  175. },
  176. transform: {
  177. filter: { id: {
  178. include: (0, __rolldown_pluginutils.makeIdFiltersToMatchWithQuery)(include),
  179. exclude: [...exclude ? (0, __rolldown_pluginutils.makeIdFiltersToMatchWithQuery)(ensureArray(exclude)) : [], /\/node_modules\//]
  180. } },
  181. async handler(code, id, options) {
  182. if (id.includes("/node_modules/")) return;
  183. const [filepath] = id.split("?");
  184. if (!filter(filepath)) return;
  185. const ssr = (options === null || options === void 0 ? void 0 : options.ssr) === true;
  186. const babelOptions = (() => {
  187. if (staticBabelOptions) return staticBabelOptions;
  188. const newBabelOptions = createBabelOptions(typeof opts.babel === "function" ? opts.babel(id, { ssr }) : opts.babel);
  189. runPluginOverrides === null || runPluginOverrides === void 0 || runPluginOverrides(newBabelOptions, {
  190. id,
  191. ssr
  192. });
  193. return newBabelOptions;
  194. })();
  195. const plugins = [...babelOptions.plugins];
  196. const isJSX = filepath.endsWith("x");
  197. const useFastRefresh = !skipFastRefresh && !ssr && (isJSX || (opts.jsxRuntime === "classic" ? importReactRE.test(code) : code.includes(jsxImportDevRuntime) || code.includes(jsxImportRuntime)));
  198. if (useFastRefresh) plugins.push([await loadPlugin("react-refresh/babel"), { skipEnvCheck: true }]);
  199. if (opts.jsxRuntime === "classic" && isJSX) {
  200. if (!isProduction) plugins.push(await loadPlugin("@babel/plugin-transform-react-jsx-self"), await loadPlugin("@babel/plugin-transform-react-jsx-source"));
  201. }
  202. if (canSkipBabel(plugins, babelOptions)) return;
  203. const parserPlugins = [...babelOptions.parserOpts.plugins];
  204. if (!filepath.endsWith(".ts")) parserPlugins.push("jsx");
  205. if (tsRE.test(filepath)) parserPlugins.push("typescript");
  206. const babel$1 = await loadBabel();
  207. const result = await babel$1.transformAsync(code, {
  208. ...babelOptions,
  209. root: projectRoot,
  210. filename: id,
  211. sourceFileName: filepath,
  212. retainLines: getReactCompilerPlugin(plugins) != null ? false : !isProduction && isJSX && opts.jsxRuntime !== "classic",
  213. parserOpts: {
  214. ...babelOptions.parserOpts,
  215. sourceType: "module",
  216. allowAwaitOutsideFunction: true,
  217. plugins: parserPlugins
  218. },
  219. generatorOpts: {
  220. ...babelOptions.generatorOpts,
  221. importAttributesKeyword: "with",
  222. decoratorsBeforeExport: true
  223. },
  224. plugins,
  225. sourceMaps: true
  226. });
  227. if (result) {
  228. if (!useFastRefresh) return {
  229. code: result.code,
  230. map: result.map
  231. };
  232. return addRefreshWrapper(result.code, result.map, "@vitejs/plugin-react", id, opts.reactRefreshHost);
  233. }
  234. }
  235. }
  236. };
  237. const dependencies = [
  238. "react",
  239. "react-dom",
  240. jsxImportDevRuntime,
  241. jsxImportRuntime
  242. ];
  243. const staticBabelPlugins = typeof opts.babel === "object" ? ((_opts$babel = opts.babel) === null || _opts$babel === void 0 ? void 0 : _opts$babel.plugins) ?? [] : [];
  244. const reactCompilerPlugin = getReactCompilerPlugin(staticBabelPlugins);
  245. if (reactCompilerPlugin != null) {
  246. const reactCompilerRuntimeModule = getReactCompilerRuntimeModule(reactCompilerPlugin);
  247. dependencies.push(reactCompilerRuntimeModule);
  248. }
  249. const viteReactRefresh = {
  250. name: "vite:react-refresh",
  251. enforce: "pre",
  252. config: (userConfig) => ({
  253. build: silenceUseClientWarning(userConfig),
  254. optimizeDeps: { include: dependencies },
  255. resolve: { dedupe: ["react", "react-dom"] }
  256. }),
  257. resolveId: {
  258. filter: { id: (0, __rolldown_pluginutils.exactRegex)(runtimePublicPath) },
  259. handler(id) {
  260. if (id === runtimePublicPath) return id;
  261. }
  262. },
  263. load: {
  264. filter: { id: (0, __rolldown_pluginutils.exactRegex)(runtimePublicPath) },
  265. handler(id) {
  266. if (id === runtimePublicPath) return (0, node_fs.readFileSync)(refreshRuntimePath, "utf-8").replace(/__README_URL__/g, "https://github.com/vitejs/vite-plugin-react/tree/main/packages/plugin-react");
  267. }
  268. },
  269. transformIndexHtml(_, config) {
  270. if (!skipFastRefresh) return [{
  271. tag: "script",
  272. attrs: { type: "module" },
  273. children: getPreambleCode(config.server.config.base)
  274. }];
  275. }
  276. };
  277. return [viteBabel, viteReactRefresh];
  278. }
  279. viteReact.preambleCode = preambleCode;
  280. function canSkipBabel(plugins, babelOptions) {
  281. return !(plugins.length || babelOptions.presets.length || babelOptions.configFile || babelOptions.babelrc);
  282. }
  283. const loadedPlugin = /* @__PURE__ */ new Map();
  284. function loadPlugin(path) {
  285. const cached = loadedPlugin.get(path);
  286. if (cached) return cached;
  287. const promise = import(path).then((module$1) => {
  288. const value = module$1.default || module$1;
  289. loadedPlugin.set(path, value);
  290. return value;
  291. });
  292. loadedPlugin.set(path, promise);
  293. return promise;
  294. }
  295. function createBabelOptions(rawOptions) {
  296. var _babelOptions$parserO;
  297. const babelOptions = {
  298. babelrc: false,
  299. configFile: false,
  300. ...rawOptions
  301. };
  302. babelOptions.plugins || (babelOptions.plugins = []);
  303. babelOptions.presets || (babelOptions.presets = []);
  304. babelOptions.overrides || (babelOptions.overrides = []);
  305. babelOptions.parserOpts || (babelOptions.parserOpts = {});
  306. (_babelOptions$parserO = babelOptions.parserOpts).plugins || (_babelOptions$parserO.plugins = []);
  307. return babelOptions;
  308. }
  309. function defined(value) {
  310. return value !== void 0;
  311. }
  312. function getReactCompilerPlugin(plugins) {
  313. return plugins.find((p) => p === "babel-plugin-react-compiler" || Array.isArray(p) && p[0] === "babel-plugin-react-compiler");
  314. }
  315. function getReactCompilerRuntimeModule(plugin) {
  316. let moduleName = "react/compiler-runtime";
  317. if (Array.isArray(plugin)) {
  318. var _plugin$, _plugin$2, _plugin$3;
  319. if (((_plugin$ = plugin[1]) === null || _plugin$ === void 0 ? void 0 : _plugin$.target) === "17" || ((_plugin$2 = plugin[1]) === null || _plugin$2 === void 0 ? void 0 : _plugin$2.target) === "18") moduleName = "react-compiler-runtime";
  320. else if (typeof ((_plugin$3 = plugin[1]) === null || _plugin$3 === void 0 ? void 0 : _plugin$3.runtimeModule) === "string") {
  321. var _plugin$4;
  322. moduleName = (_plugin$4 = plugin[1]) === null || _plugin$4 === void 0 ? void 0 : _plugin$4.runtimeModule;
  323. }
  324. }
  325. return moduleName;
  326. }
  327. function ensureArray(value) {
  328. return Array.isArray(value) ? value : [value];
  329. }
  330. //#endregion
  331. module.exports = viteReact;
  332. module.exports.default = module.exports