source: imaps-frontend/node_modules/@vitejs/plugin-react/dist/index.cjs@ d565449

main
Last change on this file since d565449 was d565449, checked in by stefan toskovski <stefantoska84@…>, 4 weeks ago

Update repo after prototype presentation

  • Property mode set to 100644
File size: 10.9 KB
RevLine 
[d565449]1'use strict';
2
3const vite = require('vite');
4const fs = require('node:fs');
5const path = require('node:path');
6const node_module = require('node:module');
7
8var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
9function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e.default : e; }
10
11const fs__default = /*#__PURE__*/_interopDefaultCompat(fs);
12const path__default = /*#__PURE__*/_interopDefaultCompat(path);
13
14const runtimePublicPath = "/@react-refresh";
15const _require = node_module.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href)));
16const reactRefreshDir = path__default.dirname(
17 _require.resolve("react-refresh/package.json")
18);
19const runtimeFilePath = path__default.join(
20 reactRefreshDir,
21 "cjs/react-refresh-runtime.development.js"
22);
23const runtimeCode = `
24const exports = {}
25${fs__default.readFileSync(runtimeFilePath, "utf-8")}
26${fs__default.readFileSync(_require.resolve("./refreshUtils.js"), "utf-8")}
27export default exports
28`;
29const preambleCode = `
30import RefreshRuntime from "__BASE__${runtimePublicPath.slice(1)}"
31RefreshRuntime.injectIntoGlobalHook(window)
32window.$RefreshReg$ = () => {}
33window.$RefreshSig$ = () => (type) => type
34window.__vite_plugin_react_preamble_installed__ = true
35`;
36const sharedHeader = `
37import RefreshRuntime from "${runtimePublicPath}";
38
39const inWebWorker = typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope;
40`.replace(/\n+/g, "");
41const functionHeader = `
42let prevRefreshReg;
43let prevRefreshSig;
44
45if (import.meta.hot && !inWebWorker) {
46 if (!window.__vite_plugin_react_preamble_installed__) {
47 throw new Error(
48 "@vitejs/plugin-react can't detect preamble. Something is wrong. " +
49 "See https://github.com/vitejs/vite-plugin-react/pull/11#discussion_r430879201"
50 );
51 }
52
53 prevRefreshReg = window.$RefreshReg$;
54 prevRefreshSig = window.$RefreshSig$;
55 window.$RefreshReg$ = (type, id) => {
56 RefreshRuntime.register(type, __SOURCE__ + " " + id)
57 };
58 window.$RefreshSig$ = RefreshRuntime.createSignatureFunctionForTransform;
59}`.replace(/\n+/g, "");
60const functionFooter = `
61if (import.meta.hot && !inWebWorker) {
62 window.$RefreshReg$ = prevRefreshReg;
63 window.$RefreshSig$ = prevRefreshSig;
64}`;
65const sharedFooter = `
66if (import.meta.hot && !inWebWorker) {
67 RefreshRuntime.__hmr_import(import.meta.url).then((currentExports) => {
68 RefreshRuntime.registerExportsForReactRefresh(__SOURCE__, currentExports);
69 import.meta.hot.accept((nextExports) => {
70 if (!nextExports) return;
71 const invalidateMessage = RefreshRuntime.validateRefreshBoundaryAndEnqueueUpdate(currentExports, nextExports);
72 if (invalidateMessage) import.meta.hot.invalidate(invalidateMessage);
73 });
74 });
75}`;
76function addRefreshWrapper(code, id) {
77 return sharedHeader + functionHeader.replace("__SOURCE__", JSON.stringify(id)) + code + functionFooter + sharedFooter.replace("__SOURCE__", JSON.stringify(id));
78}
79function addClassComponentRefreshWrapper(code, id) {
80 return sharedHeader + code + sharedFooter.replace("__SOURCE__", JSON.stringify(id));
81}
82
83let babel;
84async function loadBabel() {
85 if (!babel) {
86 babel = await import('@babel/core');
87 }
88 return babel;
89}
90const reactCompRE = /extends\s+(?:React\.)?(?:Pure)?Component/;
91const refreshContentRE = /\$Refresh(?:Reg|Sig)\$\(/;
92const defaultIncludeRE = /\.[tj]sx?$/;
93const tsRE = /\.tsx?$/;
94function viteReact(opts = {}) {
95 let devBase = "/";
96 const filter = vite.createFilter(opts.include ?? defaultIncludeRE, opts.exclude);
97 const jsxImportSource = opts.jsxImportSource ?? "react";
98 const jsxImportRuntime = `${jsxImportSource}/jsx-runtime`;
99 const jsxImportDevRuntime = `${jsxImportSource}/jsx-dev-runtime`;
100 let isProduction = true;
101 let projectRoot = process.cwd();
102 let skipFastRefresh = false;
103 let runPluginOverrides;
104 let staticBabelOptions;
105 const importReactRE = /\bimport\s+(?:\*\s+as\s+)?React\b/;
106 const viteBabel = {
107 name: "vite:react-babel",
108 enforce: "pre",
109 config() {
110 if (opts.jsxRuntime === "classic") {
111 return {
112 esbuild: {
113 jsx: "transform"
114 }
115 };
116 } else {
117 return {
118 esbuild: {
119 jsx: "automatic",
120 jsxImportSource: opts.jsxImportSource
121 },
122 optimizeDeps: { esbuildOptions: { jsx: "automatic" } }
123 };
124 }
125 },
126 configResolved(config) {
127 devBase = config.base;
128 projectRoot = config.root;
129 isProduction = config.isProduction;
130 skipFastRefresh = isProduction || config.command === "build" || config.server.hmr === false;
131 if ("jsxPure" in opts) {
132 config.logger.warnOnce(
133 "[@vitejs/plugin-react] jsxPure was removed. You can configure esbuild.jsxSideEffects directly."
134 );
135 }
136 const hooks = config.plugins.map((plugin) => plugin.api?.reactBabel).filter(defined);
137 if (hooks.length > 0) {
138 runPluginOverrides = (babelOptions, context) => {
139 hooks.forEach((hook) => hook(babelOptions, context, config));
140 };
141 } else if (typeof opts.babel !== "function") {
142 staticBabelOptions = createBabelOptions(opts.babel);
143 }
144 },
145 async transform(code, id, options) {
146 if (id.includes("/node_modules/"))
147 return;
148 const [filepath] = id.split("?");
149 if (!filter(filepath))
150 return;
151 const ssr = options?.ssr === true;
152 const babelOptions = (() => {
153 if (staticBabelOptions)
154 return staticBabelOptions;
155 const newBabelOptions = createBabelOptions(
156 typeof opts.babel === "function" ? opts.babel(id, { ssr }) : opts.babel
157 );
158 runPluginOverrides?.(newBabelOptions, { id, ssr });
159 return newBabelOptions;
160 })();
161 const plugins = [...babelOptions.plugins];
162 const isJSX = filepath.endsWith("x");
163 const useFastRefresh = !skipFastRefresh && !ssr && (isJSX || (opts.jsxRuntime === "classic" ? importReactRE.test(code) : code.includes(jsxImportDevRuntime) || code.includes(jsxImportRuntime)));
164 if (useFastRefresh) {
165 plugins.push([
166 await loadPlugin("react-refresh/babel"),
167 { skipEnvCheck: true }
168 ]);
169 }
170 if (opts.jsxRuntime === "classic" && isJSX) {
171 if (!isProduction) {
172 plugins.push(
173 await loadPlugin("@babel/plugin-transform-react-jsx-self"),
174 await loadPlugin("@babel/plugin-transform-react-jsx-source")
175 );
176 }
177 }
178 if (!plugins.length && !babelOptions.presets.length && !babelOptions.configFile && !babelOptions.babelrc) {
179 return;
180 }
181 const parserPlugins = [...babelOptions.parserOpts.plugins];
182 if (!filepath.endsWith(".ts")) {
183 parserPlugins.push("jsx");
184 }
185 if (tsRE.test(filepath)) {
186 parserPlugins.push("typescript");
187 }
188 const babel2 = await loadBabel();
189 const result = await babel2.transformAsync(code, {
190 ...babelOptions,
191 root: projectRoot,
192 filename: id,
193 sourceFileName: filepath,
194 // Required for esbuild.jsxDev to provide correct line numbers
195 // This crates issues the react compiler because the re-order is too important
196 // People should use @babel/plugin-transform-react-jsx-development to get back good line numbers
197 retainLines: hasCompiler(plugins) ? false : !isProduction && isJSX && opts.jsxRuntime !== "classic",
198 parserOpts: {
199 ...babelOptions.parserOpts,
200 sourceType: "module",
201 allowAwaitOutsideFunction: true,
202 plugins: parserPlugins
203 },
204 generatorOpts: {
205 ...babelOptions.generatorOpts,
206 decoratorsBeforeExport: true
207 },
208 plugins,
209 sourceMaps: true
210 });
211 if (result) {
212 let code2 = result.code;
213 if (useFastRefresh) {
214 if (refreshContentRE.test(code2)) {
215 code2 = addRefreshWrapper(code2, id);
216 } else if (reactCompRE.test(code2)) {
217 code2 = addClassComponentRefreshWrapper(code2, id);
218 }
219 }
220 return { code: code2, map: result.map };
221 }
222 }
223 };
224 const dependencies = ["react", jsxImportDevRuntime, jsxImportRuntime];
225 const staticBabelPlugins = typeof opts.babel === "object" ? opts.babel?.plugins ?? [] : [];
226 if (hasCompilerWithDefaultRuntime(staticBabelPlugins)) {
227 dependencies.push("react/compiler-runtime");
228 }
229 const viteReactRefresh = {
230 name: "vite:react-refresh",
231 enforce: "pre",
232 config: (userConfig) => ({
233 build: silenceUseClientWarning(userConfig),
234 optimizeDeps: {
235 include: dependencies
236 },
237 resolve: {
238 dedupe: ["react", "react-dom"]
239 }
240 }),
241 resolveId(id) {
242 if (id === runtimePublicPath) {
243 return id;
244 }
245 },
246 load(id) {
247 if (id === runtimePublicPath) {
248 return runtimeCode;
249 }
250 },
251 transformIndexHtml() {
252 if (!skipFastRefresh)
253 return [
254 {
255 tag: "script",
256 attrs: { type: "module" },
257 children: preambleCode.replace(`__BASE__`, devBase)
258 }
259 ];
260 }
261 };
262 return [viteBabel, viteReactRefresh];
263}
264viteReact.preambleCode = preambleCode;
265const silenceUseClientWarning = (userConfig) => ({
266 rollupOptions: {
267 onwarn(warning, defaultHandler) {
268 if (warning.code === "MODULE_LEVEL_DIRECTIVE" && warning.message.includes("use client")) {
269 return;
270 }
271 if (userConfig.build?.rollupOptions?.onwarn) {
272 userConfig.build.rollupOptions.onwarn(warning, defaultHandler);
273 } else {
274 defaultHandler(warning);
275 }
276 }
277 }
278});
279const loadedPlugin = /* @__PURE__ */ new Map();
280function loadPlugin(path) {
281 const cached = loadedPlugin.get(path);
282 if (cached)
283 return cached;
284 const promise = import(path).then((module) => {
285 const value = module.default || module;
286 loadedPlugin.set(path, value);
287 return value;
288 });
289 loadedPlugin.set(path, promise);
290 return promise;
291}
292function createBabelOptions(rawOptions) {
293 var _a;
294 const babelOptions = {
295 babelrc: false,
296 configFile: false,
297 ...rawOptions
298 };
299 babelOptions.plugins || (babelOptions.plugins = []);
300 babelOptions.presets || (babelOptions.presets = []);
301 babelOptions.overrides || (babelOptions.overrides = []);
302 babelOptions.parserOpts || (babelOptions.parserOpts = {});
303 (_a = babelOptions.parserOpts).plugins || (_a.plugins = []);
304 return babelOptions;
305}
306function defined(value) {
307 return value !== void 0;
308}
309function hasCompiler(plugins) {
310 return plugins.some(
311 (p) => p === "babel-plugin-react-compiler" || Array.isArray(p) && p[0] === "babel-plugin-react-compiler"
312 );
313}
314function hasCompilerWithDefaultRuntime(plugins) {
315 return plugins.some(
316 (p) => p === "babel-plugin-react-compiler" || Array.isArray(p) && p[0] === "babel-plugin-react-compiler" && p[1]?.runtimeModule === void 0
317 );
318}
319
320module.exports = viteReact;
321module.exports.default = viteReact;
Note: See TracBrowser for help on using the repository browser.