市场夺宝奇兵
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2067 lines
68 KiB

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