index.cjs 77 KB

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