ab76d7ecfe7d79561668c3bd46556b8e2a3048570a0bb2c92fea2c173ce3b459caa7ef09e1478391f3e701ab79d41e552bf6857bf0ee7cc61e4306157e6e26 68 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146
  1. "use strict";
  2. var __create = Object.create;
  3. var __defProp = Object.defineProperty;
  4. var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
  5. var __getOwnPropNames = Object.getOwnPropertyNames;
  6. var __getProtoOf = Object.getPrototypeOf;
  7. var __hasOwnProp = Object.prototype.hasOwnProperty;
  8. var __export = (target, all) => {
  9. for (var name in all)
  10. __defProp(target, name, { get: all[name], enumerable: true });
  11. };
  12. var __copyProps = (to, from, except, desc) => {
  13. if (from && typeof from === "object" || typeof from === "function") {
  14. for (let key of __getOwnPropNames(from))
  15. if (!__hasOwnProp.call(to, key) && key !== except)
  16. __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  17. }
  18. return to;
  19. };
  20. var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  21. // If the importer is in node compatibility mode or this is not an ESM
  22. // file that has been converted to a CommonJS file using a Babel-
  23. // compatible transform (i.e. "__esModule" has not been set), then set
  24. // "default" to the CommonJS "module.exports" for node compatibility.
  25. isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  26. mod
  27. ));
  28. var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
  29. // src/index.ts
  30. var src_exports = {};
  31. __export(src_exports, {
  32. createEsbuildPlugin: () => createEsbuildPlugin,
  33. createFarmPlugin: () => createFarmPlugin,
  34. createRolldownPlugin: () => createRolldownPlugin,
  35. createRollupPlugin: () => createRollupPlugin,
  36. createRspackPlugin: () => createRspackPlugin,
  37. createUnplugin: () => createUnplugin,
  38. createVitePlugin: () => createVitePlugin,
  39. createWebpackPlugin: () => createWebpackPlugin
  40. });
  41. module.exports = __toCommonJS(src_exports);
  42. // src/esbuild/index.ts
  43. var import_fs2 = __toESM(require("fs"));
  44. var import_path3 = __toESM(require("path"));
  45. // src/esbuild/utils.ts
  46. var import_buffer = require("buffer");
  47. var import_fs = __toESM(require("fs"));
  48. var import_path2 = __toESM(require("path"));
  49. // node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.0/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs
  50. var comma = ",".charCodeAt(0);
  51. var semicolon = ";".charCodeAt(0);
  52. var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  53. var intToChar = new Uint8Array(64);
  54. var charToInt = new Uint8Array(128);
  55. for (let i = 0; i < chars.length; i++) {
  56. const c = chars.charCodeAt(i);
  57. intToChar[i] = c;
  58. charToInt[c] = i;
  59. }
  60. function decodeInteger(reader, relative) {
  61. let value = 0;
  62. let shift = 0;
  63. let integer = 0;
  64. do {
  65. const c = reader.next();
  66. integer = charToInt[c];
  67. value |= (integer & 31) << shift;
  68. shift += 5;
  69. } while (integer & 32);
  70. const shouldNegate = value & 1;
  71. value >>>= 1;
  72. if (shouldNegate) {
  73. value = -2147483648 | -value;
  74. }
  75. return relative + value;
  76. }
  77. function encodeInteger(builder, num, relative) {
  78. let delta = num - relative;
  79. delta = delta < 0 ? -delta << 1 | 1 : delta << 1;
  80. do {
  81. let clamped = delta & 31;
  82. delta >>>= 5;
  83. if (delta > 0)
  84. clamped |= 32;
  85. builder.write(intToChar[clamped]);
  86. } while (delta > 0);
  87. return num;
  88. }
  89. function hasMoreVlq(reader, max) {
  90. if (reader.pos >= max)
  91. return false;
  92. return reader.peek() !== comma;
  93. }
  94. var bufLength = 1024 * 16;
  95. var td = typeof TextDecoder !== "undefined" ? /* @__PURE__ */ new TextDecoder() : typeof Buffer !== "undefined" ? {
  96. decode(buf) {
  97. const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength);
  98. return out.toString();
  99. }
  100. } : {
  101. decode(buf) {
  102. let out = "";
  103. for (let i = 0; i < buf.length; i++) {
  104. out += String.fromCharCode(buf[i]);
  105. }
  106. return out;
  107. }
  108. };
  109. var StringWriter = class {
  110. constructor() {
  111. this.pos = 0;
  112. this.out = "";
  113. this.buffer = new Uint8Array(bufLength);
  114. }
  115. write(v) {
  116. const { buffer } = this;
  117. buffer[this.pos++] = v;
  118. if (this.pos === bufLength) {
  119. this.out += td.decode(buffer);
  120. this.pos = 0;
  121. }
  122. }
  123. flush() {
  124. const { buffer, out, pos } = this;
  125. return pos > 0 ? out + td.decode(buffer.subarray(0, pos)) : out;
  126. }
  127. };
  128. var StringReader = class {
  129. constructor(buffer) {
  130. this.pos = 0;
  131. this.buffer = buffer;
  132. }
  133. next() {
  134. return this.buffer.charCodeAt(this.pos++);
  135. }
  136. peek() {
  137. return this.buffer.charCodeAt(this.pos);
  138. }
  139. indexOf(char) {
  140. const { buffer, pos } = this;
  141. const idx = buffer.indexOf(char, pos);
  142. return idx === -1 ? buffer.length : idx;
  143. }
  144. };
  145. function decode(mappings) {
  146. const { length } = mappings;
  147. const reader = new StringReader(mappings);
  148. const decoded = [];
  149. let genColumn = 0;
  150. let sourcesIndex = 0;
  151. let sourceLine = 0;
  152. let sourceColumn = 0;
  153. let namesIndex = 0;
  154. do {
  155. const semi = reader.indexOf(";");
  156. const line = [];
  157. let sorted = true;
  158. let lastCol = 0;
  159. genColumn = 0;
  160. while (reader.pos < semi) {
  161. let seg;
  162. genColumn = decodeInteger(reader, genColumn);
  163. if (genColumn < lastCol)
  164. sorted = false;
  165. lastCol = genColumn;
  166. if (hasMoreVlq(reader, semi)) {
  167. sourcesIndex = decodeInteger(reader, sourcesIndex);
  168. sourceLine = decodeInteger(reader, sourceLine);
  169. sourceColumn = decodeInteger(reader, sourceColumn);
  170. if (hasMoreVlq(reader, semi)) {
  171. namesIndex = decodeInteger(reader, namesIndex);
  172. seg = [genColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex];
  173. } else {
  174. seg = [genColumn, sourcesIndex, sourceLine, sourceColumn];
  175. }
  176. } else {
  177. seg = [genColumn];
  178. }
  179. line.push(seg);
  180. reader.pos++;
  181. }
  182. if (!sorted)
  183. sort(line);
  184. decoded.push(line);
  185. reader.pos = semi + 1;
  186. } while (reader.pos <= length);
  187. return decoded;
  188. }
  189. function sort(line) {
  190. line.sort(sortComparator);
  191. }
  192. function sortComparator(a, b) {
  193. return a[0] - b[0];
  194. }
  195. function encode(decoded) {
  196. const writer = new StringWriter();
  197. let sourcesIndex = 0;
  198. let sourceLine = 0;
  199. let sourceColumn = 0;
  200. let namesIndex = 0;
  201. for (let i = 0; i < decoded.length; i++) {
  202. const line = decoded[i];
  203. if (i > 0)
  204. writer.write(semicolon);
  205. if (line.length === 0)
  206. continue;
  207. let genColumn = 0;
  208. for (let j = 0; j < line.length; j++) {
  209. const segment = line[j];
  210. if (j > 0)
  211. writer.write(comma);
  212. genColumn = encodeInteger(writer, segment[0], genColumn);
  213. if (segment.length === 1)
  214. continue;
  215. sourcesIndex = encodeInteger(writer, segment[1], sourcesIndex);
  216. sourceLine = encodeInteger(writer, segment[2], sourceLine);
  217. sourceColumn = encodeInteger(writer, segment[3], sourceColumn);
  218. if (segment.length === 4)
  219. continue;
  220. namesIndex = encodeInteger(writer, segment[4], namesIndex);
  221. }
  222. }
  223. return writer.flush();
  224. }
  225. // node_modules/.pnpm/@jridgewell+resolve-uri@3.1.2/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.mjs
  226. var schemeRegex = /^[\w+.-]+:\/\//;
  227. var urlRegex = /^([\w+.-]+:)\/\/([^@/#?]*@)?([^:/#?]*)(:\d+)?(\/[^#?]*)?(\?[^#]*)?(#.*)?/;
  228. var fileRegex = /^file:(?:\/\/((?![a-z]:)[^/#?]*)?)?(\/?[^#?]*)(\?[^#]*)?(#.*)?/i;
  229. function isAbsoluteUrl(input) {
  230. return schemeRegex.test(input);
  231. }
  232. function isSchemeRelativeUrl(input) {
  233. return input.startsWith("//");
  234. }
  235. function isAbsolutePath(input) {
  236. return input.startsWith("/");
  237. }
  238. function isFileUrl(input) {
  239. return input.startsWith("file:");
  240. }
  241. function isRelative(input) {
  242. return /^[.?#]/.test(input);
  243. }
  244. function parseAbsoluteUrl(input) {
  245. const match = urlRegex.exec(input);
  246. return makeUrl(match[1], match[2] || "", match[3], match[4] || "", match[5] || "/", match[6] || "", match[7] || "");
  247. }
  248. function parseFileUrl(input) {
  249. const match = fileRegex.exec(input);
  250. const path5 = match[2];
  251. return makeUrl("file:", "", match[1] || "", "", isAbsolutePath(path5) ? path5 : "/" + path5, match[3] || "", match[4] || "");
  252. }
  253. function makeUrl(scheme, user, host, port, path5, query, hash) {
  254. return {
  255. scheme,
  256. user,
  257. host,
  258. port,
  259. path: path5,
  260. query,
  261. hash,
  262. type: 7
  263. };
  264. }
  265. function parseUrl(input) {
  266. if (isSchemeRelativeUrl(input)) {
  267. const url2 = parseAbsoluteUrl("http:" + input);
  268. url2.scheme = "";
  269. url2.type = 6;
  270. return url2;
  271. }
  272. if (isAbsolutePath(input)) {
  273. const url2 = parseAbsoluteUrl("http://foo.com" + input);
  274. url2.scheme = "";
  275. url2.host = "";
  276. url2.type = 5;
  277. return url2;
  278. }
  279. if (isFileUrl(input))
  280. return parseFileUrl(input);
  281. if (isAbsoluteUrl(input))
  282. return parseAbsoluteUrl(input);
  283. const url = parseAbsoluteUrl("http://foo.com/" + input);
  284. url.scheme = "";
  285. url.host = "";
  286. url.type = input ? input.startsWith("?") ? 3 : input.startsWith("#") ? 2 : 4 : 1;
  287. return url;
  288. }
  289. function stripPathFilename(path5) {
  290. if (path5.endsWith("/.."))
  291. return path5;
  292. const index = path5.lastIndexOf("/");
  293. return path5.slice(0, index + 1);
  294. }
  295. function mergePaths(url, base) {
  296. normalizePath(base, base.type);
  297. if (url.path === "/") {
  298. url.path = base.path;
  299. } else {
  300. url.path = stripPathFilename(base.path) + url.path;
  301. }
  302. }
  303. function normalizePath(url, type) {
  304. const rel = type <= 4;
  305. const pieces = url.path.split("/");
  306. let pointer = 1;
  307. let positive = 0;
  308. let addTrailingSlash = false;
  309. for (let i = 1; i < pieces.length; i++) {
  310. const piece = pieces[i];
  311. if (!piece) {
  312. addTrailingSlash = true;
  313. continue;
  314. }
  315. addTrailingSlash = false;
  316. if (piece === ".")
  317. continue;
  318. if (piece === "..") {
  319. if (positive) {
  320. addTrailingSlash = true;
  321. positive--;
  322. pointer--;
  323. } else if (rel) {
  324. pieces[pointer++] = piece;
  325. }
  326. continue;
  327. }
  328. pieces[pointer++] = piece;
  329. positive++;
  330. }
  331. let path5 = "";
  332. for (let i = 1; i < pointer; i++) {
  333. path5 += "/" + pieces[i];
  334. }
  335. if (!path5 || addTrailingSlash && !path5.endsWith("/..")) {
  336. path5 += "/";
  337. }
  338. url.path = path5;
  339. }
  340. function resolve(input, base) {
  341. if (!input && !base)
  342. return "";
  343. const url = parseUrl(input);
  344. let inputType = url.type;
  345. if (base && inputType !== 7) {
  346. const baseUrl = parseUrl(base);
  347. const baseType = baseUrl.type;
  348. switch (inputType) {
  349. case 1:
  350. url.hash = baseUrl.hash;
  351. // fall through
  352. case 2:
  353. url.query = baseUrl.query;
  354. // fall through
  355. case 3:
  356. case 4:
  357. mergePaths(url, baseUrl);
  358. // fall through
  359. case 5:
  360. url.user = baseUrl.user;
  361. url.host = baseUrl.host;
  362. url.port = baseUrl.port;
  363. // fall through
  364. case 6:
  365. url.scheme = baseUrl.scheme;
  366. }
  367. if (baseType > inputType)
  368. inputType = baseType;
  369. }
  370. normalizePath(url, inputType);
  371. const queryHash = url.query + url.hash;
  372. switch (inputType) {
  373. // This is impossible, because of the empty checks at the start of the function.
  374. // case UrlType.Empty:
  375. case 2:
  376. case 3:
  377. return queryHash;
  378. case 4: {
  379. const path5 = url.path.slice(1);
  380. if (!path5)
  381. return queryHash || ".";
  382. if (isRelative(base || input) && !isRelative(path5)) {
  383. return "./" + path5 + queryHash;
  384. }
  385. return path5 + queryHash;
  386. }
  387. case 5:
  388. return url.path + queryHash;
  389. default:
  390. return url.scheme + "//" + url.user + url.host + url.port + url.path + queryHash;
  391. }
  392. }
  393. // node_modules/.pnpm/@jridgewell+trace-mapping@0.3.25/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.mjs
  394. function resolve2(input, base) {
  395. if (base && !base.endsWith("/"))
  396. base += "/";
  397. return resolve(input, base);
  398. }
  399. function stripFilename(path5) {
  400. if (!path5)
  401. return "";
  402. const index = path5.lastIndexOf("/");
  403. return path5.slice(0, index + 1);
  404. }
  405. var COLUMN = 0;
  406. function maybeSort(mappings, owned) {
  407. const unsortedIndex = nextUnsortedSegmentLine(mappings, 0);
  408. if (unsortedIndex === mappings.length)
  409. return mappings;
  410. if (!owned)
  411. mappings = mappings.slice();
  412. for (let i = unsortedIndex; i < mappings.length; i = nextUnsortedSegmentLine(mappings, i + 1)) {
  413. mappings[i] = sortSegments(mappings[i], owned);
  414. }
  415. return mappings;
  416. }
  417. function nextUnsortedSegmentLine(mappings, start) {
  418. for (let i = start; i < mappings.length; i++) {
  419. if (!isSorted(mappings[i]))
  420. return i;
  421. }
  422. return mappings.length;
  423. }
  424. function isSorted(line) {
  425. for (let j = 1; j < line.length; j++) {
  426. if (line[j][COLUMN] < line[j - 1][COLUMN]) {
  427. return false;
  428. }
  429. }
  430. return true;
  431. }
  432. function sortSegments(line, owned) {
  433. if (!owned)
  434. line = line.slice();
  435. return line.sort(sortComparator2);
  436. }
  437. function sortComparator2(a, b) {
  438. return a[COLUMN] - b[COLUMN];
  439. }
  440. var found = false;
  441. function binarySearch(haystack, needle, low, high) {
  442. while (low <= high) {
  443. const mid = low + (high - low >> 1);
  444. const cmp = haystack[mid][COLUMN] - needle;
  445. if (cmp === 0) {
  446. found = true;
  447. return mid;
  448. }
  449. if (cmp < 0) {
  450. low = mid + 1;
  451. } else {
  452. high = mid - 1;
  453. }
  454. }
  455. found = false;
  456. return low - 1;
  457. }
  458. function upperBound(haystack, needle, index) {
  459. for (let i = index + 1; i < haystack.length; index = i++) {
  460. if (haystack[i][COLUMN] !== needle)
  461. break;
  462. }
  463. return index;
  464. }
  465. function lowerBound(haystack, needle, index) {
  466. for (let i = index - 1; i >= 0; index = i--) {
  467. if (haystack[i][COLUMN] !== needle)
  468. break;
  469. }
  470. return index;
  471. }
  472. function memoizedState() {
  473. return {
  474. lastKey: -1,
  475. lastNeedle: -1,
  476. lastIndex: -1
  477. };
  478. }
  479. function memoizedBinarySearch(haystack, needle, state, key) {
  480. const { lastKey, lastNeedle, lastIndex } = state;
  481. let low = 0;
  482. let high = haystack.length - 1;
  483. if (key === lastKey) {
  484. if (needle === lastNeedle) {
  485. found = lastIndex !== -1 && haystack[lastIndex][COLUMN] === needle;
  486. return lastIndex;
  487. }
  488. if (needle >= lastNeedle) {
  489. low = lastIndex === -1 ? 0 : lastIndex;
  490. } else {
  491. high = lastIndex;
  492. }
  493. }
  494. state.lastKey = key;
  495. state.lastNeedle = needle;
  496. return state.lastIndex = binarySearch(haystack, needle, low, high);
  497. }
  498. var LEAST_UPPER_BOUND = -1;
  499. var GREATEST_LOWER_BOUND = 1;
  500. var TraceMap = class {
  501. constructor(map, mapUrl) {
  502. const isString2 = typeof map === "string";
  503. if (!isString2 && map._decodedMemo)
  504. return map;
  505. const parsed = isString2 ? JSON.parse(map) : map;
  506. const { version, file, names, sourceRoot, sources, sourcesContent } = parsed;
  507. this.version = version;
  508. this.file = file;
  509. this.names = names || [];
  510. this.sourceRoot = sourceRoot;
  511. this.sources = sources;
  512. this.sourcesContent = sourcesContent;
  513. this.ignoreList = parsed.ignoreList || parsed.x_google_ignoreList || void 0;
  514. const from = resolve2(sourceRoot || "", stripFilename(mapUrl));
  515. this.resolvedSources = sources.map((s) => resolve2(s || "", from));
  516. const { mappings } = parsed;
  517. if (typeof mappings === "string") {
  518. this._encoded = mappings;
  519. this._decoded = void 0;
  520. } else {
  521. this._encoded = void 0;
  522. this._decoded = maybeSort(mappings, isString2);
  523. }
  524. this._decodedMemo = memoizedState();
  525. this._bySources = void 0;
  526. this._bySourceMemos = void 0;
  527. }
  528. };
  529. function cast(map) {
  530. return map;
  531. }
  532. function decodedMappings(map) {
  533. var _a;
  534. return (_a = cast(map))._decoded || (_a._decoded = decode(cast(map)._encoded));
  535. }
  536. function traceSegment(map, line, column) {
  537. const decoded = decodedMappings(map);
  538. if (line >= decoded.length)
  539. return null;
  540. const segments = decoded[line];
  541. const index = traceSegmentInternal(segments, cast(map)._decodedMemo, line, column, GREATEST_LOWER_BOUND);
  542. return index === -1 ? null : segments[index];
  543. }
  544. function traceSegmentInternal(segments, memo, line, column, bias) {
  545. let index = memoizedBinarySearch(segments, column, memo, line);
  546. if (found) {
  547. index = (bias === LEAST_UPPER_BOUND ? upperBound : lowerBound)(segments, column, index);
  548. } else if (bias === LEAST_UPPER_BOUND)
  549. index++;
  550. if (index === -1 || index === segments.length)
  551. return -1;
  552. return index;
  553. }
  554. // node_modules/.pnpm/@jridgewell+set-array@1.2.1/node_modules/@jridgewell/set-array/dist/set-array.mjs
  555. var SetArray = class {
  556. constructor() {
  557. this._indexes = { __proto__: null };
  558. this.array = [];
  559. }
  560. };
  561. function cast2(set) {
  562. return set;
  563. }
  564. function get(setarr, key) {
  565. return cast2(setarr)._indexes[key];
  566. }
  567. function put(setarr, key) {
  568. const index = get(setarr, key);
  569. if (index !== void 0)
  570. return index;
  571. const { array, _indexes: indexes } = cast2(setarr);
  572. const length = array.push(key);
  573. return indexes[key] = length - 1;
  574. }
  575. function remove(setarr, key) {
  576. const index = get(setarr, key);
  577. if (index === void 0)
  578. return;
  579. const { array, _indexes: indexes } = cast2(setarr);
  580. for (let i = index + 1; i < array.length; i++) {
  581. const k = array[i];
  582. array[i - 1] = k;
  583. indexes[k]--;
  584. }
  585. indexes[key] = void 0;
  586. array.pop();
  587. }
  588. // node_modules/.pnpm/@jridgewell+gen-mapping@0.3.5/node_modules/@jridgewell/gen-mapping/dist/gen-mapping.mjs
  589. var COLUMN2 = 0;
  590. var SOURCES_INDEX = 1;
  591. var SOURCE_LINE = 2;
  592. var SOURCE_COLUMN = 3;
  593. var NAMES_INDEX = 4;
  594. var NO_NAME = -1;
  595. var GenMapping = class {
  596. constructor({ file, sourceRoot } = {}) {
  597. this._names = new SetArray();
  598. this._sources = new SetArray();
  599. this._sourcesContent = [];
  600. this._mappings = [];
  601. this.file = file;
  602. this.sourceRoot = sourceRoot;
  603. this._ignoreList = new SetArray();
  604. }
  605. };
  606. function cast3(map) {
  607. return map;
  608. }
  609. var maybeAddSegment = (map, genLine, genColumn, source, sourceLine, sourceColumn, name, content) => {
  610. return addSegmentInternal(true, map, genLine, genColumn, source, sourceLine, sourceColumn, name, content);
  611. };
  612. function setSourceContent(map, source, content) {
  613. const { _sources: sources, _sourcesContent: sourcesContent } = cast3(map);
  614. const index = put(sources, source);
  615. sourcesContent[index] = content;
  616. }
  617. function setIgnore(map, source, ignore = true) {
  618. const { _sources: sources, _sourcesContent: sourcesContent, _ignoreList: ignoreList } = cast3(map);
  619. const index = put(sources, source);
  620. if (index === sourcesContent.length)
  621. sourcesContent[index] = null;
  622. if (ignore)
  623. put(ignoreList, index);
  624. else
  625. remove(ignoreList, index);
  626. }
  627. function toDecodedMap(map) {
  628. const { _mappings: mappings, _sources: sources, _sourcesContent: sourcesContent, _names: names, _ignoreList: ignoreList } = cast3(map);
  629. removeEmptyFinalLines(mappings);
  630. return {
  631. version: 3,
  632. file: map.file || void 0,
  633. names: names.array,
  634. sourceRoot: map.sourceRoot || void 0,
  635. sources: sources.array,
  636. sourcesContent,
  637. mappings,
  638. ignoreList: ignoreList.array
  639. };
  640. }
  641. function toEncodedMap(map) {
  642. const decoded = toDecodedMap(map);
  643. return Object.assign(Object.assign({}, decoded), { mappings: encode(decoded.mappings) });
  644. }
  645. function addSegmentInternal(skipable, map, genLine, genColumn, source, sourceLine, sourceColumn, name, content) {
  646. const { _mappings: mappings, _sources: sources, _sourcesContent: sourcesContent, _names: names } = cast3(map);
  647. const line = getLine(mappings, genLine);
  648. const index = getColumnIndex(line, genColumn);
  649. if (!source) {
  650. if (skipable && skipSourceless(line, index))
  651. return;
  652. return insert(line, index, [genColumn]);
  653. }
  654. const sourcesIndex = put(sources, source);
  655. const namesIndex = name ? put(names, name) : NO_NAME;
  656. if (sourcesIndex === sourcesContent.length)
  657. sourcesContent[sourcesIndex] = content !== null && content !== void 0 ? content : null;
  658. if (skipable && skipSource(line, index, sourcesIndex, sourceLine, sourceColumn, namesIndex)) {
  659. return;
  660. }
  661. return insert(line, index, name ? [genColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex] : [genColumn, sourcesIndex, sourceLine, sourceColumn]);
  662. }
  663. function getLine(mappings, index) {
  664. for (let i = mappings.length; i <= index; i++) {
  665. mappings[i] = [];
  666. }
  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[COLUMN2])
  674. break;
  675. }
  676. return index;
  677. }
  678. function insert(array, index, value) {
  679. for (let i = array.length; i > index; i--) {
  680. array[i] = array[i - 1];
  681. }
  682. array[index] = value;
  683. }
  684. function removeEmptyFinalLines(mappings) {
  685. const { length } = mappings;
  686. let len = length;
  687. for (let i = len - 1; i >= 0; len = i, i--) {
  688. if (mappings[i].length > 0)
  689. break;
  690. }
  691. if (len < length)
  692. mappings.length = len;
  693. }
  694. function skipSourceless(line, index) {
  695. if (index === 0)
  696. return true;
  697. const prev = line[index - 1];
  698. return prev.length === 1;
  699. }
  700. function skipSource(line, index, sourcesIndex, sourceLine, sourceColumn, namesIndex) {
  701. if (index === 0)
  702. return false;
  703. const prev = line[index - 1];
  704. if (prev.length === 1)
  705. return false;
  706. return sourcesIndex === prev[SOURCES_INDEX] && sourceLine === prev[SOURCE_LINE] && sourceColumn === prev[SOURCE_COLUMN] && namesIndex === (prev.length === 5 ? prev[NAMES_INDEX] : NO_NAME);
  707. }
  708. // node_modules/.pnpm/@ampproject+remapping@2.3.0/node_modules/@ampproject/remapping/dist/remapping.mjs
  709. var SOURCELESS_MAPPING = /* @__PURE__ */ SegmentObject("", -1, -1, "", null, false);
  710. var EMPTY_SOURCES = [];
  711. function SegmentObject(source, line, column, name, content, ignore) {
  712. return { source, line, column, name, content, ignore };
  713. }
  714. function Source(map, sources, source, content, ignore) {
  715. return {
  716. map,
  717. sources,
  718. source,
  719. content,
  720. ignore
  721. };
  722. }
  723. function MapSource(map, sources) {
  724. return Source(map, sources, "", null, false);
  725. }
  726. function OriginalSource(source, content, ignore) {
  727. return Source(null, EMPTY_SOURCES, source, content, ignore);
  728. }
  729. function traceMappings(tree) {
  730. const gen = new GenMapping({ file: tree.map.file });
  731. const { sources: rootSources, map } = tree;
  732. const rootNames = map.names;
  733. const rootMappings = decodedMappings(map);
  734. for (let i = 0; i < rootMappings.length; i++) {
  735. const segments = rootMappings[i];
  736. for (let j = 0; j < segments.length; j++) {
  737. const segment = segments[j];
  738. const genCol = segment[0];
  739. let traced = SOURCELESS_MAPPING;
  740. if (segment.length !== 1) {
  741. const source2 = rootSources[segment[1]];
  742. traced = originalPositionFor(source2, segment[2], segment[3], segment.length === 5 ? rootNames[segment[4]] : "");
  743. if (traced == null)
  744. continue;
  745. }
  746. const { column, line, name, content, source, ignore } = traced;
  747. maybeAddSegment(gen, i, genCol, source, line, column, name);
  748. if (source && content != null)
  749. setSourceContent(gen, source, content);
  750. if (ignore)
  751. setIgnore(gen, source, true);
  752. }
  753. }
  754. return gen;
  755. }
  756. function originalPositionFor(source, line, column, name) {
  757. if (!source.map) {
  758. return SegmentObject(source.source, line, column, name, source.content, source.ignore);
  759. }
  760. const segment = traceSegment(source.map, line, column);
  761. if (segment == null)
  762. return null;
  763. if (segment.length === 1)
  764. return SOURCELESS_MAPPING;
  765. return originalPositionFor(source.sources[segment[1]], segment[2], segment[3], segment.length === 5 ? source.map.names[segment[4]] : name);
  766. }
  767. function asArray(value) {
  768. if (Array.isArray(value))
  769. return value;
  770. return [value];
  771. }
  772. function buildSourceMapTree(input, loader) {
  773. const maps = asArray(input).map((m) => new TraceMap(m, ""));
  774. const map = maps.pop();
  775. for (let i = 0; i < maps.length; i++) {
  776. if (maps[i].sources.length > 1) {
  777. throw new Error(`Transformation map ${i} must have exactly one source file.
  778. Did you specify these with the most recent transformation maps first?`);
  779. }
  780. }
  781. let tree = build(map, loader, "", 0);
  782. for (let i = maps.length - 1; i >= 0; i--) {
  783. tree = MapSource(maps[i], [tree]);
  784. }
  785. return tree;
  786. }
  787. function build(map, loader, importer, importerDepth) {
  788. const { resolvedSources, sourcesContent, ignoreList } = map;
  789. const depth = importerDepth + 1;
  790. const children = resolvedSources.map((sourceFile, i) => {
  791. const ctx = {
  792. importer,
  793. depth,
  794. source: sourceFile || "",
  795. content: void 0,
  796. ignore: void 0
  797. };
  798. const sourceMap = loader(ctx.source, ctx);
  799. const { source, content, ignore } = ctx;
  800. if (sourceMap)
  801. return build(new TraceMap(sourceMap, source), loader, source, depth);
  802. const sourceContent = content !== void 0 ? content : sourcesContent ? sourcesContent[i] : null;
  803. const ignored = ignore !== void 0 ? ignore : ignoreList ? ignoreList.includes(i) : false;
  804. return OriginalSource(source, sourceContent, ignored);
  805. });
  806. return MapSource(map, children);
  807. }
  808. var SourceMap = class {
  809. constructor(map, options) {
  810. const out = options.decodedMappings ? toDecodedMap(map) : toEncodedMap(map);
  811. this.version = out.version;
  812. this.file = out.file;
  813. this.mappings = out.mappings;
  814. this.names = out.names;
  815. this.ignoreList = out.ignoreList;
  816. this.sourceRoot = out.sourceRoot;
  817. this.sources = out.sources;
  818. if (!options.excludeContent) {
  819. this.sourcesContent = out.sourcesContent;
  820. }
  821. }
  822. toString() {
  823. return JSON.stringify(this);
  824. }
  825. };
  826. function remapping(input, loader, options) {
  827. const opts = typeof options === "object" ? options : { excludeContent: !!options, decodedMappings: false };
  828. const tree = buildSourceMapTree(input, loader);
  829. return new SourceMap(traceMappings(tree), opts);
  830. }
  831. // src/esbuild/utils.ts
  832. var import_acorn = require("acorn");
  833. // src/utils.ts
  834. var import_path = require("path");
  835. function normalizeAbsolutePath(path5) {
  836. if ((0, import_path.isAbsolute)(path5))
  837. return (0, import_path.normalize)(path5);
  838. else
  839. return path5;
  840. }
  841. function toArray(array) {
  842. array = array || [];
  843. if (Array.isArray(array))
  844. return array;
  845. return [array];
  846. }
  847. function shouldLoad(id, plugin, externalModules) {
  848. if (id.startsWith(plugin.__virtualModulePrefix))
  849. id = decodeURIComponent(id.slice(plugin.__virtualModulePrefix.length));
  850. if (plugin.loadInclude && !plugin.loadInclude(id))
  851. return false;
  852. return !externalModules.has(id);
  853. }
  854. function transformUse(data, plugin, transformLoader) {
  855. if (data.resource == null)
  856. return [];
  857. const id = normalizeAbsolutePath(data.resource + (data.resourceQuery || ""));
  858. if (!plugin.transformInclude || plugin.transformInclude(id)) {
  859. return [{
  860. loader: `${transformLoader}?unpluginName=${encodeURIComponent(plugin.name)}`
  861. }];
  862. }
  863. return [];
  864. }
  865. // src/esbuild/utils.ts
  866. var ExtToLoader = {
  867. ".js": "js",
  868. ".mjs": "js",
  869. ".cjs": "js",
  870. ".jsx": "jsx",
  871. ".ts": "ts",
  872. ".cts": "ts",
  873. ".mts": "ts",
  874. ".tsx": "tsx",
  875. ".css": "css",
  876. ".less": "css",
  877. ".stylus": "css",
  878. ".scss": "css",
  879. ".sass": "css",
  880. ".json": "json",
  881. ".txt": "text"
  882. };
  883. function guessLoader(code, id) {
  884. return ExtToLoader[import_path2.default.extname(id).toLowerCase()] || "js";
  885. }
  886. function unwrapLoader(loader, code, id) {
  887. if (typeof loader === "function")
  888. return loader(code, id);
  889. return loader;
  890. }
  891. function fixSourceMap(map) {
  892. if (!Object.prototype.hasOwnProperty.call(map, "toString")) {
  893. Object.defineProperty(map, "toString", {
  894. enumerable: false,
  895. value: function toString() {
  896. return JSON.stringify(this);
  897. }
  898. });
  899. }
  900. if (!Object.prototype.hasOwnProperty.call(map, "toUrl")) {
  901. Object.defineProperty(map, "toUrl", {
  902. enumerable: false,
  903. value: function toUrl() {
  904. return `data:application/json;charset=utf-8;base64,${import_buffer.Buffer.from(this.toString()).toString("base64")}`;
  905. }
  906. });
  907. }
  908. return map;
  909. }
  910. var nullSourceMap = {
  911. names: [],
  912. sources: [],
  913. mappings: "",
  914. version: 3
  915. };
  916. function combineSourcemaps(filename, sourcemapList) {
  917. sourcemapList = sourcemapList.filter((m) => m.sources);
  918. if (sourcemapList.length === 0 || sourcemapList.every((m) => m.sources.length === 0)) {
  919. return { ...nullSourceMap };
  920. }
  921. let map;
  922. let mapIndex = 1;
  923. const useArrayInterface = sourcemapList.slice(0, -1).find((m) => m.sources.length !== 1) === void 0;
  924. if (useArrayInterface) {
  925. map = remapping(sourcemapList, () => null, true);
  926. } else {
  927. map = remapping(
  928. sourcemapList[0],
  929. (sourcefile) => {
  930. if (sourcefile === filename && sourcemapList[mapIndex])
  931. return sourcemapList[mapIndex++];
  932. else
  933. return { ...nullSourceMap };
  934. },
  935. true
  936. );
  937. }
  938. if (!map.file)
  939. delete map.file;
  940. return map;
  941. }
  942. function createBuildContext(build2) {
  943. const watchFiles = [];
  944. const { initialOptions } = build2;
  945. return {
  946. parse(code, opts = {}) {
  947. return import_acorn.Parser.parse(code, {
  948. sourceType: "module",
  949. ecmaVersion: "latest",
  950. locations: true,
  951. ...opts
  952. });
  953. },
  954. addWatchFile() {
  955. throw new Error("unplugin/esbuild: addWatchFile outside supported hooks (resolveId, load, transform)");
  956. },
  957. emitFile(emittedFile) {
  958. const outFileName = emittedFile.fileName || emittedFile.name;
  959. if (initialOptions.outdir && emittedFile.source && outFileName) {
  960. const outPath = import_path2.default.resolve(initialOptions.outdir, outFileName);
  961. const outDir = import_path2.default.dirname(outPath);
  962. if (!import_fs.default.existsSync(outDir))
  963. import_fs.default.mkdirSync(outDir, { recursive: true });
  964. import_fs.default.writeFileSync(outPath, emittedFile.source);
  965. }
  966. },
  967. getWatchFiles() {
  968. return watchFiles;
  969. },
  970. getNativeBuildContext() {
  971. return { framework: "esbuild", build: build2 };
  972. }
  973. };
  974. }
  975. function createPluginContext(context) {
  976. const errors = [];
  977. const warnings = [];
  978. const pluginContext = {
  979. error(message) {
  980. errors.push(normalizeMessage(message));
  981. },
  982. warn(message) {
  983. warnings.push(normalizeMessage(message));
  984. }
  985. };
  986. const mixedContext = {
  987. ...context,
  988. ...pluginContext,
  989. addWatchFile(id) {
  990. context.getWatchFiles().push(id);
  991. }
  992. };
  993. return {
  994. errors,
  995. warnings,
  996. mixedContext
  997. };
  998. }
  999. function normalizeMessage(message) {
  1000. if (typeof message === "string")
  1001. message = { message };
  1002. return {
  1003. id: message.id,
  1004. pluginName: message.plugin,
  1005. text: message.message,
  1006. location: message.loc ? {
  1007. file: message.loc.file,
  1008. line: message.loc.line,
  1009. column: message.loc.column
  1010. } : null,
  1011. detail: message.meta,
  1012. notes: []
  1013. };
  1014. }
  1015. function processCodeWithSourceMap(map, code) {
  1016. if (map) {
  1017. if (!map.sourcesContent || map.sourcesContent.length === 0)
  1018. map.sourcesContent = [code];
  1019. map = fixSourceMap(map);
  1020. code += `
  1021. //# sourceMappingURL=${map.toUrl()}`;
  1022. }
  1023. return code;
  1024. }
  1025. // src/esbuild/index.ts
  1026. function getEsbuildPlugin(factory) {
  1027. return (userOptions) => {
  1028. const meta = {
  1029. framework: "esbuild"
  1030. };
  1031. const plugins = toArray(factory(userOptions, meta));
  1032. const setupPlugins = async (build2) => {
  1033. const setup = buildSetup(meta);
  1034. const loaders = [];
  1035. for (const plugin of plugins) {
  1036. const loader = {};
  1037. await setup(plugin)({
  1038. ...build2,
  1039. onLoad(_options, callback) {
  1040. loader.options = _options;
  1041. loader.onLoadCb = callback;
  1042. },
  1043. onTransform(_options, callback) {
  1044. loader.options || (loader.options = _options);
  1045. loader.onTransformCb = callback;
  1046. }
  1047. }, build2);
  1048. if (loader.onLoadCb || loader.onTransformCb)
  1049. loaders.push(loader);
  1050. }
  1051. if (loaders.length) {
  1052. build2.onLoad(loaders.length === 1 ? loaders[0].options : { filter: /.*/ }, async (args) => {
  1053. function checkFilter(options) {
  1054. return loaders.length === 1 || !(options == null ? void 0 : options.filter) || options.filter.test(args.path);
  1055. }
  1056. let result;
  1057. for (const { options, onLoadCb } of loaders) {
  1058. if (!checkFilter(options))
  1059. continue;
  1060. if (onLoadCb)
  1061. result = await onLoadCb(args);
  1062. if (result == null ? void 0 : result.contents)
  1063. break;
  1064. }
  1065. let fsContentsCache;
  1066. for (const { options, onTransformCb } of loaders) {
  1067. if (!checkFilter(options))
  1068. continue;
  1069. if (onTransformCb) {
  1070. const newArgs = {
  1071. ...result,
  1072. ...args,
  1073. async getContents() {
  1074. if (result == null ? void 0 : result.contents)
  1075. return result.contents;
  1076. if (fsContentsCache)
  1077. return fsContentsCache;
  1078. return fsContentsCache = await import_fs2.default.promises.readFile(args.path, "utf8");
  1079. }
  1080. };
  1081. const _result = await onTransformCb(newArgs);
  1082. if (_result == null ? void 0 : _result.contents)
  1083. result = _result;
  1084. }
  1085. }
  1086. if (result == null ? void 0 : result.contents)
  1087. return result;
  1088. });
  1089. }
  1090. };
  1091. return {
  1092. name: (plugins.length === 1 ? plugins[0].name : meta.esbuildHostName) ?? `unplugin-host:${plugins.map((p) => p.name).join(":")}`,
  1093. setup: setupPlugins
  1094. };
  1095. };
  1096. }
  1097. function buildSetup(meta) {
  1098. return (plugin) => {
  1099. return (build2, rawBuild) => {
  1100. var _a, _b, _c, _d, _e;
  1101. meta.build = build2;
  1102. const context = createBuildContext(build2);
  1103. const { onStart, onEnd, onResolve, onLoad, onTransform, initialOptions } = build2;
  1104. const onResolveFilter = ((_a = plugin.esbuild) == null ? void 0 : _a.onResolveFilter) ?? /.*/;
  1105. const onLoadFilter = ((_b = plugin.esbuild) == null ? void 0 : _b.onLoadFilter) ?? /.*/;
  1106. const loader = ((_c = plugin.esbuild) == null ? void 0 : _c.loader) ?? guessLoader;
  1107. if ((_d = plugin.esbuild) == null ? void 0 : _d.config)
  1108. plugin.esbuild.config.call(context, initialOptions);
  1109. if (plugin.buildStart)
  1110. onStart(() => plugin.buildStart.call(context));
  1111. if (plugin.buildEnd || plugin.writeBundle) {
  1112. onEnd(async () => {
  1113. if (plugin.buildEnd)
  1114. await plugin.buildEnd.call(context);
  1115. if (plugin.writeBundle)
  1116. await plugin.writeBundle();
  1117. });
  1118. }
  1119. if (plugin.resolveId) {
  1120. onResolve({ filter: onResolveFilter }, async (args) => {
  1121. var _a2;
  1122. if ((_a2 = initialOptions.external) == null ? void 0 : _a2.includes(args.path)) {
  1123. return void 0;
  1124. }
  1125. const { errors, warnings, mixedContext } = createPluginContext(context);
  1126. const isEntry = args.kind === "entry-point";
  1127. const result = await plugin.resolveId.call(
  1128. mixedContext,
  1129. args.path,
  1130. // We explicitly have this if statement here for consistency with
  1131. // the integration of other bundlers.
  1132. // Here, `args.importer` is just an empty string on entry files
  1133. // whereas the equivalent on other bundlers is`undefined.`
  1134. isEntry ? void 0 : args.importer,
  1135. { isEntry }
  1136. );
  1137. if (typeof result === "string") {
  1138. return {
  1139. path: result,
  1140. namespace: plugin.name,
  1141. errors,
  1142. warnings,
  1143. watchFiles: mixedContext.getWatchFiles()
  1144. };
  1145. } else if (typeof result === "object" && result !== null) {
  1146. return {
  1147. path: result.id,
  1148. external: result.external,
  1149. namespace: plugin.name,
  1150. errors,
  1151. warnings,
  1152. watchFiles: mixedContext.getWatchFiles()
  1153. };
  1154. }
  1155. });
  1156. }
  1157. if (plugin.load) {
  1158. onLoad({ filter: onLoadFilter }, async (args) => {
  1159. const id = args.path + args.suffix;
  1160. const { errors, warnings, mixedContext } = createPluginContext(context);
  1161. const resolveDir = import_path3.default.dirname(args.path);
  1162. let code, map;
  1163. if (plugin.load && (!plugin.loadInclude || plugin.loadInclude(id))) {
  1164. const result = await plugin.load.call(mixedContext, id);
  1165. if (typeof result === "string") {
  1166. code = result;
  1167. } else if (typeof result === "object" && result !== null) {
  1168. code = result.code;
  1169. map = result.map;
  1170. }
  1171. }
  1172. if (code === void 0)
  1173. return null;
  1174. if (map)
  1175. code = processCodeWithSourceMap(map, code);
  1176. return {
  1177. contents: code,
  1178. errors,
  1179. warnings,
  1180. watchFiles: mixedContext.getWatchFiles(),
  1181. loader: unwrapLoader(loader, code, args.path),
  1182. resolveDir
  1183. };
  1184. });
  1185. }
  1186. if (plugin.transform) {
  1187. onTransform({ filter: onLoadFilter }, async (args) => {
  1188. const id = args.path + args.suffix;
  1189. if (plugin.transformInclude && !plugin.transformInclude(id))
  1190. return;
  1191. const { mixedContext, errors, warnings } = createPluginContext(context);
  1192. const resolveDir = import_path3.default.dirname(args.path);
  1193. let code = await args.getContents();
  1194. let map;
  1195. const result = await plugin.transform.call(mixedContext, code, id);
  1196. if (typeof result === "string") {
  1197. code = result;
  1198. } else if (typeof result === "object" && result !== null) {
  1199. code = result.code;
  1200. if (map && result.map) {
  1201. map = combineSourcemaps(args.path, [
  1202. result.map === "string" ? JSON.parse(result.map) : result.map,
  1203. map
  1204. ]);
  1205. } else {
  1206. if (typeof result.map === "string") {
  1207. map = JSON.parse(result.map);
  1208. } else {
  1209. map = result.map;
  1210. }
  1211. }
  1212. }
  1213. if (code) {
  1214. if (map)
  1215. code = processCodeWithSourceMap(map, code);
  1216. return {
  1217. contents: code,
  1218. errors,
  1219. warnings,
  1220. watchFiles: mixedContext.getWatchFiles(),
  1221. loader: unwrapLoader(loader, code, args.path),
  1222. resolveDir
  1223. };
  1224. }
  1225. });
  1226. }
  1227. if ((_e = plugin.esbuild) == null ? void 0 : _e.setup)
  1228. return plugin.esbuild.setup(rawBuild);
  1229. };
  1230. };
  1231. }
  1232. // src/farm/index.ts
  1233. var import_path6 = __toESM(require("path"));
  1234. // src/farm/context.ts
  1235. var import_buffer2 = require("buffer");
  1236. var import_path4 = require("path");
  1237. var import_acorn2 = require("acorn");
  1238. function createFarmContext(context, currentResolveId) {
  1239. return {
  1240. parse(code, opts = {}) {
  1241. return import_acorn2.Parser.parse(code, {
  1242. sourceType: "module",
  1243. ecmaVersion: "latest",
  1244. locations: true,
  1245. ...opts
  1246. });
  1247. },
  1248. addWatchFile(id) {
  1249. context.addWatchFile(currentResolveId || id, id);
  1250. },
  1251. emitFile(emittedFile) {
  1252. const outFileName = emittedFile.fileName || emittedFile.name;
  1253. if (emittedFile.source && outFileName) {
  1254. context.emitFile({
  1255. resolvedPath: outFileName,
  1256. name: outFileName,
  1257. content: [...import_buffer2.Buffer.from(emittedFile.source)],
  1258. resourceType: (0, import_path4.extname)(outFileName)
  1259. });
  1260. }
  1261. },
  1262. getWatchFiles() {
  1263. return context.getWatchFiles();
  1264. },
  1265. getNativeBuildContext() {
  1266. return { framework: "farm", context };
  1267. }
  1268. };
  1269. }
  1270. function unpluginContext(context) {
  1271. return {
  1272. error: (error) => context.error(
  1273. typeof error === "string" ? new Error(error) : error
  1274. ),
  1275. warn: (error) => context.warn(typeof error === "string" ? new Error(error) : error)
  1276. };
  1277. }
  1278. // src/farm/utils.ts
  1279. var import_path5 = __toESM(require("path"));
  1280. var querystring = __toESM(require("querystring"));
  1281. var ExtToLoader2 = {
  1282. ".js": "js",
  1283. ".mjs": "js",
  1284. ".cjs": "js",
  1285. ".jsx": "jsx",
  1286. ".ts": "ts",
  1287. ".cts": "ts",
  1288. ".mts": "ts",
  1289. ".tsx": "tsx",
  1290. ".json": "json",
  1291. ".toml": "toml",
  1292. ".text": "text",
  1293. ".wasm": "wasm",
  1294. ".napi": "napi",
  1295. ".node": "napi"
  1296. };
  1297. function guessIdLoader(id) {
  1298. return ExtToLoader2[import_path5.default.extname(id).toLowerCase()] || "js";
  1299. }
  1300. function transformQuery(context) {
  1301. const queryParamsObject = {};
  1302. context.query.forEach(([param, value]) => {
  1303. queryParamsObject[param] = value;
  1304. });
  1305. const transformQuery2 = querystring.stringify(queryParamsObject);
  1306. context.resolvedPath = `${context.resolvedPath}?${transformQuery2}`;
  1307. }
  1308. function convertEnforceToPriority(value) {
  1309. const defaultPriority = 100;
  1310. const enforceToPriority = {
  1311. pre: 101,
  1312. post: 99
  1313. };
  1314. return enforceToPriority[value] !== void 0 ? enforceToPriority[value] : defaultPriority;
  1315. }
  1316. function convertWatchEventChange(value) {
  1317. const watchEventChange = {
  1318. Added: "create",
  1319. Updated: "update",
  1320. Removed: "delete"
  1321. };
  1322. return watchEventChange[value];
  1323. }
  1324. function getContentValue(content) {
  1325. return typeof content === "string" ? content : content.code;
  1326. }
  1327. function isString(variable) {
  1328. return typeof variable === "string";
  1329. }
  1330. function isObject(variable) {
  1331. return typeof variable === "object" && variable !== null;
  1332. }
  1333. function customParseQueryString(url) {
  1334. if (!url)
  1335. return [];
  1336. const queryString = url.split("?")[1];
  1337. const parsedParams = querystring.parse(queryString);
  1338. const paramsArray = [];
  1339. for (const key in parsedParams)
  1340. paramsArray.push([key, parsedParams[key]]);
  1341. return paramsArray;
  1342. }
  1343. // src/farm/index.ts
  1344. function getFarmPlugin(factory) {
  1345. return (userOptions) => {
  1346. const meta = {
  1347. framework: "farm"
  1348. };
  1349. const rawPlugins = toArray(factory(userOptions, meta));
  1350. const plugins = rawPlugins.map((rawPlugin) => {
  1351. const plugin = toFarmPlugin(rawPlugin, userOptions);
  1352. if (rawPlugin.farm)
  1353. Object.assign(plugin, rawPlugin.farm);
  1354. return plugin;
  1355. });
  1356. return plugins.length === 1 ? plugins[0] : plugins;
  1357. };
  1358. }
  1359. function toFarmPlugin(plugin, options) {
  1360. const farmPlugin = {
  1361. name: plugin.name,
  1362. priority: convertEnforceToPriority(plugin.enforce)
  1363. };
  1364. if (plugin.farm) {
  1365. Object.keys(plugin.farm).forEach((key) => {
  1366. const value = plugin.farm[key];
  1367. if (value)
  1368. Reflect.set(farmPlugin, key, value);
  1369. });
  1370. }
  1371. if (plugin.buildStart) {
  1372. const _buildStart = plugin.buildStart;
  1373. farmPlugin.buildStart = {
  1374. async executor(_, context) {
  1375. await _buildStart.call(createFarmContext(context));
  1376. }
  1377. };
  1378. }
  1379. if (plugin.resolveId) {
  1380. const _resolveId = plugin.resolveId;
  1381. let filters = [];
  1382. if (options)
  1383. filters = (options == null ? void 0 : options.filters) ?? [];
  1384. farmPlugin.resolve = {
  1385. filters: { sources: [".*", ...filters], importers: [".*"] },
  1386. async executor(params, context) {
  1387. const resolvedIdPath = import_path6.default.resolve(
  1388. process.cwd(),
  1389. params.importer ?? ""
  1390. );
  1391. let isEntry = false;
  1392. if (isObject(params.kind) && "entry" in params.kind) {
  1393. const kindWithEntry = params.kind;
  1394. isEntry = kindWithEntry.entry === "index";
  1395. }
  1396. const farmContext = createFarmContext(context, resolvedIdPath);
  1397. const resolveIdResult = await _resolveId.call(
  1398. Object.assign(unpluginContext(context), farmContext),
  1399. params.source,
  1400. resolvedIdPath ?? null,
  1401. { isEntry }
  1402. );
  1403. if (isString(resolveIdResult)) {
  1404. return {
  1405. resolvedPath: resolveIdResult,
  1406. query: customParseQueryString(resolveIdResult),
  1407. sideEffects: false,
  1408. external: false,
  1409. meta: {}
  1410. };
  1411. } else if (isObject(resolveIdResult)) {
  1412. return {
  1413. resolvedPath: resolveIdResult == null ? void 0 : resolveIdResult.id,
  1414. query: customParseQueryString(resolveIdResult.id),
  1415. sideEffects: false,
  1416. external: resolveIdResult == null ? void 0 : resolveIdResult.external,
  1417. meta: {}
  1418. };
  1419. }
  1420. return null;
  1421. }
  1422. };
  1423. }
  1424. if (plugin.load) {
  1425. const _load = plugin.load;
  1426. farmPlugin.load = {
  1427. filters: {
  1428. resolvedPaths: [".*"]
  1429. },
  1430. async executor(id, context) {
  1431. if (plugin.loadInclude && !plugin.loadInclude(id.resolvedPath))
  1432. return null;
  1433. const loader = guessIdLoader(id.resolvedPath);
  1434. const shouldLoadInclude = plugin.loadInclude && plugin.loadInclude(id.resolvedPath);
  1435. const farmContext = createFarmContext(context, id.resolvedPath);
  1436. const content = await _load.call(
  1437. Object.assign(unpluginContext(context), farmContext),
  1438. id.resolvedPath
  1439. );
  1440. const loadFarmResult = {
  1441. content: getContentValue(content),
  1442. moduleType: loader
  1443. };
  1444. if (shouldLoadInclude)
  1445. return loadFarmResult;
  1446. return null;
  1447. }
  1448. };
  1449. }
  1450. if (plugin.transform) {
  1451. const _transform = plugin.transform;
  1452. farmPlugin.transform = {
  1453. filters: { resolvedPaths: [".*"], moduleTypes: [".*"] },
  1454. async executor(params, context) {
  1455. if (params.query.length)
  1456. transformQuery(params);
  1457. if (plugin.transformInclude && !plugin.transformInclude(params.resolvedPath)) {
  1458. return null;
  1459. }
  1460. const loader = params.moduleType ?? guessIdLoader(params.resolvedPath);
  1461. const shouldTransformInclude = plugin.transformInclude && plugin.transformInclude(params.resolvedPath);
  1462. const farmContext = createFarmContext(context, params.resolvedPath);
  1463. const resource = await _transform.call(
  1464. Object.assign(unpluginContext(context), farmContext),
  1465. params.content,
  1466. params.resolvedPath
  1467. );
  1468. if (resource && typeof resource !== "string") {
  1469. const transformFarmResult = {
  1470. content: getContentValue(resource),
  1471. moduleType: loader,
  1472. sourceMap: JSON.stringify(resource.map)
  1473. };
  1474. if (shouldTransformInclude)
  1475. return transformFarmResult;
  1476. return transformFarmResult;
  1477. }
  1478. }
  1479. };
  1480. }
  1481. if (plugin.watchChange) {
  1482. const _watchChange = plugin.watchChange;
  1483. farmPlugin.updateModules = {
  1484. async executor(param, context) {
  1485. const updatePathContent = param.paths[0];
  1486. const ModifiedPath = updatePathContent[0];
  1487. const eventChange = convertWatchEventChange(
  1488. updatePathContent[1]
  1489. );
  1490. await _watchChange.call(createFarmContext(context), ModifiedPath, {
  1491. event: eventChange
  1492. });
  1493. }
  1494. };
  1495. }
  1496. if (plugin.buildEnd) {
  1497. const _buildEnd = plugin.buildEnd;
  1498. farmPlugin.buildEnd = {
  1499. async executor(_, context) {
  1500. await _buildEnd.call(createFarmContext(context));
  1501. }
  1502. };
  1503. }
  1504. if (plugin.writeBundle) {
  1505. const _writeBundle = plugin.writeBundle;
  1506. farmPlugin.finish = {
  1507. async executor() {
  1508. await _writeBundle();
  1509. }
  1510. };
  1511. }
  1512. return farmPlugin;
  1513. }
  1514. // src/rollup/index.ts
  1515. function getRollupPlugin(factory) {
  1516. return (userOptions) => {
  1517. const meta = {
  1518. framework: "rollup"
  1519. };
  1520. const rawPlugins = toArray(factory(userOptions, meta));
  1521. const plugins = rawPlugins.map((plugin) => toRollupPlugin(plugin));
  1522. return plugins.length === 1 ? plugins[0] : plugins;
  1523. };
  1524. }
  1525. function toRollupPlugin(plugin, containRollupOptions = true) {
  1526. if (plugin.transform && plugin.transformInclude) {
  1527. const _transform = plugin.transform;
  1528. plugin.transform = function(code, id) {
  1529. if (plugin.transformInclude && !plugin.transformInclude(id))
  1530. return null;
  1531. return _transform.call(this, code, id);
  1532. };
  1533. }
  1534. if (plugin.load && plugin.loadInclude) {
  1535. const _load = plugin.load;
  1536. plugin.load = function(id) {
  1537. if (plugin.loadInclude && !plugin.loadInclude(id))
  1538. return null;
  1539. return _load.call(this, id);
  1540. };
  1541. }
  1542. if (plugin.rollup && containRollupOptions)
  1543. Object.assign(plugin, plugin.rollup);
  1544. return plugin;
  1545. }
  1546. // src/rolldown/index.ts
  1547. function getRolldownPlugin(factory) {
  1548. return (userOptions) => {
  1549. const meta = {
  1550. framework: "rolldown"
  1551. };
  1552. const rawPlugins = toArray(factory(userOptions, meta));
  1553. const plugins = rawPlugins.map((rawPlugin) => {
  1554. const plugin = toRollupPlugin(rawPlugin, false);
  1555. if (rawPlugin.rolldown)
  1556. Object.assign(plugin, rawPlugin.rolldown);
  1557. return plugin;
  1558. });
  1559. return plugins.length === 1 ? plugins[0] : plugins;
  1560. };
  1561. }
  1562. // src/rspack/index.ts
  1563. var import_fs4 = __toESM(require("fs"));
  1564. var import_path9 = require("path");
  1565. // src/rspack/context.ts
  1566. var import_buffer3 = require("buffer");
  1567. var import_path7 = require("path");
  1568. var import_acorn3 = require("acorn");
  1569. function createBuildContext2(compiler, compilation, loaderContext) {
  1570. return {
  1571. getNativeBuildContext() {
  1572. return {
  1573. framework: "rspack",
  1574. compiler,
  1575. compilation,
  1576. loaderContext
  1577. };
  1578. },
  1579. addWatchFile(file) {
  1580. compilation.fileDependencies.add((0, import_path7.resolve)(process.cwd(), file));
  1581. },
  1582. getWatchFiles() {
  1583. return Array.from(compilation.fileDependencies);
  1584. },
  1585. parse(code, opts = {}) {
  1586. return import_acorn3.Parser.parse(code, {
  1587. sourceType: "module",
  1588. ecmaVersion: "latest",
  1589. locations: true,
  1590. ...opts
  1591. });
  1592. },
  1593. emitFile(emittedFile) {
  1594. const outFileName = emittedFile.fileName || emittedFile.name;
  1595. if (emittedFile.source && outFileName) {
  1596. const { sources } = compilation.compiler.webpack;
  1597. compilation.emitAsset(
  1598. outFileName,
  1599. new sources.RawSource(
  1600. typeof emittedFile.source === "string" ? emittedFile.source : import_buffer3.Buffer.from(emittedFile.source)
  1601. )
  1602. );
  1603. }
  1604. }
  1605. };
  1606. }
  1607. function normalizeMessage2(error) {
  1608. const err = new Error(typeof error === "string" ? error : error.message);
  1609. if (typeof error === "object") {
  1610. err.stack = error.stack;
  1611. err.cause = error.meta;
  1612. }
  1613. return err;
  1614. }
  1615. // src/rspack/utils.ts
  1616. var import_fs3 = __toESM(require("fs"));
  1617. var import_path8 = require("path");
  1618. function encodeVirtualModuleId(id, plugin) {
  1619. return (0, import_path8.resolve)(plugin.__virtualModulePrefix, encodeURIComponent(id));
  1620. }
  1621. function decodeVirtualModuleId(encoded, _plugin) {
  1622. return decodeURIComponent((0, import_path8.basename)(encoded));
  1623. }
  1624. function isVirtualModuleId(encoded, plugin) {
  1625. return (0, import_path8.dirname)(encoded) === plugin.__virtualModulePrefix;
  1626. }
  1627. var FakeVirtualModulesPlugin = class {
  1628. constructor(plugin) {
  1629. this.plugin = plugin;
  1630. }
  1631. name = "FakeVirtualModulesPlugin";
  1632. apply(compiler) {
  1633. const dir = this.plugin.__virtualModulePrefix;
  1634. if (!import_fs3.default.existsSync(dir)) {
  1635. import_fs3.default.mkdirSync(dir, { recursive: true });
  1636. }
  1637. compiler.hooks.shutdown.tap(this.name, () => {
  1638. if (import_fs3.default.existsSync(dir)) {
  1639. import_fs3.default.rmdirSync(dir, { recursive: true });
  1640. }
  1641. });
  1642. }
  1643. async writeModule(file) {
  1644. const path5 = encodeVirtualModuleId(file, this.plugin);
  1645. await import_fs3.default.promises.writeFile(path5, "");
  1646. return path5;
  1647. }
  1648. };
  1649. // src/rspack/index.ts
  1650. var TRANSFORM_LOADER = (0, import_path9.resolve)(
  1651. __dirname,
  1652. false ? "../../dist/rspack/loaders/transform.js" : "rspack/loaders/transform"
  1653. );
  1654. var LOAD_LOADER = (0, import_path9.resolve)(
  1655. __dirname,
  1656. false ? "../../dist/rspack/loaders/load.js" : "rspack/loaders/load"
  1657. );
  1658. function getRspackPlugin(factory) {
  1659. return (userOptions) => {
  1660. return {
  1661. apply(compiler) {
  1662. const VIRTUAL_MODULE_PREFIX = (0, import_path9.resolve)(compiler.options.context ?? process.cwd(), "node_modules/.virtual");
  1663. const injected = compiler.$unpluginContext || {};
  1664. compiler.$unpluginContext = injected;
  1665. const meta = {
  1666. framework: "rspack",
  1667. rspack: {
  1668. compiler
  1669. }
  1670. };
  1671. const rawPlugins = toArray(factory(userOptions, meta));
  1672. for (const rawPlugin of rawPlugins) {
  1673. const plugin = Object.assign(
  1674. rawPlugin,
  1675. {
  1676. __unpluginMeta: meta,
  1677. __virtualModulePrefix: VIRTUAL_MODULE_PREFIX
  1678. }
  1679. );
  1680. injected[plugin.name] = plugin;
  1681. compiler.hooks.thisCompilation.tap(plugin.name, (compilation) => {
  1682. if (typeof compilation.hooks.childCompiler === "undefined")
  1683. throw new Error("`compilation.hooks.childCompiler` only support by @rspack/core>=0.4.1");
  1684. compilation.hooks.childCompiler.tap(plugin.name, (childCompiler) => {
  1685. childCompiler.$unpluginContext = injected;
  1686. });
  1687. });
  1688. const externalModules = /* @__PURE__ */ new Set();
  1689. if (plugin.resolveId) {
  1690. const vfs = new FakeVirtualModulesPlugin(plugin);
  1691. vfs.apply(compiler);
  1692. plugin.__vfsModules = /* @__PURE__ */ new Set();
  1693. compiler.hooks.compilation.tap(plugin.name, (compilation, { normalModuleFactory }) => {
  1694. normalModuleFactory.hooks.resolve.tapPromise(plugin.name, async (resolveData) => {
  1695. const id = normalizeAbsolutePath(resolveData.request);
  1696. const requestContext = resolveData.contextInfo;
  1697. let importer = requestContext.issuer !== "" ? requestContext.issuer : void 0;
  1698. const isEntry = requestContext.issuer === "";
  1699. if (importer == null ? void 0 : importer.startsWith(plugin.__virtualModulePrefix))
  1700. importer = decodeURIComponent(importer.slice(plugin.__virtualModulePrefix.length));
  1701. const context = createBuildContext2(compiler, compilation);
  1702. let error;
  1703. const pluginContext = {
  1704. error(msg) {
  1705. if (error == null)
  1706. error = normalizeMessage2(msg);
  1707. else
  1708. console.error(`unplugin/rspack: multiple errors returned from resolveId hook: ${msg}`);
  1709. },
  1710. warn(msg) {
  1711. console.warn(`unplugin/rspack: warning from resolveId hook: ${msg}`);
  1712. }
  1713. };
  1714. const resolveIdResult = await plugin.resolveId.call({ ...context, ...pluginContext }, id, importer, { isEntry });
  1715. if (error != null)
  1716. throw error;
  1717. if (resolveIdResult == null)
  1718. return;
  1719. let resolved = typeof resolveIdResult === "string" ? resolveIdResult : resolveIdResult.id;
  1720. const isExternal = typeof resolveIdResult === "string" ? false : resolveIdResult.external === true;
  1721. if (isExternal)
  1722. externalModules.add(resolved);
  1723. if (!import_fs4.default.existsSync(resolved)) {
  1724. if (!plugin.__vfsModules.has(resolved)) {
  1725. plugin.__vfsModules.add(resolved);
  1726. await vfs.writeModule(resolved);
  1727. }
  1728. resolved = encodeVirtualModuleId(resolved, plugin);
  1729. }
  1730. resolveData.request = resolved;
  1731. });
  1732. });
  1733. }
  1734. if (plugin.load) {
  1735. compiler.options.module.rules.unshift({
  1736. enforce: plugin.enforce,
  1737. include(id) {
  1738. if (isVirtualModuleId(id, plugin))
  1739. id = decodeVirtualModuleId(id, plugin);
  1740. if (plugin.loadInclude && !plugin.loadInclude(id))
  1741. return false;
  1742. return !externalModules.has(id);
  1743. },
  1744. use: [{
  1745. loader: LOAD_LOADER,
  1746. options: {
  1747. unpluginName: plugin.name
  1748. }
  1749. }],
  1750. type: "javascript/auto"
  1751. });
  1752. }
  1753. if (plugin.transform) {
  1754. compiler.options.module.rules.unshift({
  1755. enforce: plugin.enforce,
  1756. use(data) {
  1757. return transformUse(data, plugin, TRANSFORM_LOADER);
  1758. }
  1759. });
  1760. }
  1761. if (plugin.rspack)
  1762. plugin.rspack(compiler);
  1763. if (plugin.watchChange || plugin.buildStart) {
  1764. compiler.hooks.make.tapPromise(plugin.name, async (compilation) => {
  1765. const context = createBuildContext2(compiler, compilation);
  1766. if (plugin.watchChange && (compiler.modifiedFiles || compiler.removedFiles)) {
  1767. const promises = [];
  1768. if (compiler.modifiedFiles) {
  1769. compiler.modifiedFiles.forEach(
  1770. (file) => promises.push(Promise.resolve(plugin.watchChange.call(context, file, { event: "update" })))
  1771. );
  1772. }
  1773. if (compiler.removedFiles) {
  1774. compiler.removedFiles.forEach(
  1775. (file) => promises.push(Promise.resolve(plugin.watchChange.call(context, file, { event: "delete" })))
  1776. );
  1777. }
  1778. await Promise.all(promises);
  1779. }
  1780. if (plugin.buildStart)
  1781. return await plugin.buildStart.call(context);
  1782. });
  1783. }
  1784. if (plugin.buildEnd) {
  1785. compiler.hooks.emit.tapPromise(plugin.name, async (compilation) => {
  1786. await plugin.buildEnd.call(createBuildContext2(compiler, compilation));
  1787. });
  1788. }
  1789. if (plugin.writeBundle) {
  1790. compiler.hooks.afterEmit.tapPromise(plugin.name, async () => {
  1791. await plugin.writeBundle();
  1792. });
  1793. }
  1794. }
  1795. }
  1796. };
  1797. };
  1798. }
  1799. // src/vite/index.ts
  1800. function getVitePlugin(factory) {
  1801. return (userOptions) => {
  1802. const meta = {
  1803. framework: "vite"
  1804. };
  1805. const rawPlugins = toArray(factory(userOptions, meta));
  1806. const plugins = rawPlugins.map((rawPlugin) => {
  1807. const plugin = toRollupPlugin(rawPlugin, false);
  1808. if (rawPlugin.vite)
  1809. Object.assign(plugin, rawPlugin.vite);
  1810. return plugin;
  1811. });
  1812. return plugins.length === 1 ? plugins[0] : plugins;
  1813. };
  1814. }
  1815. // src/webpack/index.ts
  1816. var import_fs5 = __toESM(require("fs"));
  1817. var import_path11 = require("path");
  1818. var import_process2 = __toESM(require("process"));
  1819. var import_webpack_virtual_modules = __toESM(require("webpack-virtual-modules"));
  1820. // src/webpack/context.ts
  1821. var import_buffer4 = require("buffer");
  1822. var import_module = require("module");
  1823. var import_path10 = require("path");
  1824. var import_process = __toESM(require("process"));
  1825. var import_acorn4 = require("acorn");
  1826. function contextOptionsFromCompilation(compilation) {
  1827. return {
  1828. addWatchFile(file) {
  1829. (compilation.fileDependencies ?? compilation.compilationDependencies).add(file);
  1830. },
  1831. getWatchFiles() {
  1832. return Array.from(compilation.fileDependencies ?? compilation.compilationDependencies);
  1833. }
  1834. };
  1835. }
  1836. function getSource(fileSource) {
  1837. const webpackRequire = (0, import_module.createRequire)(require.resolve("webpack"));
  1838. const RawSource = webpackRequire("webpack-sources").RawSource;
  1839. return new RawSource(
  1840. typeof fileSource === "string" ? fileSource : import_buffer4.Buffer.from(fileSource.buffer).toString("utf-8")
  1841. );
  1842. }
  1843. function createBuildContext3(options, compiler, compilation, loaderContext) {
  1844. return {
  1845. parse(code, opts = {}) {
  1846. return import_acorn4.Parser.parse(code, {
  1847. sourceType: "module",
  1848. ecmaVersion: "latest",
  1849. locations: true,
  1850. ...opts
  1851. });
  1852. },
  1853. addWatchFile(id) {
  1854. options.addWatchFile((0, import_path10.resolve)(import_process.default.cwd(), id));
  1855. },
  1856. emitFile(emittedFile) {
  1857. const outFileName = emittedFile.fileName || emittedFile.name;
  1858. if (emittedFile.source && outFileName) {
  1859. if (!compilation)
  1860. throw new Error("unplugin/webpack: emitFile outside supported hooks (buildStart, buildEnd, load, transform, watchChange)");
  1861. compilation.emitAsset(
  1862. outFileName,
  1863. getSource(emittedFile.source)
  1864. );
  1865. }
  1866. },
  1867. getWatchFiles() {
  1868. return options.getWatchFiles();
  1869. },
  1870. getNativeBuildContext() {
  1871. return { framework: "webpack", compiler, compilation, loaderContext };
  1872. }
  1873. };
  1874. }
  1875. function normalizeMessage3(error) {
  1876. const err = new Error(typeof error === "string" ? error : error.message);
  1877. if (typeof error === "object") {
  1878. err.stack = error.stack;
  1879. err.cause = error.meta;
  1880. }
  1881. return err;
  1882. }
  1883. // src/webpack/index.ts
  1884. var TRANSFORM_LOADER2 = (0, import_path11.resolve)(
  1885. __dirname,
  1886. false ? "../../dist/webpack/loaders/transform" : "webpack/loaders/transform"
  1887. );
  1888. var LOAD_LOADER2 = (0, import_path11.resolve)(
  1889. __dirname,
  1890. false ? "../../dist/webpack/loaders/load" : "webpack/loaders/load"
  1891. );
  1892. function getWebpackPlugin(factory) {
  1893. return (userOptions) => {
  1894. return {
  1895. apply(compiler) {
  1896. const VIRTUAL_MODULE_PREFIX = (0, import_path11.resolve)(compiler.options.context ?? import_process2.default.cwd(), "_virtual_");
  1897. const injected = compiler.$unpluginContext || {};
  1898. compiler.$unpluginContext = injected;
  1899. const meta = {
  1900. framework: "webpack",
  1901. webpack: {
  1902. compiler
  1903. }
  1904. };
  1905. const rawPlugins = toArray(factory(userOptions, meta));
  1906. for (const rawPlugin of rawPlugins) {
  1907. const plugin = Object.assign(
  1908. rawPlugin,
  1909. {
  1910. __unpluginMeta: meta,
  1911. __virtualModulePrefix: VIRTUAL_MODULE_PREFIX
  1912. }
  1913. );
  1914. injected[plugin.name] = plugin;
  1915. compiler.hooks.thisCompilation.tap(plugin.name, (compilation) => {
  1916. compilation.hooks.childCompiler.tap(plugin.name, (childCompiler) => {
  1917. childCompiler.$unpluginContext = injected;
  1918. });
  1919. });
  1920. const externalModules = /* @__PURE__ */ new Set();
  1921. if (plugin.resolveId) {
  1922. let vfs = compiler.options.plugins.find((i) => i instanceof import_webpack_virtual_modules.default);
  1923. if (!vfs) {
  1924. vfs = new import_webpack_virtual_modules.default();
  1925. compiler.options.plugins.push(vfs);
  1926. }
  1927. plugin.__vfsModules = /* @__PURE__ */ new Set();
  1928. plugin.__vfs = vfs;
  1929. const resolverPlugin = {
  1930. apply(resolver) {
  1931. const target = resolver.ensureHook("resolve");
  1932. resolver.getHook("resolve").tapAsync(plugin.name, async (request, resolveContext, callback) => {
  1933. if (!request.request)
  1934. return callback();
  1935. if (normalizeAbsolutePath(request.request).startsWith(plugin.__virtualModulePrefix))
  1936. return callback();
  1937. const id = normalizeAbsolutePath(request.request);
  1938. const requestContext = request.context;
  1939. let importer = requestContext.issuer !== "" ? requestContext.issuer : void 0;
  1940. const isEntry = requestContext.issuer === "";
  1941. if (importer == null ? void 0 : importer.startsWith(plugin.__virtualModulePrefix))
  1942. importer = decodeURIComponent(importer.slice(plugin.__virtualModulePrefix.length));
  1943. const fileDependencies = /* @__PURE__ */ new Set();
  1944. const context = createBuildContext3({
  1945. addWatchFile(file) {
  1946. var _a;
  1947. fileDependencies.add(file);
  1948. (_a = resolveContext.fileDependencies) == null ? void 0 : _a.add(file);
  1949. },
  1950. getWatchFiles() {
  1951. return Array.from(fileDependencies);
  1952. }
  1953. }, compiler);
  1954. let error;
  1955. const pluginContext = {
  1956. error(msg) {
  1957. if (error == null)
  1958. error = normalizeMessage3(msg);
  1959. else
  1960. console.error(`unplugin/webpack: multiple errors returned from resolveId hook: ${msg}`);
  1961. },
  1962. warn(msg) {
  1963. console.warn(`unplugin/webpack: warning from resolveId hook: ${msg}`);
  1964. }
  1965. };
  1966. const resolveIdResult = await plugin.resolveId.call({ ...context, ...pluginContext }, id, importer, { isEntry });
  1967. if (error != null)
  1968. return callback(error);
  1969. if (resolveIdResult == null)
  1970. return callback();
  1971. let resolved = typeof resolveIdResult === "string" ? resolveIdResult : resolveIdResult.id;
  1972. const isExternal = typeof resolveIdResult === "string" ? false : resolveIdResult.external === true;
  1973. if (isExternal)
  1974. externalModules.add(resolved);
  1975. if (!import_fs5.default.existsSync(resolved)) {
  1976. resolved = normalizeAbsolutePath(
  1977. plugin.__virtualModulePrefix + encodeURIComponent(resolved)
  1978. // URI encode id so webpack doesn't think it's part of the path
  1979. );
  1980. if (!plugin.__vfsModules.has(resolved)) {
  1981. plugin.__vfs.writeModule(resolved, "");
  1982. plugin.__vfsModules.add(resolved);
  1983. }
  1984. }
  1985. const newRequest = {
  1986. ...request,
  1987. request: resolved
  1988. };
  1989. resolver.doResolve(target, newRequest, null, resolveContext, callback);
  1990. });
  1991. }
  1992. };
  1993. compiler.options.resolve.plugins = compiler.options.resolve.plugins || [];
  1994. compiler.options.resolve.plugins.push(resolverPlugin);
  1995. }
  1996. if (plugin.load) {
  1997. compiler.options.module.rules.unshift({
  1998. include(id) {
  1999. return shouldLoad(id, plugin, externalModules);
  2000. },
  2001. enforce: plugin.enforce,
  2002. use: [{
  2003. loader: LOAD_LOADER2,
  2004. options: {
  2005. unpluginName: plugin.name
  2006. }
  2007. }],
  2008. type: "javascript/auto"
  2009. });
  2010. }
  2011. if (plugin.transform) {
  2012. compiler.options.module.rules.unshift({
  2013. enforce: plugin.enforce,
  2014. use(data) {
  2015. return transformUse(data, plugin, TRANSFORM_LOADER2);
  2016. }
  2017. });
  2018. }
  2019. if (plugin.webpack)
  2020. plugin.webpack(compiler);
  2021. if (plugin.watchChange || plugin.buildStart) {
  2022. compiler.hooks.make.tapPromise(plugin.name, async (compilation) => {
  2023. const context = createBuildContext3(contextOptionsFromCompilation(compilation), compiler, compilation);
  2024. if (plugin.watchChange && (compiler.modifiedFiles || compiler.removedFiles)) {
  2025. const promises = [];
  2026. if (compiler.modifiedFiles) {
  2027. compiler.modifiedFiles.forEach(
  2028. (file) => promises.push(Promise.resolve(plugin.watchChange.call(context, file, { event: "update" })))
  2029. );
  2030. }
  2031. if (compiler.removedFiles) {
  2032. compiler.removedFiles.forEach(
  2033. (file) => promises.push(Promise.resolve(plugin.watchChange.call(context, file, { event: "delete" })))
  2034. );
  2035. }
  2036. await Promise.all(promises);
  2037. }
  2038. if (plugin.buildStart)
  2039. return await plugin.buildStart.call(context);
  2040. });
  2041. }
  2042. if (plugin.buildEnd) {
  2043. compiler.hooks.emit.tapPromise(plugin.name, async (compilation) => {
  2044. await plugin.buildEnd.call(createBuildContext3(contextOptionsFromCompilation(compilation), compiler, compilation));
  2045. });
  2046. }
  2047. if (plugin.writeBundle) {
  2048. compiler.hooks.afterEmit.tapPromise(plugin.name, async () => {
  2049. await plugin.writeBundle();
  2050. });
  2051. }
  2052. }
  2053. }
  2054. };
  2055. };
  2056. }
  2057. // src/define.ts
  2058. function createUnplugin(factory) {
  2059. return {
  2060. get esbuild() {
  2061. return getEsbuildPlugin(factory);
  2062. },
  2063. get rollup() {
  2064. return getRollupPlugin(factory);
  2065. },
  2066. get vite() {
  2067. return getVitePlugin(factory);
  2068. },
  2069. /** @experimental do not use it in production */
  2070. get rolldown() {
  2071. return getRolldownPlugin(factory);
  2072. },
  2073. get webpack() {
  2074. return getWebpackPlugin(factory);
  2075. },
  2076. get rspack() {
  2077. return getRspackPlugin(factory);
  2078. },
  2079. get farm() {
  2080. return getFarmPlugin(factory);
  2081. },
  2082. get raw() {
  2083. return factory;
  2084. }
  2085. };
  2086. }
  2087. function createEsbuildPlugin(factory) {
  2088. return getEsbuildPlugin(factory);
  2089. }
  2090. function createRollupPlugin(factory) {
  2091. return getRollupPlugin(factory);
  2092. }
  2093. function createVitePlugin(factory) {
  2094. return getVitePlugin(factory);
  2095. }
  2096. function createRolldownPlugin(factory) {
  2097. return getRolldownPlugin(factory);
  2098. }
  2099. function createWebpackPlugin(factory) {
  2100. return getWebpackPlugin(factory);
  2101. }
  2102. function createRspackPlugin(factory) {
  2103. return getRspackPlugin(factory);
  2104. }
  2105. function createFarmPlugin(factory) {
  2106. return getFarmPlugin(factory);
  2107. }
  2108. // Annotate the CommonJS export names for ESM import in node:
  2109. 0 && (module.exports = {
  2110. createEsbuildPlugin,
  2111. createFarmPlugin,
  2112. createRolldownPlugin,
  2113. createRollupPlugin,
  2114. createRspackPlugin,
  2115. createUnplugin,
  2116. createVitePlugin,
  2117. createWebpackPlugin
  2118. });