版博士V2.0程序
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.
 
 
 
 

1563 строки
48 KiB

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