index.mjs 79 KB

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