index.cjs 86 KB

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