版博士V2.0程序
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.
 
 
 
 

2755 строки
78 KiB

  1. 'use strict';
  2. Object.defineProperty(exports, '__esModule', { value: true });
  3. const fs = require('node:fs');
  4. const vite = require('vite');
  5. const node_module = require('node:module');
  6. const path = require('node:path');
  7. const node_crypto = require('node:crypto');
  8. const require$$0 = require('tty');
  9. const require$$1 = require('util');
  10. function resolveCompiler(root) {
  11. const compiler = tryResolveCompiler(root) || tryResolveCompiler();
  12. if (!compiler) {
  13. throw new Error(
  14. `Failed to resolve vue/compiler-sfc.
  15. @vitejs/plugin-vue requires vue (>=3.2.25) to be present in the dependency tree.`
  16. );
  17. }
  18. return compiler;
  19. }
  20. function tryResolveCompiler(root) {
  21. const vueMeta = tryRequire("vue/package.json", root);
  22. if (vueMeta && vueMeta.version.split(".")[0] >= 3) {
  23. return tryRequire("vue/compiler-sfc", root);
  24. }
  25. }
  26. const _require = node_module.createRequire((typeof document === 'undefined' ? new (require('u' + 'rl').URL)('file:' + __filename).href : (document.currentScript && document.currentScript.src || new URL('index.cjs', document.baseURI).href)));
  27. function tryRequire(id, from) {
  28. try {
  29. return from ? _require(_require.resolve(id, { paths: [from] })) : _require(id);
  30. } catch (e) {
  31. }
  32. }
  33. function parseVueRequest(id) {
  34. const [filename, rawQuery] = id.split(`?`, 2);
  35. const query = Object.fromEntries(new URLSearchParams(rawQuery));
  36. if (query.vue != null) {
  37. query.vue = true;
  38. }
  39. if (query.index != null) {
  40. query.index = Number(query.index);
  41. }
  42. if (query.raw != null) {
  43. query.raw = true;
  44. }
  45. if (query.url != null) {
  46. query.url = true;
  47. }
  48. if (query.scoped != null) {
  49. query.scoped = true;
  50. }
  51. return {
  52. filename,
  53. query
  54. };
  55. }
  56. function slash(path) {
  57. const isExtendedLengthPath = /^\\\\\?\\/.test(path);
  58. if (isExtendedLengthPath) {
  59. return path;
  60. }
  61. return path.replace(/\\/g, '/');
  62. }
  63. const cache = /* @__PURE__ */ new Map();
  64. const prevCache = /* @__PURE__ */ new Map();
  65. function createDescriptor(filename, source, { root, isProduction, sourceMap, compiler }) {
  66. const { descriptor, errors } = compiler.parse(source, {
  67. filename,
  68. sourceMap
  69. });
  70. const normalizedPath = slash(path.normalize(path.relative(root, filename)));
  71. descriptor.id = getHash(normalizedPath + (isProduction ? source : ""));
  72. cache.set(filename, descriptor);
  73. return { descriptor, errors };
  74. }
  75. function getPrevDescriptor(filename) {
  76. return prevCache.get(filename);
  77. }
  78. function setPrevDescriptor(filename, entry) {
  79. prevCache.set(filename, entry);
  80. }
  81. function getDescriptor(filename, options, createIfNotFound = true) {
  82. if (cache.has(filename)) {
  83. return cache.get(filename);
  84. }
  85. if (createIfNotFound) {
  86. const { descriptor, errors } = createDescriptor(
  87. filename,
  88. fs.readFileSync(filename, "utf-8"),
  89. options
  90. );
  91. if (errors.length) {
  92. throw errors[0];
  93. }
  94. return descriptor;
  95. }
  96. }
  97. function getSrcDescriptor(filename, query) {
  98. if (query.scoped) {
  99. return cache.get(`${filename}?src=${query.src}`);
  100. }
  101. return cache.get(filename);
  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 node_crypto.createHash("sha256").update(text).digest("hex").substring(0, 8);
  112. }
  113. function createRollupError(id, error) {
  114. const { message, name, stack } = error;
  115. const rollupError = {
  116. id,
  117. plugin: "vue",
  118. message,
  119. name,
  120. stack
  121. };
  122. if ("code" in error && error.loc) {
  123. rollupError.loc = {
  124. file: id,
  125. line: error.loc.start.line,
  126. column: error.loc.start.column
  127. };
  128. }
  129. return rollupError;
  130. }
  131. async function transformTemplateAsModule(code, descriptor, options, pluginContext, ssr) {
  132. const result = compile(code, descriptor, options, pluginContext, ssr);
  133. let returnCode = result.code;
  134. if (options.devServer && options.devServer.config.server.hmr !== false && !ssr && !options.isProduction) {
  135. returnCode += `
  136. import.meta.hot.accept(({ render }) => {
  137. __VUE_HMR_RUNTIME__.rerender(${JSON.stringify(descriptor.id)}, render)
  138. })`;
  139. }
  140. return {
  141. code: returnCode,
  142. map: result.map
  143. };
  144. }
  145. function transformTemplateInMain(code, descriptor, options, pluginContext, ssr) {
  146. const result = compile(code, descriptor, options, pluginContext, ssr);
  147. return {
  148. ...result,
  149. code: result.code.replace(
  150. /\nexport (function|const) (render|ssrRender)/,
  151. "\n$1 _sfc_$2"
  152. )
  153. };
  154. }
  155. function compile(code, descriptor, options, pluginContext, ssr) {
  156. const filename = descriptor.filename;
  157. const result = options.compiler.compileTemplate({
  158. ...resolveTemplateCompilerOptions(descriptor, options, ssr),
  159. source: code
  160. });
  161. if (result.errors.length) {
  162. result.errors.forEach(
  163. (error) => pluginContext.error(
  164. typeof error === "string" ? { id: filename, message: error } : createRollupError(filename, error)
  165. )
  166. );
  167. }
  168. if (result.tips.length) {
  169. result.tips.forEach(
  170. (tip) => pluginContext.warn({
  171. id: filename,
  172. message: tip
  173. })
  174. );
  175. }
  176. return result;
  177. }
  178. function resolveTemplateCompilerOptions(descriptor, options, ssr) {
  179. const block = descriptor.template;
  180. if (!block) {
  181. return;
  182. }
  183. const resolvedScript = getResolvedScript(descriptor, ssr);
  184. const hasScoped = descriptor.styles.some((s) => s.scoped);
  185. const { id, filename, cssVars } = descriptor;
  186. let transformAssetUrls = options.template?.transformAssetUrls;
  187. let assetUrlOptions;
  188. if (options.devServer) {
  189. if (filename.startsWith(options.root)) {
  190. const devBase = options.devServer.config.base;
  191. assetUrlOptions = {
  192. base: (options.devServer.config.server?.origin ?? "") + devBase + slash(path.relative(options.root, path.dirname(filename)))
  193. };
  194. }
  195. } else if (transformAssetUrls !== false) {
  196. assetUrlOptions = {
  197. includeAbsolute: true
  198. };
  199. }
  200. if (transformAssetUrls && typeof transformAssetUrls === "object") {
  201. if (Object.values(transformAssetUrls).some((val) => Array.isArray(val))) {
  202. transformAssetUrls = {
  203. ...assetUrlOptions,
  204. tags: transformAssetUrls
  205. };
  206. } else {
  207. transformAssetUrls = { ...assetUrlOptions, ...transformAssetUrls };
  208. }
  209. } else {
  210. transformAssetUrls = assetUrlOptions;
  211. }
  212. let preprocessOptions = block.lang && options.template?.preprocessOptions;
  213. if (block.lang === "pug") {
  214. preprocessOptions = {
  215. doctype: "html",
  216. ...preprocessOptions
  217. };
  218. }
  219. const expressionPlugins = options.template?.compilerOptions?.expressionPlugins || [];
  220. const lang = descriptor.scriptSetup?.lang || descriptor.script?.lang;
  221. if (lang && /tsx?$/.test(lang) && !expressionPlugins.includes("typescript")) {
  222. expressionPlugins.push("typescript");
  223. }
  224. return {
  225. ...options.template,
  226. id,
  227. filename,
  228. scoped: hasScoped,
  229. slotted: descriptor.slotted,
  230. isProd: options.isProduction,
  231. inMap: block.src ? void 0 : block.map,
  232. ssr,
  233. ssrCssVars: cssVars,
  234. transformAssetUrls,
  235. preprocessLang: block.lang,
  236. preprocessOptions,
  237. compilerOptions: {
  238. ...options.template?.compilerOptions,
  239. scopeId: hasScoped ? `data-v-${id}` : void 0,
  240. bindingMetadata: resolvedScript ? resolvedScript.bindings : void 0,
  241. expressionPlugins,
  242. sourceMap: options.sourceMap
  243. }
  244. };
  245. }
  246. const clientCache = /* @__PURE__ */ new WeakMap();
  247. const ssrCache = /* @__PURE__ */ new WeakMap();
  248. function getResolvedScript(descriptor, ssr) {
  249. return (ssr ? ssrCache : clientCache).get(descriptor);
  250. }
  251. function setResolvedScript(descriptor, script, ssr) {
  252. (ssr ? ssrCache : clientCache).set(descriptor, script);
  253. }
  254. function isUseInlineTemplate(descriptor, isProd) {
  255. return isProd && !!descriptor.scriptSetup && !descriptor.template?.src;
  256. }
  257. function resolveScript(descriptor, options, ssr) {
  258. if (!descriptor.script && !descriptor.scriptSetup) {
  259. return null;
  260. }
  261. const cacheToUse = ssr ? ssrCache : clientCache;
  262. const cached = cacheToUse.get(descriptor);
  263. if (cached) {
  264. return cached;
  265. }
  266. let resolved = null;
  267. resolved = options.compiler.compileScript(descriptor, {
  268. ...options.script,
  269. id: descriptor.id,
  270. isProd: options.isProduction,
  271. inlineTemplate: isUseInlineTemplate(descriptor, !options.devServer),
  272. reactivityTransform: options.reactivityTransform !== false,
  273. templateOptions: resolveTemplateCompilerOptions(descriptor, options, ssr),
  274. sourceMap: options.sourceMap
  275. });
  276. cacheToUse.set(descriptor, resolved);
  277. return resolved;
  278. }
  279. const comma = ','.charCodeAt(0);
  280. const semicolon = ';'.charCodeAt(0);
  281. const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
  282. const intToChar = new Uint8Array(64); // 64 possible chars.
  283. const charToInt = new Uint8Array(128); // z is 122 in ASCII
  284. for (let i = 0; i < chars.length; i++) {
  285. const c = chars.charCodeAt(i);
  286. intToChar[i] = c;
  287. charToInt[c] = i;
  288. }
  289. // Provide a fallback for older environments.
  290. const td = typeof TextDecoder !== 'undefined'
  291. ? /* #__PURE__ */ new TextDecoder()
  292. : typeof Buffer !== 'undefined'
  293. ? {
  294. decode(buf) {
  295. const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength);
  296. return out.toString();
  297. },
  298. }
  299. : {
  300. decode(buf) {
  301. let out = '';
  302. for (let i = 0; i < buf.length; i++) {
  303. out += String.fromCharCode(buf[i]);
  304. }
  305. return out;
  306. },
  307. };
  308. function decode(mappings) {
  309. const state = new Int32Array(5);
  310. const decoded = [];
  311. let index = 0;
  312. do {
  313. const semi = indexOf(mappings, index);
  314. const line = [];
  315. let sorted = true;
  316. let lastCol = 0;
  317. state[0] = 0;
  318. for (let i = index; i < semi; i++) {
  319. let seg;
  320. i = decodeInteger(mappings, i, state, 0); // genColumn
  321. const col = state[0];
  322. if (col < lastCol)
  323. sorted = false;
  324. lastCol = col;
  325. if (hasMoreVlq(mappings, i, semi)) {
  326. i = decodeInteger(mappings, i, state, 1); // sourcesIndex
  327. i = decodeInteger(mappings, i, state, 2); // sourceLine
  328. i = decodeInteger(mappings, i, state, 3); // sourceColumn
  329. if (hasMoreVlq(mappings, i, semi)) {
  330. i = decodeInteger(mappings, i, state, 4); // namesIndex
  331. seg = [col, state[1], state[2], state[3], state[4]];
  332. }
  333. else {
  334. seg = [col, state[1], state[2], state[3]];
  335. }
  336. }
  337. else {
  338. seg = [col];
  339. }
  340. line.push(seg);
  341. }
  342. if (!sorted)
  343. sort(line);
  344. decoded.push(line);
  345. index = semi + 1;
  346. } while (index <= mappings.length);
  347. return decoded;
  348. }
  349. function indexOf(mappings, index) {
  350. const idx = mappings.indexOf(';', index);
  351. return idx === -1 ? mappings.length : idx;
  352. }
  353. function decodeInteger(mappings, pos, state, j) {
  354. let value = 0;
  355. let shift = 0;
  356. let integer = 0;
  357. do {
  358. const c = mappings.charCodeAt(pos++);
  359. integer = charToInt[c];
  360. value |= (integer & 31) << shift;
  361. shift += 5;
  362. } while (integer & 32);
  363. const shouldNegate = value & 1;
  364. value >>>= 1;
  365. if (shouldNegate) {
  366. value = -0x80000000 | -value;
  367. }
  368. state[j] += value;
  369. return pos;
  370. }
  371. function hasMoreVlq(mappings, i, length) {
  372. if (i >= length)
  373. return false;
  374. return mappings.charCodeAt(i) !== comma;
  375. }
  376. function sort(line) {
  377. line.sort(sortComparator$1);
  378. }
  379. function sortComparator$1(a, b) {
  380. return a[0] - b[0];
  381. }
  382. function encode(decoded) {
  383. const state = new Int32Array(5);
  384. const bufLength = 1024 * 16;
  385. const subLength = bufLength - 36;
  386. const buf = new Uint8Array(bufLength);
  387. const sub = buf.subarray(0, subLength);
  388. let pos = 0;
  389. let out = '';
  390. for (let i = 0; i < decoded.length; i++) {
  391. const line = decoded[i];
  392. if (i > 0) {
  393. if (pos === bufLength) {
  394. out += td.decode(buf);
  395. pos = 0;
  396. }
  397. buf[pos++] = semicolon;
  398. }
  399. if (line.length === 0)
  400. continue;
  401. state[0] = 0;
  402. for (let j = 0; j < line.length; j++) {
  403. const segment = line[j];
  404. // We can push up to 5 ints, each int can take at most 7 chars, and we
  405. // may push a comma.
  406. if (pos > subLength) {
  407. out += td.decode(sub);
  408. buf.copyWithin(0, subLength, pos);
  409. pos -= subLength;
  410. }
  411. if (j > 0)
  412. buf[pos++] = comma;
  413. pos = encodeInteger(buf, pos, state, segment, 0); // genColumn
  414. if (segment.length === 1)
  415. continue;
  416. pos = encodeInteger(buf, pos, state, segment, 1); // sourcesIndex
  417. pos = encodeInteger(buf, pos, state, segment, 2); // sourceLine
  418. pos = encodeInteger(buf, pos, state, segment, 3); // sourceColumn
  419. if (segment.length === 4)
  420. continue;
  421. pos = encodeInteger(buf, pos, state, segment, 4); // namesIndex
  422. }
  423. }
  424. return out + td.decode(buf.subarray(0, pos));
  425. }
  426. function encodeInteger(buf, pos, state, segment, j) {
  427. const next = segment[j];
  428. let num = next - state[j];
  429. state[j] = next;
  430. num = num < 0 ? (-num << 1) | 1 : num << 1;
  431. do {
  432. let clamped = num & 0b011111;
  433. num >>>= 5;
  434. if (num > 0)
  435. clamped |= 0b100000;
  436. buf[pos++] = intToChar[clamped];
  437. } while (num > 0);
  438. return pos;
  439. }
  440. // Matches the scheme of a URL, eg "http://"
  441. const schemeRegex = /^[\w+.-]+:\/\//;
  442. /**
  443. * Matches the parts of a URL:
  444. * 1. Scheme, including ":", guaranteed.
  445. * 2. User/password, including "@", optional.
  446. * 3. Host, guaranteed.
  447. * 4. Port, including ":", optional.
  448. * 5. Path, including "/", optional.
  449. * 6. Query, including "?", optional.
  450. * 7. Hash, including "#", optional.
  451. */
  452. const urlRegex = /^([\w+.-]+:)\/\/([^@/#?]*@)?([^:/#?]*)(:\d+)?(\/[^#?]*)?(\?[^#]*)?(#.*)?/;
  453. /**
  454. * File URLs are weird. They dont' need the regular `//` in the scheme, they may or may not start
  455. * with a leading `/`, they can have a domain (but only if they don't start with a Windows drive).
  456. *
  457. * 1. Host, optional.
  458. * 2. Path, which may include "/", guaranteed.
  459. * 3. Query, including "?", optional.
  460. * 4. Hash, including "#", optional.
  461. */
  462. const fileRegex = /^file:(?:\/\/((?![a-z]:)[^/#?]*)?)?(\/?[^#?]*)(\?[^#]*)?(#.*)?/i;
  463. var UrlType;
  464. (function (UrlType) {
  465. UrlType[UrlType["Empty"] = 1] = "Empty";
  466. UrlType[UrlType["Hash"] = 2] = "Hash";
  467. UrlType[UrlType["Query"] = 3] = "Query";
  468. UrlType[UrlType["RelativePath"] = 4] = "RelativePath";
  469. UrlType[UrlType["AbsolutePath"] = 5] = "AbsolutePath";
  470. UrlType[UrlType["SchemeRelative"] = 6] = "SchemeRelative";
  471. UrlType[UrlType["Absolute"] = 7] = "Absolute";
  472. })(UrlType || (UrlType = {}));
  473. function isAbsoluteUrl(input) {
  474. return schemeRegex.test(input);
  475. }
  476. function isSchemeRelativeUrl(input) {
  477. return input.startsWith('//');
  478. }
  479. function isAbsolutePath(input) {
  480. return input.startsWith('/');
  481. }
  482. function isFileUrl(input) {
  483. return input.startsWith('file:');
  484. }
  485. function isRelative(input) {
  486. return /^[.?#]/.test(input);
  487. }
  488. function parseAbsoluteUrl(input) {
  489. const match = urlRegex.exec(input);
  490. return makeUrl(match[1], match[2] || '', match[3], match[4] || '', match[5] || '/', match[6] || '', match[7] || '');
  491. }
  492. function parseFileUrl(input) {
  493. const match = fileRegex.exec(input);
  494. const path = match[2];
  495. return makeUrl('file:', '', match[1] || '', '', isAbsolutePath(path) ? path : '/' + path, match[3] || '', match[4] || '');
  496. }
  497. function makeUrl(scheme, user, host, port, path, query, hash) {
  498. return {
  499. scheme,
  500. user,
  501. host,
  502. port,
  503. path,
  504. query,
  505. hash,
  506. type: UrlType.Absolute,
  507. };
  508. }
  509. function parseUrl(input) {
  510. if (isSchemeRelativeUrl(input)) {
  511. const url = parseAbsoluteUrl('http:' + input);
  512. url.scheme = '';
  513. url.type = UrlType.SchemeRelative;
  514. return url;
  515. }
  516. if (isAbsolutePath(input)) {
  517. const url = parseAbsoluteUrl('http://foo.com' + input);
  518. url.scheme = '';
  519. url.host = '';
  520. url.type = UrlType.AbsolutePath;
  521. return url;
  522. }
  523. if (isFileUrl(input))
  524. return parseFileUrl(input);
  525. if (isAbsoluteUrl(input))
  526. return parseAbsoluteUrl(input);
  527. const url = parseAbsoluteUrl('http://foo.com/' + input);
  528. url.scheme = '';
  529. url.host = '';
  530. url.type = input
  531. ? input.startsWith('?')
  532. ? UrlType.Query
  533. : input.startsWith('#')
  534. ? UrlType.Hash
  535. : UrlType.RelativePath
  536. : UrlType.Empty;
  537. return url;
  538. }
  539. function stripPathFilename(path) {
  540. // If a path ends with a parent directory "..", then it's a relative path with excess parent
  541. // paths. It's not a file, so we can't strip it.
  542. if (path.endsWith('/..'))
  543. return path;
  544. const index = path.lastIndexOf('/');
  545. return path.slice(0, index + 1);
  546. }
  547. function mergePaths(url, base) {
  548. normalizePath(base, base.type);
  549. // If the path is just a "/", then it was an empty path to begin with (remember, we're a relative
  550. // path).
  551. if (url.path === '/') {
  552. url.path = base.path;
  553. }
  554. else {
  555. // Resolution happens relative to the base path's directory, not the file.
  556. url.path = stripPathFilename(base.path) + url.path;
  557. }
  558. }
  559. /**
  560. * The path can have empty directories "//", unneeded parents "foo/..", or current directory
  561. * "foo/.". We need to normalize to a standard representation.
  562. */
  563. function normalizePath(url, type) {
  564. const rel = type <= UrlType.RelativePath;
  565. const pieces = url.path.split('/');
  566. // We need to preserve the first piece always, so that we output a leading slash. The item at
  567. // pieces[0] is an empty string.
  568. let pointer = 1;
  569. // Positive is the number of real directories we've output, used for popping a parent directory.
  570. // Eg, "foo/bar/.." will have a positive 2, and we can decrement to be left with just "foo".
  571. let positive = 0;
  572. // We need to keep a trailing slash if we encounter an empty directory (eg, splitting "foo/" will
  573. // generate `["foo", ""]` pieces). And, if we pop a parent directory. But once we encounter a
  574. // real directory, we won't need to append, unless the other conditions happen again.
  575. let addTrailingSlash = false;
  576. for (let i = 1; i < pieces.length; i++) {
  577. const piece = pieces[i];
  578. // An empty directory, could be a trailing slash, or just a double "//" in the path.
  579. if (!piece) {
  580. addTrailingSlash = true;
  581. continue;
  582. }
  583. // If we encounter a real directory, then we don't need to append anymore.
  584. addTrailingSlash = false;
  585. // A current directory, which we can always drop.
  586. if (piece === '.')
  587. continue;
  588. // A parent directory, we need to see if there are any real directories we can pop. Else, we
  589. // have an excess of parents, and we'll need to keep the "..".
  590. if (piece === '..') {
  591. if (positive) {
  592. addTrailingSlash = true;
  593. positive--;
  594. pointer--;
  595. }
  596. else if (rel) {
  597. // If we're in a relativePath, then we need to keep the excess parents. Else, in an absolute
  598. // URL, protocol relative URL, or an absolute path, we don't need to keep excess.
  599. pieces[pointer++] = piece;
  600. }
  601. continue;
  602. }
  603. // We've encountered a real directory. Move it to the next insertion pointer, which accounts for
  604. // any popped or dropped directories.
  605. pieces[pointer++] = piece;
  606. positive++;
  607. }
  608. let path = '';
  609. for (let i = 1; i < pointer; i++) {
  610. path += '/' + pieces[i];
  611. }
  612. if (!path || (addTrailingSlash && !path.endsWith('/..'))) {
  613. path += '/';
  614. }
  615. url.path = path;
  616. }
  617. /**
  618. * Attempts to resolve `input` URL/path relative to `base`.
  619. */
  620. function resolve$1(input, base) {
  621. if (!input && !base)
  622. return '';
  623. const url = parseUrl(input);
  624. let inputType = url.type;
  625. if (base && inputType !== UrlType.Absolute) {
  626. const baseUrl = parseUrl(base);
  627. const baseType = baseUrl.type;
  628. switch (inputType) {
  629. case UrlType.Empty:
  630. url.hash = baseUrl.hash;
  631. // fall through
  632. case UrlType.Hash:
  633. url.query = baseUrl.query;
  634. // fall through
  635. case UrlType.Query:
  636. case UrlType.RelativePath:
  637. mergePaths(url, baseUrl);
  638. // fall through
  639. case UrlType.AbsolutePath:
  640. // The host, user, and port are joined, you can't copy one without the others.
  641. url.user = baseUrl.user;
  642. url.host = baseUrl.host;
  643. url.port = baseUrl.port;
  644. // fall through
  645. case UrlType.SchemeRelative:
  646. // The input doesn't have a schema at least, so we need to copy at least that over.
  647. url.scheme = baseUrl.scheme;
  648. }
  649. if (baseType > inputType)
  650. inputType = baseType;
  651. }
  652. normalizePath(url, inputType);
  653. const queryHash = url.query + url.hash;
  654. switch (inputType) {
  655. // This is impossible, because of the empty checks at the start of the function.
  656. // case UrlType.Empty:
  657. case UrlType.Hash:
  658. case UrlType.Query:
  659. return queryHash;
  660. case UrlType.RelativePath: {
  661. // The first char is always a "/", and we need it to be relative.
  662. const path = url.path.slice(1);
  663. if (!path)
  664. return queryHash || '.';
  665. if (isRelative(base || input) && !isRelative(path)) {
  666. // If base started with a leading ".", or there is no base and input started with a ".",
  667. // then we need to ensure that the relative path starts with a ".". We don't know if
  668. // relative starts with a "..", though, so check before prepending.
  669. return './' + path + queryHash;
  670. }
  671. return path + queryHash;
  672. }
  673. case UrlType.AbsolutePath:
  674. return url.path + queryHash;
  675. default:
  676. return url.scheme + '//' + url.user + url.host + url.port + url.path + queryHash;
  677. }
  678. }
  679. function resolve(input, base) {
  680. // The base is always treated as a directory, if it's not empty.
  681. // https://github.com/mozilla/source-map/blob/8cb3ee57/lib/util.js#L327
  682. // https://github.com/chromium/chromium/blob/da4adbb3/third_party/blink/renderer/devtools/front_end/sdk/SourceMap.js#L400-L401
  683. if (base && !base.endsWith('/'))
  684. base += '/';
  685. return resolve$1(input, base);
  686. }
  687. /**
  688. * Removes everything after the last "/", but leaves the slash.
  689. */
  690. function stripFilename(path) {
  691. if (!path)
  692. return '';
  693. const index = path.lastIndexOf('/');
  694. return path.slice(0, index + 1);
  695. }
  696. const COLUMN$1 = 0;
  697. function maybeSort(mappings, owned) {
  698. const unsortedIndex = nextUnsortedSegmentLine(mappings, 0);
  699. if (unsortedIndex === mappings.length)
  700. return mappings;
  701. // If we own the array (meaning we parsed it from JSON), then we're free to directly mutate it. If
  702. // not, we do not want to modify the consumer's input array.
  703. if (!owned)
  704. mappings = mappings.slice();
  705. for (let i = unsortedIndex; i < mappings.length; i = nextUnsortedSegmentLine(mappings, i + 1)) {
  706. mappings[i] = sortSegments(mappings[i], owned);
  707. }
  708. return mappings;
  709. }
  710. function nextUnsortedSegmentLine(mappings, start) {
  711. for (let i = start; i < mappings.length; i++) {
  712. if (!isSorted(mappings[i]))
  713. return i;
  714. }
  715. return mappings.length;
  716. }
  717. function isSorted(line) {
  718. for (let j = 1; j < line.length; j++) {
  719. if (line[j][COLUMN$1] < line[j - 1][COLUMN$1]) {
  720. return false;
  721. }
  722. }
  723. return true;
  724. }
  725. function sortSegments(line, owned) {
  726. if (!owned)
  727. line = line.slice();
  728. return line.sort(sortComparator);
  729. }
  730. function sortComparator(a, b) {
  731. return a[COLUMN$1] - b[COLUMN$1];
  732. }
  733. function memoizedState() {
  734. return {
  735. lastKey: -1,
  736. lastNeedle: -1,
  737. lastIndex: -1,
  738. };
  739. }
  740. /**
  741. * Returns the decoded (array of lines of segments) form of the SourceMap's mappings field.
  742. */
  743. let decodedMappings;
  744. /**
  745. * Iterates each mapping in generated position order.
  746. */
  747. let eachMapping;
  748. class TraceMap {
  749. constructor(map, mapUrl) {
  750. const isString = typeof map === 'string';
  751. if (!isString && map._decodedMemo)
  752. return map;
  753. const parsed = (isString ? JSON.parse(map) : map);
  754. const { version, file, names, sourceRoot, sources, sourcesContent } = parsed;
  755. this.version = version;
  756. this.file = file;
  757. this.names = names;
  758. this.sourceRoot = sourceRoot;
  759. this.sources = sources;
  760. this.sourcesContent = sourcesContent;
  761. const from = resolve(sourceRoot || '', stripFilename(mapUrl));
  762. this.resolvedSources = sources.map((s) => resolve(s || '', from));
  763. const { mappings } = parsed;
  764. if (typeof mappings === 'string') {
  765. this._encoded = mappings;
  766. this._decoded = undefined;
  767. }
  768. else {
  769. this._encoded = undefined;
  770. this._decoded = maybeSort(mappings, isString);
  771. }
  772. this._decodedMemo = memoizedState();
  773. this._bySources = undefined;
  774. this._bySourceMemos = undefined;
  775. }
  776. }
  777. (() => {
  778. decodedMappings = (map) => {
  779. return (map._decoded || (map._decoded = decode(map._encoded)));
  780. };
  781. eachMapping = (map, cb) => {
  782. const decoded = decodedMappings(map);
  783. const { names, resolvedSources } = map;
  784. for (let i = 0; i < decoded.length; i++) {
  785. const line = decoded[i];
  786. for (let j = 0; j < line.length; j++) {
  787. const seg = line[j];
  788. const generatedLine = i + 1;
  789. const generatedColumn = seg[0];
  790. let source = null;
  791. let originalLine = null;
  792. let originalColumn = null;
  793. let name = null;
  794. if (seg.length !== 1) {
  795. source = resolvedSources[seg[1]];
  796. originalLine = seg[2] + 1;
  797. originalColumn = seg[3];
  798. }
  799. if (seg.length === 5)
  800. name = names[seg[4]];
  801. cb({
  802. generatedLine,
  803. generatedColumn,
  804. source,
  805. originalLine,
  806. originalColumn,
  807. name,
  808. });
  809. }
  810. }
  811. };
  812. })();
  813. /**
  814. * Gets the index associated with `key` in the backing array, if it is already present.
  815. */
  816. let get;
  817. /**
  818. * Puts `key` into the backing array, if it is not already present. Returns
  819. * the index of the `key` in the backing array.
  820. */
  821. let put;
  822. /**
  823. * SetArray acts like a `Set` (allowing only one occurrence of a string `key`), but provides the
  824. * index of the `key` in the backing array.
  825. *
  826. * This is designed to allow synchronizing a second array with the contents of the backing array,
  827. * like how in a sourcemap `sourcesContent[i]` is the source content associated with `source[i]`,
  828. * and there are never duplicates.
  829. */
  830. class SetArray {
  831. constructor() {
  832. this._indexes = { __proto__: null };
  833. this.array = [];
  834. }
  835. }
  836. (() => {
  837. get = (strarr, key) => strarr._indexes[key];
  838. put = (strarr, key) => {
  839. // The key may or may not be present. If it is present, it's a number.
  840. const index = get(strarr, key);
  841. if (index !== undefined)
  842. return index;
  843. const { array, _indexes: indexes } = strarr;
  844. return (indexes[key] = array.push(key) - 1);
  845. };
  846. })();
  847. const COLUMN = 0;
  848. const SOURCES_INDEX = 1;
  849. const SOURCE_LINE = 2;
  850. const SOURCE_COLUMN = 3;
  851. const NAMES_INDEX = 4;
  852. const NO_NAME = -1;
  853. /**
  854. * A high-level API to associate a generated position with an original source position. Line is
  855. * 1-based, but column is 0-based, due to legacy behavior in `source-map` library.
  856. */
  857. let addMapping;
  858. /**
  859. * Returns a sourcemap object (with decoded mappings) suitable for passing to a library that expects
  860. * a sourcemap, or to JSON.stringify.
  861. */
  862. let toDecodedMap;
  863. /**
  864. * Returns a sourcemap object (with encoded mappings) suitable for passing to a library that expects
  865. * a sourcemap, or to JSON.stringify.
  866. */
  867. let toEncodedMap;
  868. /**
  869. * Constructs a new GenMapping, using the already present mappings of the input.
  870. */
  871. let fromMap;
  872. // This split declaration is only so that terser can elminiate the static initialization block.
  873. let addSegmentInternal;
  874. /**
  875. * Provides the state to generate a sourcemap.
  876. */
  877. class GenMapping {
  878. constructor({ file, sourceRoot } = {}) {
  879. this._names = new SetArray();
  880. this._sources = new SetArray();
  881. this._sourcesContent = [];
  882. this._mappings = [];
  883. this.file = file;
  884. this.sourceRoot = sourceRoot;
  885. }
  886. }
  887. (() => {
  888. addMapping = (map, mapping) => {
  889. return addMappingInternal(false, map, mapping);
  890. };
  891. toDecodedMap = (map) => {
  892. const { file, sourceRoot, _mappings: mappings, _sources: sources, _sourcesContent: sourcesContent, _names: names, } = map;
  893. removeEmptyFinalLines(mappings);
  894. return {
  895. version: 3,
  896. file: file || undefined,
  897. names: names.array,
  898. sourceRoot: sourceRoot || undefined,
  899. sources: sources.array,
  900. sourcesContent,
  901. mappings,
  902. };
  903. };
  904. toEncodedMap = (map) => {
  905. const decoded = toDecodedMap(map);
  906. return Object.assign(Object.assign({}, decoded), { mappings: encode(decoded.mappings) });
  907. };
  908. fromMap = (input) => {
  909. const map = new TraceMap(input);
  910. const gen = new GenMapping({ file: map.file, sourceRoot: map.sourceRoot });
  911. putAll(gen._names, map.names);
  912. putAll(gen._sources, map.sources);
  913. gen._sourcesContent = map.sourcesContent || map.sources.map(() => null);
  914. gen._mappings = decodedMappings(map);
  915. return gen;
  916. };
  917. // Internal helpers
  918. addSegmentInternal = (skipable, map, genLine, genColumn, source, sourceLine, sourceColumn, name, content) => {
  919. const { _mappings: mappings, _sources: sources, _sourcesContent: sourcesContent, _names: names, } = map;
  920. const line = getLine(mappings, genLine);
  921. const index = getColumnIndex(line, genColumn);
  922. if (!source) {
  923. if (skipable && skipSourceless(line, index))
  924. return;
  925. return insert(line, index, [genColumn]);
  926. }
  927. const sourcesIndex = put(sources, source);
  928. const namesIndex = name ? put(names, name) : NO_NAME;
  929. if (sourcesIndex === sourcesContent.length)
  930. sourcesContent[sourcesIndex] = content !== null && content !== void 0 ? content : null;
  931. if (skipable && skipSource(line, index, sourcesIndex, sourceLine, sourceColumn, namesIndex)) {
  932. return;
  933. }
  934. return insert(line, index, name
  935. ? [genColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex]
  936. : [genColumn, sourcesIndex, sourceLine, sourceColumn]);
  937. };
  938. })();
  939. function getLine(mappings, index) {
  940. for (let i = mappings.length; i <= index; i++) {
  941. mappings[i] = [];
  942. }
  943. return mappings[index];
  944. }
  945. function getColumnIndex(line, genColumn) {
  946. let index = line.length;
  947. for (let i = index - 1; i >= 0; index = i--) {
  948. const current = line[i];
  949. if (genColumn >= current[COLUMN])
  950. break;
  951. }
  952. return index;
  953. }
  954. function insert(array, index, value) {
  955. for (let i = array.length; i > index; i--) {
  956. array[i] = array[i - 1];
  957. }
  958. array[index] = value;
  959. }
  960. function removeEmptyFinalLines(mappings) {
  961. const { length } = mappings;
  962. let len = length;
  963. for (let i = len - 1; i >= 0; len = i, i--) {
  964. if (mappings[i].length > 0)
  965. break;
  966. }
  967. if (len < length)
  968. mappings.length = len;
  969. }
  970. function putAll(strarr, array) {
  971. for (let i = 0; i < array.length; i++)
  972. put(strarr, array[i]);
  973. }
  974. function skipSourceless(line, index) {
  975. // The start of a line is already sourceless, so adding a sourceless segment to the beginning
  976. // doesn't generate any useful information.
  977. if (index === 0)
  978. return true;
  979. const prev = line[index - 1];
  980. // If the previous segment is also sourceless, then adding another sourceless segment doesn't
  981. // genrate any new information. Else, this segment will end the source/named segment and point to
  982. // a sourceless position, which is useful.
  983. return prev.length === 1;
  984. }
  985. function skipSource(line, index, sourcesIndex, sourceLine, sourceColumn, namesIndex) {
  986. // A source/named segment at the start of a line gives position at that genColumn
  987. if (index === 0)
  988. return false;
  989. const prev = line[index - 1];
  990. // If the previous segment is sourceless, then we're transitioning to a source.
  991. if (prev.length === 1)
  992. return false;
  993. // If the previous segment maps to the exact same source position, then this segment doesn't
  994. // provide any new position information.
  995. return (sourcesIndex === prev[SOURCES_INDEX] &&
  996. sourceLine === prev[SOURCE_LINE] &&
  997. sourceColumn === prev[SOURCE_COLUMN] &&
  998. namesIndex === (prev.length === 5 ? prev[NAMES_INDEX] : NO_NAME));
  999. }
  1000. function addMappingInternal(skipable, map, mapping) {
  1001. const { generated, source, original, name, content } = mapping;
  1002. if (!source) {
  1003. return addSegmentInternal(skipable, map, generated.line - 1, generated.column, null, null, null, null, null);
  1004. }
  1005. const s = source;
  1006. return addSegmentInternal(skipable, map, generated.line - 1, generated.column, s, original.line - 1, original.column, name, content);
  1007. }
  1008. function getDefaultExportFromCjs (x) {
  1009. return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
  1010. }
  1011. var srcExports = {};
  1012. var src = {
  1013. get exports(){ return srcExports; },
  1014. set exports(v){ srcExports = v; },
  1015. };
  1016. var browserExports = {};
  1017. var browser = {
  1018. get exports(){ return browserExports; },
  1019. set exports(v){ browserExports = v; },
  1020. };
  1021. /**
  1022. * Helpers.
  1023. */
  1024. var ms;
  1025. var hasRequiredMs;
  1026. function requireMs () {
  1027. if (hasRequiredMs) return ms;
  1028. hasRequiredMs = 1;
  1029. var s = 1000;
  1030. var m = s * 60;
  1031. var h = m * 60;
  1032. var d = h * 24;
  1033. var w = d * 7;
  1034. var y = d * 365.25;
  1035. /**
  1036. * Parse or format the given `val`.
  1037. *
  1038. * Options:
  1039. *
  1040. * - `long` verbose formatting [false]
  1041. *
  1042. * @param {String|Number} val
  1043. * @param {Object} [options]
  1044. * @throws {Error} throw an error if val is not a non-empty string or a number
  1045. * @return {String|Number}
  1046. * @api public
  1047. */
  1048. ms = function(val, options) {
  1049. options = options || {};
  1050. var type = typeof val;
  1051. if (type === 'string' && val.length > 0) {
  1052. return parse(val);
  1053. } else if (type === 'number' && isFinite(val)) {
  1054. return options.long ? fmtLong(val) : fmtShort(val);
  1055. }
  1056. throw new Error(
  1057. 'val is not a non-empty string or a valid number. val=' +
  1058. JSON.stringify(val)
  1059. );
  1060. };
  1061. /**
  1062. * Parse the given `str` and return milliseconds.
  1063. *
  1064. * @param {String} str
  1065. * @return {Number}
  1066. * @api private
  1067. */
  1068. function parse(str) {
  1069. str = String(str);
  1070. if (str.length > 100) {
  1071. return;
  1072. }
  1073. 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(
  1074. str
  1075. );
  1076. if (!match) {
  1077. return;
  1078. }
  1079. var n = parseFloat(match[1]);
  1080. var type = (match[2] || 'ms').toLowerCase();
  1081. switch (type) {
  1082. case 'years':
  1083. case 'year':
  1084. case 'yrs':
  1085. case 'yr':
  1086. case 'y':
  1087. return n * y;
  1088. case 'weeks':
  1089. case 'week':
  1090. case 'w':
  1091. return n * w;
  1092. case 'days':
  1093. case 'day':
  1094. case 'd':
  1095. return n * d;
  1096. case 'hours':
  1097. case 'hour':
  1098. case 'hrs':
  1099. case 'hr':
  1100. case 'h':
  1101. return n * h;
  1102. case 'minutes':
  1103. case 'minute':
  1104. case 'mins':
  1105. case 'min':
  1106. case 'm':
  1107. return n * m;
  1108. case 'seconds':
  1109. case 'second':
  1110. case 'secs':
  1111. case 'sec':
  1112. case 's':
  1113. return n * s;
  1114. case 'milliseconds':
  1115. case 'millisecond':
  1116. case 'msecs':
  1117. case 'msec':
  1118. case 'ms':
  1119. return n;
  1120. default:
  1121. return undefined;
  1122. }
  1123. }
  1124. /**
  1125. * Short format for `ms`.
  1126. *
  1127. * @param {Number} ms
  1128. * @return {String}
  1129. * @api private
  1130. */
  1131. function fmtShort(ms) {
  1132. var msAbs = Math.abs(ms);
  1133. if (msAbs >= d) {
  1134. return Math.round(ms / d) + 'd';
  1135. }
  1136. if (msAbs >= h) {
  1137. return Math.round(ms / h) + 'h';
  1138. }
  1139. if (msAbs >= m) {
  1140. return Math.round(ms / m) + 'm';
  1141. }
  1142. if (msAbs >= s) {
  1143. return Math.round(ms / s) + 's';
  1144. }
  1145. return ms + 'ms';
  1146. }
  1147. /**
  1148. * Long format for `ms`.
  1149. *
  1150. * @param {Number} ms
  1151. * @return {String}
  1152. * @api private
  1153. */
  1154. function fmtLong(ms) {
  1155. var msAbs = Math.abs(ms);
  1156. if (msAbs >= d) {
  1157. return plural(ms, msAbs, d, 'day');
  1158. }
  1159. if (msAbs >= h) {
  1160. return plural(ms, msAbs, h, 'hour');
  1161. }
  1162. if (msAbs >= m) {
  1163. return plural(ms, msAbs, m, 'minute');
  1164. }
  1165. if (msAbs >= s) {
  1166. return plural(ms, msAbs, s, 'second');
  1167. }
  1168. return ms + ' ms';
  1169. }
  1170. /**
  1171. * Pluralization helper.
  1172. */
  1173. function plural(ms, msAbs, n, name) {
  1174. var isPlural = msAbs >= n * 1.5;
  1175. return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');
  1176. }
  1177. return ms;
  1178. }
  1179. var common;
  1180. var hasRequiredCommon;
  1181. function requireCommon () {
  1182. if (hasRequiredCommon) return common;
  1183. hasRequiredCommon = 1;
  1184. /**
  1185. * This is the common logic for both the Node.js and web browser
  1186. * implementations of `debug()`.
  1187. */
  1188. function setup(env) {
  1189. createDebug.debug = createDebug;
  1190. createDebug.default = createDebug;
  1191. createDebug.coerce = coerce;
  1192. createDebug.disable = disable;
  1193. createDebug.enable = enable;
  1194. createDebug.enabled = enabled;
  1195. createDebug.humanize = requireMs();
  1196. createDebug.destroy = destroy;
  1197. Object.keys(env).forEach(key => {
  1198. createDebug[key] = env[key];
  1199. });
  1200. /**
  1201. * The currently active debug mode names, and names to skip.
  1202. */
  1203. createDebug.names = [];
  1204. createDebug.skips = [];
  1205. /**
  1206. * Map of special "%n" handling functions, for the debug "format" argument.
  1207. *
  1208. * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
  1209. */
  1210. createDebug.formatters = {};
  1211. /**
  1212. * Selects a color for a debug namespace
  1213. * @param {String} namespace The namespace string for the debug instance to be colored
  1214. * @return {Number|String} An ANSI color code for the given namespace
  1215. * @api private
  1216. */
  1217. function selectColor(namespace) {
  1218. let hash = 0;
  1219. for (let i = 0; i < namespace.length; i++) {
  1220. hash = ((hash << 5) - hash) + namespace.charCodeAt(i);
  1221. hash |= 0; // Convert to 32bit integer
  1222. }
  1223. return createDebug.colors[Math.abs(hash) % createDebug.colors.length];
  1224. }
  1225. createDebug.selectColor = selectColor;
  1226. /**
  1227. * Create a debugger with the given `namespace`.
  1228. *
  1229. * @param {String} namespace
  1230. * @return {Function}
  1231. * @api public
  1232. */
  1233. function createDebug(namespace) {
  1234. let prevTime;
  1235. let enableOverride = null;
  1236. let namespacesCache;
  1237. let enabledCache;
  1238. function debug(...args) {
  1239. // Disabled?
  1240. if (!debug.enabled) {
  1241. return;
  1242. }
  1243. const self = debug;
  1244. // Set `diff` timestamp
  1245. const curr = Number(new Date());
  1246. const ms = curr - (prevTime || curr);
  1247. self.diff = ms;
  1248. self.prev = prevTime;
  1249. self.curr = curr;
  1250. prevTime = curr;
  1251. args[0] = createDebug.coerce(args[0]);
  1252. if (typeof args[0] !== 'string') {
  1253. // Anything else let's inspect with %O
  1254. args.unshift('%O');
  1255. }
  1256. // Apply any `formatters` transformations
  1257. let index = 0;
  1258. args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {
  1259. // If we encounter an escaped % then don't increase the array index
  1260. if (match === '%%') {
  1261. return '%';
  1262. }
  1263. index++;
  1264. const formatter = createDebug.formatters[format];
  1265. if (typeof formatter === 'function') {
  1266. const val = args[index];
  1267. match = formatter.call(self, val);
  1268. // Now we need to remove `args[index]` since it's inlined in the `format`
  1269. args.splice(index, 1);
  1270. index--;
  1271. }
  1272. return match;
  1273. });
  1274. // Apply env-specific formatting (colors, etc.)
  1275. createDebug.formatArgs.call(self, args);
  1276. const logFn = self.log || createDebug.log;
  1277. logFn.apply(self, args);
  1278. }
  1279. debug.namespace = namespace;
  1280. debug.useColors = createDebug.useColors();
  1281. debug.color = createDebug.selectColor(namespace);
  1282. debug.extend = extend;
  1283. debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release.
  1284. Object.defineProperty(debug, 'enabled', {
  1285. enumerable: true,
  1286. configurable: false,
  1287. get: () => {
  1288. if (enableOverride !== null) {
  1289. return enableOverride;
  1290. }
  1291. if (namespacesCache !== createDebug.namespaces) {
  1292. namespacesCache = createDebug.namespaces;
  1293. enabledCache = createDebug.enabled(namespace);
  1294. }
  1295. return enabledCache;
  1296. },
  1297. set: v => {
  1298. enableOverride = v;
  1299. }
  1300. });
  1301. // Env-specific initialization logic for debug instances
  1302. if (typeof createDebug.init === 'function') {
  1303. createDebug.init(debug);
  1304. }
  1305. return debug;
  1306. }
  1307. function extend(namespace, delimiter) {
  1308. const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);
  1309. newDebug.log = this.log;
  1310. return newDebug;
  1311. }
  1312. /**
  1313. * Enables a debug mode by namespaces. This can include modes
  1314. * separated by a colon and wildcards.
  1315. *
  1316. * @param {String} namespaces
  1317. * @api public
  1318. */
  1319. function enable(namespaces) {
  1320. createDebug.save(namespaces);
  1321. createDebug.namespaces = namespaces;
  1322. createDebug.names = [];
  1323. createDebug.skips = [];
  1324. let i;
  1325. const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
  1326. const len = split.length;
  1327. for (i = 0; i < len; i++) {
  1328. if (!split[i]) {
  1329. // ignore empty strings
  1330. continue;
  1331. }
  1332. namespaces = split[i].replace(/\*/g, '.*?');
  1333. if (namespaces[0] === '-') {
  1334. createDebug.skips.push(new RegExp('^' + namespaces.slice(1) + '$'));
  1335. } else {
  1336. createDebug.names.push(new RegExp('^' + namespaces + '$'));
  1337. }
  1338. }
  1339. }
  1340. /**
  1341. * Disable debug output.
  1342. *
  1343. * @return {String} namespaces
  1344. * @api public
  1345. */
  1346. function disable() {
  1347. const namespaces = [
  1348. ...createDebug.names.map(toNamespace),
  1349. ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace)
  1350. ].join(',');
  1351. createDebug.enable('');
  1352. return namespaces;
  1353. }
  1354. /**
  1355. * Returns true if the given mode name is enabled, false otherwise.
  1356. *
  1357. * @param {String} name
  1358. * @return {Boolean}
  1359. * @api public
  1360. */
  1361. function enabled(name) {
  1362. if (name[name.length - 1] === '*') {
  1363. return true;
  1364. }
  1365. let i;
  1366. let len;
  1367. for (i = 0, len = createDebug.skips.length; i < len; i++) {
  1368. if (createDebug.skips[i].test(name)) {
  1369. return false;
  1370. }
  1371. }
  1372. for (i = 0, len = createDebug.names.length; i < len; i++) {
  1373. if (createDebug.names[i].test(name)) {
  1374. return true;
  1375. }
  1376. }
  1377. return false;
  1378. }
  1379. /**
  1380. * Convert regexp to namespace
  1381. *
  1382. * @param {RegExp} regxep
  1383. * @return {String} namespace
  1384. * @api private
  1385. */
  1386. function toNamespace(regexp) {
  1387. return regexp.toString()
  1388. .substring(2, regexp.toString().length - 2)
  1389. .replace(/\.\*\?$/, '*');
  1390. }
  1391. /**
  1392. * Coerce `val`.
  1393. *
  1394. * @param {Mixed} val
  1395. * @return {Mixed}
  1396. * @api private
  1397. */
  1398. function coerce(val) {
  1399. if (val instanceof Error) {
  1400. return val.stack || val.message;
  1401. }
  1402. return val;
  1403. }
  1404. /**
  1405. * XXX DO NOT USE. This is a temporary stub function.
  1406. * XXX It WILL be removed in the next major release.
  1407. */
  1408. function destroy() {
  1409. console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');
  1410. }
  1411. createDebug.enable(createDebug.load());
  1412. return createDebug;
  1413. }
  1414. common = setup;
  1415. return common;
  1416. }
  1417. /* eslint-env browser */
  1418. var hasRequiredBrowser;
  1419. function requireBrowser () {
  1420. if (hasRequiredBrowser) return browserExports;
  1421. hasRequiredBrowser = 1;
  1422. (function (module, exports) {
  1423. /**
  1424. * This is the web browser implementation of `debug()`.
  1425. */
  1426. exports.formatArgs = formatArgs;
  1427. exports.save = save;
  1428. exports.load = load;
  1429. exports.useColors = useColors;
  1430. exports.storage = localstorage();
  1431. exports.destroy = (() => {
  1432. let warned = false;
  1433. return () => {
  1434. if (!warned) {
  1435. warned = true;
  1436. console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');
  1437. }
  1438. };
  1439. })();
  1440. /**
  1441. * Colors.
  1442. */
  1443. exports.colors = [
  1444. '#0000CC',
  1445. '#0000FF',
  1446. '#0033CC',
  1447. '#0033FF',
  1448. '#0066CC',
  1449. '#0066FF',
  1450. '#0099CC',
  1451. '#0099FF',
  1452. '#00CC00',
  1453. '#00CC33',
  1454. '#00CC66',
  1455. '#00CC99',
  1456. '#00CCCC',
  1457. '#00CCFF',
  1458. '#3300CC',
  1459. '#3300FF',
  1460. '#3333CC',
  1461. '#3333FF',
  1462. '#3366CC',
  1463. '#3366FF',
  1464. '#3399CC',
  1465. '#3399FF',
  1466. '#33CC00',
  1467. '#33CC33',
  1468. '#33CC66',
  1469. '#33CC99',
  1470. '#33CCCC',
  1471. '#33CCFF',
  1472. '#6600CC',
  1473. '#6600FF',
  1474. '#6633CC',
  1475. '#6633FF',
  1476. '#66CC00',
  1477. '#66CC33',
  1478. '#9900CC',
  1479. '#9900FF',
  1480. '#9933CC',
  1481. '#9933FF',
  1482. '#99CC00',
  1483. '#99CC33',
  1484. '#CC0000',
  1485. '#CC0033',
  1486. '#CC0066',
  1487. '#CC0099',
  1488. '#CC00CC',
  1489. '#CC00FF',
  1490. '#CC3300',
  1491. '#CC3333',
  1492. '#CC3366',
  1493. '#CC3399',
  1494. '#CC33CC',
  1495. '#CC33FF',
  1496. '#CC6600',
  1497. '#CC6633',
  1498. '#CC9900',
  1499. '#CC9933',
  1500. '#CCCC00',
  1501. '#CCCC33',
  1502. '#FF0000',
  1503. '#FF0033',
  1504. '#FF0066',
  1505. '#FF0099',
  1506. '#FF00CC',
  1507. '#FF00FF',
  1508. '#FF3300',
  1509. '#FF3333',
  1510. '#FF3366',
  1511. '#FF3399',
  1512. '#FF33CC',
  1513. '#FF33FF',
  1514. '#FF6600',
  1515. '#FF6633',
  1516. '#FF9900',
  1517. '#FF9933',
  1518. '#FFCC00',
  1519. '#FFCC33'
  1520. ];
  1521. /**
  1522. * Currently only WebKit-based Web Inspectors, Firefox >= v31,
  1523. * and the Firebug extension (any Firefox version) are known
  1524. * to support "%c" CSS customizations.
  1525. *
  1526. * TODO: add a `localStorage` variable to explicitly enable/disable colors
  1527. */
  1528. // eslint-disable-next-line complexity
  1529. function useColors() {
  1530. // NB: In an Electron preload script, document will be defined but not fully
  1531. // initialized. Since we know we're in Chrome, we'll just detect this case
  1532. // explicitly
  1533. if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {
  1534. return true;
  1535. }
  1536. // Internet Explorer and Edge do not support colors.
  1537. if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
  1538. return false;
  1539. }
  1540. // Is webkit? http://stackoverflow.com/a/16459606/376773
  1541. // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
  1542. return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||
  1543. // Is firebug? http://stackoverflow.com/a/398120/376773
  1544. (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||
  1545. // Is firefox >= v31?
  1546. // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
  1547. (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) ||
  1548. // Double check webkit in userAgent just in case we are in a worker
  1549. (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/));
  1550. }
  1551. /**
  1552. * Colorize log arguments if enabled.
  1553. *
  1554. * @api public
  1555. */
  1556. function formatArgs(args) {
  1557. args[0] = (this.useColors ? '%c' : '') +
  1558. this.namespace +
  1559. (this.useColors ? ' %c' : ' ') +
  1560. args[0] +
  1561. (this.useColors ? '%c ' : ' ') +
  1562. '+' + module.exports.humanize(this.diff);
  1563. if (!this.useColors) {
  1564. return;
  1565. }
  1566. const c = 'color: ' + this.color;
  1567. args.splice(1, 0, c, 'color: inherit');
  1568. // The final "%c" is somewhat tricky, because there could be other
  1569. // arguments passed either before or after the %c, so we need to
  1570. // figure out the correct index to insert the CSS into
  1571. let index = 0;
  1572. let lastC = 0;
  1573. args[0].replace(/%[a-zA-Z%]/g, match => {
  1574. if (match === '%%') {
  1575. return;
  1576. }
  1577. index++;
  1578. if (match === '%c') {
  1579. // We only are interested in the *last* %c
  1580. // (the user may have provided their own)
  1581. lastC = index;
  1582. }
  1583. });
  1584. args.splice(lastC, 0, c);
  1585. }
  1586. /**
  1587. * Invokes `console.debug()` when available.
  1588. * No-op when `console.debug` is not a "function".
  1589. * If `console.debug` is not available, falls back
  1590. * to `console.log`.
  1591. *
  1592. * @api public
  1593. */
  1594. exports.log = console.debug || console.log || (() => {});
  1595. /**
  1596. * Save `namespaces`.
  1597. *
  1598. * @param {String} namespaces
  1599. * @api private
  1600. */
  1601. function save(namespaces) {
  1602. try {
  1603. if (namespaces) {
  1604. exports.storage.setItem('debug', namespaces);
  1605. } else {
  1606. exports.storage.removeItem('debug');
  1607. }
  1608. } catch (error) {
  1609. // Swallow
  1610. // XXX (@Qix-) should we be logging these?
  1611. }
  1612. }
  1613. /**
  1614. * Load `namespaces`.
  1615. *
  1616. * @return {String} returns the previously persisted debug modes
  1617. * @api private
  1618. */
  1619. function load() {
  1620. let r;
  1621. try {
  1622. r = exports.storage.getItem('debug');
  1623. } catch (error) {
  1624. // Swallow
  1625. // XXX (@Qix-) should we be logging these?
  1626. }
  1627. // If debug isn't set in LS, and we're in Electron, try to load $DEBUG
  1628. if (!r && typeof process !== 'undefined' && 'env' in process) {
  1629. r = process.env.DEBUG;
  1630. }
  1631. return r;
  1632. }
  1633. /**
  1634. * Localstorage attempts to return the localstorage.
  1635. *
  1636. * This is necessary because safari throws
  1637. * when a user disables cookies/localstorage
  1638. * and you attempt to access it.
  1639. *
  1640. * @return {LocalStorage}
  1641. * @api private
  1642. */
  1643. function localstorage() {
  1644. try {
  1645. // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context
  1646. // The Browser also has localStorage in the global context.
  1647. return localStorage;
  1648. } catch (error) {
  1649. // Swallow
  1650. // XXX (@Qix-) should we be logging these?
  1651. }
  1652. }
  1653. module.exports = requireCommon()(exports);
  1654. const {formatters} = module.exports;
  1655. /**
  1656. * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
  1657. */
  1658. formatters.j = function (v) {
  1659. try {
  1660. return JSON.stringify(v);
  1661. } catch (error) {
  1662. return '[UnexpectedJSONParseError]: ' + error.message;
  1663. }
  1664. };
  1665. } (browser, browserExports));
  1666. return browserExports;
  1667. }
  1668. var nodeExports = {};
  1669. var node = {
  1670. get exports(){ return nodeExports; },
  1671. set exports(v){ nodeExports = v; },
  1672. };
  1673. /**
  1674. * Module dependencies.
  1675. */
  1676. var hasRequiredNode;
  1677. function requireNode () {
  1678. if (hasRequiredNode) return nodeExports;
  1679. hasRequiredNode = 1;
  1680. (function (module, exports) {
  1681. const tty = require$$0;
  1682. const util = require$$1;
  1683. /**
  1684. * This is the Node.js implementation of `debug()`.
  1685. */
  1686. exports.init = init;
  1687. exports.log = log;
  1688. exports.formatArgs = formatArgs;
  1689. exports.save = save;
  1690. exports.load = load;
  1691. exports.useColors = useColors;
  1692. exports.destroy = util.deprecate(
  1693. () => {},
  1694. 'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'
  1695. );
  1696. /**
  1697. * Colors.
  1698. */
  1699. exports.colors = [6, 2, 3, 4, 5, 1];
  1700. try {
  1701. // Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json)
  1702. // eslint-disable-next-line import/no-extraneous-dependencies
  1703. const supportsColor = require('supports-color');
  1704. if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) {
  1705. exports.colors = [
  1706. 20,
  1707. 21,
  1708. 26,
  1709. 27,
  1710. 32,
  1711. 33,
  1712. 38,
  1713. 39,
  1714. 40,
  1715. 41,
  1716. 42,
  1717. 43,
  1718. 44,
  1719. 45,
  1720. 56,
  1721. 57,
  1722. 62,
  1723. 63,
  1724. 68,
  1725. 69,
  1726. 74,
  1727. 75,
  1728. 76,
  1729. 77,
  1730. 78,
  1731. 79,
  1732. 80,
  1733. 81,
  1734. 92,
  1735. 93,
  1736. 98,
  1737. 99,
  1738. 112,
  1739. 113,
  1740. 128,
  1741. 129,
  1742. 134,
  1743. 135,
  1744. 148,
  1745. 149,
  1746. 160,
  1747. 161,
  1748. 162,
  1749. 163,
  1750. 164,
  1751. 165,
  1752. 166,
  1753. 167,
  1754. 168,
  1755. 169,
  1756. 170,
  1757. 171,
  1758. 172,
  1759. 173,
  1760. 178,
  1761. 179,
  1762. 184,
  1763. 185,
  1764. 196,
  1765. 197,
  1766. 198,
  1767. 199,
  1768. 200,
  1769. 201,
  1770. 202,
  1771. 203,
  1772. 204,
  1773. 205,
  1774. 206,
  1775. 207,
  1776. 208,
  1777. 209,
  1778. 214,
  1779. 215,
  1780. 220,
  1781. 221
  1782. ];
  1783. }
  1784. } catch (error) {
  1785. // Swallow - we only care if `supports-color` is available; it doesn't have to be.
  1786. }
  1787. /**
  1788. * Build up the default `inspectOpts` object from the environment variables.
  1789. *
  1790. * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js
  1791. */
  1792. exports.inspectOpts = Object.keys(process.env).filter(key => {
  1793. return /^debug_/i.test(key);
  1794. }).reduce((obj, key) => {
  1795. // Camel-case
  1796. const prop = key
  1797. .substring(6)
  1798. .toLowerCase()
  1799. .replace(/_([a-z])/g, (_, k) => {
  1800. return k.toUpperCase();
  1801. });
  1802. // Coerce string value into JS value
  1803. let val = process.env[key];
  1804. if (/^(yes|on|true|enabled)$/i.test(val)) {
  1805. val = true;
  1806. } else if (/^(no|off|false|disabled)$/i.test(val)) {
  1807. val = false;
  1808. } else if (val === 'null') {
  1809. val = null;
  1810. } else {
  1811. val = Number(val);
  1812. }
  1813. obj[prop] = val;
  1814. return obj;
  1815. }, {});
  1816. /**
  1817. * Is stdout a TTY? Colored output is enabled when `true`.
  1818. */
  1819. function useColors() {
  1820. return 'colors' in exports.inspectOpts ?
  1821. Boolean(exports.inspectOpts.colors) :
  1822. tty.isatty(process.stderr.fd);
  1823. }
  1824. /**
  1825. * Adds ANSI color escape codes if enabled.
  1826. *
  1827. * @api public
  1828. */
  1829. function formatArgs(args) {
  1830. const {namespace: name, useColors} = this;
  1831. if (useColors) {
  1832. const c = this.color;
  1833. const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c);
  1834. const prefix = ` ${colorCode};1m${name} \u001B[0m`;
  1835. args[0] = prefix + args[0].split('\n').join('\n' + prefix);
  1836. args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m');
  1837. } else {
  1838. args[0] = getDate() + name + ' ' + args[0];
  1839. }
  1840. }
  1841. function getDate() {
  1842. if (exports.inspectOpts.hideDate) {
  1843. return '';
  1844. }
  1845. return new Date().toISOString() + ' ';
  1846. }
  1847. /**
  1848. * Invokes `util.format()` with the specified arguments and writes to stderr.
  1849. */
  1850. function log(...args) {
  1851. return process.stderr.write(util.format(...args) + '\n');
  1852. }
  1853. /**
  1854. * Save `namespaces`.
  1855. *
  1856. * @param {String} namespaces
  1857. * @api private
  1858. */
  1859. function save(namespaces) {
  1860. if (namespaces) {
  1861. process.env.DEBUG = namespaces;
  1862. } else {
  1863. // If you set a process.env field to null or undefined, it gets cast to the
  1864. // string 'null' or 'undefined'. Just delete instead.
  1865. delete process.env.DEBUG;
  1866. }
  1867. }
  1868. /**
  1869. * Load `namespaces`.
  1870. *
  1871. * @return {String} returns the previously persisted debug modes
  1872. * @api private
  1873. */
  1874. function load() {
  1875. return process.env.DEBUG;
  1876. }
  1877. /**
  1878. * Init logic for `debug` instances.
  1879. *
  1880. * Create a new `inspectOpts` object in case `useColors` is set
  1881. * differently for a particular `debug` instance.
  1882. */
  1883. function init(debug) {
  1884. debug.inspectOpts = {};
  1885. const keys = Object.keys(exports.inspectOpts);
  1886. for (let i = 0; i < keys.length; i++) {
  1887. debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]];
  1888. }
  1889. }
  1890. module.exports = requireCommon()(exports);
  1891. const {formatters} = module.exports;
  1892. /**
  1893. * Map %o to `util.inspect()`, all on a single line.
  1894. */
  1895. formatters.o = function (v) {
  1896. this.inspectOpts.colors = this.useColors;
  1897. return util.inspect(v, this.inspectOpts)
  1898. .split('\n')
  1899. .map(str => str.trim())
  1900. .join(' ');
  1901. };
  1902. /**
  1903. * Map %O to `util.inspect()`, allowing multiple lines if needed.
  1904. */
  1905. formatters.O = function (v) {
  1906. this.inspectOpts.colors = this.useColors;
  1907. return util.inspect(v, this.inspectOpts);
  1908. };
  1909. } (node, nodeExports));
  1910. return nodeExports;
  1911. }
  1912. /**
  1913. * Detect Electron renderer / nwjs process, which is node, but we should
  1914. * treat as a browser.
  1915. */
  1916. (function (module) {
  1917. if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) {
  1918. module.exports = requireBrowser();
  1919. } else {
  1920. module.exports = requireNode();
  1921. }
  1922. } (src));
  1923. const _debug = /*@__PURE__*/getDefaultExportFromCjs(srcExports);
  1924. const debug = _debug("vite:hmr");
  1925. const directRequestRE = /(?:\?|&)direct\b/;
  1926. async function handleHotUpdate({ file, modules, read, server }, options) {
  1927. const prevDescriptor = getDescriptor(file, options, false);
  1928. if (!prevDescriptor) {
  1929. return;
  1930. }
  1931. setPrevDescriptor(file, prevDescriptor);
  1932. const content = await read();
  1933. const { descriptor } = createDescriptor(file, content, options);
  1934. let needRerender = false;
  1935. const affectedModules = /* @__PURE__ */ new Set();
  1936. const mainModule = modules.filter((m) => !/type=/.test(m.url) || /type=script/.test(m.url)).sort((m1, m2) => {
  1937. return m1.url.length - m2.url.length;
  1938. })[0];
  1939. const templateModule = modules.find((m) => /type=template/.test(m.url));
  1940. const scriptChanged = hasScriptChanged(prevDescriptor, descriptor);
  1941. if (scriptChanged) {
  1942. let scriptModule;
  1943. if (descriptor.scriptSetup?.lang && !descriptor.scriptSetup.src || descriptor.script?.lang && !descriptor.script.src) {
  1944. const scriptModuleRE = new RegExp(
  1945. `type=script.*&lang.${descriptor.scriptSetup?.lang || descriptor.script?.lang}$`
  1946. );
  1947. scriptModule = modules.find((m) => scriptModuleRE.test(m.url));
  1948. }
  1949. affectedModules.add(scriptModule || mainModule);
  1950. }
  1951. if (!isEqualBlock(descriptor.template, prevDescriptor.template)) {
  1952. if (!scriptChanged) {
  1953. setResolvedScript(
  1954. descriptor,
  1955. getResolvedScript(prevDescriptor, false),
  1956. false
  1957. );
  1958. }
  1959. affectedModules.add(templateModule);
  1960. needRerender = true;
  1961. }
  1962. let didUpdateStyle = false;
  1963. const prevStyles = prevDescriptor.styles || [];
  1964. const nextStyles = descriptor.styles || [];
  1965. if (prevDescriptor.cssVars.join("") !== descriptor.cssVars.join("")) {
  1966. affectedModules.add(mainModule);
  1967. }
  1968. if (prevStyles.some((s) => s.scoped) !== nextStyles.some((s) => s.scoped)) {
  1969. affectedModules.add(templateModule);
  1970. affectedModules.add(mainModule);
  1971. }
  1972. for (let i = 0; i < nextStyles.length; i++) {
  1973. const prev = prevStyles[i];
  1974. const next = nextStyles[i];
  1975. if (!prev || !isEqualBlock(prev, next)) {
  1976. didUpdateStyle = true;
  1977. const mod = modules.find(
  1978. (m) => m.url.includes(`type=style&index=${i}`) && m.url.endsWith(`.${next.lang || "css"}`) && !directRequestRE.test(m.url)
  1979. );
  1980. if (mod) {
  1981. affectedModules.add(mod);
  1982. if (mod.url.includes("&inline")) {
  1983. affectedModules.add(mainModule);
  1984. }
  1985. } else {
  1986. affectedModules.add(mainModule);
  1987. }
  1988. }
  1989. }
  1990. if (prevStyles.length > nextStyles.length) {
  1991. affectedModules.add(mainModule);
  1992. }
  1993. const prevCustoms = prevDescriptor.customBlocks || [];
  1994. const nextCustoms = descriptor.customBlocks || [];
  1995. if (prevCustoms.length !== nextCustoms.length) {
  1996. affectedModules.add(mainModule);
  1997. } else {
  1998. for (let i = 0; i < nextCustoms.length; i++) {
  1999. const prev = prevCustoms[i];
  2000. const next = nextCustoms[i];
  2001. if (!prev || !isEqualBlock(prev, next)) {
  2002. const mod = modules.find(
  2003. (m) => m.url.includes(`type=${prev.type}&index=${i}`)
  2004. );
  2005. if (mod) {
  2006. affectedModules.add(mod);
  2007. } else {
  2008. affectedModules.add(mainModule);
  2009. }
  2010. }
  2011. }
  2012. }
  2013. const updateType = [];
  2014. if (needRerender) {
  2015. updateType.push(`template`);
  2016. if (!templateModule) {
  2017. affectedModules.add(mainModule);
  2018. } else if (mainModule && !affectedModules.has(mainModule)) {
  2019. const styleImporters = [...mainModule.importers].filter(
  2020. (m) => vite.isCSSRequest(m.url)
  2021. );
  2022. styleImporters.forEach((m) => affectedModules.add(m));
  2023. }
  2024. }
  2025. if (didUpdateStyle) {
  2026. updateType.push(`style`);
  2027. }
  2028. if (updateType.length) {
  2029. debug(`[vue:update(${updateType.join("&")})] ${file}`);
  2030. }
  2031. return [...affectedModules].filter(Boolean);
  2032. }
  2033. function isEqualBlock(a, b) {
  2034. if (!a && !b)
  2035. return true;
  2036. if (!a || !b)
  2037. return false;
  2038. if (a.src && b.src && a.src === b.src)
  2039. return true;
  2040. if (a.content !== b.content)
  2041. return false;
  2042. const keysA = Object.keys(a.attrs);
  2043. const keysB = Object.keys(b.attrs);
  2044. if (keysA.length !== keysB.length) {
  2045. return false;
  2046. }
  2047. return keysA.every((key) => a.attrs[key] === b.attrs[key]);
  2048. }
  2049. function isOnlyTemplateChanged(prev, next) {
  2050. 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]));
  2051. }
  2052. function hasScriptChanged(prev, next) {
  2053. if (!isEqualBlock(prev.script, next.script)) {
  2054. return true;
  2055. }
  2056. if (!isEqualBlock(prev.scriptSetup, next.scriptSetup)) {
  2057. return true;
  2058. }
  2059. const prevResolvedScript = getResolvedScript(prev, false);
  2060. const prevImports = prevResolvedScript?.imports;
  2061. if (prevImports) {
  2062. return !next.template || next.shouldForceReload(prevImports);
  2063. }
  2064. return false;
  2065. }
  2066. const EXPORT_HELPER_ID = "\0plugin-vue:export-helper";
  2067. const helperCode = `
  2068. export default (sfc, props) => {
  2069. const target = sfc.__vccOpts || sfc;
  2070. for (const [key, val] of props) {
  2071. target[key] = val;
  2072. }
  2073. return target;
  2074. }
  2075. `;
  2076. async function transformMain(code, filename, options, pluginContext, ssr, asCustomElement) {
  2077. const { devServer, isProduction, devToolsEnabled } = options;
  2078. const prevDescriptor = getPrevDescriptor(filename);
  2079. const { descriptor, errors } = createDescriptor(filename, code, options);
  2080. if (errors.length) {
  2081. errors.forEach(
  2082. (error) => pluginContext.error(createRollupError(filename, error))
  2083. );
  2084. return null;
  2085. }
  2086. const attachedProps = [];
  2087. const hasScoped = descriptor.styles.some((s) => s.scoped);
  2088. const { code: scriptCode, map: scriptMap } = await genScriptCode(
  2089. descriptor,
  2090. options,
  2091. pluginContext,
  2092. ssr
  2093. );
  2094. const hasTemplateImport = descriptor.template && !isUseInlineTemplate(descriptor, !devServer);
  2095. let templateCode = "";
  2096. let templateMap = void 0;
  2097. if (hasTemplateImport) {
  2098. ({ code: templateCode, map: templateMap } = await genTemplateCode(
  2099. descriptor,
  2100. options,
  2101. pluginContext,
  2102. ssr
  2103. ));
  2104. }
  2105. if (hasTemplateImport) {
  2106. attachedProps.push(
  2107. ssr ? ["ssrRender", "_sfc_ssrRender"] : ["render", "_sfc_render"]
  2108. );
  2109. } else {
  2110. if (prevDescriptor && !isEqualBlock(descriptor.template, prevDescriptor.template)) {
  2111. attachedProps.push([ssr ? "ssrRender" : "render", "() => {}"]);
  2112. }
  2113. }
  2114. const stylesCode = await genStyleCode(
  2115. descriptor,
  2116. pluginContext,
  2117. asCustomElement,
  2118. attachedProps
  2119. );
  2120. const customBlocksCode = await genCustomBlockCode(descriptor, pluginContext);
  2121. const output = [
  2122. scriptCode,
  2123. templateCode,
  2124. stylesCode,
  2125. customBlocksCode
  2126. ];
  2127. if (hasScoped) {
  2128. attachedProps.push([`__scopeId`, JSON.stringify(`data-v-${descriptor.id}`)]);
  2129. }
  2130. if (devToolsEnabled || devServer && !isProduction) {
  2131. attachedProps.push([
  2132. `__file`,
  2133. JSON.stringify(isProduction ? path.basename(filename) : filename)
  2134. ]);
  2135. }
  2136. if (devServer && devServer.config.server.hmr !== false && !ssr && !isProduction) {
  2137. output.push(`_sfc_main.__hmrId = ${JSON.stringify(descriptor.id)}`);
  2138. output.push(
  2139. `typeof __VUE_HMR_RUNTIME__ !== 'undefined' && __VUE_HMR_RUNTIME__.createRecord(_sfc_main.__hmrId, _sfc_main)`
  2140. );
  2141. if (prevDescriptor && isOnlyTemplateChanged(prevDescriptor, descriptor)) {
  2142. output.push(`export const _rerender_only = true`);
  2143. }
  2144. output.push(
  2145. `import.meta.hot.accept(mod => {`,
  2146. ` if (!mod) return`,
  2147. ` const { default: updated, _rerender_only } = mod`,
  2148. ` if (_rerender_only) {`,
  2149. ` __VUE_HMR_RUNTIME__.rerender(updated.__hmrId, updated.render)`,
  2150. ` } else {`,
  2151. ` __VUE_HMR_RUNTIME__.reload(updated.__hmrId, updated)`,
  2152. ` }`,
  2153. `})`
  2154. );
  2155. }
  2156. if (ssr) {
  2157. const normalizedFilename = vite.normalizePath(
  2158. path.relative(options.root, filename)
  2159. );
  2160. output.push(
  2161. `import { useSSRContext as __vite_useSSRContext } from 'vue'`,
  2162. `const _sfc_setup = _sfc_main.setup`,
  2163. `_sfc_main.setup = (props, ctx) => {`,
  2164. ` const ssrContext = __vite_useSSRContext()`,
  2165. ` ;(ssrContext.modules || (ssrContext.modules = new Set())).add(${JSON.stringify(
  2166. normalizedFilename
  2167. )})`,
  2168. ` return _sfc_setup ? _sfc_setup(props, ctx) : undefined`,
  2169. `}`
  2170. );
  2171. }
  2172. let resolvedMap = void 0;
  2173. if (options.sourceMap) {
  2174. if (scriptMap && templateMap) {
  2175. const gen = fromMap(
  2176. // version property of result.map is declared as string
  2177. // but actually it is `3`
  2178. scriptMap
  2179. );
  2180. const tracer = new TraceMap(
  2181. // same above
  2182. templateMap
  2183. );
  2184. const offset = (scriptCode.match(/\r?\n/g)?.length ?? 0) + 1;
  2185. eachMapping(tracer, (m) => {
  2186. if (m.source == null)
  2187. return;
  2188. addMapping(gen, {
  2189. source: m.source,
  2190. original: { line: m.originalLine, column: m.originalColumn },
  2191. generated: {
  2192. line: m.generatedLine + offset,
  2193. column: m.generatedColumn
  2194. }
  2195. });
  2196. });
  2197. resolvedMap = toEncodedMap(gen);
  2198. resolvedMap.sourcesContent = templateMap.sourcesContent;
  2199. } else {
  2200. resolvedMap = scriptMap ?? templateMap;
  2201. }
  2202. }
  2203. if (!attachedProps.length) {
  2204. output.push(`export default _sfc_main`);
  2205. } else {
  2206. output.push(
  2207. `import _export_sfc from '${EXPORT_HELPER_ID}'`,
  2208. `export default /*#__PURE__*/_export_sfc(_sfc_main, [${attachedProps.map(([key, val]) => `['${key}',${val}]`).join(",")}])`
  2209. );
  2210. }
  2211. let resolvedCode = output.join("\n");
  2212. const lang = descriptor.scriptSetup?.lang || descriptor.script?.lang;
  2213. if (lang && /tsx?$/.test(lang) && !descriptor.script?.src) {
  2214. const { code: code2, map } = await vite.transformWithEsbuild(
  2215. resolvedCode,
  2216. filename,
  2217. {
  2218. loader: "ts",
  2219. target: "esnext",
  2220. sourcemap: options.sourceMap
  2221. },
  2222. resolvedMap
  2223. );
  2224. resolvedCode = code2;
  2225. resolvedMap = resolvedMap ? map : resolvedMap;
  2226. }
  2227. return {
  2228. code: resolvedCode,
  2229. map: resolvedMap || {
  2230. mappings: ""
  2231. },
  2232. meta: {
  2233. vite: {
  2234. lang: descriptor.script?.lang || descriptor.scriptSetup?.lang || "js"
  2235. }
  2236. }
  2237. };
  2238. }
  2239. async function genTemplateCode(descriptor, options, pluginContext, ssr) {
  2240. const template = descriptor.template;
  2241. const hasScoped = descriptor.styles.some((style) => style.scoped);
  2242. if (!template.lang && !template.src) {
  2243. return transformTemplateInMain(
  2244. template.content,
  2245. descriptor,
  2246. options,
  2247. pluginContext,
  2248. ssr
  2249. );
  2250. } else {
  2251. if (template.src) {
  2252. await linkSrcToDescriptor(
  2253. template.src,
  2254. descriptor,
  2255. pluginContext,
  2256. hasScoped
  2257. );
  2258. }
  2259. const src = template.src || descriptor.filename;
  2260. const srcQuery = template.src ? hasScoped ? `&src=${descriptor.id}` : "&src=true" : "";
  2261. const scopedQuery = hasScoped ? `&scoped=${descriptor.id}` : ``;
  2262. const attrsQuery = attrsToQuery(template.attrs, "js", true);
  2263. const query = `?vue&type=template${srcQuery}${scopedQuery}${attrsQuery}`;
  2264. const request = JSON.stringify(src + query);
  2265. const renderFnName = ssr ? "ssrRender" : "render";
  2266. return {
  2267. code: `import { ${renderFnName} as _sfc_${renderFnName} } from ${request}`,
  2268. map: void 0
  2269. };
  2270. }
  2271. }
  2272. async function genScriptCode(descriptor, options, pluginContext, ssr) {
  2273. let scriptCode = `const _sfc_main = {}`;
  2274. let map;
  2275. const script = resolveScript(descriptor, options, ssr);
  2276. if (script) {
  2277. if ((!script.lang || script.lang === "ts" && options.devServer) && !script.src) {
  2278. const userPlugins = options.script?.babelParserPlugins || [];
  2279. const defaultPlugins = script.lang === "ts" ? userPlugins.includes("decorators") ? ["typescript"] : ["typescript", "decorators-legacy"] : [];
  2280. scriptCode = options.compiler.rewriteDefault(
  2281. script.content,
  2282. "_sfc_main",
  2283. [...defaultPlugins, ...userPlugins]
  2284. );
  2285. map = script.map;
  2286. } else {
  2287. if (script.src) {
  2288. await linkSrcToDescriptor(script.src, descriptor, pluginContext, false);
  2289. }
  2290. const src = script.src || descriptor.filename;
  2291. const langFallback = script.src && path.extname(src).slice(1) || "js";
  2292. const attrsQuery = attrsToQuery(script.attrs, langFallback);
  2293. const srcQuery = script.src ? `&src=true` : ``;
  2294. const query = `?vue&type=script${srcQuery}${attrsQuery}`;
  2295. const request = JSON.stringify(src + query);
  2296. scriptCode = `import _sfc_main from ${request}
  2297. export * from ${request}`;
  2298. }
  2299. }
  2300. return {
  2301. code: scriptCode,
  2302. map
  2303. };
  2304. }
  2305. async function genStyleCode(descriptor, pluginContext, asCustomElement, attachedProps) {
  2306. let stylesCode = ``;
  2307. let cssModulesMap;
  2308. if (descriptor.styles.length) {
  2309. for (let i = 0; i < descriptor.styles.length; i++) {
  2310. const style = descriptor.styles[i];
  2311. if (style.src) {
  2312. await linkSrcToDescriptor(
  2313. style.src,
  2314. descriptor,
  2315. pluginContext,
  2316. style.scoped
  2317. );
  2318. }
  2319. const src = style.src || descriptor.filename;
  2320. const attrsQuery = attrsToQuery(style.attrs, "css");
  2321. const srcQuery = style.src ? style.scoped ? `&src=${descriptor.id}` : "&src=true" : "";
  2322. const directQuery = asCustomElement ? `&inline` : ``;
  2323. const scopedQuery = style.scoped ? `&scoped=${descriptor.id}` : ``;
  2324. const query = `?vue&type=style&index=${i}${srcQuery}${directQuery}${scopedQuery}`;
  2325. const styleRequest = src + query + attrsQuery;
  2326. if (style.module) {
  2327. if (asCustomElement) {
  2328. throw new Error(
  2329. `<style module> is not supported in custom elements mode.`
  2330. );
  2331. }
  2332. const [importCode, nameMap] = genCSSModulesCode(
  2333. i,
  2334. styleRequest,
  2335. style.module
  2336. );
  2337. stylesCode += importCode;
  2338. Object.assign(cssModulesMap || (cssModulesMap = {}), nameMap);
  2339. } else {
  2340. if (asCustomElement) {
  2341. stylesCode += `
  2342. import _style_${i} from ${JSON.stringify(
  2343. styleRequest
  2344. )}`;
  2345. } else {
  2346. stylesCode += `
  2347. import ${JSON.stringify(styleRequest)}`;
  2348. }
  2349. }
  2350. }
  2351. if (asCustomElement) {
  2352. attachedProps.push([
  2353. `styles`,
  2354. `[${descriptor.styles.map((_, i) => `_style_${i}`).join(",")}]`
  2355. ]);
  2356. }
  2357. }
  2358. if (cssModulesMap) {
  2359. const mappingCode = Object.entries(cssModulesMap).reduce(
  2360. (code, [key, value]) => code + `"${key}":${value},
  2361. `,
  2362. "{\n"
  2363. ) + "}";
  2364. stylesCode += `
  2365. const cssModules = ${mappingCode}`;
  2366. attachedProps.push([`__cssModules`, `cssModules`]);
  2367. }
  2368. return stylesCode;
  2369. }
  2370. function genCSSModulesCode(index, request, moduleName) {
  2371. const styleVar = `style${index}`;
  2372. const exposedName = typeof moduleName === "string" ? moduleName : "$style";
  2373. const moduleRequest = request.replace(/\.(\w+)$/, ".module.$1");
  2374. return [
  2375. `
  2376. import ${styleVar} from ${JSON.stringify(moduleRequest)}`,
  2377. { [exposedName]: styleVar }
  2378. ];
  2379. }
  2380. async function genCustomBlockCode(descriptor, pluginContext) {
  2381. let code = "";
  2382. for (let index = 0; index < descriptor.customBlocks.length; index++) {
  2383. const block = descriptor.customBlocks[index];
  2384. if (block.src) {
  2385. await linkSrcToDescriptor(block.src, descriptor, pluginContext, false);
  2386. }
  2387. const src = block.src || descriptor.filename;
  2388. const attrsQuery = attrsToQuery(block.attrs, block.type);
  2389. const srcQuery = block.src ? `&src=true` : ``;
  2390. const query = `?vue&type=${block.type}&index=${index}${srcQuery}${attrsQuery}`;
  2391. const request = JSON.stringify(src + query);
  2392. code += `import block${index} from ${request}
  2393. `;
  2394. code += `if (typeof block${index} === 'function') block${index}(_sfc_main)
  2395. `;
  2396. }
  2397. return code;
  2398. }
  2399. async function linkSrcToDescriptor(src, descriptor, pluginContext, scoped) {
  2400. const srcFile = (await pluginContext.resolve(src, descriptor.filename))?.id || src;
  2401. setSrcDescriptor(srcFile.replace(/\?.*$/, ""), descriptor, scoped);
  2402. }
  2403. const ignoreList = ["id", "index", "src", "type", "lang", "module", "scoped"];
  2404. function attrsToQuery(attrs, langFallback, forceLangFallback = false) {
  2405. let query = ``;
  2406. for (const name in attrs) {
  2407. const value = attrs[name];
  2408. if (!ignoreList.includes(name)) {
  2409. query += `&${encodeURIComponent(name)}${value ? `=${encodeURIComponent(value)}` : ``}`;
  2410. }
  2411. }
  2412. if (langFallback || attrs.lang) {
  2413. query += `lang` in attrs ? forceLangFallback ? `&lang.${langFallback}` : `&lang.${attrs.lang}` : `&lang.${langFallback}`;
  2414. }
  2415. return query;
  2416. }
  2417. async function transformStyle(code, descriptor, index, options, pluginContext, filename) {
  2418. const block = descriptor.styles[index];
  2419. const result = await options.compiler.compileStyleAsync({
  2420. ...options.style,
  2421. filename: descriptor.filename,
  2422. id: `data-v-${descriptor.id}`,
  2423. isProd: options.isProduction,
  2424. source: code,
  2425. scoped: block.scoped,
  2426. ...options.cssDevSourcemap ? {
  2427. postcssOptions: {
  2428. map: {
  2429. from: filename,
  2430. inline: false,
  2431. annotation: false
  2432. }
  2433. }
  2434. } : {}
  2435. });
  2436. if (result.errors.length) {
  2437. result.errors.forEach((error) => {
  2438. if (error.line && error.column) {
  2439. error.loc = {
  2440. file: descriptor.filename,
  2441. line: error.line + block.loc.start.line,
  2442. column: error.column
  2443. };
  2444. }
  2445. pluginContext.error(error);
  2446. });
  2447. return null;
  2448. }
  2449. const map = result.map ? await vite.formatPostcssSourceMap(
  2450. // version property of result.map is declared as string
  2451. // but actually it is a number
  2452. result.map,
  2453. filename
  2454. ) : { mappings: "" };
  2455. return {
  2456. code: result.code,
  2457. map
  2458. };
  2459. }
  2460. function vuePlugin(rawOptions = {}) {
  2461. const {
  2462. include = /\.vue$/,
  2463. exclude,
  2464. customElement = /\.ce\.vue$/,
  2465. reactivityTransform = false
  2466. } = rawOptions;
  2467. const filter = vite.createFilter(include, exclude);
  2468. const customElementFilter = typeof customElement === "boolean" ? () => customElement : vite.createFilter(customElement);
  2469. const refTransformFilter = reactivityTransform === false ? () => false : reactivityTransform === true ? vite.createFilter(/\.(j|t)sx?$/, /node_modules/) : vite.createFilter(reactivityTransform);
  2470. let options = {
  2471. isProduction: process.env.NODE_ENV === "production",
  2472. compiler: null,
  2473. // to be set in buildStart
  2474. ...rawOptions,
  2475. include,
  2476. exclude,
  2477. customElement,
  2478. reactivityTransform,
  2479. root: process.cwd(),
  2480. sourceMap: true,
  2481. cssDevSourcemap: false,
  2482. devToolsEnabled: process.env.NODE_ENV !== "production"
  2483. };
  2484. return {
  2485. name: "vite:vue",
  2486. handleHotUpdate(ctx) {
  2487. if (!filter(ctx.file)) {
  2488. return;
  2489. }
  2490. return handleHotUpdate(ctx, options);
  2491. },
  2492. config(config) {
  2493. return {
  2494. resolve: {
  2495. dedupe: config.build?.ssr ? [] : ["vue"]
  2496. },
  2497. define: {
  2498. __VUE_OPTIONS_API__: config.define?.__VUE_OPTIONS_API__ ?? true,
  2499. __VUE_PROD_DEVTOOLS__: config.define?.__VUE_PROD_DEVTOOLS__ ?? false
  2500. },
  2501. ssr: {
  2502. external: config.legacy?.buildSsrCjsExternalHeuristics ? ["vue", "@vue/server-renderer"] : []
  2503. }
  2504. };
  2505. },
  2506. configResolved(config) {
  2507. options = {
  2508. ...options,
  2509. root: config.root,
  2510. sourceMap: config.command === "build" ? !!config.build.sourcemap : true,
  2511. cssDevSourcemap: config.css?.devSourcemap ?? false,
  2512. isProduction: config.isProduction,
  2513. devToolsEnabled: !!config.define.__VUE_PROD_DEVTOOLS__ || !config.isProduction
  2514. };
  2515. },
  2516. configureServer(server) {
  2517. options.devServer = server;
  2518. },
  2519. buildStart() {
  2520. options.compiler = options.compiler || resolveCompiler(options.root);
  2521. },
  2522. async resolveId(id) {
  2523. if (id === EXPORT_HELPER_ID) {
  2524. return id;
  2525. }
  2526. if (parseVueRequest(id).query.vue) {
  2527. return id;
  2528. }
  2529. },
  2530. load(id, opt) {
  2531. const ssr = opt?.ssr === true;
  2532. if (id === EXPORT_HELPER_ID) {
  2533. return helperCode;
  2534. }
  2535. const { filename, query } = parseVueRequest(id);
  2536. if (query.vue) {
  2537. if (query.src) {
  2538. return fs.readFileSync(filename, "utf-8");
  2539. }
  2540. const descriptor = getDescriptor(filename, options);
  2541. let block;
  2542. if (query.type === "script") {
  2543. block = getResolvedScript(descriptor, ssr);
  2544. } else if (query.type === "template") {
  2545. block = descriptor.template;
  2546. } else if (query.type === "style") {
  2547. block = descriptor.styles[query.index];
  2548. } else if (query.index != null) {
  2549. block = descriptor.customBlocks[query.index];
  2550. }
  2551. if (block) {
  2552. return {
  2553. code: block.content,
  2554. map: block.map
  2555. };
  2556. }
  2557. }
  2558. },
  2559. transform(code, id, opt) {
  2560. const ssr = opt?.ssr === true;
  2561. const { filename, query } = parseVueRequest(id);
  2562. if (query.raw || query.url) {
  2563. return;
  2564. }
  2565. if (!filter(filename) && !query.vue) {
  2566. if (!query.vue && refTransformFilter(filename) && options.compiler.shouldTransformRef(code)) {
  2567. return options.compiler.transformRef(code, {
  2568. filename,
  2569. sourceMap: true
  2570. });
  2571. }
  2572. return;
  2573. }
  2574. if (!query.vue) {
  2575. return transformMain(
  2576. code,
  2577. filename,
  2578. options,
  2579. this,
  2580. ssr,
  2581. customElementFilter(filename)
  2582. );
  2583. } else {
  2584. const descriptor = query.src ? getSrcDescriptor(filename, query) : getDescriptor(filename, options);
  2585. if (query.type === "template") {
  2586. return transformTemplateAsModule(code, descriptor, options, this, ssr);
  2587. } else if (query.type === "style") {
  2588. return transformStyle(
  2589. code,
  2590. descriptor,
  2591. Number(query.index),
  2592. options,
  2593. this,
  2594. filename
  2595. );
  2596. }
  2597. }
  2598. }
  2599. };
  2600. }
  2601. module.exports = vuePlugin;
  2602. module.exports.default = vuePlugin;
  2603. module.exports.parseVueRequest = parseVueRequest;