index.cjs 63 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879
  1. const require_context = require('./context-DwbtaXxf.cjs');
  2. const require_webpack_like = require('./webpack-like-BAQNtVsj.cjs');
  3. const require_context$1 = require('./context-PvRDlMNZ.cjs');
  4. const require_utils = require('./utils-D30tqOw3.cjs');
  5. const require_context$2 = require('./context-Df-kn6rn.cjs');
  6. const node_fs = require_context.__toESM(require("node:fs"));
  7. const node_path = require_context.__toESM(require("node:path"));
  8. const node_buffer = require_context.__toESM(require("node:buffer"));
  9. const node_querystring = require_context.__toESM(require("node:querystring"));
  10. const node_process = require_context.__toESM(require("node:process"));
  11. const webpack_virtual_modules = require_context.__toESM(require("webpack-virtual-modules"));
  12. //#region node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.0/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs
  13. const comma = ",".charCodeAt(0);
  14. const semicolon = ";".charCodeAt(0);
  15. const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  16. const intToChar = new Uint8Array(64);
  17. const charToInt = new Uint8Array(128);
  18. for (let i = 0; i < chars.length; i++) {
  19. const c = chars.charCodeAt(i);
  20. intToChar[i] = c;
  21. charToInt[c] = i;
  22. }
  23. function decodeInteger(reader, relative) {
  24. let value = 0;
  25. let shift = 0;
  26. let integer = 0;
  27. do {
  28. const c = reader.next();
  29. integer = charToInt[c];
  30. value |= (integer & 31) << shift;
  31. shift += 5;
  32. } while (integer & 32);
  33. const shouldNegate = value & 1;
  34. value >>>= 1;
  35. if (shouldNegate) value = -2147483648 | -value;
  36. return relative + value;
  37. }
  38. function encodeInteger(builder, num, relative) {
  39. let delta = num - relative;
  40. delta = delta < 0 ? -delta << 1 | 1 : delta << 1;
  41. do {
  42. let clamped = delta & 31;
  43. delta >>>= 5;
  44. if (delta > 0) clamped |= 32;
  45. builder.write(intToChar[clamped]);
  46. } while (delta > 0);
  47. return num;
  48. }
  49. function hasMoreVlq(reader, max) {
  50. if (reader.pos >= max) return false;
  51. return reader.peek() !== comma;
  52. }
  53. const bufLength = 1024 * 16;
  54. const td = typeof TextDecoder !== "undefined" ? /* @__PURE__ */ new TextDecoder() : typeof Buffer !== "undefined" ? { decode(buf) {
  55. const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength);
  56. return out.toString();
  57. } } : { decode(buf) {
  58. let out = "";
  59. for (let i = 0; i < buf.length; i++) out += String.fromCharCode(buf[i]);
  60. return out;
  61. } };
  62. var StringWriter = class {
  63. constructor() {
  64. this.pos = 0;
  65. this.out = "";
  66. this.buffer = new Uint8Array(bufLength);
  67. }
  68. write(v) {
  69. const { buffer } = this;
  70. buffer[this.pos++] = v;
  71. if (this.pos === bufLength) {
  72. this.out += td.decode(buffer);
  73. this.pos = 0;
  74. }
  75. }
  76. flush() {
  77. const { buffer, out, pos } = this;
  78. return pos > 0 ? out + td.decode(buffer.subarray(0, pos)) : out;
  79. }
  80. };
  81. var StringReader = class {
  82. constructor(buffer) {
  83. this.pos = 0;
  84. this.buffer = buffer;
  85. }
  86. next() {
  87. return this.buffer.charCodeAt(this.pos++);
  88. }
  89. peek() {
  90. return this.buffer.charCodeAt(this.pos);
  91. }
  92. indexOf(char) {
  93. const { buffer, pos } = this;
  94. const idx = buffer.indexOf(char, pos);
  95. return idx === -1 ? buffer.length : idx;
  96. }
  97. };
  98. function decode(mappings) {
  99. const { length } = mappings;
  100. const reader = new StringReader(mappings);
  101. const decoded = [];
  102. let genColumn = 0;
  103. let sourcesIndex = 0;
  104. let sourceLine = 0;
  105. let sourceColumn = 0;
  106. let namesIndex = 0;
  107. do {
  108. const semi = reader.indexOf(";");
  109. const line = [];
  110. let sorted = true;
  111. let lastCol = 0;
  112. genColumn = 0;
  113. while (reader.pos < semi) {
  114. let seg;
  115. genColumn = decodeInteger(reader, genColumn);
  116. if (genColumn < lastCol) sorted = false;
  117. lastCol = genColumn;
  118. if (hasMoreVlq(reader, semi)) {
  119. sourcesIndex = decodeInteger(reader, sourcesIndex);
  120. sourceLine = decodeInteger(reader, sourceLine);
  121. sourceColumn = decodeInteger(reader, sourceColumn);
  122. if (hasMoreVlq(reader, semi)) {
  123. namesIndex = decodeInteger(reader, namesIndex);
  124. seg = [
  125. genColumn,
  126. sourcesIndex,
  127. sourceLine,
  128. sourceColumn,
  129. namesIndex
  130. ];
  131. } else seg = [
  132. genColumn,
  133. sourcesIndex,
  134. sourceLine,
  135. sourceColumn
  136. ];
  137. } else seg = [genColumn];
  138. line.push(seg);
  139. reader.pos++;
  140. }
  141. if (!sorted) sort(line);
  142. decoded.push(line);
  143. reader.pos = semi + 1;
  144. } while (reader.pos <= length);
  145. return decoded;
  146. }
  147. function sort(line) {
  148. line.sort(sortComparator$1);
  149. }
  150. function sortComparator$1(a, b) {
  151. return a[0] - b[0];
  152. }
  153. function encode(decoded) {
  154. const writer = new StringWriter();
  155. let sourcesIndex = 0;
  156. let sourceLine = 0;
  157. let sourceColumn = 0;
  158. let namesIndex = 0;
  159. for (let i = 0; i < decoded.length; i++) {
  160. const line = decoded[i];
  161. if (i > 0) writer.write(semicolon);
  162. if (line.length === 0) continue;
  163. let genColumn = 0;
  164. for (let j = 0; j < line.length; j++) {
  165. const segment = line[j];
  166. if (j > 0) writer.write(comma);
  167. genColumn = encodeInteger(writer, segment[0], genColumn);
  168. if (segment.length === 1) continue;
  169. sourcesIndex = encodeInteger(writer, segment[1], sourcesIndex);
  170. sourceLine = encodeInteger(writer, segment[2], sourceLine);
  171. sourceColumn = encodeInteger(writer, segment[3], sourceColumn);
  172. if (segment.length === 4) continue;
  173. namesIndex = encodeInteger(writer, segment[4], namesIndex);
  174. }
  175. }
  176. return writer.flush();
  177. }
  178. //#endregion
  179. //#region node_modules/.pnpm/@jridgewell+resolve-uri@3.1.2/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.mjs
  180. const schemeRegex = /^[\w+.-]+:\/\//;
  181. /**
  182. * Matches the parts of a URL:
  183. * 1. Scheme, including ":", guaranteed.
  184. * 2. User/password, including "@", optional.
  185. * 3. Host, guaranteed.
  186. * 4. Port, including ":", optional.
  187. * 5. Path, including "/", optional.
  188. * 6. Query, including "?", optional.
  189. * 7. Hash, including "#", optional.
  190. */
  191. const urlRegex = /^([\w+.-]+:)\/\/([^@/#?]*@)?([^:/#?]*)(:\d+)?(\/[^#?]*)?(\?[^#]*)?(#.*)?/;
  192. /**
  193. * File URLs are weird. They dont' need the regular `//` in the scheme, they may or may not start
  194. * with a leading `/`, they can have a domain (but only if they don't start with a Windows drive).
  195. *
  196. * 1. Host, optional.
  197. * 2. Path, which may include "/", guaranteed.
  198. * 3. Query, including "?", optional.
  199. * 4. Hash, including "#", optional.
  200. */
  201. const fileRegex = /^file:(?:\/\/((?![a-z]:)[^/#?]*)?)?(\/?[^#?]*)(\?[^#]*)?(#.*)?/i;
  202. function isAbsoluteUrl(input) {
  203. return schemeRegex.test(input);
  204. }
  205. function isSchemeRelativeUrl(input) {
  206. return input.startsWith("//");
  207. }
  208. function isAbsolutePath(input) {
  209. return input.startsWith("/");
  210. }
  211. function isFileUrl(input) {
  212. return input.startsWith("file:");
  213. }
  214. function isRelative(input) {
  215. return /^[.?#]/.test(input);
  216. }
  217. function parseAbsoluteUrl(input) {
  218. const match = urlRegex.exec(input);
  219. return makeUrl(match[1], match[2] || "", match[3], match[4] || "", match[5] || "/", match[6] || "", match[7] || "");
  220. }
  221. function parseFileUrl(input) {
  222. const match = fileRegex.exec(input);
  223. const path$4 = match[2];
  224. return makeUrl("file:", "", match[1] || "", "", isAbsolutePath(path$4) ? path$4 : "/" + path$4, match[3] || "", match[4] || "");
  225. }
  226. function makeUrl(scheme, user, host, port, path$4, query, hash) {
  227. return {
  228. scheme,
  229. user,
  230. host,
  231. port,
  232. path: path$4,
  233. query,
  234. hash,
  235. type: 7
  236. };
  237. }
  238. function parseUrl(input) {
  239. if (isSchemeRelativeUrl(input)) {
  240. const url$1 = parseAbsoluteUrl("http:" + input);
  241. url$1.scheme = "";
  242. url$1.type = 6;
  243. return url$1;
  244. }
  245. if (isAbsolutePath(input)) {
  246. const url$1 = parseAbsoluteUrl("http://foo.com" + input);
  247. url$1.scheme = "";
  248. url$1.host = "";
  249. url$1.type = 5;
  250. return url$1;
  251. }
  252. if (isFileUrl(input)) return parseFileUrl(input);
  253. if (isAbsoluteUrl(input)) return parseAbsoluteUrl(input);
  254. const url = parseAbsoluteUrl("http://foo.com/" + input);
  255. url.scheme = "";
  256. url.host = "";
  257. url.type = input ? input.startsWith("?") ? 3 : input.startsWith("#") ? 2 : 4 : 1;
  258. return url;
  259. }
  260. function stripPathFilename(path$4) {
  261. if (path$4.endsWith("/..")) return path$4;
  262. const index = path$4.lastIndexOf("/");
  263. return path$4.slice(0, index + 1);
  264. }
  265. function mergePaths(url, base) {
  266. normalizePath(base, base.type);
  267. if (url.path === "/") url.path = base.path;
  268. else url.path = stripPathFilename(base.path) + url.path;
  269. }
  270. /**
  271. * The path can have empty directories "//", unneeded parents "foo/..", or current directory
  272. * "foo/.". We need to normalize to a standard representation.
  273. */
  274. function normalizePath(url, type) {
  275. const rel = type <= 4;
  276. const pieces = url.path.split("/");
  277. let pointer = 1;
  278. let positive = 0;
  279. let addTrailingSlash = false;
  280. for (let i = 1; i < pieces.length; i++) {
  281. const piece = pieces[i];
  282. if (!piece) {
  283. addTrailingSlash = true;
  284. continue;
  285. }
  286. addTrailingSlash = false;
  287. if (piece === ".") continue;
  288. if (piece === "..") {
  289. if (positive) {
  290. addTrailingSlash = true;
  291. positive--;
  292. pointer--;
  293. } else if (rel) pieces[pointer++] = piece;
  294. continue;
  295. }
  296. pieces[pointer++] = piece;
  297. positive++;
  298. }
  299. let path$4 = "";
  300. for (let i = 1; i < pointer; i++) path$4 += "/" + pieces[i];
  301. if (!path$4 || addTrailingSlash && !path$4.endsWith("/..")) path$4 += "/";
  302. url.path = path$4;
  303. }
  304. /**
  305. * Attempts to resolve `input` URL/path relative to `base`.
  306. */
  307. function resolve$3(input, base) {
  308. if (!input && !base) return "";
  309. const url = parseUrl(input);
  310. let inputType = url.type;
  311. if (base && inputType !== 7) {
  312. const baseUrl = parseUrl(base);
  313. const baseType = baseUrl.type;
  314. switch (inputType) {
  315. case 1: url.hash = baseUrl.hash;
  316. case 2: url.query = baseUrl.query;
  317. case 3:
  318. case 4: mergePaths(url, baseUrl);
  319. case 5:
  320. url.user = baseUrl.user;
  321. url.host = baseUrl.host;
  322. url.port = baseUrl.port;
  323. case 6: url.scheme = baseUrl.scheme;
  324. }
  325. if (baseType > inputType) inputType = baseType;
  326. }
  327. normalizePath(url, inputType);
  328. const queryHash = url.query + url.hash;
  329. switch (inputType) {
  330. case 2:
  331. case 3: return queryHash;
  332. case 4: {
  333. const path$4 = url.path.slice(1);
  334. if (!path$4) return queryHash || ".";
  335. if (isRelative(base || input) && !isRelative(path$4)) return "./" + path$4 + queryHash;
  336. return path$4 + queryHash;
  337. }
  338. case 5: return url.path + queryHash;
  339. default: return url.scheme + "//" + url.user + url.host + url.port + url.path + queryHash;
  340. }
  341. }
  342. //#endregion
  343. //#region node_modules/.pnpm/@jridgewell+trace-mapping@0.3.25/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.mjs
  344. function resolve$2(input, base) {
  345. if (base && !base.endsWith("/")) base += "/";
  346. return resolve$3(input, base);
  347. }
  348. /**
  349. * Removes everything after the last "/", but leaves the slash.
  350. */
  351. function stripFilename(path$4) {
  352. if (!path$4) return "";
  353. const index = path$4.lastIndexOf("/");
  354. return path$4.slice(0, index + 1);
  355. }
  356. const COLUMN$1 = 0;
  357. function maybeSort(mappings, owned) {
  358. const unsortedIndex = nextUnsortedSegmentLine(mappings, 0);
  359. if (unsortedIndex === mappings.length) return mappings;
  360. if (!owned) mappings = mappings.slice();
  361. for (let i = unsortedIndex; i < mappings.length; i = nextUnsortedSegmentLine(mappings, i + 1)) mappings[i] = sortSegments(mappings[i], owned);
  362. return mappings;
  363. }
  364. function nextUnsortedSegmentLine(mappings, start) {
  365. for (let i = start; i < mappings.length; i++) if (!isSorted(mappings[i])) return i;
  366. return mappings.length;
  367. }
  368. function isSorted(line) {
  369. for (let j = 1; j < line.length; j++) if (line[j][COLUMN$1] < line[j - 1][COLUMN$1]) return false;
  370. return true;
  371. }
  372. function sortSegments(line, owned) {
  373. if (!owned) line = line.slice();
  374. return line.sort(sortComparator);
  375. }
  376. function sortComparator(a, b) {
  377. return a[COLUMN$1] - b[COLUMN$1];
  378. }
  379. let found = false;
  380. /**
  381. * A binary search implementation that returns the index if a match is found.
  382. * If no match is found, then the left-index (the index associated with the item that comes just
  383. * before the desired index) is returned. To maintain proper sort order, a splice would happen at
  384. * the next index:
  385. *
  386. * ```js
  387. * const array = [1, 3];
  388. * const needle = 2;
  389. * const index = binarySearch(array, needle, (item, needle) => item - needle);
  390. *
  391. * assert.equal(index, 0);
  392. * array.splice(index + 1, 0, needle);
  393. * assert.deepEqual(array, [1, 2, 3]);
  394. * ```
  395. */
  396. function binarySearch(haystack, needle, low, high) {
  397. while (low <= high) {
  398. const mid = low + (high - low >> 1);
  399. const cmp = haystack[mid][COLUMN$1] - needle;
  400. if (cmp === 0) {
  401. found = true;
  402. return mid;
  403. }
  404. if (cmp < 0) low = mid + 1;
  405. else high = mid - 1;
  406. }
  407. found = false;
  408. return low - 1;
  409. }
  410. function upperBound(haystack, needle, index) {
  411. for (let i = index + 1; i < haystack.length; index = i++) if (haystack[i][COLUMN$1] !== needle) break;
  412. return index;
  413. }
  414. function lowerBound(haystack, needle, index) {
  415. for (let i = index - 1; i >= 0; index = i--) if (haystack[i][COLUMN$1] !== needle) break;
  416. return index;
  417. }
  418. function memoizedState() {
  419. return {
  420. lastKey: -1,
  421. lastNeedle: -1,
  422. lastIndex: -1
  423. };
  424. }
  425. /**
  426. * This overly complicated beast is just to record the last tested line/column and the resulting
  427. * index, allowing us to skip a few tests if mappings are monotonically increasing.
  428. */
  429. function memoizedBinarySearch(haystack, needle, state, key) {
  430. const { lastKey, lastNeedle, lastIndex } = state;
  431. let low = 0;
  432. let high = haystack.length - 1;
  433. if (key === lastKey) {
  434. if (needle === lastNeedle) {
  435. found = lastIndex !== -1 && haystack[lastIndex][COLUMN$1] === needle;
  436. return lastIndex;
  437. }
  438. if (needle >= lastNeedle) low = lastIndex === -1 ? 0 : lastIndex;
  439. else high = lastIndex;
  440. }
  441. state.lastKey = key;
  442. state.lastNeedle = needle;
  443. return state.lastIndex = binarySearch(haystack, needle, low, high);
  444. }
  445. const LEAST_UPPER_BOUND = -1;
  446. const GREATEST_LOWER_BOUND = 1;
  447. var TraceMap = class {
  448. constructor(map, mapUrl) {
  449. const isString$1 = typeof map === "string";
  450. if (!isString$1 && map._decodedMemo) return map;
  451. const parsed = isString$1 ? JSON.parse(map) : map;
  452. const { version, file, names, sourceRoot, sources, sourcesContent } = parsed;
  453. this.version = version;
  454. this.file = file;
  455. this.names = names || [];
  456. this.sourceRoot = sourceRoot;
  457. this.sources = sources;
  458. this.sourcesContent = sourcesContent;
  459. this.ignoreList = parsed.ignoreList || parsed.x_google_ignoreList || void 0;
  460. const from = resolve$2(sourceRoot || "", stripFilename(mapUrl));
  461. this.resolvedSources = sources.map((s) => resolve$2(s || "", from));
  462. const { mappings } = parsed;
  463. if (typeof mappings === "string") {
  464. this._encoded = mappings;
  465. this._decoded = void 0;
  466. } else {
  467. this._encoded = void 0;
  468. this._decoded = maybeSort(mappings, isString$1);
  469. }
  470. this._decodedMemo = memoizedState();
  471. this._bySources = void 0;
  472. this._bySourceMemos = void 0;
  473. }
  474. };
  475. /**
  476. * Typescript doesn't allow friend access to private fields, so this just casts the map into a type
  477. * with public access modifiers.
  478. */
  479. function cast$2(map) {
  480. return map;
  481. }
  482. /**
  483. * Returns the decoded (array of lines of segments) form of the SourceMap's mappings field.
  484. */
  485. function decodedMappings(map) {
  486. var _a;
  487. return (_a = cast$2(map))._decoded || (_a._decoded = decode(cast$2(map)._encoded));
  488. }
  489. /**
  490. * A low-level API to find the segment associated with a generated line/column (think, from a
  491. * stack trace). Line and column here are 0-based, unlike `originalPositionFor`.
  492. */
  493. function traceSegment(map, line, column) {
  494. const decoded = decodedMappings(map);
  495. if (line >= decoded.length) return null;
  496. const segments = decoded[line];
  497. const index = traceSegmentInternal(segments, cast$2(map)._decodedMemo, line, column, GREATEST_LOWER_BOUND);
  498. return index === -1 ? null : segments[index];
  499. }
  500. function traceSegmentInternal(segments, memo, line, column, bias) {
  501. let index = memoizedBinarySearch(segments, column, memo, line);
  502. if (found) index = (bias === LEAST_UPPER_BOUND ? upperBound : lowerBound)(segments, column, index);
  503. else if (bias === LEAST_UPPER_BOUND) index++;
  504. if (index === -1 || index === segments.length) return -1;
  505. return index;
  506. }
  507. //#endregion
  508. //#region node_modules/.pnpm/@jridgewell+set-array@1.2.1/node_modules/@jridgewell/set-array/dist/set-array.mjs
  509. /**
  510. * SetArray acts like a `Set` (allowing only one occurrence of a string `key`), but provides the
  511. * index of the `key` in the backing array.
  512. *
  513. * This is designed to allow synchronizing a second array with the contents of the backing array,
  514. * like how in a sourcemap `sourcesContent[i]` is the source content associated with `source[i]`,
  515. * and there are never duplicates.
  516. */
  517. var SetArray = class {
  518. constructor() {
  519. this._indexes = { __proto__: null };
  520. this.array = [];
  521. }
  522. };
  523. /**
  524. * Typescript doesn't allow friend access to private fields, so this just casts the set into a type
  525. * with public access modifiers.
  526. */
  527. function cast$1(set) {
  528. return set;
  529. }
  530. /**
  531. * Gets the index associated with `key` in the backing array, if it is already present.
  532. */
  533. function get(setarr, key) {
  534. return cast$1(setarr)._indexes[key];
  535. }
  536. /**
  537. * Puts `key` into the backing array, if it is not already present. Returns
  538. * the index of the `key` in the backing array.
  539. */
  540. function put(setarr, key) {
  541. const index = get(setarr, key);
  542. if (index !== void 0) return index;
  543. const { array, _indexes: indexes } = cast$1(setarr);
  544. const length = array.push(key);
  545. return indexes[key] = length - 1;
  546. }
  547. /**
  548. * Removes the key, if it exists in the set.
  549. */
  550. function remove(setarr, key) {
  551. const index = get(setarr, key);
  552. if (index === void 0) return;
  553. const { array, _indexes: indexes } = cast$1(setarr);
  554. for (let i = index + 1; i < array.length; i++) {
  555. const k = array[i];
  556. array[i - 1] = k;
  557. indexes[k]--;
  558. }
  559. indexes[key] = void 0;
  560. array.pop();
  561. }
  562. //#endregion
  563. //#region node_modules/.pnpm/@jridgewell+gen-mapping@0.3.8/node_modules/@jridgewell/gen-mapping/dist/gen-mapping.mjs
  564. const COLUMN = 0;
  565. const SOURCES_INDEX = 1;
  566. const SOURCE_LINE = 2;
  567. const SOURCE_COLUMN = 3;
  568. const NAMES_INDEX = 4;
  569. const NO_NAME = -1;
  570. /**
  571. * Provides the state to generate a sourcemap.
  572. */
  573. var GenMapping = class {
  574. constructor({ file, sourceRoot } = {}) {
  575. this._names = new SetArray();
  576. this._sources = new SetArray();
  577. this._sourcesContent = [];
  578. this._mappings = [];
  579. this.file = file;
  580. this.sourceRoot = sourceRoot;
  581. this._ignoreList = new SetArray();
  582. }
  583. };
  584. /**
  585. * Typescript doesn't allow friend access to private fields, so this just casts the map into a type
  586. * with public access modifiers.
  587. */
  588. function cast(map) {
  589. return map;
  590. }
  591. /**
  592. * Same as `addSegment`, but will only add the segment if it generates useful information in the
  593. * resulting map. This only works correctly if segments are added **in order**, meaning you should
  594. * not add a segment with a lower generated line/column than one that came before.
  595. */
  596. const maybeAddSegment = (map, genLine, genColumn, source, sourceLine, sourceColumn, name, content) => {
  597. return addSegmentInternal(true, map, genLine, genColumn, source, sourceLine, sourceColumn, name, content);
  598. };
  599. /**
  600. * Adds/removes the content of the source file to the source map.
  601. */
  602. function setSourceContent(map, source, content) {
  603. const { _sources: sources, _sourcesContent: sourcesContent } = cast(map);
  604. const index = put(sources, source);
  605. sourcesContent[index] = content;
  606. }
  607. function setIgnore(map, source, ignore = true) {
  608. const { _sources: sources, _sourcesContent: sourcesContent, _ignoreList: ignoreList } = cast(map);
  609. const index = put(sources, source);
  610. if (index === sourcesContent.length) sourcesContent[index] = null;
  611. if (ignore) put(ignoreList, index);
  612. else remove(ignoreList, index);
  613. }
  614. /**
  615. * Returns a sourcemap object (with decoded mappings) suitable for passing to a library that expects
  616. * a sourcemap, or to JSON.stringify.
  617. */
  618. function toDecodedMap(map) {
  619. const { _mappings: mappings, _sources: sources, _sourcesContent: sourcesContent, _names: names, _ignoreList: ignoreList } = cast(map);
  620. removeEmptyFinalLines(mappings);
  621. return {
  622. version: 3,
  623. file: map.file || void 0,
  624. names: names.array,
  625. sourceRoot: map.sourceRoot || void 0,
  626. sources: sources.array,
  627. sourcesContent,
  628. mappings,
  629. ignoreList: ignoreList.array
  630. };
  631. }
  632. /**
  633. * Returns a sourcemap object (with encoded mappings) suitable for passing to a library that expects
  634. * a sourcemap, or to JSON.stringify.
  635. */
  636. function toEncodedMap(map) {
  637. const decoded = toDecodedMap(map);
  638. return Object.assign(Object.assign({}, decoded), { mappings: encode(decoded.mappings) });
  639. }
  640. function addSegmentInternal(skipable, map, genLine, genColumn, source, sourceLine, sourceColumn, name, content) {
  641. const { _mappings: mappings, _sources: sources, _sourcesContent: sourcesContent, _names: names } = cast(map);
  642. const line = getLine(mappings, genLine);
  643. const index = getColumnIndex(line, genColumn);
  644. if (!source) {
  645. if (skipable && skipSourceless(line, index)) return;
  646. return insert(line, index, [genColumn]);
  647. }
  648. const sourcesIndex = put(sources, source);
  649. const namesIndex = name ? put(names, name) : NO_NAME;
  650. if (sourcesIndex === sourcesContent.length) sourcesContent[sourcesIndex] = content !== null && content !== void 0 ? content : null;
  651. if (skipable && skipSource(line, index, sourcesIndex, sourceLine, sourceColumn, namesIndex)) return;
  652. return insert(line, index, name ? [
  653. genColumn,
  654. sourcesIndex,
  655. sourceLine,
  656. sourceColumn,
  657. namesIndex
  658. ] : [
  659. genColumn,
  660. sourcesIndex,
  661. sourceLine,
  662. sourceColumn
  663. ]);
  664. }
  665. function getLine(mappings, index) {
  666. for (let i = mappings.length; i <= index; i++) mappings[i] = [];
  667. return mappings[index];
  668. }
  669. function getColumnIndex(line, genColumn) {
  670. let index = line.length;
  671. for (let i = index - 1; i >= 0; index = i--) {
  672. const current = line[i];
  673. if (genColumn >= current[COLUMN]) break;
  674. }
  675. return index;
  676. }
  677. function insert(array, index, value) {
  678. for (let i = array.length; i > index; i--) array[i] = array[i - 1];
  679. array[index] = value;
  680. }
  681. function removeEmptyFinalLines(mappings) {
  682. const { length } = mappings;
  683. let len = length;
  684. for (let i = len - 1; i >= 0; len = i, i--) if (mappings[i].length > 0) break;
  685. if (len < length) mappings.length = len;
  686. }
  687. function skipSourceless(line, index) {
  688. if (index === 0) return true;
  689. const prev = line[index - 1];
  690. return prev.length === 1;
  691. }
  692. function skipSource(line, index, sourcesIndex, sourceLine, sourceColumn, namesIndex) {
  693. if (index === 0) return false;
  694. const prev = line[index - 1];
  695. if (prev.length === 1) return false;
  696. return sourcesIndex === prev[SOURCES_INDEX] && sourceLine === prev[SOURCE_LINE] && sourceColumn === prev[SOURCE_COLUMN] && namesIndex === (prev.length === 5 ? prev[NAMES_INDEX] : NO_NAME);
  697. }
  698. //#endregion
  699. //#region node_modules/.pnpm/@ampproject+remapping@2.3.0/node_modules/@ampproject/remapping/dist/remapping.mjs
  700. const SOURCELESS_MAPPING = /* @__PURE__ */ SegmentObject("", -1, -1, "", null, false);
  701. const EMPTY_SOURCES = [];
  702. function SegmentObject(source, line, column, name, content, ignore) {
  703. return {
  704. source,
  705. line,
  706. column,
  707. name,
  708. content,
  709. ignore
  710. };
  711. }
  712. function Source(map, sources, source, content, ignore) {
  713. return {
  714. map,
  715. sources,
  716. source,
  717. content,
  718. ignore
  719. };
  720. }
  721. /**
  722. * MapSource represents a single sourcemap, with the ability to trace mappings into its child nodes
  723. * (which may themselves be SourceMapTrees).
  724. */
  725. function MapSource(map, sources) {
  726. return Source(map, sources, "", null, false);
  727. }
  728. /**
  729. * A "leaf" node in the sourcemap tree, representing an original, unmodified source file. Recursive
  730. * segment tracing ends at the `OriginalSource`.
  731. */
  732. function OriginalSource(source, content, ignore) {
  733. return Source(null, EMPTY_SOURCES, source, content, ignore);
  734. }
  735. /**
  736. * traceMappings is only called on the root level SourceMapTree, and begins the process of
  737. * resolving each mapping in terms of the original source files.
  738. */
  739. function traceMappings(tree) {
  740. const gen = new GenMapping({ file: tree.map.file });
  741. const { sources: rootSources, map } = tree;
  742. const rootNames = map.names;
  743. const rootMappings = decodedMappings(map);
  744. for (let i = 0; i < rootMappings.length; i++) {
  745. const segments = rootMappings[i];
  746. for (let j = 0; j < segments.length; j++) {
  747. const segment = segments[j];
  748. const genCol = segment[0];
  749. let traced = SOURCELESS_MAPPING;
  750. if (segment.length !== 1) {
  751. const source$1 = rootSources[segment[1]];
  752. traced = originalPositionFor(source$1, segment[2], segment[3], segment.length === 5 ? rootNames[segment[4]] : "");
  753. if (traced == null) continue;
  754. }
  755. const { column, line, name, content, source, ignore } = traced;
  756. maybeAddSegment(gen, i, genCol, source, line, column, name);
  757. if (source && content != null) setSourceContent(gen, source, content);
  758. if (ignore) setIgnore(gen, source, true);
  759. }
  760. }
  761. return gen;
  762. }
  763. /**
  764. * originalPositionFor is only called on children SourceMapTrees. It recurses down into its own
  765. * child SourceMapTrees, until we find the original source map.
  766. */
  767. function originalPositionFor(source, line, column, name) {
  768. if (!source.map) return SegmentObject(source.source, line, column, name, source.content, source.ignore);
  769. const segment = traceSegment(source.map, line, column);
  770. if (segment == null) return null;
  771. if (segment.length === 1) return SOURCELESS_MAPPING;
  772. return originalPositionFor(source.sources[segment[1]], segment[2], segment[3], segment.length === 5 ? source.map.names[segment[4]] : name);
  773. }
  774. function asArray(value) {
  775. if (Array.isArray(value)) return value;
  776. return [value];
  777. }
  778. /**
  779. * Recursively builds a tree structure out of sourcemap files, with each node
  780. * being either an `OriginalSource` "leaf" or a `SourceMapTree` composed of
  781. * `OriginalSource`s and `SourceMapTree`s.
  782. *
  783. * Every sourcemap is composed of a collection of source files and mappings
  784. * into locations of those source files. When we generate a `SourceMapTree` for
  785. * the sourcemap, we attempt to load each source file's own sourcemap. If it
  786. * does not have an associated sourcemap, it is considered an original,
  787. * unmodified source file.
  788. */
  789. function buildSourceMapTree(input, loader) {
  790. const maps = asArray(input).map((m) => new TraceMap(m, ""));
  791. const map = maps.pop();
  792. for (let i = 0; i < maps.length; i++) if (maps[i].sources.length > 1) throw new Error(`Transformation map ${i} must have exactly one source file.\nDid you specify these with the most recent transformation maps first?`);
  793. let tree = build(map, loader, "", 0);
  794. for (let i = maps.length - 1; i >= 0; i--) tree = MapSource(maps[i], [tree]);
  795. return tree;
  796. }
  797. function build(map, loader, importer, importerDepth) {
  798. const { resolvedSources, sourcesContent, ignoreList } = map;
  799. const depth = importerDepth + 1;
  800. const children = resolvedSources.map((sourceFile, i) => {
  801. const ctx = {
  802. importer,
  803. depth,
  804. source: sourceFile || "",
  805. content: void 0,
  806. ignore: void 0
  807. };
  808. const sourceMap = loader(ctx.source, ctx);
  809. const { source, content, ignore } = ctx;
  810. if (sourceMap) return build(new TraceMap(sourceMap, source), loader, source, depth);
  811. const sourceContent = content !== void 0 ? content : sourcesContent ? sourcesContent[i] : null;
  812. const ignored = ignore !== void 0 ? ignore : ignoreList ? ignoreList.includes(i) : false;
  813. return OriginalSource(source, sourceContent, ignored);
  814. });
  815. return MapSource(map, children);
  816. }
  817. /**
  818. * A SourceMap v3 compatible sourcemap, which only includes fields that were
  819. * provided to it.
  820. */
  821. var SourceMap = class {
  822. constructor(map, options) {
  823. const out = options.decodedMappings ? toDecodedMap(map) : toEncodedMap(map);
  824. this.version = out.version;
  825. this.file = out.file;
  826. this.mappings = out.mappings;
  827. this.names = out.names;
  828. this.ignoreList = out.ignoreList;
  829. this.sourceRoot = out.sourceRoot;
  830. this.sources = out.sources;
  831. if (!options.excludeContent) this.sourcesContent = out.sourcesContent;
  832. }
  833. toString() {
  834. return JSON.stringify(this);
  835. }
  836. };
  837. /**
  838. * Traces through all the mappings in the root sourcemap, through the sources
  839. * (and their sourcemaps), all the way back to the original source location.
  840. *
  841. * `loader` will be called every time we encounter a source file. If it returns
  842. * a sourcemap, we will recurse into that sourcemap to continue the trace. If
  843. * it returns a falsey value, that source file is treated as an original,
  844. * unmodified source file.
  845. *
  846. * Pass `excludeContent` to exclude any self-containing source file content
  847. * from the output sourcemap.
  848. *
  849. * Pass `decodedMappings` to receive a SourceMap with decoded (instead of
  850. * VLQ encoded) mappings.
  851. */
  852. function remapping(input, loader, options) {
  853. const opts = typeof options === "object" ? options : {
  854. excludeContent: !!options,
  855. decodedMappings: false
  856. };
  857. const tree = buildSourceMapTree(input, loader);
  858. return new SourceMap(traceMappings(tree), opts);
  859. }
  860. //#endregion
  861. //#region src/esbuild/utils.ts
  862. const ExtToLoader = {
  863. ".js": "js",
  864. ".mjs": "js",
  865. ".cjs": "js",
  866. ".jsx": "jsx",
  867. ".ts": "ts",
  868. ".cts": "ts",
  869. ".mts": "ts",
  870. ".tsx": "tsx",
  871. ".css": "css",
  872. ".less": "css",
  873. ".stylus": "css",
  874. ".scss": "css",
  875. ".sass": "css",
  876. ".json": "json",
  877. ".txt": "text"
  878. };
  879. function guessLoader(code, id) {
  880. return ExtToLoader[node_path.default.extname(id).toLowerCase()] || "js";
  881. }
  882. function unwrapLoader(loader, code, id) {
  883. if (typeof loader === "function") return loader(code, id);
  884. return loader;
  885. }
  886. function fixSourceMap(map) {
  887. if (!Object.prototype.hasOwnProperty.call(map, "toString")) Object.defineProperty(map, "toString", {
  888. enumerable: false,
  889. value: function toString() {
  890. return JSON.stringify(this);
  891. }
  892. });
  893. if (!Object.prototype.hasOwnProperty.call(map, "toUrl")) Object.defineProperty(map, "toUrl", {
  894. enumerable: false,
  895. value: function toUrl() {
  896. return `data:application/json;charset=utf-8;base64,${node_buffer.Buffer.from(this.toString()).toString("base64")}`;
  897. }
  898. });
  899. return map;
  900. }
  901. const nullSourceMap = {
  902. names: [],
  903. sources: [],
  904. mappings: "",
  905. version: 3
  906. };
  907. function combineSourcemaps(filename, sourcemapList) {
  908. sourcemapList = sourcemapList.filter((m) => m.sources);
  909. if (sourcemapList.length === 0 || sourcemapList.every((m) => m.sources.length === 0)) return { ...nullSourceMap };
  910. let map;
  911. let mapIndex = 1;
  912. const useArrayInterface = sourcemapList.slice(0, -1).find((m) => m.sources.length !== 1) === void 0;
  913. if (useArrayInterface) map = remapping(sourcemapList, () => null, true);
  914. else map = remapping(sourcemapList[0], (sourcefile) => {
  915. if (sourcefile === filename && sourcemapList[mapIndex]) return sourcemapList[mapIndex++];
  916. else return { ...nullSourceMap };
  917. }, true);
  918. if (!map.file) delete map.file;
  919. return map;
  920. }
  921. function createBuildContext$2(build$1) {
  922. const watchFiles = [];
  923. const { initialOptions } = build$1;
  924. return {
  925. parse: require_context.parse,
  926. addWatchFile() {
  927. throw new Error("unplugin/esbuild: addWatchFile outside supported hooks (resolveId, load, transform)");
  928. },
  929. emitFile(emittedFile) {
  930. const outFileName = emittedFile.fileName || emittedFile.name;
  931. if (initialOptions.outdir && emittedFile.source && outFileName) {
  932. const outPath = node_path.default.resolve(initialOptions.outdir, outFileName);
  933. const outDir = node_path.default.dirname(outPath);
  934. if (!node_fs.default.existsSync(outDir)) node_fs.default.mkdirSync(outDir, { recursive: true });
  935. node_fs.default.writeFileSync(outPath, emittedFile.source);
  936. }
  937. },
  938. getWatchFiles() {
  939. return watchFiles;
  940. },
  941. getNativeBuildContext() {
  942. return {
  943. framework: "esbuild",
  944. build: build$1
  945. };
  946. }
  947. };
  948. }
  949. function createPluginContext(context) {
  950. const errors = [];
  951. const warnings = [];
  952. const pluginContext = {
  953. error(message) {
  954. errors.push(normalizeMessage$2(message));
  955. },
  956. warn(message) {
  957. warnings.push(normalizeMessage$2(message));
  958. }
  959. };
  960. const mixedContext = {
  961. ...context,
  962. ...pluginContext,
  963. addWatchFile(id) {
  964. context.getWatchFiles().push(id);
  965. }
  966. };
  967. return {
  968. errors,
  969. warnings,
  970. mixedContext
  971. };
  972. }
  973. function normalizeMessage$2(message) {
  974. if (typeof message === "string") message = { message };
  975. return {
  976. id: message.id,
  977. pluginName: message.plugin,
  978. text: message.message,
  979. location: message.loc ? {
  980. file: message.loc.file,
  981. line: message.loc.line,
  982. column: message.loc.column
  983. } : null,
  984. detail: message.meta,
  985. notes: []
  986. };
  987. }
  988. function processCodeWithSourceMap(map, code) {
  989. if (map) {
  990. if (!map.sourcesContent || map.sourcesContent.length === 0) map.sourcesContent = [code];
  991. map = fixSourceMap(map);
  992. code += `\n//# sourceMappingURL=${map.toUrl()}`;
  993. }
  994. return code;
  995. }
  996. //#endregion
  997. //#region src/esbuild/index.ts
  998. function getEsbuildPlugin(factory) {
  999. return (userOptions) => {
  1000. const meta = { framework: "esbuild" };
  1001. const plugins = require_context.toArray(factory(userOptions, meta));
  1002. const setupPlugins = async (build$1) => {
  1003. const setup = buildSetup();
  1004. const loaders = [];
  1005. for (const plugin of plugins) {
  1006. const loader = {};
  1007. await setup(plugin)({
  1008. ...build$1,
  1009. onLoad(_options, callback) {
  1010. loader.options = _options;
  1011. loader.onLoadCb = callback;
  1012. },
  1013. onTransform(_options, callback) {
  1014. loader.options ||= _options;
  1015. loader.onTransformCb = callback;
  1016. }
  1017. }, build$1);
  1018. if (loader.onLoadCb || loader.onTransformCb) loaders.push(loader);
  1019. }
  1020. if (loaders.length) build$1.onLoad(loaders.length === 1 ? loaders[0].options : { filter: /.*/ }, async (args) => {
  1021. function checkFilter(options) {
  1022. return loaders.length === 1 || !options?.filter || options.filter.test(args.path);
  1023. }
  1024. let result;
  1025. for (const { options, onLoadCb } of loaders) {
  1026. if (!checkFilter(options)) continue;
  1027. if (onLoadCb) result = await onLoadCb(args);
  1028. if (result?.contents) break;
  1029. }
  1030. let fsContentsCache;
  1031. for (const { options, onTransformCb } of loaders) {
  1032. if (!checkFilter(options)) continue;
  1033. if (onTransformCb) {
  1034. const newArgs = {
  1035. ...result,
  1036. ...args,
  1037. async getContents() {
  1038. if (result?.contents) return result.contents;
  1039. if (fsContentsCache) return fsContentsCache;
  1040. return fsContentsCache = await node_fs.default.promises.readFile(args.path, "utf8");
  1041. }
  1042. };
  1043. const _result = await onTransformCb(newArgs);
  1044. if (_result?.contents) result = _result;
  1045. }
  1046. }
  1047. if (result?.contents) return result;
  1048. });
  1049. };
  1050. return {
  1051. name: (plugins.length === 1 ? plugins[0].name : meta.esbuildHostName) ?? `unplugin-host:${plugins.map((p) => p.name).join(":")}`,
  1052. setup: setupPlugins
  1053. };
  1054. };
  1055. }
  1056. function buildSetup() {
  1057. return (plugin) => {
  1058. return (build$1, rawBuild) => {
  1059. const context = createBuildContext$2(rawBuild);
  1060. const { onStart, onEnd, onResolve, onLoad, onTransform, initialOptions } = build$1;
  1061. const onResolveFilter = plugin.esbuild?.onResolveFilter ?? /.*/;
  1062. const onLoadFilter = plugin.esbuild?.onLoadFilter ?? /.*/;
  1063. const loader = plugin.esbuild?.loader ?? guessLoader;
  1064. plugin.esbuild?.config?.call(context, initialOptions);
  1065. if (plugin.buildStart) onStart(() => plugin.buildStart.call(context));
  1066. if (plugin.buildEnd || plugin.writeBundle) onEnd(async () => {
  1067. if (plugin.buildEnd) await plugin.buildEnd.call(context);
  1068. if (plugin.writeBundle) await plugin.writeBundle();
  1069. });
  1070. if (plugin.resolveId) onResolve({ filter: onResolveFilter }, async (args) => {
  1071. const id = args.path;
  1072. if (initialOptions.external?.includes(id)) return;
  1073. const { handler, filter } = require_context.normalizeObjectHook("resolveId", plugin.resolveId);
  1074. if (!filter(id)) return;
  1075. const { errors, warnings, mixedContext } = createPluginContext(context);
  1076. const isEntry = args.kind === "entry-point";
  1077. const result = await handler.call(mixedContext, id, isEntry ? void 0 : args.importer, { isEntry });
  1078. if (typeof result === "string") return {
  1079. path: result,
  1080. namespace: plugin.name,
  1081. errors,
  1082. warnings,
  1083. watchFiles: mixedContext.getWatchFiles()
  1084. };
  1085. else if (typeof result === "object" && result !== null) return {
  1086. path: result.id,
  1087. external: result.external,
  1088. namespace: plugin.name,
  1089. errors,
  1090. warnings,
  1091. watchFiles: mixedContext.getWatchFiles()
  1092. };
  1093. });
  1094. if (plugin.load) onLoad({ filter: onLoadFilter }, async (args) => {
  1095. const { handler, filter } = require_context.normalizeObjectHook("load", plugin.load);
  1096. const id = args.path + (args.suffix || "");
  1097. if (plugin.loadInclude && !plugin.loadInclude(id)) return;
  1098. if (!filter(id)) return;
  1099. const { errors, warnings, mixedContext } = createPluginContext(context);
  1100. let code;
  1101. let map;
  1102. const result = await handler.call(mixedContext, id);
  1103. if (typeof result === "string") code = result;
  1104. else if (typeof result === "object" && result !== null) {
  1105. code = result.code;
  1106. map = result.map;
  1107. }
  1108. if (code === void 0) return null;
  1109. if (map) code = processCodeWithSourceMap(map, code);
  1110. const resolveDir = node_path.default.dirname(args.path);
  1111. return {
  1112. contents: code,
  1113. errors,
  1114. warnings,
  1115. watchFiles: mixedContext.getWatchFiles(),
  1116. loader: unwrapLoader(loader, code, args.path),
  1117. resolveDir
  1118. };
  1119. });
  1120. if (plugin.transform) onTransform({ filter: onLoadFilter }, async (args) => {
  1121. const { handler, filter } = require_context.normalizeObjectHook("transform", plugin.transform);
  1122. const id = args.path + (args.suffix || "");
  1123. if (plugin.transformInclude && !plugin.transformInclude(id)) return;
  1124. let code = await args.getContents();
  1125. if (!filter(id, code)) return;
  1126. const { mixedContext, errors, warnings } = createPluginContext(context);
  1127. const resolveDir = node_path.default.dirname(args.path);
  1128. let map;
  1129. const result = await handler.call(mixedContext, code, id);
  1130. if (typeof result === "string") code = result;
  1131. else if (typeof result === "object" && result !== null) {
  1132. code = result.code;
  1133. if (map && result.map) map = combineSourcemaps(args.path, [result.map === "string" ? JSON.parse(result.map) : result.map, map]);
  1134. else if (typeof result.map === "string") map = JSON.parse(result.map);
  1135. else map = result.map;
  1136. }
  1137. if (code) {
  1138. if (map) code = processCodeWithSourceMap(map, code);
  1139. return {
  1140. contents: code,
  1141. errors,
  1142. warnings,
  1143. watchFiles: mixedContext.getWatchFiles(),
  1144. loader: unwrapLoader(loader, code, args.path),
  1145. resolveDir
  1146. };
  1147. }
  1148. });
  1149. if (plugin.esbuild?.setup) return plugin.esbuild.setup(rawBuild);
  1150. };
  1151. };
  1152. }
  1153. //#endregion
  1154. //#region src/farm/context.ts
  1155. function createFarmContext(context, currentResolveId) {
  1156. return {
  1157. parse: require_context.parse,
  1158. addWatchFile(id) {
  1159. context.addWatchFile(id, currentResolveId || id);
  1160. },
  1161. emitFile(emittedFile) {
  1162. const outFileName = emittedFile.fileName || emittedFile.name;
  1163. if (emittedFile.source && outFileName) context.emitFile({
  1164. resolvedPath: outFileName,
  1165. name: outFileName,
  1166. content: [...node_buffer.Buffer.from(emittedFile.source)],
  1167. resourceType: (0, node_path.extname)(outFileName)
  1168. });
  1169. },
  1170. getWatchFiles() {
  1171. return context.getWatchFiles();
  1172. },
  1173. getNativeBuildContext() {
  1174. return {
  1175. framework: "farm",
  1176. context
  1177. };
  1178. }
  1179. };
  1180. }
  1181. function unpluginContext(context) {
  1182. return {
  1183. error: (error) => context.error(typeof error === "string" ? new Error(error) : error),
  1184. warn: (error) => context.warn(typeof error === "string" ? new Error(error) : error)
  1185. };
  1186. }
  1187. //#endregion
  1188. //#region src/farm/utils.ts
  1189. function convertEnforceToPriority(value) {
  1190. const defaultPriority = 100;
  1191. const enforceToPriority = {
  1192. pre: 102,
  1193. post: 98
  1194. };
  1195. return enforceToPriority[value] !== void 0 ? enforceToPriority[value] : defaultPriority;
  1196. }
  1197. function convertWatchEventChange(value) {
  1198. const watchEventChange = {
  1199. Added: "create",
  1200. Updated: "update",
  1201. Removed: "delete"
  1202. };
  1203. return watchEventChange[value];
  1204. }
  1205. function isString(variable) {
  1206. return typeof variable === "string";
  1207. }
  1208. function isObject(variable) {
  1209. return typeof variable === "object" && variable !== null;
  1210. }
  1211. function customParseQueryString(url) {
  1212. if (!url) return [];
  1213. const queryString = url.split("?")[1];
  1214. const parsedParams = node_querystring.parse(queryString);
  1215. const paramsArray = [];
  1216. for (const key in parsedParams) paramsArray.push([key, parsedParams[key]]);
  1217. return paramsArray;
  1218. }
  1219. function encodeStr(str) {
  1220. const len = str.length;
  1221. if (len === 0) return str;
  1222. const firstNullIndex = str.indexOf("\0");
  1223. if (firstNullIndex === -1) return str;
  1224. const result = Array.from({ length: len + countNulls(str, firstNullIndex) });
  1225. let pos = 0;
  1226. for (let i = 0; i < firstNullIndex; i++) result[pos++] = str[i];
  1227. for (let i = firstNullIndex; i < len; i++) {
  1228. const char = str[i];
  1229. if (char === "\0") {
  1230. result[pos++] = "\\";
  1231. result[pos++] = "0";
  1232. } else result[pos++] = char;
  1233. }
  1234. return node_path.default.posix.normalize(result.join(""));
  1235. }
  1236. function decodeStr(str) {
  1237. const len = str.length;
  1238. if (len === 0) return str;
  1239. const firstIndex = str.indexOf("\\0");
  1240. if (firstIndex === -1) return str;
  1241. const result = Array.from({ length: len - countBackslashZeros(str, firstIndex) });
  1242. let pos = 0;
  1243. for (let i$1 = 0; i$1 < firstIndex; i$1++) result[pos++] = str[i$1];
  1244. let i = firstIndex;
  1245. while (i < len) if (str[i] === "\\" && str[i + 1] === "0") {
  1246. result[pos++] = "\0";
  1247. i += 2;
  1248. } else result[pos++] = str[i++];
  1249. return node_path.default.posix.normalize(result.join(""));
  1250. }
  1251. function getContentValue(content) {
  1252. if (content === null || content === void 0) throw new Error("Content cannot be null or undefined");
  1253. const strContent = typeof content === "string" ? content : content.code || "";
  1254. return encodeStr(strContent);
  1255. }
  1256. function countNulls(str, startIndex) {
  1257. let count = 0;
  1258. const len = str.length;
  1259. for (let i = startIndex; i < len; i++) if (str[i] === "\0") count++;
  1260. return count;
  1261. }
  1262. function countBackslashZeros(str, startIndex) {
  1263. let count = 0;
  1264. const len = str.length;
  1265. for (let i = startIndex; i < len - 1; i++) if (str[i] === "\\" && str[i + 1] === "0") {
  1266. count++;
  1267. i++;
  1268. }
  1269. return count;
  1270. }
  1271. function removeQuery(pathe) {
  1272. const queryIndex = pathe.indexOf("?");
  1273. if (queryIndex !== -1) return node_path.default.posix.normalize(pathe.slice(0, queryIndex));
  1274. return node_path.default.posix.normalize(pathe);
  1275. }
  1276. function isStartsWithSlash(str) {
  1277. return str?.startsWith("/");
  1278. }
  1279. function appendQuery(id, query) {
  1280. if (!query.length) return id;
  1281. return `${id}?${stringifyQuery(query)}`;
  1282. }
  1283. function stringifyQuery(query) {
  1284. if (!query.length) return "";
  1285. let queryStr = "";
  1286. for (const [key, value] of query) queryStr += `${key}${value ? `=${value}` : ""}&`;
  1287. return `${queryStr.slice(0, -1)}`;
  1288. }
  1289. const CSS_LANGS_RES = [
  1290. [/\.(less)(?:$|\?)/, "less"],
  1291. [/\.(scss|sass)(?:$|\?)/, "sass"],
  1292. [/\.(styl|stylus)(?:$|\?)/, "stylus"],
  1293. [/\.(css)(?:$|\?)/, "css"]
  1294. ];
  1295. const JS_LANGS_RES = [
  1296. [/\.(js|mjs|cjs)(?:$|\?)/, "js"],
  1297. [/\.(jsx)(?:$|\?)/, "jsx"],
  1298. [/\.(ts|cts|mts)(?:$|\?)/, "ts"],
  1299. [/\.(tsx)(?:$|\?)/, "tsx"]
  1300. ];
  1301. function getCssModuleType(id) {
  1302. for (const [reg, lang] of CSS_LANGS_RES) if (reg.test(id)) return lang;
  1303. return null;
  1304. }
  1305. function getJsModuleType(id) {
  1306. for (const [reg, lang] of JS_LANGS_RES) if (reg.test(id)) return lang;
  1307. return null;
  1308. }
  1309. function formatLoadModuleType(id) {
  1310. const cssModuleType = getCssModuleType(id);
  1311. if (cssModuleType) return cssModuleType;
  1312. const jsModuleType = getJsModuleType(id);
  1313. if (jsModuleType) return jsModuleType;
  1314. return "js";
  1315. }
  1316. function formatTransformModuleType(id) {
  1317. return formatLoadModuleType(id);
  1318. }
  1319. //#endregion
  1320. //#region src/farm/index.ts
  1321. function getFarmPlugin(factory) {
  1322. return (userOptions) => {
  1323. const meta = { framework: "farm" };
  1324. const rawPlugins = require_context.toArray(factory(userOptions, meta));
  1325. const plugins = rawPlugins.map((rawPlugin) => {
  1326. const plugin = toFarmPlugin(rawPlugin, userOptions);
  1327. if (rawPlugin.farm) Object.assign(plugin, rawPlugin.farm);
  1328. return plugin;
  1329. });
  1330. return plugins.length === 1 ? plugins[0] : plugins;
  1331. };
  1332. }
  1333. function toFarmPlugin(plugin, options) {
  1334. const farmPlugin = {
  1335. name: plugin.name,
  1336. priority: convertEnforceToPriority(plugin.enforce)
  1337. };
  1338. if (plugin.farm) Object.keys(plugin.farm).forEach((key) => {
  1339. const value = plugin.farm[key];
  1340. if (value) Reflect.set(farmPlugin, key, value);
  1341. });
  1342. if (plugin.buildStart) {
  1343. const _buildStart = plugin.buildStart;
  1344. farmPlugin.buildStart = { async executor(_, context) {
  1345. await _buildStart.call(createFarmContext(context));
  1346. } };
  1347. }
  1348. if (plugin.resolveId) {
  1349. const _resolveId = plugin.resolveId;
  1350. let filters = [];
  1351. if (options) filters = options?.filters ?? [];
  1352. farmPlugin.resolve = {
  1353. filters: {
  1354. sources: filters.length ? filters : [".*"],
  1355. importers: [".*"]
  1356. },
  1357. async executor(params, context) {
  1358. const resolvedIdPath = node_path.default.resolve(params.importer ?? "");
  1359. const id = decodeStr(params.source);
  1360. const { handler, filter } = require_context.normalizeObjectHook("resolveId", _resolveId);
  1361. if (!filter(id)) return null;
  1362. let isEntry = false;
  1363. if (isObject(params.kind) && "entry" in params.kind) {
  1364. const kindWithEntry = params.kind;
  1365. isEntry = kindWithEntry.entry === "index";
  1366. }
  1367. const farmContext = createFarmContext(context, resolvedIdPath);
  1368. const resolveIdResult = await handler.call(Object.assign(unpluginContext(context), farmContext), id, resolvedIdPath ?? null, { isEntry });
  1369. if (isString(resolveIdResult)) return {
  1370. resolvedPath: removeQuery(encodeStr(resolveIdResult)),
  1371. query: customParseQueryString(resolveIdResult),
  1372. sideEffects: true,
  1373. external: false,
  1374. meta: {}
  1375. };
  1376. if (isObject(resolveIdResult)) return {
  1377. resolvedPath: removeQuery(encodeStr(resolveIdResult?.id)),
  1378. query: customParseQueryString(resolveIdResult?.id),
  1379. sideEffects: false,
  1380. external: Boolean(resolveIdResult?.external),
  1381. meta: {}
  1382. };
  1383. if (!isStartsWithSlash(params.source)) return null;
  1384. }
  1385. };
  1386. }
  1387. if (plugin.load) {
  1388. const _load = plugin.load;
  1389. farmPlugin.load = {
  1390. filters: { resolvedPaths: [".*"] },
  1391. async executor(params, context) {
  1392. const resolvedPath = decodeStr(params.resolvedPath);
  1393. const id = appendQuery(resolvedPath, params.query);
  1394. const loader = formatTransformModuleType(id);
  1395. if (plugin.loadInclude && !plugin.loadInclude?.(id)) return null;
  1396. const { handler, filter } = require_context.normalizeObjectHook("load", _load);
  1397. if (!filter(id)) return null;
  1398. const farmContext = createFarmContext(context, id);
  1399. const content = await handler.call(Object.assign(unpluginContext(context), farmContext), id);
  1400. const loadFarmResult = {
  1401. content: getContentValue(content),
  1402. moduleType: loader
  1403. };
  1404. return loadFarmResult;
  1405. }
  1406. };
  1407. }
  1408. if (plugin.transform) {
  1409. const _transform = plugin.transform;
  1410. farmPlugin.transform = {
  1411. filters: {
  1412. resolvedPaths: [".*"],
  1413. moduleTypes: [".*"]
  1414. },
  1415. async executor(params, context) {
  1416. const resolvedPath = decodeStr(params.resolvedPath);
  1417. const id = appendQuery(resolvedPath, params.query);
  1418. const loader = formatTransformModuleType(id);
  1419. if (plugin.transformInclude && !plugin.transformInclude(id)) return null;
  1420. const { handler, filter } = require_context.normalizeObjectHook("transform", _transform);
  1421. if (!filter(id, params.content)) return null;
  1422. const farmContext = createFarmContext(context, id);
  1423. const resource = await handler.call(Object.assign(unpluginContext(context), farmContext), params.content, id);
  1424. if (resource && typeof resource !== "string") {
  1425. const transformFarmResult = {
  1426. content: getContentValue(resource),
  1427. moduleType: loader,
  1428. sourceMap: typeof resource.map === "object" && resource.map !== null ? JSON.stringify(resource.map) : void 0
  1429. };
  1430. return transformFarmResult;
  1431. }
  1432. }
  1433. };
  1434. }
  1435. if (plugin.watchChange) {
  1436. const _watchChange = plugin.watchChange;
  1437. farmPlugin.updateModules = { async executor(param, context) {
  1438. const updatePathContent = param.paths[0];
  1439. const ModifiedPath = updatePathContent[0];
  1440. const eventChange = convertWatchEventChange(updatePathContent[1]);
  1441. await _watchChange.call(createFarmContext(context), ModifiedPath, { event: eventChange });
  1442. } };
  1443. }
  1444. if (plugin.buildEnd) {
  1445. const _buildEnd = plugin.buildEnd;
  1446. farmPlugin.buildEnd = { async executor(_, context) {
  1447. await _buildEnd.call(createFarmContext(context));
  1448. } };
  1449. }
  1450. if (plugin.writeBundle) {
  1451. const _writeBundle = plugin.writeBundle;
  1452. farmPlugin.finish = { async executor() {
  1453. await _writeBundle();
  1454. } };
  1455. }
  1456. return farmPlugin;
  1457. }
  1458. //#endregion
  1459. //#region src/rollup/index.ts
  1460. function getRollupPlugin(factory) {
  1461. return (userOptions) => {
  1462. const meta = { framework: "rollup" };
  1463. const rawPlugins = require_context.toArray(factory(userOptions, meta));
  1464. const plugins = rawPlugins.map((plugin) => toRollupPlugin(plugin, "rollup"));
  1465. return plugins.length === 1 ? plugins[0] : plugins;
  1466. };
  1467. }
  1468. function toRollupPlugin(plugin, key) {
  1469. const nativeFilter = key === "rolldown";
  1470. if (plugin.resolveId && !nativeFilter && typeof plugin.resolveId === "object" && plugin.resolveId.filter) {
  1471. const resolveIdHook = plugin.resolveId;
  1472. const { handler, filter } = require_context.normalizeObjectHook("load", resolveIdHook);
  1473. replaceHookHandler("resolveId", resolveIdHook, function(...args) {
  1474. const [id] = args;
  1475. const supportFilter = supportNativeFilter(this);
  1476. if (!supportFilter && !filter(id)) return;
  1477. return handler.apply(this, args);
  1478. });
  1479. }
  1480. if (plugin.load && (plugin.loadInclude || !nativeFilter && typeof plugin.load === "object" && plugin.load.filter)) {
  1481. const loadHook = plugin.load;
  1482. const { handler, filter } = require_context.normalizeObjectHook("load", loadHook);
  1483. replaceHookHandler("load", loadHook, function(...args) {
  1484. const [id] = args;
  1485. if (plugin.loadInclude && !plugin.loadInclude(id)) return;
  1486. const supportFilter = supportNativeFilter(this);
  1487. if (!supportFilter && !filter(id)) return;
  1488. return handler.apply(this, args);
  1489. });
  1490. }
  1491. if (plugin.transform && (plugin.transformInclude || !nativeFilter && typeof plugin.transform === "object" && plugin.transform.filter)) {
  1492. const transformHook = plugin.transform;
  1493. const { handler, filter } = require_context.normalizeObjectHook("transform", transformHook);
  1494. replaceHookHandler("transform", transformHook, function(...args) {
  1495. const [code, id] = args;
  1496. if (plugin.transformInclude && !plugin.transformInclude(id)) return;
  1497. const supportFilter = supportNativeFilter(this);
  1498. if (!supportFilter && !filter(id, code)) return;
  1499. return handler.apply(this, args);
  1500. });
  1501. }
  1502. if (plugin[key]) Object.assign(plugin, plugin[key]);
  1503. return plugin;
  1504. function replaceHookHandler(name, hook, handler) {
  1505. if (typeof hook === "function") plugin[name] = handler;
  1506. else hook.handler = handler;
  1507. }
  1508. }
  1509. function supportNativeFilter(context) {
  1510. const rollupVersion = context?.meta?.rollupVersion;
  1511. if (!rollupVersion) return false;
  1512. const [major, minor] = rollupVersion.split(".");
  1513. return Number(major) > 4 || Number(major) === 4 && Number(minor) >= 40;
  1514. }
  1515. //#endregion
  1516. //#region src/rolldown/index.ts
  1517. function getRolldownPlugin(factory) {
  1518. return (userOptions) => {
  1519. const meta = { framework: "rolldown" };
  1520. const rawPlugins = require_context.toArray(factory(userOptions, meta));
  1521. const plugins = rawPlugins.map((rawPlugin) => {
  1522. const plugin = toRollupPlugin(rawPlugin, "rolldown");
  1523. return plugin;
  1524. });
  1525. return plugins.length === 1 ? plugins[0] : plugins;
  1526. };
  1527. }
  1528. //#endregion
  1529. //#region src/rspack/index.ts
  1530. const TRANSFORM_LOADER$1 = (0, node_path.resolve)(__dirname, "rspack/loaders/transform");
  1531. const LOAD_LOADER$1 = (0, node_path.resolve)(__dirname, "rspack/loaders/load");
  1532. function getRspackPlugin(factory) {
  1533. return (userOptions) => {
  1534. return { apply(compiler) {
  1535. const VIRTUAL_MODULE_PREFIX = (0, node_path.resolve)(compiler.options.context ?? process.cwd(), "node_modules/.virtual");
  1536. const meta = {
  1537. framework: "rspack",
  1538. rspack: { compiler }
  1539. };
  1540. const rawPlugins = require_context.toArray(factory(userOptions, meta));
  1541. for (const rawPlugin of rawPlugins) {
  1542. const plugin = Object.assign(rawPlugin, {
  1543. __unpluginMeta: meta,
  1544. __virtualModulePrefix: VIRTUAL_MODULE_PREFIX
  1545. });
  1546. const externalModules = new Set();
  1547. if (plugin.resolveId) {
  1548. const vfs = new require_utils.FakeVirtualModulesPlugin(plugin);
  1549. vfs.apply(compiler);
  1550. const vfsModules = new Map();
  1551. plugin.__vfsModules = vfsModules;
  1552. plugin.__vfs = vfs;
  1553. compiler.hooks.compilation.tap(plugin.name, (compilation, { normalModuleFactory }) => {
  1554. normalModuleFactory.hooks.resolve.tapPromise(plugin.name, async (resolveData) => {
  1555. const id = require_webpack_like.normalizeAbsolutePath(resolveData.request);
  1556. const requestContext = resolveData.contextInfo;
  1557. let importer = requestContext.issuer !== "" ? requestContext.issuer : void 0;
  1558. const isEntry = requestContext.issuer === "";
  1559. if (importer?.startsWith(plugin.__virtualModulePrefix)) importer = decodeURIComponent(importer.slice(plugin.__virtualModulePrefix.length));
  1560. const context = require_context$1.createBuildContext(compiler, compilation);
  1561. let error;
  1562. const pluginContext = {
  1563. error(msg) {
  1564. if (error == null) error = require_context$1.normalizeMessage(msg);
  1565. else console.error(`unplugin/rspack: multiple errors returned from resolveId hook: ${msg}`);
  1566. },
  1567. warn(msg) {
  1568. console.warn(`unplugin/rspack: warning from resolveId hook: ${msg}`);
  1569. }
  1570. };
  1571. const { handler, filter } = require_context.normalizeObjectHook("resolveId", plugin.resolveId);
  1572. if (!filter(id)) return;
  1573. const resolveIdResult = await handler.call({
  1574. ...context,
  1575. ...pluginContext
  1576. }, id, importer, { isEntry });
  1577. if (error != null) throw error;
  1578. if (resolveIdResult == null) return;
  1579. let resolved = typeof resolveIdResult === "string" ? resolveIdResult : resolveIdResult.id;
  1580. const isExternal = typeof resolveIdResult === "string" ? false : resolveIdResult.external === true;
  1581. if (isExternal) externalModules.add(resolved);
  1582. if (!node_fs.default.existsSync(resolved)) {
  1583. if (!vfsModules.has(resolved)) {
  1584. const fsPromise = vfs.writeModule(resolved);
  1585. vfsModules.set(resolved, fsPromise);
  1586. await fsPromise;
  1587. } else await vfsModules.get(resolved);
  1588. resolved = require_utils.encodeVirtualModuleId(resolved, plugin);
  1589. }
  1590. resolveData.request = resolved;
  1591. });
  1592. });
  1593. }
  1594. if (plugin.load) compiler.options.module.rules.unshift({
  1595. enforce: plugin.enforce,
  1596. include(id) {
  1597. if (require_utils.isVirtualModuleId(id, plugin)) id = require_utils.decodeVirtualModuleId(id, plugin);
  1598. if (plugin.loadInclude && !plugin.loadInclude(id)) return false;
  1599. const { filter } = require_context.normalizeObjectHook("load", plugin.load);
  1600. if (!filter(id)) return false;
  1601. return !externalModules.has(id);
  1602. },
  1603. use: [{
  1604. loader: LOAD_LOADER$1,
  1605. options: { plugin }
  1606. }],
  1607. type: "javascript/auto"
  1608. });
  1609. if (plugin.transform) compiler.options.module.rules.unshift({
  1610. enforce: plugin.enforce,
  1611. use(data) {
  1612. return require_webpack_like.transformUse(data, plugin, TRANSFORM_LOADER$1);
  1613. }
  1614. });
  1615. if (plugin.rspack) plugin.rspack(compiler);
  1616. if (plugin.watchChange || plugin.buildStart) compiler.hooks.make.tapPromise(plugin.name, async (compilation) => {
  1617. const context = require_context$1.createBuildContext(compiler, compilation);
  1618. if (plugin.watchChange && (compiler.modifiedFiles || compiler.removedFiles)) {
  1619. const promises = [];
  1620. if (compiler.modifiedFiles) compiler.modifiedFiles.forEach((file) => promises.push(Promise.resolve(plugin.watchChange.call(context, file, { event: "update" }))));
  1621. if (compiler.removedFiles) compiler.removedFiles.forEach((file) => promises.push(Promise.resolve(plugin.watchChange.call(context, file, { event: "delete" }))));
  1622. await Promise.all(promises);
  1623. }
  1624. if (plugin.buildStart) return await plugin.buildStart.call(context);
  1625. });
  1626. if (plugin.buildEnd) compiler.hooks.emit.tapPromise(plugin.name, async (compilation) => {
  1627. await plugin.buildEnd.call(require_context$1.createBuildContext(compiler, compilation));
  1628. });
  1629. if (plugin.writeBundle) compiler.hooks.afterEmit.tapPromise(plugin.name, async () => {
  1630. await plugin.writeBundle();
  1631. });
  1632. }
  1633. } };
  1634. };
  1635. }
  1636. //#endregion
  1637. //#region src/unloader/index.ts
  1638. function getUnloaderPlugin(factory) {
  1639. return (userOptions) => {
  1640. const meta = { framework: "unloader" };
  1641. const rawPlugins = require_context.toArray(factory(userOptions, meta));
  1642. const plugins = rawPlugins.map((rawPlugin) => {
  1643. const plugin = toRollupPlugin(rawPlugin, "unloader");
  1644. return plugin;
  1645. });
  1646. return plugins.length === 1 ? plugins[0] : plugins;
  1647. };
  1648. }
  1649. //#endregion
  1650. //#region src/vite/index.ts
  1651. function getVitePlugin(factory) {
  1652. return (userOptions) => {
  1653. const meta = { framework: "vite" };
  1654. const rawPlugins = require_context.toArray(factory(userOptions, meta));
  1655. const plugins = rawPlugins.map((rawPlugin) => {
  1656. const plugin = toRollupPlugin(rawPlugin, "vite");
  1657. return plugin;
  1658. });
  1659. return plugins.length === 1 ? plugins[0] : plugins;
  1660. };
  1661. }
  1662. //#endregion
  1663. //#region src/webpack/index.ts
  1664. const TRANSFORM_LOADER = (0, node_path.resolve)(__dirname, "webpack/loaders/transform");
  1665. const LOAD_LOADER = (0, node_path.resolve)(__dirname, "webpack/loaders/load");
  1666. function getWebpackPlugin(factory) {
  1667. return (userOptions) => {
  1668. return { apply(compiler) {
  1669. const VIRTUAL_MODULE_PREFIX = (0, node_path.resolve)(compiler.options.context ?? node_process.default.cwd(), "_virtual_");
  1670. const meta = {
  1671. framework: "webpack",
  1672. webpack: { compiler }
  1673. };
  1674. const rawPlugins = require_context.toArray(factory(userOptions, meta));
  1675. for (const rawPlugin of rawPlugins) {
  1676. const plugin = Object.assign(rawPlugin, {
  1677. __unpluginMeta: meta,
  1678. __virtualModulePrefix: VIRTUAL_MODULE_PREFIX
  1679. });
  1680. const externalModules = new Set();
  1681. if (plugin.resolveId) {
  1682. let vfs = compiler.options.plugins.find((i) => i instanceof webpack_virtual_modules.default);
  1683. if (!vfs) {
  1684. vfs = new webpack_virtual_modules.default();
  1685. compiler.options.plugins.push(vfs);
  1686. }
  1687. const vfsModules = new Set();
  1688. plugin.__vfsModules = vfsModules;
  1689. plugin.__vfs = vfs;
  1690. const resolverPlugin = { apply(resolver) {
  1691. const target = resolver.ensureHook("resolve");
  1692. resolver.getHook("resolve").tapAsync(plugin.name, async (request, resolveContext, callback) => {
  1693. if (!request.request) return callback();
  1694. if (require_webpack_like.normalizeAbsolutePath(request.request).startsWith(plugin.__virtualModulePrefix)) return callback();
  1695. const id = require_webpack_like.normalizeAbsolutePath(request.request);
  1696. const requestContext = request.context;
  1697. let importer = requestContext.issuer !== "" ? requestContext.issuer : void 0;
  1698. const isEntry = requestContext.issuer === "";
  1699. if (importer?.startsWith(plugin.__virtualModulePrefix)) importer = decodeURIComponent(importer.slice(plugin.__virtualModulePrefix.length));
  1700. const fileDependencies = new Set();
  1701. const context = require_context$2.createBuildContext$1({
  1702. addWatchFile(file) {
  1703. fileDependencies.add(file);
  1704. resolveContext.fileDependencies?.add(file);
  1705. },
  1706. getWatchFiles() {
  1707. return Array.from(fileDependencies);
  1708. }
  1709. }, compiler);
  1710. let error;
  1711. const pluginContext = {
  1712. error(msg) {
  1713. if (error == null) error = require_context$2.normalizeMessage$1(msg);
  1714. else console.error(`unplugin/webpack: multiple errors returned from resolveId hook: ${msg}`);
  1715. },
  1716. warn(msg) {
  1717. console.warn(`unplugin/webpack: warning from resolveId hook: ${msg}`);
  1718. }
  1719. };
  1720. const { handler, filter } = require_context.normalizeObjectHook("resolveId", plugin.resolveId);
  1721. if (!filter(id)) return callback();
  1722. const resolveIdResult = await handler.call({
  1723. ...context,
  1724. ...pluginContext
  1725. }, id, importer, { isEntry });
  1726. if (error != null) return callback(error);
  1727. if (resolveIdResult == null) return callback();
  1728. let resolved = typeof resolveIdResult === "string" ? resolveIdResult : resolveIdResult.id;
  1729. const isExternal = typeof resolveIdResult === "string" ? false : resolveIdResult.external === true;
  1730. if (isExternal) externalModules.add(resolved);
  1731. if (!node_fs.default.existsSync(resolved)) {
  1732. resolved = require_webpack_like.normalizeAbsolutePath(plugin.__virtualModulePrefix + encodeURIComponent(resolved));
  1733. // webpack virtual module should pass in the correct path
  1734. if (!vfsModules.has(resolved)) {
  1735. plugin.__vfs.writeModule(resolved, "");
  1736. vfsModules.add(resolved);
  1737. }
  1738. }
  1739. const newRequest = {
  1740. ...request,
  1741. request: resolved
  1742. };
  1743. resolver.doResolve(target, newRequest, null, resolveContext, callback);
  1744. });
  1745. } };
  1746. compiler.options.resolve.plugins = compiler.options.resolve.plugins || [];
  1747. compiler.options.resolve.plugins.push(resolverPlugin);
  1748. }
  1749. if (plugin.load) compiler.options.module.rules.unshift({
  1750. include(id) {
  1751. return shouldLoad(id, plugin, externalModules);
  1752. },
  1753. enforce: plugin.enforce,
  1754. use: [{
  1755. loader: LOAD_LOADER,
  1756. options: { plugin }
  1757. }],
  1758. type: "javascript/auto"
  1759. });
  1760. if (plugin.transform) compiler.options.module.rules.unshift({
  1761. enforce: plugin.enforce,
  1762. use(data) {
  1763. return require_webpack_like.transformUse(data, plugin, TRANSFORM_LOADER);
  1764. }
  1765. });
  1766. if (plugin.webpack) plugin.webpack(compiler);
  1767. if (plugin.watchChange || plugin.buildStart) compiler.hooks.make.tapPromise(plugin.name, async (compilation) => {
  1768. const context = require_context$2.createBuildContext$1(require_context$2.contextOptionsFromCompilation(compilation), compiler, compilation);
  1769. if (plugin.watchChange && (compiler.modifiedFiles || compiler.removedFiles)) {
  1770. const promises = [];
  1771. if (compiler.modifiedFiles) compiler.modifiedFiles.forEach((file) => promises.push(Promise.resolve(plugin.watchChange.call(context, file, { event: "update" }))));
  1772. if (compiler.removedFiles) compiler.removedFiles.forEach((file) => promises.push(Promise.resolve(plugin.watchChange.call(context, file, { event: "delete" }))));
  1773. await Promise.all(promises);
  1774. }
  1775. if (plugin.buildStart) return await plugin.buildStart.call(context);
  1776. });
  1777. if (plugin.buildEnd) compiler.hooks.emit.tapPromise(plugin.name, async (compilation) => {
  1778. await plugin.buildEnd.call(require_context$2.createBuildContext$1(require_context$2.contextOptionsFromCompilation(compilation), compiler, compilation));
  1779. });
  1780. if (plugin.writeBundle) compiler.hooks.afterEmit.tapPromise(plugin.name, async () => {
  1781. await plugin.writeBundle();
  1782. });
  1783. }
  1784. } };
  1785. };
  1786. }
  1787. function shouldLoad(id, plugin, externalModules) {
  1788. if (id.startsWith(plugin.__virtualModulePrefix)) id = decodeURIComponent(id.slice(plugin.__virtualModulePrefix.length));
  1789. if (plugin.loadInclude && !plugin.loadInclude(id)) return false;
  1790. const { filter } = require_context.normalizeObjectHook("load", plugin.load);
  1791. if (!filter(id)) return false;
  1792. return !externalModules.has(id);
  1793. }
  1794. //#endregion
  1795. //#region src/define.ts
  1796. function createUnplugin(factory) {
  1797. return {
  1798. get esbuild() {
  1799. return getEsbuildPlugin(factory);
  1800. },
  1801. get rollup() {
  1802. return getRollupPlugin(factory);
  1803. },
  1804. get vite() {
  1805. return getVitePlugin(factory);
  1806. },
  1807. get rolldown() {
  1808. return getRolldownPlugin(factory);
  1809. },
  1810. get webpack() {
  1811. return getWebpackPlugin(factory);
  1812. },
  1813. get rspack() {
  1814. return getRspackPlugin(factory);
  1815. },
  1816. get farm() {
  1817. return getFarmPlugin(factory);
  1818. },
  1819. get unloader() {
  1820. return getUnloaderPlugin(factory);
  1821. },
  1822. get raw() {
  1823. return factory;
  1824. }
  1825. };
  1826. }
  1827. function createEsbuildPlugin(factory) {
  1828. return getEsbuildPlugin(factory);
  1829. }
  1830. function createRollupPlugin(factory) {
  1831. return getRollupPlugin(factory);
  1832. }
  1833. function createVitePlugin(factory) {
  1834. return getVitePlugin(factory);
  1835. }
  1836. function createRolldownPlugin(factory) {
  1837. return getRolldownPlugin(factory);
  1838. }
  1839. function createWebpackPlugin(factory) {
  1840. return getWebpackPlugin(factory);
  1841. }
  1842. function createRspackPlugin(factory) {
  1843. return getRspackPlugin(factory);
  1844. }
  1845. function createFarmPlugin(factory) {
  1846. return getFarmPlugin(factory);
  1847. }
  1848. function createUnloaderPlugin(factory) {
  1849. return getUnloaderPlugin(factory);
  1850. }
  1851. //#endregion
  1852. exports.createEsbuildPlugin = createEsbuildPlugin;
  1853. exports.createFarmPlugin = createFarmPlugin;
  1854. exports.createRolldownPlugin = createRolldownPlugin;
  1855. exports.createRollupPlugin = createRollupPlugin;
  1856. exports.createRspackPlugin = createRspackPlugin;
  1857. exports.createUnloaderPlugin = createUnloaderPlugin;
  1858. exports.createUnplugin = createUnplugin;
  1859. exports.createVitePlugin = createVitePlugin;
  1860. exports.createWebpackPlugin = createWebpackPlugin;