index.js 62 KB

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