index.js 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475
  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. isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  22. mod
  23. ));
  24. var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
  25. // src/index.ts
  26. var src_exports = {};
  27. __export(src_exports, {
  28. createUnplugin: () => createUnplugin
  29. });
  30. module.exports = __toCommonJS(src_exports);
  31. // src/esbuild/index.ts
  32. var import_fs = __toESM(require("fs"));
  33. var import_path3 = __toESM(require("path"));
  34. var import_chokidar = __toESM(require("chokidar"));
  35. var import_acorn = require("acorn");
  36. // src/esbuild/utils.ts
  37. var import_path2 = require("path");
  38. // node_modules/.pnpm/@jridgewell+sourcemap-codec@1.4.11/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs
  39. var comma = ",".charCodeAt(0);
  40. var semicolon = ";".charCodeAt(0);
  41. var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  42. var intToChar = new Uint8Array(64);
  43. var charToInteger = new Uint8Array(128);
  44. for (let i2 = 0; i2 < chars.length; i2++) {
  45. const c = chars.charCodeAt(i2);
  46. charToInteger[c] = i2;
  47. intToChar[i2] = c;
  48. }
  49. var td = typeof TextDecoder !== "undefined" ? new TextDecoder() : typeof Buffer !== "undefined" ? {
  50. decode(buf) {
  51. const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength);
  52. return out.toString();
  53. }
  54. } : {
  55. decode(buf) {
  56. let out = "";
  57. for (let i2 = 0; i2 < buf.length; i2++) {
  58. out += String.fromCharCode(buf[i2]);
  59. }
  60. return out;
  61. }
  62. };
  63. function decode(mappings) {
  64. const state = new Int32Array(5);
  65. const decoded = [];
  66. let line = [];
  67. let sorted = true;
  68. let lastCol = 0;
  69. for (let i2 = 0; i2 < mappings.length; ) {
  70. const c = mappings.charCodeAt(i2);
  71. if (c === comma) {
  72. i2++;
  73. } else if (c === semicolon) {
  74. state[0] = lastCol = 0;
  75. if (!sorted)
  76. sort(line);
  77. sorted = true;
  78. decoded.push(line);
  79. line = [];
  80. i2++;
  81. } else {
  82. i2 = decodeInteger(mappings, i2, state, 0);
  83. const col = state[0];
  84. if (col < lastCol)
  85. sorted = false;
  86. lastCol = col;
  87. if (!hasMoreSegments(mappings, i2)) {
  88. line.push([col]);
  89. continue;
  90. }
  91. i2 = decodeInteger(mappings, i2, state, 1);
  92. i2 = decodeInteger(mappings, i2, state, 2);
  93. i2 = decodeInteger(mappings, i2, state, 3);
  94. if (!hasMoreSegments(mappings, i2)) {
  95. line.push([col, state[1], state[2], state[3]]);
  96. continue;
  97. }
  98. i2 = decodeInteger(mappings, i2, state, 4);
  99. line.push([col, state[1], state[2], state[3], state[4]]);
  100. }
  101. }
  102. if (!sorted)
  103. sort(line);
  104. decoded.push(line);
  105. return decoded;
  106. }
  107. function decodeInteger(mappings, pos, state, j) {
  108. let value = 0;
  109. let shift = 0;
  110. let integer = 0;
  111. do {
  112. const c = mappings.charCodeAt(pos++);
  113. integer = charToInteger[c];
  114. value |= (integer & 31) << shift;
  115. shift += 5;
  116. } while (integer & 32);
  117. const shouldNegate = value & 1;
  118. value >>>= 1;
  119. if (shouldNegate) {
  120. value = -2147483648 | -value;
  121. }
  122. state[j] += value;
  123. return pos;
  124. }
  125. function hasMoreSegments(mappings, i2) {
  126. if (i2 >= mappings.length)
  127. return false;
  128. const c = mappings.charCodeAt(i2);
  129. if (c === comma || c === semicolon)
  130. return false;
  131. return true;
  132. }
  133. function sort(line) {
  134. line.sort(sortComparator);
  135. }
  136. function sortComparator(a, b) {
  137. return a[0] - b[0];
  138. }
  139. function encode(decoded) {
  140. const state = new Int32Array(5);
  141. let buf = new Uint8Array(1024);
  142. let pos = 0;
  143. for (let i2 = 0; i2 < decoded.length; i2++) {
  144. const line = decoded[i2];
  145. if (i2 > 0) {
  146. buf = reserve(buf, pos, 1);
  147. buf[pos++] = semicolon;
  148. }
  149. if (line.length === 0)
  150. continue;
  151. state[0] = 0;
  152. for (let j = 0; j < line.length; j++) {
  153. const segment = line[j];
  154. buf = reserve(buf, pos, 36);
  155. if (j > 0)
  156. buf[pos++] = comma;
  157. pos = encodeInteger(buf, pos, state, segment, 0);
  158. if (segment.length === 1)
  159. continue;
  160. pos = encodeInteger(buf, pos, state, segment, 1);
  161. pos = encodeInteger(buf, pos, state, segment, 2);
  162. pos = encodeInteger(buf, pos, state, segment, 3);
  163. if (segment.length === 4)
  164. continue;
  165. pos = encodeInteger(buf, pos, state, segment, 4);
  166. }
  167. }
  168. return td.decode(buf.subarray(0, pos));
  169. }
  170. function reserve(buf, pos, count) {
  171. if (buf.length > pos + count)
  172. return buf;
  173. const swap = new Uint8Array(buf.length * 2);
  174. swap.set(buf);
  175. return swap;
  176. }
  177. function encodeInteger(buf, pos, state, segment, j) {
  178. const next = segment[j];
  179. let num = next - state[j];
  180. state[j] = next;
  181. num = num < 0 ? -num << 1 | 1 : num << 1;
  182. do {
  183. let clamped = num & 31;
  184. num >>>= 5;
  185. if (num > 0)
  186. clamped |= 32;
  187. buf[pos++] = intToChar[clamped];
  188. } while (num > 0);
  189. return pos;
  190. }
  191. // node_modules/.pnpm/@jridgewell+resolve-uri@3.0.5/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.mjs
  192. var schemeRegex = /^[\w+.-]+:\/\//;
  193. var urlRegex = /^([\w+.-]+:)\/\/([^@/#?]*@)?([^:/#?]*)(:\d+)?(\/[^#?]*)?/;
  194. function isAbsoluteUrl(input) {
  195. return schemeRegex.test(input);
  196. }
  197. function isSchemeRelativeUrl(input) {
  198. return input.startsWith("//");
  199. }
  200. function isAbsolutePath(input) {
  201. return input.startsWith("/");
  202. }
  203. function parseAbsoluteUrl(input) {
  204. const match = urlRegex.exec(input);
  205. return {
  206. scheme: match[1],
  207. user: match[2] || "",
  208. host: match[3],
  209. port: match[4] || "",
  210. path: match[5] || "/",
  211. relativePath: false
  212. };
  213. }
  214. function parseUrl(input) {
  215. if (isSchemeRelativeUrl(input)) {
  216. const url = parseAbsoluteUrl("http:" + input);
  217. url.scheme = "";
  218. return url;
  219. }
  220. if (isAbsolutePath(input)) {
  221. const url = parseAbsoluteUrl("http://foo.com" + input);
  222. url.scheme = "";
  223. url.host = "";
  224. return url;
  225. }
  226. if (!isAbsoluteUrl(input)) {
  227. const url = parseAbsoluteUrl("http://foo.com/" + input);
  228. url.scheme = "";
  229. url.host = "";
  230. url.relativePath = true;
  231. return url;
  232. }
  233. return parseAbsoluteUrl(input);
  234. }
  235. function stripPathFilename(path2) {
  236. if (path2.endsWith("/.."))
  237. return path2;
  238. const index = path2.lastIndexOf("/");
  239. return path2.slice(0, index + 1);
  240. }
  241. function mergePaths(url, base) {
  242. if (!url.relativePath)
  243. return;
  244. normalizePath(base);
  245. if (url.path === "/") {
  246. url.path = base.path;
  247. } else {
  248. url.path = stripPathFilename(base.path) + url.path;
  249. }
  250. url.relativePath = base.relativePath;
  251. }
  252. function normalizePath(url) {
  253. const { relativePath } = url;
  254. const pieces = url.path.split("/");
  255. let pointer = 1;
  256. let positive = 0;
  257. let addTrailingSlash = false;
  258. for (let i2 = 1; i2 < pieces.length; i2++) {
  259. const piece = pieces[i2];
  260. if (!piece) {
  261. addTrailingSlash = true;
  262. continue;
  263. }
  264. addTrailingSlash = false;
  265. if (piece === ".")
  266. continue;
  267. if (piece === "..") {
  268. if (positive) {
  269. addTrailingSlash = true;
  270. positive--;
  271. pointer--;
  272. } else if (relativePath) {
  273. pieces[pointer++] = piece;
  274. }
  275. continue;
  276. }
  277. pieces[pointer++] = piece;
  278. positive++;
  279. }
  280. let path2 = "";
  281. for (let i2 = 1; i2 < pointer; i2++) {
  282. path2 += "/" + pieces[i2];
  283. }
  284. if (!path2 || addTrailingSlash && !path2.endsWith("/..")) {
  285. path2 += "/";
  286. }
  287. url.path = path2;
  288. }
  289. function resolve(input, base) {
  290. if (!input && !base)
  291. return "";
  292. const url = parseUrl(input);
  293. if (base && !url.scheme) {
  294. const baseUrl = parseUrl(base);
  295. url.scheme = baseUrl.scheme;
  296. if (!url.host || baseUrl.scheme === "file:") {
  297. url.user = baseUrl.user;
  298. url.host = baseUrl.host;
  299. url.port = baseUrl.port;
  300. }
  301. mergePaths(url, baseUrl);
  302. }
  303. normalizePath(url);
  304. if (url.relativePath) {
  305. const path2 = url.path.slice(1);
  306. if (!path2)
  307. return ".";
  308. const keepRelative = (base || input).startsWith(".");
  309. return !keepRelative || path2.startsWith(".") ? path2 : "./" + path2;
  310. }
  311. if (!url.scheme && !url.host)
  312. return url.path;
  313. return `${url.scheme}//${url.user}${url.host}${url.port}${url.path}`;
  314. }
  315. // node_modules/.pnpm/@jridgewell+trace-mapping@0.3.9/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.mjs
  316. function resolve2(input, base) {
  317. if (base && !base.endsWith("/"))
  318. base += "/";
  319. return resolve(input, base);
  320. }
  321. function stripFilename(path2) {
  322. if (!path2)
  323. return "";
  324. const index = path2.lastIndexOf("/");
  325. return path2.slice(0, index + 1);
  326. }
  327. var COLUMN = 0;
  328. var SOURCES_INDEX = 1;
  329. var SOURCE_LINE = 2;
  330. var SOURCE_COLUMN = 3;
  331. var NAMES_INDEX = 4;
  332. var REV_GENERATED_LINE = 1;
  333. var REV_GENERATED_COLUMN = 2;
  334. function maybeSort(mappings, owned) {
  335. const unsortedIndex = nextUnsortedSegmentLine(mappings, 0);
  336. if (unsortedIndex === mappings.length)
  337. return mappings;
  338. if (!owned)
  339. mappings = mappings.slice();
  340. for (let i2 = unsortedIndex; i2 < mappings.length; i2 = nextUnsortedSegmentLine(mappings, i2 + 1)) {
  341. mappings[i2] = sortSegments(mappings[i2], owned);
  342. }
  343. return mappings;
  344. }
  345. function nextUnsortedSegmentLine(mappings, start) {
  346. for (let i2 = start; i2 < mappings.length; i2++) {
  347. if (!isSorted(mappings[i2]))
  348. return i2;
  349. }
  350. return mappings.length;
  351. }
  352. function isSorted(line) {
  353. for (let j = 1; j < line.length; j++) {
  354. if (line[j][COLUMN] < line[j - 1][COLUMN]) {
  355. return false;
  356. }
  357. }
  358. return true;
  359. }
  360. function sortSegments(line, owned) {
  361. if (!owned)
  362. line = line.slice();
  363. return line.sort(sortComparator2);
  364. }
  365. function sortComparator2(a, b) {
  366. return a[COLUMN] - b[COLUMN];
  367. }
  368. var found = false;
  369. function binarySearch(haystack, needle, low, high) {
  370. while (low <= high) {
  371. const mid = low + (high - low >> 1);
  372. const cmp = haystack[mid][COLUMN] - needle;
  373. if (cmp === 0) {
  374. found = true;
  375. return mid;
  376. }
  377. if (cmp < 0) {
  378. low = mid + 1;
  379. } else {
  380. high = mid - 1;
  381. }
  382. }
  383. found = false;
  384. return low - 1;
  385. }
  386. function upperBound(haystack, needle, index) {
  387. for (let i2 = index + 1; i2 < haystack.length; i2++, index++) {
  388. if (haystack[i2][COLUMN] !== needle)
  389. break;
  390. }
  391. return index;
  392. }
  393. function lowerBound(haystack, needle, index) {
  394. for (let i2 = index - 1; i2 >= 0; i2--, index--) {
  395. if (haystack[i2][COLUMN] !== needle)
  396. break;
  397. }
  398. return index;
  399. }
  400. function memoizedState() {
  401. return {
  402. lastKey: -1,
  403. lastNeedle: -1,
  404. lastIndex: -1
  405. };
  406. }
  407. function memoizedBinarySearch(haystack, needle, state, key) {
  408. const { lastKey, lastNeedle, lastIndex } = state;
  409. let low = 0;
  410. let high = haystack.length - 1;
  411. if (key === lastKey) {
  412. if (needle === lastNeedle) {
  413. found = lastIndex !== -1 && haystack[lastIndex][COLUMN] === needle;
  414. return lastIndex;
  415. }
  416. if (needle >= lastNeedle) {
  417. low = lastIndex === -1 ? 0 : lastIndex;
  418. } else {
  419. high = lastIndex;
  420. }
  421. }
  422. state.lastKey = key;
  423. state.lastNeedle = needle;
  424. return state.lastIndex = binarySearch(haystack, needle, low, high);
  425. }
  426. function buildBySources(decoded, memos) {
  427. const sources2 = memos.map(buildNullArray);
  428. for (let i2 = 0; i2 < decoded.length; i2++) {
  429. const line = decoded[i2];
  430. for (let j = 0; j < line.length; j++) {
  431. const seg = line[j];
  432. if (seg.length === 1)
  433. continue;
  434. const sourceIndex = seg[SOURCES_INDEX];
  435. const sourceLine = seg[SOURCE_LINE];
  436. const sourceColumn = seg[SOURCE_COLUMN];
  437. const originalSource = sources2[sourceIndex];
  438. const originalLine = originalSource[sourceLine] || (originalSource[sourceLine] = []);
  439. const memo = memos[sourceIndex];
  440. const index = upperBound(originalLine, sourceColumn, memoizedBinarySearch(originalLine, sourceColumn, memo, sourceLine));
  441. insert(originalLine, memo.lastIndex = index + 1, [sourceColumn, i2, seg[COLUMN]]);
  442. }
  443. }
  444. return sources2;
  445. }
  446. function insert(array, index, value) {
  447. for (let i2 = array.length; i2 > index; i2--) {
  448. array[i2] = array[i2 - 1];
  449. }
  450. array[index] = value;
  451. }
  452. function buildNullArray() {
  453. return { __proto__: null };
  454. }
  455. var INVALID_ORIGINAL_MAPPING = Object.freeze({
  456. source: null,
  457. line: null,
  458. column: null,
  459. name: null
  460. });
  461. var INVALID_GENERATED_MAPPING = Object.freeze({
  462. line: null,
  463. column: null
  464. });
  465. var LINE_GTR_ZERO = "`line` must be greater than 0 (lines start at line 1)";
  466. var COL_GTR_EQ_ZERO = "`column` must be greater than or equal to 0 (columns start at column 0)";
  467. var LEAST_UPPER_BOUND = -1;
  468. var GREATEST_LOWER_BOUND = 1;
  469. var encodedMappings;
  470. var decodedMappings;
  471. var traceSegment;
  472. var originalPositionFor;
  473. var generatedPositionFor;
  474. var eachMapping;
  475. var presortedDecodedMap;
  476. var decodedMap;
  477. var encodedMap;
  478. var TraceMap = class {
  479. constructor(map, mapUrl) {
  480. this._decodedMemo = memoizedState();
  481. this._bySources = void 0;
  482. this._bySourceMemos = void 0;
  483. const isString = typeof map === "string";
  484. if (!isString && map.constructor === TraceMap)
  485. return map;
  486. const parsed = isString ? JSON.parse(map) : map;
  487. const { version, file, names, sourceRoot, sources: sources2, sourcesContent } = parsed;
  488. this.version = version;
  489. this.file = file;
  490. this.names = names;
  491. this.sourceRoot = sourceRoot;
  492. this.sources = sources2;
  493. this.sourcesContent = sourcesContent;
  494. if (sourceRoot || mapUrl) {
  495. const from = resolve2(sourceRoot || "", stripFilename(mapUrl));
  496. this.resolvedSources = sources2.map((s) => resolve2(s || "", from));
  497. } else {
  498. this.resolvedSources = sources2.map((s) => s || "");
  499. }
  500. const { mappings } = parsed;
  501. if (typeof mappings === "string") {
  502. this._encoded = mappings;
  503. this._decoded = void 0;
  504. } else {
  505. this._encoded = void 0;
  506. this._decoded = maybeSort(mappings, isString);
  507. }
  508. }
  509. };
  510. (() => {
  511. encodedMappings = (map) => {
  512. var _a;
  513. return (_a = map._encoded) !== null && _a !== void 0 ? _a : map._encoded = encode(map._decoded);
  514. };
  515. decodedMappings = (map) => {
  516. return map._decoded || (map._decoded = decode(map._encoded));
  517. };
  518. traceSegment = (map, line, column) => {
  519. const decoded = decodedMappings(map);
  520. if (line >= decoded.length)
  521. return null;
  522. return traceSegmentInternal(decoded[line], map._decodedMemo, line, column, GREATEST_LOWER_BOUND);
  523. };
  524. originalPositionFor = (map, { line, column, bias }) => {
  525. line--;
  526. if (line < 0)
  527. throw new Error(LINE_GTR_ZERO);
  528. if (column < 0)
  529. throw new Error(COL_GTR_EQ_ZERO);
  530. const decoded = decodedMappings(map);
  531. if (line >= decoded.length)
  532. return INVALID_ORIGINAL_MAPPING;
  533. const segment = traceSegmentInternal(decoded[line], map._decodedMemo, line, column, bias || GREATEST_LOWER_BOUND);
  534. if (segment == null)
  535. return INVALID_ORIGINAL_MAPPING;
  536. if (segment.length == 1)
  537. return INVALID_ORIGINAL_MAPPING;
  538. const { names, resolvedSources } = map;
  539. return {
  540. source: resolvedSources[segment[SOURCES_INDEX]],
  541. line: segment[SOURCE_LINE] + 1,
  542. column: segment[SOURCE_COLUMN],
  543. name: segment.length === 5 ? names[segment[NAMES_INDEX]] : null
  544. };
  545. };
  546. generatedPositionFor = (map, { source, line, column, bias }) => {
  547. line--;
  548. if (line < 0)
  549. throw new Error(LINE_GTR_ZERO);
  550. if (column < 0)
  551. throw new Error(COL_GTR_EQ_ZERO);
  552. const { sources: sources2, resolvedSources } = map;
  553. let sourceIndex = sources2.indexOf(source);
  554. if (sourceIndex === -1)
  555. sourceIndex = resolvedSources.indexOf(source);
  556. if (sourceIndex === -1)
  557. return INVALID_GENERATED_MAPPING;
  558. const generated = map._bySources || (map._bySources = buildBySources(decodedMappings(map), map._bySourceMemos = sources2.map(memoizedState)));
  559. const memos = map._bySourceMemos;
  560. const segments = generated[sourceIndex][line];
  561. if (segments == null)
  562. return INVALID_GENERATED_MAPPING;
  563. const segment = traceSegmentInternal(segments, memos[sourceIndex], line, column, bias || GREATEST_LOWER_BOUND);
  564. if (segment == null)
  565. return INVALID_GENERATED_MAPPING;
  566. return {
  567. line: segment[REV_GENERATED_LINE] + 1,
  568. column: segment[REV_GENERATED_COLUMN]
  569. };
  570. };
  571. eachMapping = (map, cb) => {
  572. const decoded = decodedMappings(map);
  573. const { names, resolvedSources } = map;
  574. for (let i2 = 0; i2 < decoded.length; i2++) {
  575. const line = decoded[i2];
  576. for (let j = 0; j < line.length; j++) {
  577. const seg = line[j];
  578. const generatedLine = i2 + 1;
  579. const generatedColumn = seg[0];
  580. let source = null;
  581. let originalLine = null;
  582. let originalColumn = null;
  583. let name = null;
  584. if (seg.length !== 1) {
  585. source = resolvedSources[seg[1]];
  586. originalLine = seg[2] + 1;
  587. originalColumn = seg[3];
  588. }
  589. if (seg.length === 5)
  590. name = names[seg[4]];
  591. cb({
  592. generatedLine,
  593. generatedColumn,
  594. source,
  595. originalLine,
  596. originalColumn,
  597. name
  598. });
  599. }
  600. }
  601. };
  602. presortedDecodedMap = (map, mapUrl) => {
  603. const clone = Object.assign({}, map);
  604. clone.mappings = [];
  605. const tracer = new TraceMap(clone, mapUrl);
  606. tracer._decoded = map.mappings;
  607. return tracer;
  608. };
  609. decodedMap = (map) => {
  610. return {
  611. version: 3,
  612. file: map.file,
  613. names: map.names,
  614. sourceRoot: map.sourceRoot,
  615. sources: map.sources,
  616. sourcesContent: map.sourcesContent,
  617. mappings: decodedMappings(map)
  618. };
  619. };
  620. encodedMap = (map) => {
  621. return {
  622. version: 3,
  623. file: map.file,
  624. names: map.names,
  625. sourceRoot: map.sourceRoot,
  626. sources: map.sources,
  627. sourcesContent: map.sourcesContent,
  628. mappings: encodedMappings(map)
  629. };
  630. };
  631. })();
  632. function traceSegmentInternal(segments, memo, line, column, bias) {
  633. let index = memoizedBinarySearch(segments, column, memo, line);
  634. if (found) {
  635. index = (bias === LEAST_UPPER_BOUND ? upperBound : lowerBound)(segments, column, index);
  636. } else if (bias === LEAST_UPPER_BOUND)
  637. index++;
  638. if (index === -1 || index === segments.length)
  639. return null;
  640. return segments[index];
  641. }
  642. // node_modules/.pnpm/@jridgewell+set-array@1.1.0/node_modules/@jridgewell/set-array/dist/set-array.mjs
  643. var get;
  644. var put;
  645. var pop;
  646. var SetArray = class {
  647. constructor() {
  648. this._indexes = { __proto__: null };
  649. this.array = [];
  650. }
  651. };
  652. (() => {
  653. get = (strarr, key) => strarr._indexes[key];
  654. put = (strarr, key) => {
  655. const index = get(strarr, key);
  656. if (index !== void 0)
  657. return index;
  658. const { array, _indexes: indexes } = strarr;
  659. return indexes[key] = array.push(key) - 1;
  660. };
  661. pop = (strarr) => {
  662. const { array, _indexes: indexes } = strarr;
  663. if (array.length === 0)
  664. return;
  665. const last = array.pop();
  666. indexes[last] = void 0;
  667. };
  668. })();
  669. // node_modules/.pnpm/@jridgewell+gen-mapping@0.1.1/node_modules/@jridgewell/gen-mapping/dist/gen-mapping.mjs
  670. var addSegment;
  671. var addMapping;
  672. var setSourceContent;
  673. var decodedMap2;
  674. var encodedMap2;
  675. var allMappings;
  676. var GenMapping = class {
  677. constructor({ file, sourceRoot } = {}) {
  678. this._names = new SetArray();
  679. this._sources = new SetArray();
  680. this._sourcesContent = [];
  681. this._mappings = [];
  682. this.file = file;
  683. this.sourceRoot = sourceRoot;
  684. }
  685. };
  686. (() => {
  687. addSegment = (map, genLine, genColumn, source, sourceLine, sourceColumn, name) => {
  688. const { _mappings: mappings, _sources: sources2, _sourcesContent: sourcesContent, _names: names } = map;
  689. const line = getLine(mappings, genLine);
  690. if (source == null) {
  691. const seg2 = [genColumn];
  692. const index2 = getColumnIndex(line, genColumn, seg2);
  693. return insert2(line, index2, seg2);
  694. }
  695. const sourcesIndex = put(sources2, source);
  696. const seg = name ? [genColumn, sourcesIndex, sourceLine, sourceColumn, put(names, name)] : [genColumn, sourcesIndex, sourceLine, sourceColumn];
  697. const index = getColumnIndex(line, genColumn, seg);
  698. if (sourcesIndex === sourcesContent.length)
  699. sourcesContent[sourcesIndex] = null;
  700. insert2(line, index, seg);
  701. };
  702. addMapping = (map, mapping) => {
  703. const { generated, source, original, name } = mapping;
  704. return addSegment(map, generated.line - 1, generated.column, source, original == null ? void 0 : original.line - 1, original === null || original === void 0 ? void 0 : original.column, name);
  705. };
  706. setSourceContent = (map, source, content) => {
  707. const { _sources: sources2, _sourcesContent: sourcesContent } = map;
  708. sourcesContent[put(sources2, source)] = content;
  709. };
  710. decodedMap2 = (map) => {
  711. const { file, sourceRoot, _mappings: mappings, _sources: sources2, _sourcesContent: sourcesContent, _names: names } = map;
  712. return {
  713. version: 3,
  714. file,
  715. names: names.array,
  716. sourceRoot: sourceRoot || void 0,
  717. sources: sources2.array,
  718. sourcesContent,
  719. mappings
  720. };
  721. };
  722. encodedMap2 = (map) => {
  723. const decoded = decodedMap2(map);
  724. return Object.assign(Object.assign({}, decoded), { mappings: encode(decoded.mappings) });
  725. };
  726. allMappings = (map) => {
  727. const out = [];
  728. const { _mappings: mappings, _sources: sources2, _names: names } = map;
  729. for (let i2 = 0; i2 < mappings.length; i2++) {
  730. const line = mappings[i2];
  731. for (let j = 0; j < line.length; j++) {
  732. const seg = line[j];
  733. const generated = { line: i2 + 1, column: seg[0] };
  734. let source = void 0;
  735. let original = void 0;
  736. let name = void 0;
  737. if (seg.length !== 1) {
  738. source = sources2.array[seg[1]];
  739. original = { line: seg[2] + 1, column: seg[3] };
  740. if (seg.length === 5)
  741. name = names.array[seg[4]];
  742. }
  743. out.push({ generated, source, original, name });
  744. }
  745. }
  746. return out;
  747. };
  748. })();
  749. function getLine(mappings, index) {
  750. for (let i2 = mappings.length; i2 <= index; i2++) {
  751. mappings[i2] = [];
  752. }
  753. return mappings[index];
  754. }
  755. function getColumnIndex(line, column, seg) {
  756. let index = line.length;
  757. for (let i2 = index - 1; i2 >= 0; i2--, index--) {
  758. const current = line[i2];
  759. const col = current[0];
  760. if (col > column)
  761. continue;
  762. if (col < column)
  763. break;
  764. const cmp = compare(current, seg);
  765. if (cmp === 0)
  766. return index;
  767. if (cmp < 0)
  768. break;
  769. }
  770. return index;
  771. }
  772. function compare(a, b) {
  773. let cmp = compareNum(a.length, b.length);
  774. if (cmp !== 0)
  775. return cmp;
  776. if (a.length === 1)
  777. return 0;
  778. cmp = compareNum(a[1], b[1]);
  779. if (cmp !== 0)
  780. return cmp;
  781. cmp = compareNum(a[2], b[2]);
  782. if (cmp !== 0)
  783. return cmp;
  784. cmp = compareNum(a[3], b[3]);
  785. if (cmp !== 0)
  786. return cmp;
  787. if (a.length === 4)
  788. return 0;
  789. return compareNum(a[4], b[4]);
  790. }
  791. function compareNum(a, b) {
  792. return a - b;
  793. }
  794. function insert2(array, index, value) {
  795. if (index === -1)
  796. return;
  797. for (let i2 = array.length; i2 > index; i2--) {
  798. array[i2] = array[i2 - 1];
  799. }
  800. array[index] = value;
  801. }
  802. // node_modules/.pnpm/@ampproject+remapping@2.2.0/node_modules/@ampproject/remapping/dist/remapping.mjs
  803. var SOURCELESS_MAPPING = {
  804. source: null,
  805. column: null,
  806. line: null,
  807. name: null,
  808. content: null
  809. };
  810. var EMPTY_SOURCES = [];
  811. function Source(map, sources2, source, content) {
  812. return {
  813. map,
  814. sources: sources2,
  815. source,
  816. content
  817. };
  818. }
  819. function MapSource(map, sources2) {
  820. return Source(map, sources2, "", null);
  821. }
  822. function OriginalSource(source, content) {
  823. return Source(null, EMPTY_SOURCES, source, content);
  824. }
  825. function traceMappings(tree) {
  826. const gen = new GenMapping({ file: tree.map.file });
  827. const { sources: rootSources, map } = tree;
  828. const rootNames = map.names;
  829. const rootMappings = decodedMappings(map);
  830. for (let i2 = 0; i2 < rootMappings.length; i2++) {
  831. const segments = rootMappings[i2];
  832. let lastSource = null;
  833. let lastSourceLine = null;
  834. let lastSourceColumn = null;
  835. for (let j = 0; j < segments.length; j++) {
  836. const segment = segments[j];
  837. const genCol = segment[0];
  838. let traced = SOURCELESS_MAPPING;
  839. if (segment.length !== 1) {
  840. const source2 = rootSources[segment[1]];
  841. traced = originalPositionFor2(source2, segment[2], segment[3], segment.length === 5 ? rootNames[segment[4]] : "");
  842. if (traced == null)
  843. continue;
  844. }
  845. const { column, line, name, content, source } = traced;
  846. if (line === lastSourceLine && column === lastSourceColumn && source === lastSource) {
  847. continue;
  848. }
  849. lastSourceLine = line;
  850. lastSourceColumn = column;
  851. lastSource = source;
  852. addSegment(gen, i2, genCol, source, line, column, name);
  853. if (content != null)
  854. setSourceContent(gen, source, content);
  855. }
  856. }
  857. return gen;
  858. }
  859. function originalPositionFor2(source, line, column, name) {
  860. if (!source.map) {
  861. return { column, line, name, source: source.source, content: source.content };
  862. }
  863. const segment = traceSegment(source.map, line, column);
  864. if (segment == null)
  865. return null;
  866. if (segment.length === 1)
  867. return SOURCELESS_MAPPING;
  868. return originalPositionFor2(source.sources[segment[1]], segment[2], segment[3], segment.length === 5 ? source.map.names[segment[4]] : name);
  869. }
  870. function asArray(value) {
  871. if (Array.isArray(value))
  872. return value;
  873. return [value];
  874. }
  875. function buildSourceMapTree(input, loader) {
  876. const maps = asArray(input).map((m) => new TraceMap(m, ""));
  877. const map = maps.pop();
  878. for (let i2 = 0; i2 < maps.length; i2++) {
  879. if (maps[i2].sources.length > 1) {
  880. throw new Error(`Transformation map ${i2} must have exactly one source file.
  881. Did you specify these with the most recent transformation maps first?`);
  882. }
  883. }
  884. let tree = build(map, loader, "", 0);
  885. for (let i2 = maps.length - 1; i2 >= 0; i2--) {
  886. tree = MapSource(maps[i2], [tree]);
  887. }
  888. return tree;
  889. }
  890. function build(map, loader, importer, importerDepth) {
  891. const { resolvedSources, sourcesContent } = map;
  892. const depth = importerDepth + 1;
  893. const children = resolvedSources.map((sourceFile, i2) => {
  894. const ctx = {
  895. importer,
  896. depth,
  897. source: sourceFile || "",
  898. content: void 0
  899. };
  900. const sourceMap = loader(ctx.source, ctx);
  901. const { source, content } = ctx;
  902. if (sourceMap)
  903. return build(new TraceMap(sourceMap, source), loader, source, depth);
  904. const sourceContent = content !== void 0 ? content : sourcesContent ? sourcesContent[i2] : null;
  905. return OriginalSource(source, sourceContent);
  906. });
  907. return MapSource(map, children);
  908. }
  909. var SourceMap = class {
  910. constructor(map, options) {
  911. const out = options.decodedMappings ? decodedMap2(map) : encodedMap2(map);
  912. this.version = out.version;
  913. this.file = out.file;
  914. this.mappings = out.mappings;
  915. this.names = out.names;
  916. this.sourceRoot = out.sourceRoot;
  917. this.sources = out.sources;
  918. if (!options.excludeContent) {
  919. this.sourcesContent = out.sourcesContent;
  920. }
  921. }
  922. toString() {
  923. return JSON.stringify(this);
  924. }
  925. };
  926. function remapping(input, loader, options) {
  927. const opts = typeof options === "object" ? options : { excludeContent: !!options, decodedMappings: false };
  928. const tree = buildSourceMapTree(input, loader);
  929. return new SourceMap(traceMappings(tree), opts);
  930. }
  931. // src/utils.ts
  932. var import_path = require("path");
  933. function normalizeAbsolutePath(path2) {
  934. if ((0, import_path.isAbsolute)(path2))
  935. return (0, import_path.normalize)(path2);
  936. else
  937. return path2;
  938. }
  939. function toArray(array) {
  940. array = array || [];
  941. if (Array.isArray(array))
  942. return array;
  943. return [array];
  944. }
  945. // src/esbuild/utils.ts
  946. var ExtToLoader = {
  947. ".js": "js",
  948. ".mjs": "js",
  949. ".cjs": "js",
  950. ".jsx": "jsx",
  951. ".ts": "ts",
  952. ".cts": "ts",
  953. ".mts": "ts",
  954. ".tsx": "tsx",
  955. ".css": "css",
  956. ".less": "css",
  957. ".stylus": "css",
  958. ".scss": "css",
  959. ".sass": "css",
  960. ".json": "json",
  961. ".txt": "text"
  962. };
  963. function guessLoader(id) {
  964. return ExtToLoader[(0, import_path2.extname)(id).toLowerCase()] || "js";
  965. }
  966. function fixSourceMap(map) {
  967. if (!("toString" in map)) {
  968. Object.defineProperty(map, "toString", {
  969. enumerable: false,
  970. value: function toString() {
  971. return JSON.stringify(this);
  972. }
  973. });
  974. }
  975. if (!("toUrl" in map)) {
  976. Object.defineProperty(map, "toUrl", {
  977. enumerable: false,
  978. value: function toUrl() {
  979. return `data:application/json;charset=utf-8;base64,${Buffer.from(this.toString()).toString("base64")}`;
  980. }
  981. });
  982. }
  983. return map;
  984. }
  985. var nullSourceMap = {
  986. names: [],
  987. sources: [],
  988. mappings: "",
  989. version: 3
  990. };
  991. function combineSourcemaps(filename, sourcemapList) {
  992. sourcemapList = sourcemapList.filter((m) => m.sources);
  993. if (sourcemapList.length === 0 || sourcemapList.every((m) => m.sources.length === 0))
  994. return { ...nullSourceMap };
  995. let map;
  996. let mapIndex = 1;
  997. const useArrayInterface = sourcemapList.slice(0, -1).find((m) => m.sources.length !== 1) === void 0;
  998. if (useArrayInterface) {
  999. map = remapping(sourcemapList, () => null, true);
  1000. } else {
  1001. map = remapping(
  1002. sourcemapList[0],
  1003. (sourcefile) => {
  1004. if (sourcefile === filename && sourcemapList[mapIndex])
  1005. return sourcemapList[mapIndex++];
  1006. else
  1007. return { ...nullSourceMap };
  1008. },
  1009. true
  1010. );
  1011. }
  1012. if (!map.file)
  1013. delete map.file;
  1014. return map;
  1015. }
  1016. // src/esbuild/index.ts
  1017. var watchListRecord = {};
  1018. var watchList = /* @__PURE__ */ new Set();
  1019. var i = 0;
  1020. function getEsbuildPlugin(factory) {
  1021. return (userOptions) => {
  1022. const meta = {
  1023. framework: "esbuild"
  1024. };
  1025. const plugins = toArray(factory(userOptions, meta));
  1026. const setup = (plugin) => plugin.esbuild?.setup ?? ((pluginBuild) => {
  1027. const { onStart, onEnd, onResolve, onLoad, initialOptions, esbuild: { build: build2 } } = pluginBuild;
  1028. meta.build = pluginBuild;
  1029. const onResolveFilter = plugin.esbuild?.onResolveFilter ?? /.*/;
  1030. const onLoadFilter = plugin.esbuild?.onLoadFilter ?? /.*/;
  1031. const context = {
  1032. parse(code, opts = {}) {
  1033. return import_acorn.Parser.parse(code, {
  1034. sourceType: "module",
  1035. ecmaVersion: "latest",
  1036. locations: true,
  1037. ...opts
  1038. });
  1039. },
  1040. addWatchFile(id) {
  1041. watchList.add(import_path3.default.resolve(id));
  1042. },
  1043. emitFile(emittedFile) {
  1044. const outFileName = emittedFile.fileName || emittedFile.name;
  1045. if (initialOptions.outdir && emittedFile.source && outFileName)
  1046. import_fs.default.writeFileSync(import_path3.default.resolve(initialOptions.outdir, outFileName), emittedFile.source);
  1047. },
  1048. getWatchFiles() {
  1049. return Array.from(watchList);
  1050. }
  1051. };
  1052. if (initialOptions.outdir && !import_fs.default.existsSync(initialOptions.outdir))
  1053. import_fs.default.mkdirSync(initialOptions.outdir, { recursive: true });
  1054. if (plugin.buildStart)
  1055. onStart(() => plugin.buildStart.call(context));
  1056. if (plugin.buildEnd || plugin.writeBundle || initialOptions.watch) {
  1057. const rebuild = () => build2({
  1058. ...initialOptions,
  1059. watch: false
  1060. });
  1061. onEnd(async () => {
  1062. if (plugin.buildEnd)
  1063. await plugin.buildEnd.call(context);
  1064. if (plugin.writeBundle)
  1065. await plugin.writeBundle();
  1066. if (initialOptions.watch) {
  1067. Object.keys(watchListRecord).forEach((id) => {
  1068. if (!watchList.has(id)) {
  1069. watchListRecord[id].close();
  1070. delete watchListRecord[id];
  1071. }
  1072. });
  1073. watchList.forEach((id) => {
  1074. if (!Object.keys(watchListRecord).includes(id)) {
  1075. watchListRecord[id] = import_chokidar.default.watch(id);
  1076. watchListRecord[id].on("change", async () => {
  1077. await plugin.watchChange?.call(context, id, { event: "update" });
  1078. rebuild();
  1079. });
  1080. watchListRecord[id].on("unlink", async () => {
  1081. await plugin.watchChange?.call(context, id, { event: "delete" });
  1082. rebuild();
  1083. });
  1084. }
  1085. });
  1086. }
  1087. });
  1088. }
  1089. if (plugin.resolveId) {
  1090. onResolve({ filter: onResolveFilter }, async (args) => {
  1091. if (initialOptions.external?.includes(args.path)) {
  1092. return void 0;
  1093. }
  1094. const isEntry = args.kind === "entry-point";
  1095. const result = await plugin.resolveId(
  1096. args.path,
  1097. isEntry ? void 0 : args.importer,
  1098. { isEntry }
  1099. );
  1100. if (typeof result === "string")
  1101. return { path: result, namespace: plugin.name };
  1102. else if (typeof result === "object" && result !== null)
  1103. return { path: result.id, external: result.external, namespace: plugin.name };
  1104. });
  1105. }
  1106. if (plugin.load || plugin.transform) {
  1107. onLoad({ filter: onLoadFilter }, async (args) => {
  1108. const id = args.path + args.suffix;
  1109. const errors = [];
  1110. const warnings = [];
  1111. const pluginContext = {
  1112. error(message) {
  1113. errors.push({ text: String(message) });
  1114. },
  1115. warn(message) {
  1116. warnings.push({ text: String(message) });
  1117. }
  1118. };
  1119. const resolveDir = import_path3.default.dirname(args.path);
  1120. let code, map;
  1121. if (plugin.load && (!plugin.loadInclude || plugin.loadInclude(id))) {
  1122. const result = await plugin.load.call(Object.assign(context, pluginContext), id);
  1123. if (typeof result === "string") {
  1124. code = result;
  1125. } else if (typeof result === "object" && result !== null) {
  1126. code = result.code;
  1127. map = result.map;
  1128. }
  1129. }
  1130. if (!plugin.transform) {
  1131. if (code === void 0)
  1132. return null;
  1133. if (map) {
  1134. if (!map.sourcesContent || map.sourcesContent.length === 0)
  1135. map.sourcesContent = [code];
  1136. map = fixSourceMap(map);
  1137. code += `
  1138. //# sourceMappingURL=${map.toUrl()}`;
  1139. }
  1140. return { contents: code, errors, warnings, loader: guessLoader(args.path), resolveDir };
  1141. }
  1142. if (!plugin.transformInclude || plugin.transformInclude(id)) {
  1143. if (!code) {
  1144. code = await import_fs.default.promises.readFile(args.path, "utf8");
  1145. }
  1146. const result = await plugin.transform.call(Object.assign(context, pluginContext), code, id);
  1147. if (typeof result === "string") {
  1148. code = result;
  1149. } else if (typeof result === "object" && result !== null) {
  1150. code = result.code;
  1151. if (map && result.map) {
  1152. map = combineSourcemaps(args.path, [
  1153. result.map,
  1154. map
  1155. ]);
  1156. } else {
  1157. map = result.map;
  1158. }
  1159. }
  1160. }
  1161. if (code) {
  1162. if (map) {
  1163. if (!map.sourcesContent || map.sourcesContent.length === 0)
  1164. map.sourcesContent = [code];
  1165. map = fixSourceMap(map);
  1166. code += `
  1167. //# sourceMappingURL=${map.toUrl()}`;
  1168. }
  1169. return { contents: code, errors, warnings, loader: guessLoader(args.path), resolveDir };
  1170. }
  1171. });
  1172. }
  1173. });
  1174. const setupMultiplePlugins = () => (build2) => {
  1175. for (const plugin of plugins)
  1176. setup(plugin)(build2);
  1177. };
  1178. return plugins.length === 1 ? { name: plugins[0].name, setup: setup(plugins[0]) } : { name: meta.esbuildHostName ?? `unplugin-host-${i++}`, setup: setupMultiplePlugins() };
  1179. };
  1180. }
  1181. // src/rollup/index.ts
  1182. function getRollupPlugin(factory) {
  1183. return (userOptions) => {
  1184. const meta = {
  1185. framework: "rollup"
  1186. };
  1187. const rawPlugins = toArray(factory(userOptions, meta));
  1188. const plugins = rawPlugins.map((plugin) => toRollupPlugin(plugin));
  1189. return plugins.length === 1 ? plugins[0] : plugins;
  1190. };
  1191. }
  1192. function toRollupPlugin(plugin, containRollupOptions = true) {
  1193. if (plugin.transform && plugin.transformInclude) {
  1194. const _transform = plugin.transform;
  1195. plugin.transform = function(code, id) {
  1196. if (plugin.transformInclude && !plugin.transformInclude(id))
  1197. return null;
  1198. return _transform.call(this, code, id);
  1199. };
  1200. }
  1201. if (plugin.load && plugin.loadInclude) {
  1202. const _load = plugin.load;
  1203. plugin.load = function(id) {
  1204. if (plugin.loadInclude && !plugin.loadInclude(id))
  1205. return null;
  1206. return _load.call(this, id);
  1207. };
  1208. }
  1209. if (plugin.rollup && containRollupOptions)
  1210. Object.assign(plugin, plugin.rollup);
  1211. return plugin;
  1212. }
  1213. // src/vite/index.ts
  1214. function getVitePlugin(factory) {
  1215. return (userOptions) => {
  1216. const meta = {
  1217. framework: "vite"
  1218. };
  1219. const rawPlugins = toArray(factory(userOptions, meta));
  1220. const plugins = rawPlugins.map((rawPlugin) => {
  1221. const plugin = toRollupPlugin(rawPlugin, false);
  1222. if (rawPlugin.vite)
  1223. Object.assign(plugin, rawPlugin.vite);
  1224. return plugin;
  1225. });
  1226. return plugins.length === 1 ? plugins[0] : plugins;
  1227. };
  1228. }
  1229. // src/webpack/index.ts
  1230. var import_fs2 = __toESM(require("fs"));
  1231. var import_url = require("url");
  1232. var import_path5 = require("path");
  1233. var import_webpack_virtual_modules = __toESM(require("webpack-virtual-modules"));
  1234. // src/webpack/context.ts
  1235. var import_path4 = require("path");
  1236. var import_webpack_sources = __toESM(require("webpack-sources"));
  1237. var import_acorn2 = require("acorn");
  1238. function createContext(compilation) {
  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. (compilation.fileDependencies ?? compilation.compilationDependencies).add(
  1250. (0, import_path4.resolve)(process.cwd(), id)
  1251. );
  1252. },
  1253. emitFile(emittedFile) {
  1254. const outFileName = emittedFile.fileName || emittedFile.name;
  1255. if (emittedFile.source && outFileName) {
  1256. compilation.emitAsset(
  1257. outFileName,
  1258. import_webpack_sources.default ? new import_webpack_sources.default.RawSource(
  1259. typeof emittedFile.source === "string" ? emittedFile.source : Buffer.from(emittedFile.source)
  1260. ) : {
  1261. source: () => emittedFile.source,
  1262. size: () => emittedFile.source.length
  1263. }
  1264. );
  1265. }
  1266. },
  1267. getWatchFiles() {
  1268. return Array.from(
  1269. compilation.fileDependencies ?? compilation.compilationDependencies
  1270. );
  1271. }
  1272. };
  1273. }
  1274. // src/webpack/index.ts
  1275. var import_meta = {};
  1276. var _dirname = typeof __dirname !== "undefined" ? __dirname : (0, import_path5.dirname)((0, import_url.fileURLToPath)(import_meta.url));
  1277. var TRANSFORM_LOADER = (0, import_path5.resolve)(
  1278. _dirname,
  1279. false ? "../../dist/webpack/loaders/transform" : "webpack/loaders/transform"
  1280. );
  1281. var LOAD_LOADER = (0, import_path5.resolve)(
  1282. _dirname,
  1283. false ? "../../dist/webpack/loaders/load" : "webpack/loaders/load"
  1284. );
  1285. var VIRTUAL_MODULE_PREFIX = (0, import_path5.resolve)(process.cwd(), "_virtual_");
  1286. function getWebpackPlugin(factory) {
  1287. return (userOptions) => {
  1288. return {
  1289. apply(compiler) {
  1290. const injected = compiler.$unpluginContext || {};
  1291. compiler.$unpluginContext = injected;
  1292. const meta = {
  1293. framework: "webpack",
  1294. webpack: {
  1295. compiler
  1296. }
  1297. };
  1298. const rawPlugins = toArray(factory(userOptions, meta));
  1299. for (const rawPlugin of rawPlugins) {
  1300. const plugin = Object.assign(
  1301. rawPlugin,
  1302. {
  1303. __unpluginMeta: meta,
  1304. __virtualModulePrefix: VIRTUAL_MODULE_PREFIX
  1305. }
  1306. );
  1307. injected[plugin.name] = plugin;
  1308. compiler.hooks.thisCompilation.tap(plugin.name, (compilation) => {
  1309. compilation.hooks.childCompiler.tap(plugin.name, (childCompiler) => {
  1310. childCompiler.$unpluginContext = injected;
  1311. });
  1312. });
  1313. const externalModules = /* @__PURE__ */ new Set();
  1314. if (plugin.transform) {
  1315. const useLoader = [{
  1316. loader: `${TRANSFORM_LOADER}?unpluginName=${encodeURIComponent(plugin.name)}`
  1317. }];
  1318. const useNone = [];
  1319. compiler.options.module.rules.unshift({
  1320. enforce: plugin.enforce,
  1321. use: (data) => {
  1322. if (data.resource == null)
  1323. return useNone;
  1324. const id = normalizeAbsolutePath(data.resource + (data.resourceQuery || ""));
  1325. if (!plugin.transformInclude || plugin.transformInclude(id))
  1326. return useLoader;
  1327. return useNone;
  1328. }
  1329. });
  1330. }
  1331. if (plugin.resolveId) {
  1332. let vfs = compiler.options.plugins.find((i2) => i2 instanceof import_webpack_virtual_modules.default);
  1333. if (!vfs) {
  1334. vfs = new import_webpack_virtual_modules.default();
  1335. compiler.options.plugins.push(vfs);
  1336. }
  1337. plugin.__vfsModules = /* @__PURE__ */ new Set();
  1338. plugin.__vfs = vfs;
  1339. const resolverPlugin = {
  1340. apply(resolver) {
  1341. const target = resolver.ensureHook("resolve");
  1342. resolver.getHook("resolve").tapAsync(plugin.name, async (request, resolveContext, callback) => {
  1343. if (!request.request)
  1344. return callback();
  1345. if (normalizeAbsolutePath(request.request).startsWith(plugin.__virtualModulePrefix))
  1346. return callback();
  1347. const id = normalizeAbsolutePath(request.request);
  1348. const requestContext = request.context;
  1349. const importer = requestContext.issuer !== "" ? requestContext.issuer : void 0;
  1350. const isEntry = requestContext.issuer === "";
  1351. const resolveIdResult = await plugin.resolveId(id, importer, { isEntry });
  1352. if (resolveIdResult == null)
  1353. return callback();
  1354. let resolved = typeof resolveIdResult === "string" ? resolveIdResult : resolveIdResult.id;
  1355. const isExternal = typeof resolveIdResult === "string" ? false : resolveIdResult.external === true;
  1356. if (isExternal)
  1357. externalModules.add(resolved);
  1358. if (!import_fs2.default.existsSync(resolved)) {
  1359. resolved = normalizeAbsolutePath(
  1360. plugin.__virtualModulePrefix + encodeURIComponent(resolved)
  1361. );
  1362. if (!plugin.__vfsModules.has(resolved)) {
  1363. plugin.__vfs.writeModule(resolved, "");
  1364. plugin.__vfsModules.add(resolved);
  1365. }
  1366. }
  1367. const newRequest = {
  1368. ...request,
  1369. request: resolved
  1370. };
  1371. resolver.doResolve(target, newRequest, null, resolveContext, callback);
  1372. });
  1373. }
  1374. };
  1375. compiler.options.resolve.plugins = compiler.options.resolve.plugins || [];
  1376. compiler.options.resolve.plugins.push(resolverPlugin);
  1377. }
  1378. if (plugin.load) {
  1379. compiler.options.module.rules.unshift({
  1380. include(id) {
  1381. if (id.startsWith(plugin.__virtualModulePrefix))
  1382. id = decodeURIComponent(id.slice(plugin.__virtualModulePrefix.length));
  1383. if (plugin.loadInclude && !plugin.loadInclude(id))
  1384. return false;
  1385. return !externalModules.has(id);
  1386. },
  1387. enforce: plugin.enforce,
  1388. use: [{
  1389. loader: LOAD_LOADER,
  1390. options: {
  1391. unpluginName: plugin.name
  1392. }
  1393. }]
  1394. });
  1395. }
  1396. if (plugin.webpack)
  1397. plugin.webpack(compiler);
  1398. if (plugin.watchChange || plugin.buildStart) {
  1399. compiler.hooks.make.tapPromise(plugin.name, async (compilation) => {
  1400. const context = createContext(compilation);
  1401. if (plugin.watchChange && (compiler.modifiedFiles || compiler.removedFiles)) {
  1402. const promises = [];
  1403. if (compiler.modifiedFiles) {
  1404. compiler.modifiedFiles.forEach(
  1405. (file) => promises.push(Promise.resolve(plugin.watchChange.call(context, file, { event: "update" })))
  1406. );
  1407. }
  1408. if (compiler.removedFiles) {
  1409. compiler.removedFiles.forEach(
  1410. (file) => promises.push(Promise.resolve(plugin.watchChange.call(context, file, { event: "delete" })))
  1411. );
  1412. }
  1413. await Promise.all(promises);
  1414. }
  1415. if (plugin.buildStart)
  1416. return await plugin.buildStart.call(context);
  1417. });
  1418. }
  1419. if (plugin.buildEnd) {
  1420. compiler.hooks.emit.tapPromise(plugin.name, async (compilation) => {
  1421. await plugin.buildEnd.call(createContext(compilation));
  1422. });
  1423. }
  1424. if (plugin.writeBundle) {
  1425. compiler.hooks.afterEmit.tap(plugin.name, () => {
  1426. plugin.writeBundle();
  1427. });
  1428. }
  1429. }
  1430. }
  1431. };
  1432. };
  1433. }
  1434. // src/define.ts
  1435. function createUnplugin(factory) {
  1436. return {
  1437. get esbuild() {
  1438. return getEsbuildPlugin(factory);
  1439. },
  1440. get rollup() {
  1441. return getRollupPlugin(factory);
  1442. },
  1443. get vite() {
  1444. return getVitePlugin(factory);
  1445. },
  1446. get webpack() {
  1447. return getWebpackPlugin(factory);
  1448. },
  1449. get raw() {
  1450. return factory;
  1451. }
  1452. };
  1453. }
  1454. // Annotate the CommonJS export names for ESM import in node:
  1455. 0 && (module.exports = {
  1456. createUnplugin
  1457. });