index.mjs 59 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736
  1. import { createRequire } from "node:module";
  2. import fs from "node:fs";
  3. import { createFilter, formatPostcssSourceMap, isCSSRequest, normalizePath, transformWithEsbuild } from "vite";
  4. import { computed, shallowRef } from "vue";
  5. import { exactRegex, makeIdFiltersToMatchWithQuery } from "@rolldown/pluginutils";
  6. import path from "node:path";
  7. import crypto from "node:crypto";
  8. import { isatty } from "node:tty";
  9. import { formatWithOptions, inspect } from "node:util";
  10. //#region package.json
  11. var version = "6.0.6";
  12. //#endregion
  13. //#region src/compiler.ts
  14. function resolveCompiler(root) {
  15. const compiler = tryResolveCompiler(root) || tryResolveCompiler();
  16. if (!compiler) throw new Error("Failed to resolve vue/compiler-sfc.\n@vitejs/plugin-vue requires vue (>=3.2.25) to be present in the dependency tree.");
  17. return compiler;
  18. }
  19. function tryResolveCompiler(root) {
  20. const vueMeta = tryRequire("vue/package.json", root);
  21. if (vueMeta && vueMeta.version.split(".")[0] >= 3) return tryRequire("vue/compiler-sfc", root);
  22. }
  23. const _require = createRequire(import.meta.url);
  24. function tryRequire(id, from) {
  25. try {
  26. return from ? _require(_require.resolve(id, { paths: [from] })) : _require(id);
  27. } catch (e) {}
  28. }
  29. //#endregion
  30. //#region src/utils/query.ts
  31. function parseVueRequest(id) {
  32. const [filename, rawQuery] = id.split(`?`, 2);
  33. const query = Object.fromEntries(new URLSearchParams(rawQuery));
  34. if (query.vue != null) query.vue = true;
  35. if (query.index != null) query.index = Number(query.index);
  36. if (query.raw != null) query.raw = true;
  37. if (query.url != null) query.url = true;
  38. if (query.scoped != null) query.scoped = true;
  39. return {
  40. filename,
  41. query
  42. };
  43. }
  44. //#endregion
  45. //#region src/utils/descriptorCache.ts
  46. const cache = /* @__PURE__ */ new Map();
  47. const hmrCache = /* @__PURE__ */ new Map();
  48. const prevCache = /* @__PURE__ */ new Map();
  49. function createDescriptor(filename, source, { root, isProduction, sourceMap, compiler, template, features }, hmr = false) {
  50. const { descriptor, errors } = compiler.parse(source, {
  51. filename,
  52. sourceMap,
  53. templateParseOptions: template?.compilerOptions
  54. });
  55. const normalizedPath = normalizePath(path.relative(root, filename));
  56. const componentIdGenerator = features?.componentIdGenerator;
  57. if (componentIdGenerator === "filepath") descriptor.id = getHash(normalizedPath);
  58. else if (componentIdGenerator === "filepath-source") descriptor.id = getHash(normalizedPath + source);
  59. else if (typeof componentIdGenerator === "function") descriptor.id = componentIdGenerator(normalizedPath, source, isProduction, getHash);
  60. else descriptor.id = getHash(normalizedPath + (isProduction ? source : ""));
  61. (hmr ? hmrCache : cache).set(filename, descriptor);
  62. return {
  63. descriptor,
  64. errors
  65. };
  66. }
  67. function getPrevDescriptor(filename) {
  68. return prevCache.get(filename);
  69. }
  70. function invalidateDescriptor(filename, hmr = false) {
  71. const _cache = hmr ? hmrCache : cache;
  72. const prev = _cache.get(filename);
  73. _cache.delete(filename);
  74. if (prev) prevCache.set(filename, prev);
  75. }
  76. function getDescriptor(filename, options, createIfNotFound = true, hmr = false, code) {
  77. const _cache = hmr ? hmrCache : cache;
  78. if (_cache.has(filename)) return _cache.get(filename);
  79. if (createIfNotFound) {
  80. const { descriptor, errors } = createDescriptor(filename, code ?? fs.readFileSync(filename, "utf-8"), options, hmr);
  81. if (errors.length && !hmr) throw errors[0];
  82. return descriptor;
  83. }
  84. }
  85. function getSrcDescriptor(filename, query) {
  86. if (query.scoped) return cache.get(`${filename}?src=${query.src}`);
  87. return cache.get(filename);
  88. }
  89. function getTempSrcDescriptor(filename, query) {
  90. return {
  91. filename,
  92. id: query.id || "",
  93. styles: [{
  94. scoped: query.scoped,
  95. loc: { start: {
  96. line: 0,
  97. column: 0
  98. } }
  99. }],
  100. isTemp: true
  101. };
  102. }
  103. function setSrcDescriptor(filename, entry, scoped) {
  104. if (scoped) {
  105. cache.set(`${filename}?src=${entry.id}`, entry);
  106. return;
  107. }
  108. cache.set(filename, entry);
  109. }
  110. function getHash(text) {
  111. return crypto.hash("sha256", text, "hex").substring(0, 8);
  112. }
  113. //#endregion
  114. //#region ../../node_modules/.pnpm/slash@5.1.0/node_modules/slash/index.js
  115. function slash(path) {
  116. if (path.startsWith("\\\\?\\")) return path;
  117. return path.replace(/\\/g, "/");
  118. }
  119. //#endregion
  120. //#region src/utils/error.ts
  121. function createRollupError(id, error) {
  122. const { message, name, stack } = error;
  123. const rollupError = {
  124. id,
  125. plugin: "vue",
  126. message,
  127. name,
  128. stack
  129. };
  130. if ("code" in error && error.loc) rollupError.loc = {
  131. file: id,
  132. line: error.loc.start.line,
  133. column: error.loc.start.column
  134. };
  135. return rollupError;
  136. }
  137. //#endregion
  138. //#region src/template.ts
  139. async function transformTemplateAsModule(code, filename, descriptor, options, pluginContext, ssr, customElement) {
  140. const result = compile(code, filename, descriptor, options, pluginContext, ssr, customElement);
  141. let returnCode = result.code;
  142. returnCode += `\nexport const multiRoot = ${JSON.stringify(result.multiRoot)}`;
  143. if (options.devServer && options.devServer.config.server.hmr !== false && !ssr && !options.isProduction) returnCode += `\nimport.meta.hot.accept(({ render }) => {
  144. __VUE_HMR_RUNTIME__.rerender(${JSON.stringify(descriptor.id)}, render)
  145. })`;
  146. return {
  147. code: returnCode,
  148. map: result.map
  149. };
  150. }
  151. /**
  152. * transform the template directly in the main SFC module
  153. */
  154. function transformTemplateInMain(code, descriptor, options, pluginContext, ssr, customElement) {
  155. const result = compile(code, descriptor.filename, descriptor, options, pluginContext, ssr, customElement);
  156. return {
  157. ...result,
  158. code: result.code.replace(/\nexport (function|const) (render|ssrRender)/, "\n$1 _sfc_$2")
  159. };
  160. }
  161. function compile(code, filename, descriptor, options, pluginContext, ssr, customElement) {
  162. resolveScript(descriptor, options, ssr, customElement);
  163. const result = options.compiler.compileTemplate({
  164. ...resolveTemplateCompilerOptions(descriptor, options, filename, ssr),
  165. source: code
  166. });
  167. if (result.errors.length) result.errors.forEach((error) => pluginContext.error(typeof error === "string" ? {
  168. id: filename,
  169. message: error
  170. } : createRollupError(filename, error)));
  171. if (result.tips.length) result.tips.forEach((tip) => pluginContext.warn({
  172. id: filename,
  173. message: tip
  174. }));
  175. return result;
  176. }
  177. function resolveTemplateCompilerOptions(descriptor, options, filename, ssr) {
  178. const block = descriptor.template;
  179. if (!block) return;
  180. const resolvedScript = getResolvedScript(descriptor, ssr);
  181. const hasScoped = descriptor.styles.some((s) => s.scoped);
  182. const { id, cssVars } = descriptor;
  183. let transformAssetUrls = options.template?.transformAssetUrls;
  184. let assetUrlOptions;
  185. if (transformAssetUrls === false) {} else if (options.devServer) {
  186. if (filename.startsWith(options.root)) {
  187. const devBase = options.devServer.config.base;
  188. assetUrlOptions = {
  189. base: (options.devServer.config.server?.origin ?? "") + devBase + slash(path.relative(options.root, path.dirname(filename))),
  190. includeAbsolute: !!devBase
  191. };
  192. }
  193. } else assetUrlOptions = { includeAbsolute: true };
  194. if (transformAssetUrls && typeof transformAssetUrls === "object") if (Object.values(transformAssetUrls).some((val) => Array.isArray(val))) transformAssetUrls = {
  195. ...assetUrlOptions,
  196. tags: transformAssetUrls
  197. };
  198. else transformAssetUrls = {
  199. ...assetUrlOptions,
  200. ...transformAssetUrls
  201. };
  202. else transformAssetUrls = assetUrlOptions;
  203. let preprocessOptions = block.lang && options.template?.preprocessOptions;
  204. if (block.lang === "pug") preprocessOptions = {
  205. doctype: "html",
  206. ...preprocessOptions
  207. };
  208. const expressionPlugins = options.template?.compilerOptions?.expressionPlugins || [];
  209. const lang = descriptor.scriptSetup?.lang || descriptor.script?.lang;
  210. if (lang && /tsx?$/.test(lang) && !expressionPlugins.includes("typescript")) expressionPlugins.push("typescript");
  211. return {
  212. ...options.template,
  213. vapor: descriptor.vapor,
  214. id,
  215. ast: canReuseAST(options.compiler.version) ? descriptor.template?.ast : void 0,
  216. filename,
  217. scoped: hasScoped,
  218. slotted: descriptor.slotted,
  219. isProd: options.isProduction,
  220. inMap: block.src ? void 0 : block.map,
  221. ssr,
  222. ssrCssVars: cssVars,
  223. transformAssetUrls,
  224. preprocessLang: block.lang === "html" ? void 0 : block.lang,
  225. preprocessOptions,
  226. compilerOptions: {
  227. ...options.template?.compilerOptions,
  228. scopeId: hasScoped ? `data-v-${id}` : void 0,
  229. bindingMetadata: resolvedScript ? resolvedScript.bindings : void 0,
  230. expressionPlugins,
  231. sourceMap: options.sourceMap
  232. }
  233. };
  234. }
  235. /**
  236. * Versions before 3.4.3 have issues when the user has passed additional
  237. * template parse options e.g. `isCustomElement`.
  238. */
  239. function canReuseAST(version) {
  240. if (version) {
  241. const [_, minor, patch] = version.split(".").map(Number);
  242. if (minor >= 4 && patch >= 3) return true;
  243. }
  244. return false;
  245. }
  246. //#endregion
  247. //#region src/script.ts
  248. let clientCache = /* @__PURE__ */ new WeakMap();
  249. let ssrCache = /* @__PURE__ */ new WeakMap();
  250. const typeDepToSFCMap = /* @__PURE__ */ new Map();
  251. function invalidateScript(filename) {
  252. const desc = cache.get(filename);
  253. if (desc) {
  254. clientCache.delete(desc);
  255. ssrCache.delete(desc);
  256. }
  257. }
  258. function getResolvedScript(descriptor, ssr) {
  259. return (ssr ? ssrCache : clientCache).get(descriptor);
  260. }
  261. function setResolvedScript(descriptor, script, ssr) {
  262. (ssr ? ssrCache : clientCache).set(descriptor, script);
  263. }
  264. function clearScriptCache() {
  265. clientCache = /* @__PURE__ */ new WeakMap();
  266. ssrCache = /* @__PURE__ */ new WeakMap();
  267. }
  268. function isUseInlineTemplate(descriptor, options) {
  269. return !options.devServer && !options.devToolsEnabled && !!descriptor.scriptSetup && !descriptor.template?.src;
  270. }
  271. const scriptIdentifier = `_sfc_main`;
  272. function resolveScript(descriptor, options, ssr, customElement) {
  273. if (!descriptor.script && !descriptor.scriptSetup) return null;
  274. const cached = getResolvedScript(descriptor, ssr);
  275. if (cached) return cached;
  276. const resolved = options.compiler.compileScript(descriptor, {
  277. ...options.script,
  278. id: descriptor.id,
  279. isProd: options.isProduction,
  280. inlineTemplate: isUseInlineTemplate(descriptor, options),
  281. templateOptions: resolveTemplateCompilerOptions(descriptor, options, descriptor.filename, ssr),
  282. sourceMap: options.sourceMap,
  283. genDefaultAs: canInlineMain(descriptor, options) ? scriptIdentifier : void 0,
  284. customElement,
  285. propsDestructure: options.features?.propsDestructure ?? options.script?.propsDestructure
  286. });
  287. if (!options.isProduction && resolved?.deps) {
  288. for (const [key, sfcs] of typeDepToSFCMap) if (sfcs.has(descriptor.filename) && !resolved.deps.includes(key)) sfcs.delete(descriptor.filename);
  289. for (const dep of resolved.deps) {
  290. const existingSet = typeDepToSFCMap.get(dep);
  291. if (!existingSet) typeDepToSFCMap.set(dep, new Set([descriptor.filename]));
  292. else existingSet.add(descriptor.filename);
  293. }
  294. }
  295. setResolvedScript(descriptor, resolved, ssr);
  296. return resolved;
  297. }
  298. function canInlineMain(descriptor, options) {
  299. if (descriptor.script?.src || descriptor.scriptSetup?.src) return false;
  300. const lang = descriptor.script?.lang || descriptor.scriptSetup?.lang;
  301. if (!lang || lang === "js") return true;
  302. if (lang === "ts" && options.devServer) return true;
  303. return false;
  304. }
  305. //#endregion
  306. //#region ../../node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.5/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs
  307. var comma = ",".charCodeAt(0);
  308. var semicolon = ";".charCodeAt(0);
  309. var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  310. var intToChar = new Uint8Array(64);
  311. var charToInt = new Uint8Array(128);
  312. for (let i = 0; i < chars.length; i++) {
  313. const c = chars.charCodeAt(i);
  314. intToChar[i] = c;
  315. charToInt[c] = i;
  316. }
  317. function decodeInteger(reader, relative) {
  318. let value = 0;
  319. let shift = 0;
  320. let integer = 0;
  321. do {
  322. integer = charToInt[reader.next()];
  323. value |= (integer & 31) << shift;
  324. shift += 5;
  325. } while (integer & 32);
  326. const shouldNegate = value & 1;
  327. value >>>= 1;
  328. if (shouldNegate) value = -2147483648 | -value;
  329. return relative + value;
  330. }
  331. function encodeInteger(builder, num, relative) {
  332. let delta = num - relative;
  333. delta = delta < 0 ? -delta << 1 | 1 : delta << 1;
  334. do {
  335. let clamped = delta & 31;
  336. delta >>>= 5;
  337. if (delta > 0) clamped |= 32;
  338. builder.write(intToChar[clamped]);
  339. } while (delta > 0);
  340. return num;
  341. }
  342. function hasMoreVlq(reader, max) {
  343. if (reader.pos >= max) return false;
  344. return reader.peek() !== comma;
  345. }
  346. var bufLength = 1024 * 16;
  347. var td = typeof TextDecoder !== "undefined" ? /* @__PURE__ */ new TextDecoder() : typeof Buffer !== "undefined" ? { decode(buf) {
  348. return Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength).toString();
  349. } } : { decode(buf) {
  350. let out = "";
  351. for (let i = 0; i < buf.length; i++) out += String.fromCharCode(buf[i]);
  352. return out;
  353. } };
  354. var StringWriter = class {
  355. constructor() {
  356. this.pos = 0;
  357. this.out = "";
  358. this.buffer = new Uint8Array(bufLength);
  359. }
  360. write(v) {
  361. const { buffer } = this;
  362. buffer[this.pos++] = v;
  363. if (this.pos === bufLength) {
  364. this.out += td.decode(buffer);
  365. this.pos = 0;
  366. }
  367. }
  368. flush() {
  369. const { buffer, out, pos } = this;
  370. return pos > 0 ? out + td.decode(buffer.subarray(0, pos)) : out;
  371. }
  372. };
  373. var StringReader = class {
  374. constructor(buffer) {
  375. this.pos = 0;
  376. this.buffer = buffer;
  377. }
  378. next() {
  379. return this.buffer.charCodeAt(this.pos++);
  380. }
  381. peek() {
  382. return this.buffer.charCodeAt(this.pos);
  383. }
  384. indexOf(char) {
  385. const { buffer, pos } = this;
  386. const idx = buffer.indexOf(char, pos);
  387. return idx === -1 ? buffer.length : idx;
  388. }
  389. };
  390. function decode(mappings) {
  391. const { length } = mappings;
  392. const reader = new StringReader(mappings);
  393. const decoded = [];
  394. let genColumn = 0;
  395. let sourcesIndex = 0;
  396. let sourceLine = 0;
  397. let sourceColumn = 0;
  398. let namesIndex = 0;
  399. do {
  400. const semi = reader.indexOf(";");
  401. const line = [];
  402. let sorted = true;
  403. let lastCol = 0;
  404. genColumn = 0;
  405. while (reader.pos < semi) {
  406. let seg;
  407. genColumn = decodeInteger(reader, genColumn);
  408. if (genColumn < lastCol) sorted = false;
  409. lastCol = genColumn;
  410. if (hasMoreVlq(reader, semi)) {
  411. sourcesIndex = decodeInteger(reader, sourcesIndex);
  412. sourceLine = decodeInteger(reader, sourceLine);
  413. sourceColumn = decodeInteger(reader, sourceColumn);
  414. if (hasMoreVlq(reader, semi)) {
  415. namesIndex = decodeInteger(reader, namesIndex);
  416. seg = [
  417. genColumn,
  418. sourcesIndex,
  419. sourceLine,
  420. sourceColumn,
  421. namesIndex
  422. ];
  423. } else seg = [
  424. genColumn,
  425. sourcesIndex,
  426. sourceLine,
  427. sourceColumn
  428. ];
  429. } else seg = [genColumn];
  430. line.push(seg);
  431. reader.pos++;
  432. }
  433. if (!sorted) sort(line);
  434. decoded.push(line);
  435. reader.pos = semi + 1;
  436. } while (reader.pos <= length);
  437. return decoded;
  438. }
  439. function sort(line) {
  440. line.sort(sortComparator$1);
  441. }
  442. function sortComparator$1(a, b) {
  443. return a[0] - b[0];
  444. }
  445. function encode(decoded) {
  446. const writer = new StringWriter();
  447. let sourcesIndex = 0;
  448. let sourceLine = 0;
  449. let sourceColumn = 0;
  450. let namesIndex = 0;
  451. for (let i = 0; i < decoded.length; i++) {
  452. const line = decoded[i];
  453. if (i > 0) writer.write(semicolon);
  454. if (line.length === 0) continue;
  455. let genColumn = 0;
  456. for (let j = 0; j < line.length; j++) {
  457. const segment = line[j];
  458. if (j > 0) writer.write(comma);
  459. genColumn = encodeInteger(writer, segment[0], genColumn);
  460. if (segment.length === 1) continue;
  461. sourcesIndex = encodeInteger(writer, segment[1], sourcesIndex);
  462. sourceLine = encodeInteger(writer, segment[2], sourceLine);
  463. sourceColumn = encodeInteger(writer, segment[3], sourceColumn);
  464. if (segment.length === 4) continue;
  465. namesIndex = encodeInteger(writer, segment[4], namesIndex);
  466. }
  467. }
  468. return writer.flush();
  469. }
  470. //#endregion
  471. //#region ../../node_modules/.pnpm/@jridgewell+resolve-uri@3.1.2/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.mjs
  472. const schemeRegex = /^[\w+.-]+:\/\//;
  473. /**
  474. * Matches the parts of a URL:
  475. * 1. Scheme, including ":", guaranteed.
  476. * 2. User/password, including "@", optional.
  477. * 3. Host, guaranteed.
  478. * 4. Port, including ":", optional.
  479. * 5. Path, including "/", optional.
  480. * 6. Query, including "?", optional.
  481. * 7. Hash, including "#", optional.
  482. */
  483. const urlRegex = /^([\w+.-]+:)\/\/([^@/#?]*@)?([^:/#?]*)(:\d+)?(\/[^#?]*)?(\?[^#]*)?(#.*)?/;
  484. /**
  485. * File URLs are weird. They dont' need the regular `//` in the scheme, they may or may not start
  486. * with a leading `/`, they can have a domain (but only if they don't start with a Windows drive).
  487. *
  488. * 1. Host, optional.
  489. * 2. Path, which may include "/", guaranteed.
  490. * 3. Query, including "?", optional.
  491. * 4. Hash, including "#", optional.
  492. */
  493. const fileRegex = /^file:(?:\/\/((?![a-z]:)[^/#?]*)?)?(\/?[^#?]*)(\?[^#]*)?(#.*)?/i;
  494. function isAbsoluteUrl(input) {
  495. return schemeRegex.test(input);
  496. }
  497. function isSchemeRelativeUrl(input) {
  498. return input.startsWith("//");
  499. }
  500. function isAbsolutePath(input) {
  501. return input.startsWith("/");
  502. }
  503. function isFileUrl(input) {
  504. return input.startsWith("file:");
  505. }
  506. function isRelative(input) {
  507. return /^[.?#]/.test(input);
  508. }
  509. function parseAbsoluteUrl(input) {
  510. const match = urlRegex.exec(input);
  511. return makeUrl(match[1], match[2] || "", match[3], match[4] || "", match[5] || "/", match[6] || "", match[7] || "");
  512. }
  513. function parseFileUrl(input) {
  514. const match = fileRegex.exec(input);
  515. const path = match[2];
  516. return makeUrl("file:", "", match[1] || "", "", isAbsolutePath(path) ? path : "/" + path, match[3] || "", match[4] || "");
  517. }
  518. function makeUrl(scheme, user, host, port, path, query, hash) {
  519. return {
  520. scheme,
  521. user,
  522. host,
  523. port,
  524. path,
  525. query,
  526. hash,
  527. type: 7
  528. };
  529. }
  530. function parseUrl(input) {
  531. if (isSchemeRelativeUrl(input)) {
  532. const url = parseAbsoluteUrl("http:" + input);
  533. url.scheme = "";
  534. url.type = 6;
  535. return url;
  536. }
  537. if (isAbsolutePath(input)) {
  538. const url = parseAbsoluteUrl("http://foo.com" + input);
  539. url.scheme = "";
  540. url.host = "";
  541. url.type = 5;
  542. return url;
  543. }
  544. if (isFileUrl(input)) return parseFileUrl(input);
  545. if (isAbsoluteUrl(input)) return parseAbsoluteUrl(input);
  546. const url = parseAbsoluteUrl("http://foo.com/" + input);
  547. url.scheme = "";
  548. url.host = "";
  549. url.type = input ? input.startsWith("?") ? 3 : input.startsWith("#") ? 2 : 4 : 1;
  550. return url;
  551. }
  552. function stripPathFilename(path) {
  553. if (path.endsWith("/..")) return path;
  554. const index = path.lastIndexOf("/");
  555. return path.slice(0, index + 1);
  556. }
  557. function mergePaths(url, base) {
  558. normalizePath$1(base, base.type);
  559. if (url.path === "/") url.path = base.path;
  560. else url.path = stripPathFilename(base.path) + url.path;
  561. }
  562. /**
  563. * The path can have empty directories "//", unneeded parents "foo/..", or current directory
  564. * "foo/.". We need to normalize to a standard representation.
  565. */
  566. function normalizePath$1(url, type) {
  567. const rel = type <= 4;
  568. const pieces = url.path.split("/");
  569. let pointer = 1;
  570. let positive = 0;
  571. let addTrailingSlash = false;
  572. for (let i = 1; i < pieces.length; i++) {
  573. const piece = pieces[i];
  574. if (!piece) {
  575. addTrailingSlash = true;
  576. continue;
  577. }
  578. addTrailingSlash = false;
  579. if (piece === ".") continue;
  580. if (piece === "..") {
  581. if (positive) {
  582. addTrailingSlash = true;
  583. positive--;
  584. pointer--;
  585. } else if (rel) pieces[pointer++] = piece;
  586. continue;
  587. }
  588. pieces[pointer++] = piece;
  589. positive++;
  590. }
  591. let path = "";
  592. for (let i = 1; i < pointer; i++) path += "/" + pieces[i];
  593. if (!path || addTrailingSlash && !path.endsWith("/..")) path += "/";
  594. url.path = path;
  595. }
  596. /**
  597. * Attempts to resolve `input` URL/path relative to `base`.
  598. */
  599. function resolve(input, base) {
  600. if (!input && !base) return "";
  601. const url = parseUrl(input);
  602. let inputType = url.type;
  603. if (base && inputType !== 7) {
  604. const baseUrl = parseUrl(base);
  605. const baseType = baseUrl.type;
  606. switch (inputType) {
  607. case 1: url.hash = baseUrl.hash;
  608. case 2: url.query = baseUrl.query;
  609. case 3:
  610. case 4: mergePaths(url, baseUrl);
  611. case 5:
  612. url.user = baseUrl.user;
  613. url.host = baseUrl.host;
  614. url.port = baseUrl.port;
  615. case 6: url.scheme = baseUrl.scheme;
  616. }
  617. if (baseType > inputType) inputType = baseType;
  618. }
  619. normalizePath$1(url, inputType);
  620. const queryHash = url.query + url.hash;
  621. switch (inputType) {
  622. case 2:
  623. case 3: return queryHash;
  624. case 4: {
  625. const path = url.path.slice(1);
  626. if (!path) return queryHash || ".";
  627. if (isRelative(base || input) && !isRelative(path)) return "./" + path + queryHash;
  628. return path + queryHash;
  629. }
  630. case 5: return url.path + queryHash;
  631. default: return url.scheme + "//" + url.user + url.host + url.port + url.path + queryHash;
  632. }
  633. }
  634. //#endregion
  635. //#region ../../node_modules/.pnpm/@jridgewell+trace-mapping@0.3.31/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.mjs
  636. function stripFilename(path) {
  637. if (!path) return "";
  638. const index = path.lastIndexOf("/");
  639. return path.slice(0, index + 1);
  640. }
  641. function resolver(mapUrl, sourceRoot) {
  642. const from = stripFilename(mapUrl);
  643. const prefix = sourceRoot ? sourceRoot + "/" : "";
  644. return (source) => resolve(prefix + (source || ""), from);
  645. }
  646. var COLUMN$1 = 0;
  647. function maybeSort(mappings, owned) {
  648. const unsortedIndex = nextUnsortedSegmentLine(mappings, 0);
  649. if (unsortedIndex === mappings.length) return mappings;
  650. if (!owned) mappings = mappings.slice();
  651. for (let i = unsortedIndex; i < mappings.length; i = nextUnsortedSegmentLine(mappings, i + 1)) mappings[i] = sortSegments(mappings[i], owned);
  652. return mappings;
  653. }
  654. function nextUnsortedSegmentLine(mappings, start) {
  655. for (let i = start; i < mappings.length; i++) if (!isSorted(mappings[i])) return i;
  656. return mappings.length;
  657. }
  658. function isSorted(line) {
  659. for (let j = 1; j < line.length; j++) if (line[j][COLUMN$1] < line[j - 1][COLUMN$1]) return false;
  660. return true;
  661. }
  662. function sortSegments(line, owned) {
  663. if (!owned) line = line.slice();
  664. return line.sort(sortComparator);
  665. }
  666. function sortComparator(a, b) {
  667. return a[COLUMN$1] - b[COLUMN$1];
  668. }
  669. function memoizedState() {
  670. return {
  671. lastKey: -1,
  672. lastNeedle: -1,
  673. lastIndex: -1
  674. };
  675. }
  676. function parse(map) {
  677. return typeof map === "string" ? JSON.parse(map) : map;
  678. }
  679. var TraceMap = class {
  680. constructor(map, mapUrl) {
  681. const isString = typeof map === "string";
  682. if (!isString && map._decodedMemo) return map;
  683. const parsed = parse(map);
  684. const { version, file, names, sourceRoot, sources, sourcesContent } = parsed;
  685. this.version = version;
  686. this.file = file;
  687. this.names = names || [];
  688. this.sourceRoot = sourceRoot;
  689. this.sources = sources;
  690. this.sourcesContent = sourcesContent;
  691. this.ignoreList = parsed.ignoreList || parsed.x_google_ignoreList || void 0;
  692. const resolve = resolver(mapUrl, sourceRoot);
  693. this.resolvedSources = sources.map(resolve);
  694. const { mappings } = parsed;
  695. if (typeof mappings === "string") {
  696. this._encoded = mappings;
  697. this._decoded = void 0;
  698. } else if (Array.isArray(mappings)) {
  699. this._encoded = void 0;
  700. this._decoded = maybeSort(mappings, isString);
  701. } else if (parsed.sections) throw new Error(`TraceMap passed sectioned source map, please use FlattenMap export instead`);
  702. else throw new Error(`invalid source map: ${JSON.stringify(parsed)}`);
  703. this._decodedMemo = memoizedState();
  704. this._bySources = void 0;
  705. this._bySourceMemos = void 0;
  706. }
  707. };
  708. function cast$1(map) {
  709. return map;
  710. }
  711. function decodedMappings(map) {
  712. var _a;
  713. return (_a = cast$1(map))._decoded || (_a._decoded = decode(cast$1(map)._encoded));
  714. }
  715. function eachMapping(map, cb) {
  716. const decoded = decodedMappings(map);
  717. const { names, resolvedSources } = map;
  718. for (let i = 0; i < decoded.length; i++) {
  719. const line = decoded[i];
  720. for (let j = 0; j < line.length; j++) {
  721. const seg = line[j];
  722. const generatedLine = i + 1;
  723. const generatedColumn = seg[0];
  724. let source = null;
  725. let originalLine = null;
  726. let originalColumn = null;
  727. let name = null;
  728. if (seg.length !== 1) {
  729. source = resolvedSources[seg[1]];
  730. originalLine = seg[2] + 1;
  731. originalColumn = seg[3];
  732. }
  733. if (seg.length === 5) name = names[seg[4]];
  734. cb({
  735. generatedLine,
  736. generatedColumn,
  737. source,
  738. originalLine,
  739. originalColumn,
  740. name
  741. });
  742. }
  743. }
  744. }
  745. //#endregion
  746. //#region ../../node_modules/.pnpm/@jridgewell+gen-mapping@0.3.13/node_modules/@jridgewell/gen-mapping/dist/gen-mapping.mjs
  747. var SetArray = class {
  748. constructor() {
  749. this._indexes = { __proto__: null };
  750. this.array = [];
  751. }
  752. };
  753. function cast(set) {
  754. return set;
  755. }
  756. function get(setarr, key) {
  757. return cast(setarr)._indexes[key];
  758. }
  759. function put(setarr, key) {
  760. const index = get(setarr, key);
  761. if (index !== void 0) return index;
  762. const { array, _indexes: indexes } = cast(setarr);
  763. return indexes[key] = array.push(key) - 1;
  764. }
  765. var COLUMN = 0;
  766. var SOURCES_INDEX = 1;
  767. var SOURCE_LINE = 2;
  768. var SOURCE_COLUMN = 3;
  769. var NAMES_INDEX = 4;
  770. var NO_NAME = -1;
  771. var GenMapping = class {
  772. constructor({ file, sourceRoot } = {}) {
  773. this._names = new SetArray();
  774. this._sources = new SetArray();
  775. this._sourcesContent = [];
  776. this._mappings = [];
  777. this.file = file;
  778. this.sourceRoot = sourceRoot;
  779. this._ignoreList = new SetArray();
  780. }
  781. };
  782. function cast2(map) {
  783. return map;
  784. }
  785. function addMapping(map, mapping) {
  786. return addMappingInternal(false, map, mapping);
  787. }
  788. function toDecodedMap(map) {
  789. const { _mappings: mappings, _sources: sources, _sourcesContent: sourcesContent, _names: names, _ignoreList: ignoreList } = cast2(map);
  790. removeEmptyFinalLines(mappings);
  791. return {
  792. version: 3,
  793. file: map.file || void 0,
  794. names: names.array,
  795. sourceRoot: map.sourceRoot || void 0,
  796. sources: sources.array,
  797. sourcesContent,
  798. mappings,
  799. ignoreList: ignoreList.array
  800. };
  801. }
  802. function toEncodedMap(map) {
  803. const decoded = toDecodedMap(map);
  804. return Object.assign({}, decoded, { mappings: encode(decoded.mappings) });
  805. }
  806. function fromMap(input) {
  807. const map = new TraceMap(input);
  808. const gen = new GenMapping({
  809. file: map.file,
  810. sourceRoot: map.sourceRoot
  811. });
  812. putAll(cast2(gen)._names, map.names);
  813. putAll(cast2(gen)._sources, map.sources);
  814. cast2(gen)._sourcesContent = map.sourcesContent || map.sources.map(() => null);
  815. cast2(gen)._mappings = decodedMappings(map);
  816. if (map.ignoreList) putAll(cast2(gen)._ignoreList, map.ignoreList);
  817. return gen;
  818. }
  819. function addSegmentInternal(skipable, map, genLine, genColumn, source, sourceLine, sourceColumn, name, content) {
  820. const { _mappings: mappings, _sources: sources, _sourcesContent: sourcesContent, _names: names } = cast2(map);
  821. const line = getIndex(mappings, genLine);
  822. const index = getColumnIndex(line, genColumn);
  823. if (!source) {
  824. if (skipable && skipSourceless(line, index)) return;
  825. return insert(line, index, [genColumn]);
  826. }
  827. assert(sourceLine);
  828. assert(sourceColumn);
  829. const sourcesIndex = put(sources, source);
  830. const namesIndex = name ? put(names, name) : NO_NAME;
  831. if (sourcesIndex === sourcesContent.length) sourcesContent[sourcesIndex] = content != null ? content : null;
  832. if (skipable && skipSource(line, index, sourcesIndex, sourceLine, sourceColumn, namesIndex)) return;
  833. return insert(line, index, name ? [
  834. genColumn,
  835. sourcesIndex,
  836. sourceLine,
  837. sourceColumn,
  838. namesIndex
  839. ] : [
  840. genColumn,
  841. sourcesIndex,
  842. sourceLine,
  843. sourceColumn
  844. ]);
  845. }
  846. function assert(_val) {}
  847. function getIndex(arr, index) {
  848. for (let i = arr.length; i <= index; i++) arr[i] = [];
  849. return arr[index];
  850. }
  851. function getColumnIndex(line, genColumn) {
  852. let index = line.length;
  853. for (let i = index - 1; i >= 0; index = i--) if (genColumn >= line[i][COLUMN]) break;
  854. return index;
  855. }
  856. function insert(array, index, value) {
  857. for (let i = array.length; i > index; i--) array[i] = array[i - 1];
  858. array[index] = value;
  859. }
  860. function removeEmptyFinalLines(mappings) {
  861. const { length } = mappings;
  862. let len = length;
  863. for (let i = len - 1; i >= 0; len = i, i--) if (mappings[i].length > 0) break;
  864. if (len < length) mappings.length = len;
  865. }
  866. function putAll(setarr, array) {
  867. for (let i = 0; i < array.length; i++) put(setarr, array[i]);
  868. }
  869. function skipSourceless(line, index) {
  870. if (index === 0) return true;
  871. return line[index - 1].length === 1;
  872. }
  873. function skipSource(line, index, sourcesIndex, sourceLine, sourceColumn, namesIndex) {
  874. if (index === 0) return false;
  875. const prev = line[index - 1];
  876. if (prev.length === 1) return false;
  877. return sourcesIndex === prev[SOURCES_INDEX] && sourceLine === prev[SOURCE_LINE] && sourceColumn === prev[SOURCE_COLUMN] && namesIndex === (prev.length === 5 ? prev[NAMES_INDEX] : NO_NAME);
  878. }
  879. function addMappingInternal(skipable, map, mapping) {
  880. const { generated, source, original, name, content } = mapping;
  881. if (!source) return addSegmentInternal(skipable, map, generated.line - 1, generated.column, null, null, null, null, null);
  882. assert(original);
  883. return addSegmentInternal(skipable, map, generated.line - 1, generated.column, source, original.line - 1, original.column, name, content);
  884. }
  885. //#endregion
  886. //#region ../../node_modules/.pnpm/obug@2.1.1/node_modules/obug/dist/core.js
  887. function coerce(value) {
  888. if (value instanceof Error) return value.stack || value.message;
  889. return value;
  890. }
  891. function selectColor(colors, namespace) {
  892. let hash = 0;
  893. for (let i = 0; i < namespace.length; i++) {
  894. hash = (hash << 5) - hash + namespace.charCodeAt(i);
  895. hash |= 0;
  896. }
  897. return colors[Math.abs(hash) % colors.length];
  898. }
  899. function matchesTemplate(search, template) {
  900. let searchIndex = 0;
  901. let templateIndex = 0;
  902. let starIndex = -1;
  903. let matchIndex = 0;
  904. while (searchIndex < search.length) if (templateIndex < template.length && (template[templateIndex] === search[searchIndex] || template[templateIndex] === "*")) if (template[templateIndex] === "*") {
  905. starIndex = templateIndex;
  906. matchIndex = searchIndex;
  907. templateIndex++;
  908. } else {
  909. searchIndex++;
  910. templateIndex++;
  911. }
  912. else if (starIndex !== -1) {
  913. templateIndex = starIndex + 1;
  914. matchIndex++;
  915. searchIndex = matchIndex;
  916. } else return false;
  917. while (templateIndex < template.length && template[templateIndex] === "*") templateIndex++;
  918. return templateIndex === template.length;
  919. }
  920. function humanize(value) {
  921. if (value >= 1e3) return `${(value / 1e3).toFixed(1)}s`;
  922. return `${value}ms`;
  923. }
  924. let globalNamespaces = "";
  925. function createDebug$1(namespace, options) {
  926. let prevTime;
  927. let enableOverride;
  928. let namespacesCache;
  929. let enabledCache;
  930. const debug = (...args) => {
  931. if (!debug.enabled) return;
  932. const curr = Date.now();
  933. const diff = curr - (prevTime || curr);
  934. prevTime = curr;
  935. args[0] = coerce(args[0]);
  936. if (typeof args[0] !== "string") args.unshift("%O");
  937. let index = 0;
  938. args[0] = args[0].replace(/%([a-z%])/gi, (match, format) => {
  939. if (match === "%%") return "%";
  940. index++;
  941. const formatter = options.formatters[format];
  942. if (typeof formatter === "function") {
  943. const value = args[index];
  944. match = formatter.call(debug, value);
  945. args.splice(index, 1);
  946. index--;
  947. }
  948. return match;
  949. });
  950. options.formatArgs.call(debug, diff, args);
  951. debug.log(...args);
  952. };
  953. debug.extend = function(namespace$1, delimiter = ":") {
  954. return createDebug$1(this.namespace + delimiter + namespace$1, {
  955. useColors: this.useColors,
  956. color: this.color,
  957. formatArgs: this.formatArgs,
  958. formatters: this.formatters,
  959. inspectOpts: this.inspectOpts,
  960. log: this.log,
  961. humanize: this.humanize
  962. });
  963. };
  964. Object.assign(debug, options);
  965. debug.namespace = namespace;
  966. Object.defineProperty(debug, "enabled", {
  967. enumerable: true,
  968. configurable: false,
  969. get: () => {
  970. if (enableOverride != null) return enableOverride;
  971. if (namespacesCache !== globalNamespaces) {
  972. namespacesCache = globalNamespaces;
  973. enabledCache = enabled(namespace);
  974. }
  975. return enabledCache;
  976. },
  977. set: (v) => {
  978. enableOverride = v;
  979. }
  980. });
  981. return debug;
  982. }
  983. let names = [];
  984. let skips = [];
  985. function enable(namespaces$1) {
  986. globalNamespaces = namespaces$1;
  987. names = [];
  988. skips = [];
  989. const split = globalNamespaces.trim().replace(/\s+/g, ",").split(",").filter(Boolean);
  990. for (const ns of split) if (ns[0] === "-") skips.push(ns.slice(1));
  991. else names.push(ns);
  992. }
  993. function enabled(name) {
  994. for (const skip of skips) if (matchesTemplate(name, skip)) return false;
  995. for (const ns of names) if (matchesTemplate(name, ns)) return true;
  996. return false;
  997. }
  998. //#endregion
  999. //#region ../../node_modules/.pnpm/obug@2.1.1/node_modules/obug/dist/node.js
  1000. const colors = process.stderr.getColorDepth && process.stderr.getColorDepth() > 2 ? [
  1001. 20,
  1002. 21,
  1003. 26,
  1004. 27,
  1005. 32,
  1006. 33,
  1007. 38,
  1008. 39,
  1009. 40,
  1010. 41,
  1011. 42,
  1012. 43,
  1013. 44,
  1014. 45,
  1015. 56,
  1016. 57,
  1017. 62,
  1018. 63,
  1019. 68,
  1020. 69,
  1021. 74,
  1022. 75,
  1023. 76,
  1024. 77,
  1025. 78,
  1026. 79,
  1027. 80,
  1028. 81,
  1029. 92,
  1030. 93,
  1031. 98,
  1032. 99,
  1033. 112,
  1034. 113,
  1035. 128,
  1036. 129,
  1037. 134,
  1038. 135,
  1039. 148,
  1040. 149,
  1041. 160,
  1042. 161,
  1043. 162,
  1044. 163,
  1045. 164,
  1046. 165,
  1047. 166,
  1048. 167,
  1049. 168,
  1050. 169,
  1051. 170,
  1052. 171,
  1053. 172,
  1054. 173,
  1055. 178,
  1056. 179,
  1057. 184,
  1058. 185,
  1059. 196,
  1060. 197,
  1061. 198,
  1062. 199,
  1063. 200,
  1064. 201,
  1065. 202,
  1066. 203,
  1067. 204,
  1068. 205,
  1069. 206,
  1070. 207,
  1071. 208,
  1072. 209,
  1073. 214,
  1074. 215,
  1075. 220,
  1076. 221
  1077. ] : [
  1078. 6,
  1079. 2,
  1080. 3,
  1081. 4,
  1082. 5,
  1083. 1
  1084. ];
  1085. const inspectOpts = Object.keys(process.env).filter((key) => /^debug_/i.test(key)).reduce((obj, key) => {
  1086. const prop = key.slice(6).toLowerCase().replace(/_([a-z])/g, (_, k) => k.toUpperCase());
  1087. let value = process.env[key];
  1088. const lowerCase = typeof value === "string" && value.toLowerCase();
  1089. if (value === "null") value = null;
  1090. else if (lowerCase === "yes" || lowerCase === "on" || lowerCase === "true" || lowerCase === "enabled") value = true;
  1091. else if (lowerCase === "no" || lowerCase === "off" || lowerCase === "false" || lowerCase === "disabled") value = false;
  1092. else value = Number(value);
  1093. obj[prop] = value;
  1094. return obj;
  1095. }, {});
  1096. function useColors() {
  1097. return "colors" in inspectOpts ? Boolean(inspectOpts.colors) : isatty(process.stderr.fd);
  1098. }
  1099. function getDate() {
  1100. if (inspectOpts.hideDate) return "";
  1101. return `${(/* @__PURE__ */ new Date()).toISOString()} `;
  1102. }
  1103. function formatArgs(diff, args) {
  1104. const { namespace: name, useColors: useColors$1 } = this;
  1105. if (useColors$1) {
  1106. const c = this.color;
  1107. const colorCode = `\u001B[3${c < 8 ? c : `8;5;${c}`}`;
  1108. const prefix = ` ${colorCode};1m${name} \u001B[0m`;
  1109. args[0] = prefix + args[0].split("\n").join(`\n${prefix}`);
  1110. args.push(`${colorCode}m+${this.humanize(diff)}\u001B[0m`);
  1111. } else args[0] = `${getDate()}${name} ${args[0]}`;
  1112. }
  1113. function log(...args) {
  1114. process.stderr.write(`${formatWithOptions(this.inspectOpts, ...args)}\n`);
  1115. }
  1116. const defaultOptions = {
  1117. useColors: useColors(),
  1118. formatArgs,
  1119. formatters: {
  1120. o(v) {
  1121. this.inspectOpts.colors = this.useColors;
  1122. return inspect(v, this.inspectOpts).split("\n").map((str) => str.trim()).join(" ");
  1123. },
  1124. O(v) {
  1125. this.inspectOpts.colors = this.useColors;
  1126. return inspect(v, this.inspectOpts);
  1127. }
  1128. },
  1129. inspectOpts,
  1130. log,
  1131. humanize
  1132. };
  1133. function createDebug(namespace, options) {
  1134. var _ref;
  1135. const color = (_ref = options && options.color) !== null && _ref !== void 0 ? _ref : selectColor(colors, namespace);
  1136. return createDebug$1(namespace, Object.assign(defaultOptions, { color }, options));
  1137. }
  1138. enable(process.env.DEBUG || "");
  1139. //#endregion
  1140. //#region src/handleHotUpdate.ts
  1141. const debug = createDebug("vite:hmr");
  1142. /**
  1143. * Vite-specific HMR handling
  1144. */
  1145. async function handleHotUpdate({ file, modules, read }, options, customElement, typeDepModules) {
  1146. const prevDescriptor = getDescriptor(file, options, false, true);
  1147. if (!prevDescriptor) return;
  1148. const { descriptor } = createDescriptor(file, await read(), options, true);
  1149. let needRerender = false;
  1150. const nonJsModules = modules.filter((m) => m.type !== "js");
  1151. const jsModules = modules.filter((m) => m.type === "js");
  1152. const affectedModules = new Set(nonJsModules);
  1153. const mainModule = getMainModule(jsModules);
  1154. const templateModule = jsModules.find((m) => /type=template/.test(m.url));
  1155. resolveScript(descriptor, options, false, customElement);
  1156. const scriptChanged = hasScriptChanged(prevDescriptor, descriptor);
  1157. if (scriptChanged) affectedModules.add(getScriptModule(jsModules) || mainModule);
  1158. if (!isEqualBlock(descriptor.template, prevDescriptor.template)) {
  1159. if (!scriptChanged) setResolvedScript(descriptor, getResolvedScript(prevDescriptor, false), false);
  1160. affectedModules.add(templateModule);
  1161. needRerender = true;
  1162. }
  1163. let didUpdateStyle = false;
  1164. const prevStyles = prevDescriptor.styles || [];
  1165. const nextStyles = descriptor.styles || [];
  1166. if (prevDescriptor.cssVars.join("") !== descriptor.cssVars.join("")) affectedModules.add(mainModule);
  1167. if (prevStyles.some((s) => s.scoped) !== nextStyles.some((s) => s.scoped)) {
  1168. affectedModules.add(templateModule);
  1169. affectedModules.add(mainModule);
  1170. }
  1171. for (let i = 0; i < nextStyles.length; i++) {
  1172. const prev = prevStyles[i];
  1173. const next = nextStyles[i];
  1174. if (!prev || !isEqualBlock(prev, next)) {
  1175. didUpdateStyle = true;
  1176. const mod = jsModules.find((m) => m.url.includes(`type=style&index=${i}`) && m.url.endsWith(`.${next.lang || "css"}`));
  1177. if (mod) {
  1178. affectedModules.add(mod);
  1179. if (mod.url.includes("&inline")) affectedModules.add(mainModule);
  1180. } else affectedModules.add(mainModule);
  1181. }
  1182. }
  1183. if (prevStyles.length > nextStyles.length) affectedModules.add(mainModule);
  1184. const prevCustoms = prevDescriptor.customBlocks || [];
  1185. const nextCustoms = descriptor.customBlocks || [];
  1186. if (prevCustoms.length !== nextCustoms.length) affectedModules.add(mainModule);
  1187. else for (let i = 0; i < nextCustoms.length; i++) {
  1188. const prev = prevCustoms[i];
  1189. const next = nextCustoms[i];
  1190. if (!prev || !isEqualBlock(prev, next)) {
  1191. const mod = jsModules.find((m) => m.url.includes(`type=${prev.type}&index=${i}`));
  1192. if (mod) affectedModules.add(mod);
  1193. else affectedModules.add(mainModule);
  1194. }
  1195. }
  1196. const updateType = [];
  1197. if (needRerender) {
  1198. updateType.push(`template`);
  1199. if (!templateModule) affectedModules.add(mainModule);
  1200. else if (mainModule && !affectedModules.has(mainModule)) [...mainModule.importers].filter((m) => isCSSRequest(m.url)).forEach((m) => affectedModules.add(m));
  1201. }
  1202. if (didUpdateStyle) updateType.push(`style`);
  1203. if (updateType.length) {
  1204. if (file.endsWith(".vue")) invalidateDescriptor(file);
  1205. else cache.set(file, descriptor);
  1206. debug(`[vue:update(${updateType.join("&")})] ${file}`);
  1207. }
  1208. return [...affectedModules, ...typeDepModules || []].filter(Boolean);
  1209. }
  1210. function isEqualBlock(a, b) {
  1211. if (!a && !b) return true;
  1212. if (!a || !b) return false;
  1213. if (a.src && b.src && a.src === b.src) return true;
  1214. if (a.content !== b.content) return false;
  1215. const keysA = Object.keys(a.attrs);
  1216. const keysB = Object.keys(b.attrs);
  1217. if (keysA.length !== keysB.length) return false;
  1218. return keysA.every((key) => a.attrs[key] === b.attrs[key]);
  1219. }
  1220. function isOnlyTemplateChanged(prev, next) {
  1221. return !hasScriptChanged(prev, next) && prev.styles.length === next.styles.length && prev.styles.every((s, i) => isEqualBlock(s, next.styles[i])) && prev.customBlocks.length === next.customBlocks.length && prev.customBlocks.every((s, i) => isEqualBlock(s, next.customBlocks[i]));
  1222. }
  1223. function deepEqual(obj1, obj2, excludeProps = [], deepParentsOfObj1 = []) {
  1224. if (typeof obj1 !== typeof obj2) return false;
  1225. if (obj1 == null || obj2 == null || typeof obj1 !== "object" || deepParentsOfObj1.includes(obj1)) return obj1 === obj2;
  1226. const keys1 = Object.keys(obj1);
  1227. const keys2 = Object.keys(obj2);
  1228. if (keys1.length !== keys2.length) return false;
  1229. for (const key of keys1) {
  1230. if (excludeProps.includes(key)) continue;
  1231. if (!deepEqual(obj1[key], obj2[key], excludeProps, [...deepParentsOfObj1, obj1])) return false;
  1232. }
  1233. return true;
  1234. }
  1235. function isEqualAst(prev, next) {
  1236. if (typeof prev === "undefined" || typeof next === "undefined") return prev === next;
  1237. if (prev.length !== next.length) return false;
  1238. for (let i = 0; i < prev.length; i++) {
  1239. const prevNode = prev[i];
  1240. const nextNode = next[i];
  1241. if (!deepEqual(prevNode, nextNode, [
  1242. "start",
  1243. "end",
  1244. "loc",
  1245. "range",
  1246. "leadingComments",
  1247. "trailingComments",
  1248. "innerComments",
  1249. "_ownerScope",
  1250. "_resolvedReference",
  1251. "_resolvedElements"
  1252. ])) return false;
  1253. }
  1254. return true;
  1255. }
  1256. function hasScriptChanged(prev, next) {
  1257. if (prev.vapor !== next.vapor) return true;
  1258. const prevScript = getResolvedScript(prev, false);
  1259. const nextScript = getResolvedScript(next, false);
  1260. if (!isEqualBlock(prev.script, next.script) && !isEqualAst(prevScript?.scriptAst, nextScript?.scriptAst)) return true;
  1261. if (!isEqualBlock(prev.scriptSetup, next.scriptSetup) && !isEqualAst(prevScript?.scriptSetupAst, nextScript?.scriptSetupAst)) return true;
  1262. const prevImports = getResolvedScript(prev, false)?.imports;
  1263. if (prevImports) return !next.template || next.shouldForceReload(prevImports);
  1264. return false;
  1265. }
  1266. function getMainModule(jsModules) {
  1267. return jsModules.filter((m) => !/type=/.test(m.url) || /type=script/.test(m.url)).sort((m1, m2) => {
  1268. return m1.url.length - m2.url.length;
  1269. })[0];
  1270. }
  1271. function getScriptModule(jsModules) {
  1272. return jsModules.find((m) => /type=script.*&lang\.\w+$/.test(m.url));
  1273. }
  1274. function handleTypeDepChange(affectedComponents, { modules, server: { moduleGraph } }) {
  1275. const affected = /* @__PURE__ */ new Set();
  1276. for (const file of affectedComponents) {
  1277. invalidateScript(file);
  1278. const mods = moduleGraph.getModulesByFile(file);
  1279. if (mods) {
  1280. const arr = [...mods];
  1281. affected.add(getScriptModule(arr) || getMainModule(arr));
  1282. }
  1283. }
  1284. return [...modules, ...affected];
  1285. }
  1286. //#endregion
  1287. //#region src/helper.ts
  1288. const EXPORT_HELPER_ID = "\0plugin-vue:export-helper";
  1289. const helperCode = `
  1290. export default (sfc, props) => {
  1291. const target = sfc.__vccOpts || sfc;
  1292. for (const [key, val] of props) {
  1293. target[key] = val;
  1294. }
  1295. return target;
  1296. }
  1297. `;
  1298. //#endregion
  1299. //#region src/main.ts
  1300. async function transformMain(code, filename, options, pluginContext, ssr, customElement) {
  1301. const { devServer, isProduction, devToolsEnabled } = options;
  1302. const prevDescriptor = getPrevDescriptor(filename);
  1303. const { descriptor, errors } = createDescriptor(filename, code, options);
  1304. if (fs.existsSync(filename)) getDescriptor(filename, options, true, true, filename.endsWith(".vue") ? void 0 : code);
  1305. if (errors.length) {
  1306. errors.forEach((error) => pluginContext.error(createRollupError(filename, error)));
  1307. return null;
  1308. }
  1309. const attachedProps = [];
  1310. const hasScoped = descriptor.styles.some((s) => s.scoped);
  1311. const isTemplateOnlyVapor = !descriptor.script && !descriptor.scriptSetup && descriptor.vapor;
  1312. const { code: scriptCode, map: scriptMap } = await genScriptCode(descriptor, options, pluginContext, ssr, customElement);
  1313. const hasTemplateImport = descriptor.template && !isUseInlineTemplate(descriptor, options);
  1314. const isTemplateInlined = !!descriptor.template && (!descriptor.template.lang || descriptor.template.lang === "html") && !descriptor.template.src;
  1315. let templateCode = "";
  1316. let templateMap = void 0;
  1317. let templateMultiRoot;
  1318. if (hasTemplateImport) ({code: templateCode, map: templateMap, multiRoot: templateMultiRoot} = await genTemplateCode(descriptor, options, pluginContext, ssr, customElement));
  1319. if (hasTemplateImport) attachedProps.push(ssr ? ["ssrRender", "_sfc_ssrRender"] : ["render", "_sfc_render"]);
  1320. else if (prevDescriptor && !isEqualBlock(descriptor.template, prevDescriptor.template)) attachedProps.push([ssr ? "ssrRender" : "render", "() => {}"]);
  1321. const stylesCode = await genStyleCode(descriptor, pluginContext, customElement, attachedProps);
  1322. const customBlocksCode = await genCustomBlockCode(descriptor, pluginContext);
  1323. const output = [
  1324. scriptCode,
  1325. templateCode,
  1326. isTemplateOnlyVapor ? `${scriptIdentifier}.__multiRoot = ${isTemplateInlined ? templateMultiRoot : "_sfc_multiRoot"}` : "",
  1327. stylesCode,
  1328. customBlocksCode
  1329. ];
  1330. if (hasScoped) attachedProps.push([`__scopeId`, JSON.stringify(`data-v-${descriptor.id}`)]);
  1331. if (devToolsEnabled || devServer && !isProduction) attachedProps.push([`__file`, JSON.stringify(isProduction ? path.basename(filename) : filename)]);
  1332. if (devServer && devServer.config.server.hmr !== false && !ssr && !isProduction) {
  1333. output.push(`_sfc_main.__hmrId = ${JSON.stringify(descriptor.id)}`);
  1334. output.push("typeof __VUE_HMR_RUNTIME__ !== 'undefined' && __VUE_HMR_RUNTIME__.createRecord(_sfc_main.__hmrId, _sfc_main)");
  1335. output.push(`import.meta.hot.on('file-changed', ({ file }) => {`, ` __VUE_HMR_RUNTIME__.CHANGED_FILE = file`, `})`);
  1336. if (prevDescriptor && isOnlyTemplateChanged(prevDescriptor, descriptor)) output.push(`export const _rerender_only = __VUE_HMR_RUNTIME__.CHANGED_FILE === ${JSON.stringify(normalizePath(filename))}`);
  1337. output.push(`import.meta.hot.accept(mod => {`, ` if (!mod) return`, ` const { default: updated, _rerender_only } = mod`, ` if (_rerender_only) {`, ` __VUE_HMR_RUNTIME__.rerender(updated.__hmrId, updated.render)`, ` } else {`, ` __VUE_HMR_RUNTIME__.reload(updated.__hmrId, updated)`, ` }`, `})`);
  1338. }
  1339. if (ssr) {
  1340. const normalizedFilename = normalizePath(path.relative(options.root, filename));
  1341. output.push(`import { useSSRContext as __vite_useSSRContext } from 'vue'`, `const _sfc_setup = _sfc_main.setup`, `_sfc_main.setup = (props, ctx) => {`, ` const ssrContext = __vite_useSSRContext()`, ` ;(ssrContext.modules || (ssrContext.modules = new Set())).add(${JSON.stringify(normalizedFilename)})`, ` return _sfc_setup ? _sfc_setup(props, ctx) : undefined`, `}`);
  1342. }
  1343. let resolvedMap = void 0;
  1344. if (options.sourceMap) if (templateMap) {
  1345. const gen = fromMap(scriptMap ?? {
  1346. file: filename,
  1347. sourceRoot: "",
  1348. version: 3,
  1349. sources: [],
  1350. sourcesContent: [],
  1351. names: [],
  1352. mappings: ""
  1353. });
  1354. const tracer = new TraceMap(templateMap);
  1355. const offset = (scriptCode.match(/\r?\n/g)?.length ?? 0) + 1;
  1356. eachMapping(tracer, (m) => {
  1357. if (m.source == null) return;
  1358. addMapping(gen, {
  1359. source: m.source,
  1360. original: {
  1361. line: m.originalLine,
  1362. column: m.originalColumn
  1363. },
  1364. generated: {
  1365. line: m.generatedLine + offset,
  1366. column: m.generatedColumn
  1367. }
  1368. });
  1369. });
  1370. resolvedMap = toEncodedMap(gen);
  1371. resolvedMap.sourcesContent = templateMap.sourcesContent;
  1372. } else resolvedMap = scriptMap;
  1373. if (!attachedProps.length) output.push(`export default _sfc_main`);
  1374. else output.push(`import _export_sfc from '${EXPORT_HELPER_ID}'`, `export default /*#__PURE__*/_export_sfc(_sfc_main, [${attachedProps.map(([key, val]) => `['${key}',${val}]`).join(",")}])`);
  1375. let resolvedCode = output.join("\n");
  1376. const lang = descriptor.scriptSetup?.lang || descriptor.script?.lang;
  1377. if (lang && /tsx?$/.test(lang) && !descriptor.script?.src) {
  1378. const { transformWithOxc } = await import("vite");
  1379. if (transformWithOxc) {
  1380. const { code, map } = await transformWithOxc(resolvedCode, filename, {
  1381. ...options.devServer?.config.oxc,
  1382. lang: "ts",
  1383. sourcemap: options.sourceMap
  1384. }, resolvedMap);
  1385. resolvedCode = code;
  1386. resolvedMap = resolvedMap ? map : resolvedMap;
  1387. } else {
  1388. const { code, map } = await transformWithEsbuild(resolvedCode, filename, {
  1389. target: "esnext",
  1390. charset: "utf8",
  1391. ...options.devServer?.config.esbuild,
  1392. loader: "ts",
  1393. sourcemap: options.sourceMap
  1394. }, resolvedMap);
  1395. resolvedCode = code;
  1396. resolvedMap = resolvedMap ? map : resolvedMap;
  1397. }
  1398. }
  1399. return {
  1400. code: resolvedCode,
  1401. map: resolvedMap || { mappings: "" },
  1402. meta: { vite: { lang: descriptor.script?.lang || descriptor.scriptSetup?.lang || "js" } }
  1403. };
  1404. }
  1405. async function genTemplateCode(descriptor, options, pluginContext, ssr, customElement) {
  1406. const template = descriptor.template;
  1407. const hasScoped = descriptor.styles.some((style) => style.scoped);
  1408. const needsMultiRoot = !descriptor.script && !descriptor.scriptSetup && descriptor.vapor;
  1409. if ((!template.lang || template.lang === "html") && !template.src) {
  1410. const result = transformTemplateInMain(template.content, descriptor, options, pluginContext, ssr, customElement);
  1411. return {
  1412. ...result,
  1413. multiRoot: needsMultiRoot ? result.multiRoot : void 0
  1414. };
  1415. } else {
  1416. if (template.src) await linkSrcToDescriptor(template.src, descriptor, pluginContext, hasScoped);
  1417. const src = template.src || descriptor.filename;
  1418. const query = `?vue&type=template${template.src ? hasScoped ? `&src=${descriptor.id}` : "&src=true" : ""}${hasScoped ? `&scoped=${descriptor.id}` : ``}${attrsToQuery(template.attrs, "js", true)}`;
  1419. const request = JSON.stringify(src + query);
  1420. const renderFnName = ssr ? "ssrRender" : "render";
  1421. return {
  1422. code: `import { ${renderFnName} as _sfc_${renderFnName}${needsMultiRoot ? ", multiRoot as _sfc_multiRoot" : ""} } from ${request}`,
  1423. map: void 0
  1424. };
  1425. }
  1426. }
  1427. async function genScriptCode(descriptor, options, pluginContext, ssr, customElement) {
  1428. let scriptCode = `const ${scriptIdentifier} = { ${descriptor.vapor ? "__vapor: true" : ""} }`;
  1429. let map;
  1430. const script = resolveScript(descriptor, options, ssr, customElement);
  1431. if (script) if (canInlineMain(descriptor, options)) {
  1432. if (!options.compiler.version) {
  1433. const userPlugins = options.script?.babelParserPlugins || [];
  1434. const defaultPlugins = script.lang === "ts" ? userPlugins.includes("decorators") ? ["typescript"] : ["typescript", "decorators-legacy"] : [];
  1435. scriptCode = options.compiler.rewriteDefault(script.content, scriptIdentifier, [...defaultPlugins, ...userPlugins]);
  1436. } else scriptCode = script.content;
  1437. map = script.map;
  1438. } else {
  1439. if (script.src) await linkSrcToDescriptor(script.src, descriptor, pluginContext, false);
  1440. const src = script.src || descriptor.filename;
  1441. const langFallback = script.src && path.extname(src).slice(1) || "js";
  1442. const attrsQuery = attrsToQuery(script.attrs, langFallback);
  1443. const query = `?vue&type=script${script.src ? `&src=true` : ``}${attrsQuery}`;
  1444. const request = JSON.stringify(src + query);
  1445. scriptCode = `import _sfc_main from ${request}\nexport * from ${request}`;
  1446. }
  1447. return {
  1448. code: scriptCode,
  1449. map
  1450. };
  1451. }
  1452. async function genStyleCode(descriptor, pluginContext, customElement, attachedProps) {
  1453. let stylesCode = ``;
  1454. let cssModulesMap;
  1455. if (descriptor.styles.length) {
  1456. for (let i = 0; i < descriptor.styles.length; i++) {
  1457. const style = descriptor.styles[i];
  1458. if (style.src) await linkSrcToDescriptor(style.src, descriptor, pluginContext, style.scoped);
  1459. const src = style.src || descriptor.filename;
  1460. const attrsQuery = attrsToQuery(style.attrs, "css");
  1461. const srcQuery = style.src ? style.scoped ? `&src=${descriptor.id}` : "&src=true" : "";
  1462. const directQuery = customElement ? `&inline` : ``;
  1463. const scopedQuery = style.scoped ? `&scoped=${descriptor.id}` : ``;
  1464. const styleRequest = src + `?vue&type=style&index=${i}${srcQuery}${directQuery}${scopedQuery}` + attrsQuery;
  1465. if (style.module) {
  1466. if (customElement) throw new Error(`<style module> is not supported in custom elements mode.`);
  1467. const [importCode, nameMap] = genCSSModulesCode(i, styleRequest, style.module);
  1468. stylesCode += importCode;
  1469. Object.assign(cssModulesMap ||= {}, nameMap);
  1470. } else if (customElement) stylesCode += `\nimport _style_${i} from ${JSON.stringify(styleRequest)}`;
  1471. else stylesCode += `\nimport ${JSON.stringify(styleRequest)}`;
  1472. }
  1473. if (customElement) attachedProps.push([`styles`, `[${descriptor.styles.map((_, i) => `_style_${i}`).join(",")}]`]);
  1474. }
  1475. if (cssModulesMap) {
  1476. const mappingCode = Object.entries(cssModulesMap).reduce((code, [key, value]) => code + `"${key}":${value},\n`, "{\n") + "}";
  1477. stylesCode += `\nconst cssModules = ${mappingCode}`;
  1478. attachedProps.push([`__cssModules`, `cssModules`]);
  1479. }
  1480. return stylesCode;
  1481. }
  1482. function genCSSModulesCode(index, request, moduleName) {
  1483. const styleVar = `style${index}`;
  1484. const exposedName = typeof moduleName === "string" ? moduleName : "$style";
  1485. const moduleRequest = request.replace(/\.(\w+)$/, ".module.$1");
  1486. return [`\nimport ${styleVar} from ${JSON.stringify(moduleRequest)}`, { [exposedName]: styleVar }];
  1487. }
  1488. async function genCustomBlockCode(descriptor, pluginContext) {
  1489. let code = "";
  1490. for (let index = 0; index < descriptor.customBlocks.length; index++) {
  1491. const block = descriptor.customBlocks[index];
  1492. if (block.src) await linkSrcToDescriptor(block.src, descriptor, pluginContext, false);
  1493. const src = block.src || descriptor.filename;
  1494. const attrsQuery = attrsToQuery(block.attrs, block.type);
  1495. const srcQuery = block.src ? `&src=true` : ``;
  1496. const query = `?vue&type=${block.type}&index=${index}${srcQuery}${attrsQuery}`;
  1497. const request = JSON.stringify(src + query);
  1498. code += `import block${index} from ${request}\n`;
  1499. code += `if (typeof block${index} === 'function') block${index}(_sfc_main)\n`;
  1500. }
  1501. return code;
  1502. }
  1503. /**
  1504. * For blocks with src imports, it is important to link the imported file
  1505. * with its owner SFC descriptor so that we can get the information about
  1506. * the owner SFC when compiling that file in the transform phase.
  1507. */
  1508. async function linkSrcToDescriptor(src, descriptor, pluginContext, scoped) {
  1509. setSrcDescriptor(((await pluginContext.resolve(src, descriptor.filename))?.id || src).replace(/\?.*$/, ""), descriptor, scoped);
  1510. }
  1511. const ignoreList = [
  1512. "id",
  1513. "index",
  1514. "src",
  1515. "type",
  1516. "lang",
  1517. "module",
  1518. "scoped",
  1519. "generic"
  1520. ];
  1521. function attrsToQuery(attrs, langFallback, forceLangFallback = false) {
  1522. let query = ``;
  1523. for (const name in attrs) {
  1524. const value = attrs[name];
  1525. if (!ignoreList.includes(name)) query += `&${encodeURIComponent(name)}${value ? `=${encodeURIComponent(value)}` : ``}`;
  1526. }
  1527. if (langFallback || attrs.lang) query += `lang` in attrs ? forceLangFallback ? `&lang.${langFallback}` : `&lang.${attrs.lang}` : `&lang.${langFallback}`;
  1528. return query;
  1529. }
  1530. //#endregion
  1531. //#region src/style.ts
  1532. async function transformStyle(code, descriptor, index, options, pluginContext, filename) {
  1533. const block = descriptor.styles[index];
  1534. const result = await options.compiler.compileStyleAsync({
  1535. ...options.style,
  1536. filename: descriptor.filename,
  1537. id: `data-v-${descriptor.id}`,
  1538. isProd: options.isProduction,
  1539. source: code,
  1540. scoped: block.scoped,
  1541. ...options.cssDevSourcemap ? { postcssOptions: { map: {
  1542. from: filename,
  1543. inline: false,
  1544. annotation: false
  1545. } } } : {}
  1546. });
  1547. if (result.errors.length) {
  1548. result.errors.forEach((error) => {
  1549. if (error.line && error.column) error.loc = {
  1550. file: descriptor.filename,
  1551. line: error.line + block.loc.start.line,
  1552. column: error.column
  1553. };
  1554. pluginContext.error(error);
  1555. });
  1556. return null;
  1557. }
  1558. const map = result.map ? await formatPostcssSourceMap(result.map, filename) : { mappings: "" };
  1559. return {
  1560. code: result.code,
  1561. map,
  1562. meta: block.scoped && !descriptor.isTemp ? { vite: { cssScopeTo: [descriptor.filename, "default"] } } : void 0
  1563. };
  1564. }
  1565. //#endregion
  1566. //#region src/index.ts
  1567. function vuePlugin(rawOptions = {}) {
  1568. clearScriptCache();
  1569. const options = shallowRef({
  1570. isProduction: process.env.NODE_ENV === "production",
  1571. compiler: null,
  1572. customElement: /\.ce\.vue$/,
  1573. ...rawOptions,
  1574. root: process.cwd(),
  1575. sourceMap: true,
  1576. cssDevSourcemap: false
  1577. });
  1578. const include = shallowRef(rawOptions.include ?? /\.vue$/);
  1579. const exclude = shallowRef(rawOptions.exclude);
  1580. let optionsHookIsCalled = false;
  1581. const filter = computed(() => createFilter(include.value, exclude.value));
  1582. const customElementFilter = computed(() => {
  1583. const customElement = options.value.features?.customElement || options.value.customElement;
  1584. return typeof customElement === "boolean" ? () => customElement : createFilter(customElement);
  1585. });
  1586. let transformCachedModule = false;
  1587. const plugin = {
  1588. name: "vite:vue",
  1589. api: {
  1590. get options() {
  1591. return options.value;
  1592. },
  1593. set options(value) {
  1594. options.value = value;
  1595. },
  1596. get include() {
  1597. return include.value;
  1598. },
  1599. set include(value) {
  1600. if (optionsHookIsCalled) throw new Error("include cannot be updated after `options` hook is called");
  1601. include.value = value;
  1602. },
  1603. get exclude() {
  1604. return exclude.value;
  1605. },
  1606. set exclude(value) {
  1607. if (optionsHookIsCalled) throw new Error("exclude cannot be updated after `options` hook is called");
  1608. exclude.value = value;
  1609. },
  1610. version
  1611. },
  1612. handleHotUpdate(ctx) {
  1613. ctx.server.ws.send({
  1614. type: "custom",
  1615. event: "file-changed",
  1616. data: { file: normalizePath(ctx.file) }
  1617. });
  1618. if (options.value.compiler.invalidateTypeCache) options.value.compiler.invalidateTypeCache(ctx.file);
  1619. let typeDepModules;
  1620. const matchesFilter = filter.value(ctx.file);
  1621. if (typeDepToSFCMap.has(ctx.file)) {
  1622. typeDepModules = handleTypeDepChange(typeDepToSFCMap.get(ctx.file), ctx);
  1623. if (!matchesFilter) return typeDepModules;
  1624. }
  1625. if (matchesFilter) return handleHotUpdate(ctx, options.value, customElementFilter.value(ctx.file), typeDepModules);
  1626. },
  1627. config(config) {
  1628. const parseDefine = (v) => {
  1629. try {
  1630. return typeof v === "string" ? JSON.parse(v) : v;
  1631. } catch (err) {
  1632. return v;
  1633. }
  1634. };
  1635. return {
  1636. resolve: { dedupe: config.build?.ssr ? [] : ["vue"] },
  1637. define: {
  1638. __VUE_OPTIONS_API__: options.value.features?.optionsAPI ?? parseDefine(config.define?.__VUE_OPTIONS_API__) ?? true,
  1639. __VUE_PROD_DEVTOOLS__: (options.value.features?.prodDevtools || parseDefine(config.define?.__VUE_PROD_DEVTOOLS__)) ?? false,
  1640. __VUE_PROD_HYDRATION_MISMATCH_DETAILS__: (options.value.features?.prodHydrationMismatchDetails || parseDefine(config.define?.__VUE_PROD_HYDRATION_MISMATCH_DETAILS__)) ?? false
  1641. },
  1642. ssr: { external: config.legacy?.buildSsrCjsExternalHeuristics ? ["vue", "@vue/server-renderer"] : [] }
  1643. };
  1644. },
  1645. configResolved(config) {
  1646. options.value = {
  1647. ...options.value,
  1648. root: config.root,
  1649. sourceMap: config.command === "build" ? !!config.build.sourcemap : true,
  1650. cssDevSourcemap: config.css?.devSourcemap ?? false,
  1651. isProduction: config.isProduction,
  1652. devToolsEnabled: !!(options.value.features?.prodDevtools || config.define.__VUE_PROD_DEVTOOLS__ || !config.isProduction)
  1653. };
  1654. const _warn = config.logger.warn;
  1655. config.logger.warn = (...args) => {
  1656. if (args[0].match(/\[lightningcss\] '(deep|slotted|global)' is not recognized as a valid pseudo-/)) return;
  1657. _warn(...args);
  1658. };
  1659. transformCachedModule = config.command === "build" && options.value.sourceMap && config.build.watch != null;
  1660. },
  1661. options() {
  1662. optionsHookIsCalled = true;
  1663. plugin.transform.filter = { id: {
  1664. include: [...makeIdFiltersToMatchWithQuery(ensureArray(include.value)), /[?&]vue\b/],
  1665. exclude: exclude.value
  1666. } };
  1667. },
  1668. shouldTransformCachedModule({ id }) {
  1669. if (transformCachedModule && parseVueRequest(id).query.vue) return true;
  1670. return false;
  1671. },
  1672. configureServer(server) {
  1673. options.value.devServer = server;
  1674. },
  1675. buildStart() {
  1676. const compiler = options.value.compiler = options.value.compiler || resolveCompiler(options.value.root);
  1677. if (compiler.invalidateTypeCache) options.value.devServer?.watcher.on("unlink", (file) => {
  1678. compiler.invalidateTypeCache(file);
  1679. });
  1680. },
  1681. resolveId: {
  1682. filter: { id: [exactRegex(EXPORT_HELPER_ID), /[?&]vue\b/] },
  1683. handler(id) {
  1684. if (id === "\0plugin-vue:export-helper") return id;
  1685. if (parseVueRequest(id).query.vue) return id;
  1686. }
  1687. },
  1688. load: {
  1689. filter: { id: [exactRegex(EXPORT_HELPER_ID), /[?&]vue\b/] },
  1690. handler(id, opt) {
  1691. if (id === "\0plugin-vue:export-helper") return helperCode;
  1692. const ssr = opt?.ssr === true;
  1693. const { filename, query } = parseVueRequest(id);
  1694. if (query.vue) {
  1695. if (query.src) return fs.readFileSync(filename, "utf-8");
  1696. const descriptor = getDescriptor(filename, options.value);
  1697. let block;
  1698. if (query.type === "script") block = resolveScript(descriptor, options.value, ssr, customElementFilter.value(filename));
  1699. else if (query.type === "template") block = descriptor.template;
  1700. else if (query.type === "style") block = descriptor.styles[query.index];
  1701. else if (query.index != null) block = descriptor.customBlocks[query.index];
  1702. if (block) return {
  1703. code: block.content,
  1704. map: block.map
  1705. };
  1706. }
  1707. }
  1708. },
  1709. transform: { handler(code, id, opt) {
  1710. const ssr = opt?.ssr === true;
  1711. const { filename, query } = parseVueRequest(id);
  1712. if (query.raw || query.url) return;
  1713. if (!filter.value(filename) && !query.vue) return;
  1714. if (!query.vue) return transformMain(code, filename, options.value, this, ssr, customElementFilter.value(filename));
  1715. else {
  1716. const descriptor = query.src ? getSrcDescriptor(filename, query) || getTempSrcDescriptor(filename, query) : getDescriptor(filename, options.value);
  1717. if (query.src) this.addWatchFile(filename);
  1718. if (query.type === "template") return transformTemplateAsModule(code, filename, descriptor, options.value, this, ssr, customElementFilter.value(filename));
  1719. else if (query.type === "style") return transformStyle(code, descriptor, Number(query.index || 0), options.value, this, filename);
  1720. }
  1721. } }
  1722. };
  1723. return plugin;
  1724. }
  1725. function ensureArray(value) {
  1726. return Array.isArray(value) ? value : [value];
  1727. }
  1728. function vuePluginCjs(options) {
  1729. return vuePlugin.call(this, options);
  1730. }
  1731. Object.assign(vuePluginCjs, {
  1732. default: vuePluginCjs,
  1733. parseVueRequest
  1734. });
  1735. //#endregion
  1736. export { vuePlugin as default, vuePluginCjs as "module.exports", parseVueRequest };