index.cjs 83 KB

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