index.mjs 77 KB

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