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

1005 строки
30 KiB

  1. 'use strict';
  2. const node_path = require('node:path');
  3. const fs = require('fs-extra');
  4. const _debug = require('debug');
  5. const kolorist = require('kolorist');
  6. const sirv = require('sirv');
  7. const pluginutils = require('@rollup/pluginutils');
  8. const node_url = require('node:url');
  9. function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e.default : e; }
  10. const fs__default = /*#__PURE__*/_interopDefaultCompat(fs);
  11. const _debug__default = /*#__PURE__*/_interopDefaultCompat(_debug);
  12. const sirv__default = /*#__PURE__*/_interopDefaultCompat(sirv);
  13. const DEFAULT_TIMEOUT = 6e4;
  14. const defaultSerialize = (i) => i;
  15. const defaultDeserialize = defaultSerialize;
  16. function createBirpc(functions, options) {
  17. const {
  18. post,
  19. on,
  20. eventNames = [],
  21. serialize = defaultSerialize,
  22. deserialize = defaultDeserialize,
  23. timeout = DEFAULT_TIMEOUT
  24. } = options;
  25. const rpcPromiseMap = /* @__PURE__ */ new Map();
  26. let _promise;
  27. const rpc = new Proxy({}, {
  28. get(_, method) {
  29. const sendEvent = (...args) => {
  30. post(serialize({ m: method, a: args, t: "q" }));
  31. };
  32. if (eventNames.includes(method)) {
  33. sendEvent.asEvent = sendEvent;
  34. return sendEvent;
  35. }
  36. const sendCall = async (...args) => {
  37. await _promise;
  38. return new Promise((resolve, reject) => {
  39. const id = nanoid();
  40. rpcPromiseMap.set(id, { resolve, reject });
  41. post(serialize({ m: method, a: args, i: id, t: "q" }));
  42. if (timeout >= 0) {
  43. setTimeout(() => {
  44. reject(new Error(`[birpc] timeout on calling "${method}"`));
  45. rpcPromiseMap.delete(id);
  46. }, timeout);
  47. }
  48. });
  49. };
  50. sendCall.asEvent = sendEvent;
  51. return sendCall;
  52. }
  53. });
  54. _promise = on(async (data, ...extra) => {
  55. const msg = deserialize(data);
  56. if (msg.t === "q") {
  57. const { m: method, a: args } = msg;
  58. let result, error;
  59. try {
  60. result = await functions[method].apply(rpc, args);
  61. } catch (e) {
  62. error = e;
  63. }
  64. if (msg.i)
  65. post(serialize({ t: "s", i: msg.i, r: result, e: error }), ...extra);
  66. } else {
  67. const { i: ack, r: result, e: error } = msg;
  68. const promise = rpcPromiseMap.get(ack);
  69. if (promise) {
  70. if (error)
  71. promise.reject(error);
  72. else
  73. promise.resolve(result);
  74. }
  75. rpcPromiseMap.delete(ack);
  76. }
  77. });
  78. return rpc;
  79. }
  80. const cacheMap = /* @__PURE__ */ new WeakMap();
  81. function cachedMap(items, fn) {
  82. return items.map((i) => {
  83. let r = cacheMap.get(i);
  84. if (!r) {
  85. r = fn(i);
  86. cacheMap.set(i, r);
  87. }
  88. return r;
  89. });
  90. }
  91. function createBirpcGroup(functions, channels, options = {}) {
  92. const getChannels = () => typeof channels === "function" ? channels() : channels;
  93. const getClients = (channels2 = getChannels()) => cachedMap(channels2, (s) => createBirpc(functions, { ...options, ...s }));
  94. const broadcastProxy = new Proxy({}, {
  95. get(_, method) {
  96. const client = getClients();
  97. const functions2 = client.map((c) => c[method]);
  98. const sendCall = (...args) => {
  99. return Promise.all(functions2.map((i) => i(...args)));
  100. };
  101. sendCall.asEvent = (...args) => {
  102. functions2.map((i) => i.asEvent(...args));
  103. };
  104. return sendCall;
  105. }
  106. });
  107. function updateChannels(fn) {
  108. const channels2 = getChannels();
  109. fn?.(channels2);
  110. return getClients(channels2);
  111. }
  112. getClients();
  113. return {
  114. get clients() {
  115. return getClients();
  116. },
  117. updateChannels,
  118. broadcast: broadcastProxy,
  119. /**
  120. * @deprecated use `broadcast`
  121. */
  122. boardcast: broadcastProxy
  123. };
  124. }
  125. const urlAlphabet = "useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";
  126. function nanoid(size = 21) {
  127. let id = "";
  128. let i = size;
  129. while (i--)
  130. id += urlAlphabet[Math.random() * 64 | 0];
  131. return id;
  132. }
  133. function createRPCServer(name, ws, functions) {
  134. const event = `${name}:rpc`;
  135. const group = createBirpcGroup(
  136. functions,
  137. () => cachedMap(
  138. Array.from(ws?.clients || []),
  139. (socket) => {
  140. return {
  141. on: (fn) => {
  142. ws.on(event, (data, source) => {
  143. if (socket === source)
  144. fn(data);
  145. });
  146. },
  147. post: (data) => {
  148. socket.send(event, data);
  149. }
  150. };
  151. }
  152. )
  153. );
  154. ws.on("connection", () => {
  155. group.updateChannels();
  156. });
  157. return group.broadcast;
  158. }
  159. const defaults = {
  160. ignoreUnknown: false,
  161. respectType: false,
  162. respectFunctionNames: false,
  163. respectFunctionProperties: false,
  164. unorderedObjects: true,
  165. unorderedArrays: false,
  166. unorderedSets: false
  167. };
  168. function objectHash(object, options = {}) {
  169. options = { ...defaults, ...options };
  170. const hasher = createHasher(options);
  171. hasher.dispatch(object);
  172. return hasher.toString();
  173. }
  174. function createHasher(options) {
  175. const buff = [];
  176. let context = [];
  177. const write = (str) => {
  178. buff.push(str);
  179. };
  180. return {
  181. toString() {
  182. return buff.join("");
  183. },
  184. getContext() {
  185. return context;
  186. },
  187. dispatch(value) {
  188. if (options.replacer) {
  189. value = options.replacer(value);
  190. }
  191. const type = value === null ? "null" : typeof value;
  192. return this["_" + type](value);
  193. },
  194. _object(object) {
  195. const pattern = /\[object (.*)]/i;
  196. const objString = Object.prototype.toString.call(object);
  197. const _objType = pattern.exec(objString);
  198. const objType = _objType ? _objType[1].toLowerCase() : "unknown:[" + objString.toLowerCase() + "]";
  199. let objectNumber = null;
  200. if ((objectNumber = context.indexOf(object)) >= 0) {
  201. return this.dispatch("[CIRCULAR:" + objectNumber + "]");
  202. } else {
  203. context.push(object);
  204. }
  205. if (typeof Buffer !== "undefined" && Buffer.isBuffer && Buffer.isBuffer(object)) {
  206. write("buffer:");
  207. return write(object.toString("utf8"));
  208. }
  209. if (objType !== "object" && objType !== "function" && objType !== "asyncfunction") {
  210. if (this["_" + objType]) {
  211. this["_" + objType](object);
  212. } else if (options.ignoreUnknown) {
  213. return write("[" + objType + "]");
  214. } else {
  215. throw new Error('Unknown object type "' + objType + '"');
  216. }
  217. } else {
  218. let keys = Object.keys(object);
  219. if (options.unorderedObjects) {
  220. keys = keys.sort();
  221. }
  222. if (options.respectType !== false && !isNativeFunction(object)) {
  223. keys.splice(0, 0, "prototype", "__proto__", "letructor");
  224. }
  225. if (options.excludeKeys) {
  226. keys = keys.filter(function(key) {
  227. return !options.excludeKeys(key);
  228. });
  229. }
  230. write("object:" + keys.length + ":");
  231. for (const key of keys) {
  232. this.dispatch(key);
  233. write(":");
  234. if (!options.excludeValues) {
  235. this.dispatch(object[key]);
  236. }
  237. write(",");
  238. }
  239. }
  240. },
  241. _array(arr, unordered) {
  242. unordered = typeof unordered !== "undefined" ? unordered : options.unorderedArrays !== false;
  243. write("array:" + arr.length + ":");
  244. if (!unordered || arr.length <= 1) {
  245. for (const entry of arr) {
  246. this.dispatch(entry);
  247. }
  248. return;
  249. }
  250. const contextAdditions = [];
  251. const entries = arr.map((entry) => {
  252. const hasher = createHasher(options);
  253. hasher.dispatch(entry);
  254. contextAdditions.push(hasher.getContext());
  255. return hasher.toString();
  256. });
  257. context = [...context, ...contextAdditions];
  258. entries.sort();
  259. return this._array(entries, false);
  260. },
  261. _date(date) {
  262. return write("date:" + date.toJSON());
  263. },
  264. _symbol(sym) {
  265. return write("symbol:" + sym.toString());
  266. },
  267. _error(err) {
  268. return write("error:" + err.toString());
  269. },
  270. _boolean(bool) {
  271. return write("bool:" + bool.toString());
  272. },
  273. _string(string) {
  274. write("string:" + string.length + ":");
  275. write(string.toString());
  276. },
  277. _function(fn) {
  278. write("fn:");
  279. if (isNativeFunction(fn)) {
  280. this.dispatch("[native]");
  281. } else {
  282. this.dispatch(fn.toString());
  283. }
  284. if (options.respectFunctionNames !== false) {
  285. this.dispatch("function-name:" + String(fn.name));
  286. }
  287. if (options.respectFunctionProperties) {
  288. this._object(fn);
  289. }
  290. },
  291. _number(number) {
  292. return write("number:" + number.toString());
  293. },
  294. _xml(xml) {
  295. return write("xml:" + xml.toString());
  296. },
  297. _null() {
  298. return write("Null");
  299. },
  300. _undefined() {
  301. return write("Undefined");
  302. },
  303. _regexp(regex) {
  304. return write("regex:" + regex.toString());
  305. },
  306. _uint8array(arr) {
  307. write("uint8array:");
  308. return this.dispatch(Array.prototype.slice.call(arr));
  309. },
  310. _uint8clampedarray(arr) {
  311. write("uint8clampedarray:");
  312. return this.dispatch(Array.prototype.slice.call(arr));
  313. },
  314. _int8array(arr) {
  315. write("int8array:");
  316. return this.dispatch(Array.prototype.slice.call(arr));
  317. },
  318. _uint16array(arr) {
  319. write("uint16array:");
  320. return this.dispatch(Array.prototype.slice.call(arr));
  321. },
  322. _int16array(arr) {
  323. write("int16array:");
  324. return this.dispatch(Array.prototype.slice.call(arr));
  325. },
  326. _uint32array(arr) {
  327. write("uint32array:");
  328. return this.dispatch(Array.prototype.slice.call(arr));
  329. },
  330. _int32array(arr) {
  331. write("int32array:");
  332. return this.dispatch(Array.prototype.slice.call(arr));
  333. },
  334. _float32array(arr) {
  335. write("float32array:");
  336. return this.dispatch(Array.prototype.slice.call(arr));
  337. },
  338. _float64array(arr) {
  339. write("float64array:");
  340. return this.dispatch(Array.prototype.slice.call(arr));
  341. },
  342. _arraybuffer(arr) {
  343. write("arraybuffer:");
  344. return this.dispatch(new Uint8Array(arr));
  345. },
  346. _url(url) {
  347. return write("url:" + url.toString());
  348. },
  349. _map(map) {
  350. write("map:");
  351. const arr = [...map];
  352. return this._array(arr, options.unorderedSets !== false);
  353. },
  354. _set(set) {
  355. write("set:");
  356. const arr = [...set];
  357. return this._array(arr, options.unorderedSets !== false);
  358. },
  359. _file(file) {
  360. write("file:");
  361. return this.dispatch([file.name, file.size, file.type, file.lastModfied]);
  362. },
  363. _blob() {
  364. if (options.ignoreUnknown) {
  365. return write("[blob]");
  366. }
  367. throw new Error('Hashing Blob objects is currently not supported\nUse "options.replacer" or "options.ignoreUnknown"\n');
  368. },
  369. _domwindow() {
  370. return write("domwindow");
  371. },
  372. _bigint(number) {
  373. return write("bigint:" + number.toString());
  374. },
  375. _process() {
  376. return write("process");
  377. },
  378. _timer() {
  379. return write("timer");
  380. },
  381. _pipe() {
  382. return write("pipe");
  383. },
  384. _tcp() {
  385. return write("tcp");
  386. },
  387. _udp() {
  388. return write("udp");
  389. },
  390. _tty() {
  391. return write("tty");
  392. },
  393. _statwatcher() {
  394. return write("statwatcher");
  395. },
  396. _securecontext() {
  397. return write("securecontext");
  398. },
  399. _connection() {
  400. return write("connection");
  401. },
  402. _zlib() {
  403. return write("zlib");
  404. },
  405. _context() {
  406. return write("context");
  407. },
  408. _nodescript() {
  409. return write("nodescript");
  410. },
  411. _httpparser() {
  412. return write("httpparser");
  413. },
  414. _dataview() {
  415. return write("dataview");
  416. },
  417. _signal() {
  418. return write("signal");
  419. },
  420. _fsevent() {
  421. return write("fsevent");
  422. },
  423. _tlswrap() {
  424. return write("tlswrap");
  425. }
  426. };
  427. }
  428. function isNativeFunction(f) {
  429. if (typeof f !== "function") {
  430. return false;
  431. }
  432. const exp = /^function\s+\w*\s*\(\s*\)\s*{\s+\[native code]\s+}$/i;
  433. return exp.exec(Function.prototype.toString.call(f)) != null;
  434. }
  435. class WordArray {
  436. constructor(words, sigBytes) {
  437. words = this.words = words || [];
  438. this.sigBytes = sigBytes !== void 0 ? sigBytes : words.length * 4;
  439. }
  440. toString(encoder) {
  441. return (encoder || Hex).stringify(this);
  442. }
  443. concat(wordArray) {
  444. this.clamp();
  445. if (this.sigBytes % 4) {
  446. for (let i = 0; i < wordArray.sigBytes; i++) {
  447. const thatByte = wordArray.words[i >>> 2] >>> 24 - i % 4 * 8 & 255;
  448. this.words[this.sigBytes + i >>> 2] |= thatByte << 24 - (this.sigBytes + i) % 4 * 8;
  449. }
  450. } else {
  451. for (let j = 0; j < wordArray.sigBytes; j += 4) {
  452. this.words[this.sigBytes + j >>> 2] = wordArray.words[j >>> 2];
  453. }
  454. }
  455. this.sigBytes += wordArray.sigBytes;
  456. return this;
  457. }
  458. clamp() {
  459. this.words[this.sigBytes >>> 2] &= 4294967295 << 32 - this.sigBytes % 4 * 8;
  460. this.words.length = Math.ceil(this.sigBytes / 4);
  461. }
  462. clone() {
  463. return new WordArray([...this.words]);
  464. }
  465. }
  466. const Hex = {
  467. stringify(wordArray) {
  468. const hexChars = [];
  469. for (let i = 0; i < wordArray.sigBytes; i++) {
  470. const bite = wordArray.words[i >>> 2] >>> 24 - i % 4 * 8 & 255;
  471. hexChars.push(
  472. (bite >>> 4).toString(16),
  473. (bite & 15).toString(16)
  474. );
  475. }
  476. return hexChars.join("");
  477. }
  478. };
  479. const Base64 = {
  480. stringify(wordArray) {
  481. const keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  482. const base64Chars = [];
  483. for (let i = 0; i < wordArray.sigBytes; i += 3) {
  484. const byte1 = wordArray.words[i >>> 2] >>> 24 - i % 4 * 8 & 255;
  485. const byte2 = wordArray.words[i + 1 >>> 2] >>> 24 - (i + 1) % 4 * 8 & 255;
  486. const byte3 = wordArray.words[i + 2 >>> 2] >>> 24 - (i + 2) % 4 * 8 & 255;
  487. const triplet = byte1 << 16 | byte2 << 8 | byte3;
  488. for (let j = 0; j < 4 && i * 8 + j * 6 < wordArray.sigBytes * 8; j++) {
  489. base64Chars.push(keyStr.charAt(triplet >>> 6 * (3 - j) & 63));
  490. }
  491. }
  492. return base64Chars.join("");
  493. }
  494. };
  495. const Latin1 = {
  496. parse(latin1Str) {
  497. const latin1StrLength = latin1Str.length;
  498. const words = [];
  499. for (let i = 0; i < latin1StrLength; i++) {
  500. words[i >>> 2] |= (latin1Str.charCodeAt(i) & 255) << 24 - i % 4 * 8;
  501. }
  502. return new WordArray(words, latin1StrLength);
  503. }
  504. };
  505. const Utf8 = {
  506. parse(utf8Str) {
  507. return Latin1.parse(unescape(encodeURIComponent(utf8Str)));
  508. }
  509. };
  510. class BufferedBlockAlgorithm {
  511. constructor() {
  512. this._minBufferSize = 0;
  513. this.blockSize = 512 / 32;
  514. this.reset();
  515. }
  516. reset() {
  517. this._data = new WordArray();
  518. this._nDataBytes = 0;
  519. }
  520. _append(data) {
  521. if (typeof data === "string") {
  522. data = Utf8.parse(data);
  523. }
  524. this._data.concat(data);
  525. this._nDataBytes += data.sigBytes;
  526. }
  527. _doProcessBlock(_dataWords, _offset) {
  528. }
  529. _process(doFlush) {
  530. let processedWords;
  531. let nBlocksReady = this._data.sigBytes / (this.blockSize * 4);
  532. if (doFlush) {
  533. nBlocksReady = Math.ceil(nBlocksReady);
  534. } else {
  535. nBlocksReady = Math.max((nBlocksReady | 0) - this._minBufferSize, 0);
  536. }
  537. const nWordsReady = nBlocksReady * this.blockSize;
  538. const nBytesReady = Math.min(nWordsReady * 4, this._data.sigBytes);
  539. if (nWordsReady) {
  540. for (let offset = 0; offset < nWordsReady; offset += this.blockSize) {
  541. this._doProcessBlock(this._data.words, offset);
  542. }
  543. processedWords = this._data.words.splice(0, nWordsReady);
  544. this._data.sigBytes -= nBytesReady;
  545. }
  546. return new WordArray(processedWords, nBytesReady);
  547. }
  548. }
  549. class Hasher extends BufferedBlockAlgorithm {
  550. update(messageUpdate) {
  551. this._append(messageUpdate);
  552. this._process();
  553. return this;
  554. }
  555. finalize(messageUpdate) {
  556. if (messageUpdate) {
  557. this._append(messageUpdate);
  558. }
  559. }
  560. }
  561. const H = [1779033703, -1150833019, 1013904242, -1521486534, 1359893119, -1694144372, 528734635, 1541459225];
  562. const K = [1116352408, 1899447441, -1245643825, -373957723, 961987163, 1508970993, -1841331548, -1424204075, -670586216, 310598401, 607225278, 1426881987, 1925078388, -2132889090, -1680079193, -1046744716, -459576895, -272742522, 264347078, 604807628, 770255983, 1249150122, 1555081692, 1996064986, -1740746414, -1473132947, -1341970488, -1084653625, -958395405, -710438585, 113926993, 338241895, 666307205, 773529912, 1294757372, 1396182291, 1695183700, 1986661051, -2117940946, -1838011259, -1564481375, -1474664885, -1035236496, -949202525, -778901479, -694614492, -200395387, 275423344, 430227734, 506948616, 659060556, 883997877, 958139571, 1322822218, 1537002063, 1747873779, 1955562222, 2024104815, -2067236844, -1933114872, -1866530822, -1538233109, -1090935817, -965641998];
  563. const W = [];
  564. class SHA256 extends Hasher {
  565. constructor() {
  566. super();
  567. this.reset();
  568. }
  569. reset() {
  570. super.reset();
  571. this._hash = new WordArray([...H]);
  572. }
  573. _doProcessBlock(M, offset) {
  574. const H2 = this._hash.words;
  575. let a = H2[0];
  576. let b = H2[1];
  577. let c = H2[2];
  578. let d = H2[3];
  579. let e = H2[4];
  580. let f = H2[5];
  581. let g = H2[6];
  582. let h = H2[7];
  583. for (let i = 0; i < 64; i++) {
  584. if (i < 16) {
  585. W[i] = M[offset + i] | 0;
  586. } else {
  587. const gamma0x = W[i - 15];
  588. const gamma0 = (gamma0x << 25 | gamma0x >>> 7) ^ (gamma0x << 14 | gamma0x >>> 18) ^ gamma0x >>> 3;
  589. const gamma1x = W[i - 2];
  590. const gamma1 = (gamma1x << 15 | gamma1x >>> 17) ^ (gamma1x << 13 | gamma1x >>> 19) ^ gamma1x >>> 10;
  591. W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16];
  592. }
  593. const ch = e & f ^ ~e & g;
  594. const maj = a & b ^ a & c ^ b & c;
  595. const sigma0 = (a << 30 | a >>> 2) ^ (a << 19 | a >>> 13) ^ (a << 10 | a >>> 22);
  596. const sigma1 = (e << 26 | e >>> 6) ^ (e << 21 | e >>> 11) ^ (e << 7 | e >>> 25);
  597. const t1 = h + sigma1 + ch + K[i] + W[i];
  598. const t2 = sigma0 + maj;
  599. h = g;
  600. g = f;
  601. f = e;
  602. e = d + t1 | 0;
  603. d = c;
  604. c = b;
  605. b = a;
  606. a = t1 + t2 | 0;
  607. }
  608. H2[0] = H2[0] + a | 0;
  609. H2[1] = H2[1] + b | 0;
  610. H2[2] = H2[2] + c | 0;
  611. H2[3] = H2[3] + d | 0;
  612. H2[4] = H2[4] + e | 0;
  613. H2[5] = H2[5] + f | 0;
  614. H2[6] = H2[6] + g | 0;
  615. H2[7] = H2[7] + h | 0;
  616. }
  617. finalize(messageUpdate) {
  618. super.finalize(messageUpdate);
  619. const nBitsTotal = this._nDataBytes * 8;
  620. const nBitsLeft = this._data.sigBytes * 8;
  621. this._data.words[nBitsLeft >>> 5] |= 128 << 24 - nBitsLeft % 32;
  622. this._data.words[(nBitsLeft + 64 >>> 9 << 4) + 14] = Math.floor(nBitsTotal / 4294967296);
  623. this._data.words[(nBitsLeft + 64 >>> 9 << 4) + 15] = nBitsTotal;
  624. this._data.sigBytes = this._data.words.length * 4;
  625. this._process();
  626. return this._hash;
  627. }
  628. }
  629. function sha256base64(message) {
  630. return new SHA256().finalize(message).toString(Base64);
  631. }
  632. function hash(object, options = {}) {
  633. const hashed = typeof object === "string" ? object : objectHash(object, options);
  634. return sha256base64(hashed).slice(0, 10);
  635. }
  636. const DIR_DIST = typeof __dirname !== "undefined" ? __dirname : node_path.dirname(node_url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (document.currentScript && document.currentScript.src || new URL('index.cjs', document.baseURI).href))));
  637. const DIR_CLIENT = node_path.resolve(DIR_DIST, "../dist/client");
  638. const debug = _debug__default("vite-plugin-inspect");
  639. const NAME = "vite-plugin-inspect";
  640. const dummyLoadPluginName = "__load__";
  641. function PluginInspect(options = {}) {
  642. const {
  643. dev = true,
  644. build = false,
  645. outputDir = ".vite-inspect"
  646. } = options;
  647. if (!dev && !build) {
  648. return {
  649. name: NAME
  650. };
  651. }
  652. const filter = pluginutils.createFilter(options.include, options.exclude);
  653. let config;
  654. const transformMap = {};
  655. const transformMapSSR = {};
  656. const idMap = {};
  657. const idMapSSR = {};
  658. function hijackHook(plugin2, name, wrapper) {
  659. if (!plugin2[name])
  660. return;
  661. debug(`hijack plugin "${name}"`, plugin2.name);
  662. let order = plugin2.order || plugin2.enforce || "normal";
  663. const hook = plugin2[name];
  664. if ("handler" in hook) {
  665. const oldFn = hook.handler;
  666. order += `-${hook.order || hook.enforce || "normal"}`;
  667. hook.handler = function(...args) {
  668. return wrapper(oldFn, this, args, order);
  669. };
  670. } else if ("transform" in hook) {
  671. const oldFn = hook.transform;
  672. order += `-${hook.order || hook.enforce || "normal"}`;
  673. hook.transform = function(...args) {
  674. return wrapper(oldFn, this, args, order);
  675. };
  676. } else {
  677. const oldFn = hook;
  678. plugin2[name] = function(...args) {
  679. return wrapper(oldFn, this, args, order);
  680. };
  681. }
  682. }
  683. function hijackPlugin(plugin2) {
  684. hijackHook(plugin2, "transform", async (fn, context, args, order) => {
  685. const code = args[0];
  686. const id = args[1];
  687. const ssr = args[2]?.ssr;
  688. const start = Date.now();
  689. const _result = await fn.apply(context, args);
  690. const end = Date.now();
  691. const result = typeof _result === "string" ? _result : _result?.code;
  692. const map = ssr ? transformMapSSR : transformMap;
  693. if (filter(id) && result != null) {
  694. if (!map[id])
  695. map[id] = [{ name: dummyLoadPluginName, result: code, start, end: start }];
  696. map[id].push({ name: plugin2.name, result, start, end, order });
  697. }
  698. return _result;
  699. });
  700. hijackHook(plugin2, "load", async (fn, context, args) => {
  701. const id = args[0];
  702. const ssr = args[1]?.ssr;
  703. const start = Date.now();
  704. const _result = await fn.apply(context, args);
  705. const end = Date.now();
  706. const result = typeof _result === "string" ? _result : _result?.code;
  707. const map = ssr ? transformMapSSR : transformMap;
  708. if (filter(id) && result != null)
  709. map[id] = [{ name: plugin2.name, result, start, end }];
  710. return _result;
  711. });
  712. hijackHook(plugin2, "resolveId", async (fn, context, args) => {
  713. const id = args[0];
  714. const ssr = args[2]?.ssr;
  715. const start = Date.now();
  716. const _result = await fn.apply(context, args);
  717. const end = Date.now();
  718. const result = typeof _result === "object" ? _result?.id : _result;
  719. const map = ssr ? idMapSSR : idMap;
  720. if (result && result !== id) {
  721. if (!map[id])
  722. map[id] = [];
  723. map[id].push({ name: plugin2.name, result, start, end });
  724. }
  725. return _result;
  726. });
  727. }
  728. function resolveId(id = "", ssr = false) {
  729. if (id.startsWith("./"))
  730. id = node_path.resolve(config.root, id).replace(/\\/g, "/");
  731. return resolveIdRec(id, ssr);
  732. }
  733. function resolveIdRec(id, ssr = false) {
  734. const map = ssr ? idMapSSR : idMap;
  735. return map[id]?.[0] ? resolveIdRec(map[id][0].result, ssr) : id;
  736. }
  737. function getPluginMetrics(ssr = false) {
  738. const map = {};
  739. const defaultMetricInfo = () => ({
  740. transform: { invokeCount: 0, totalTime: 0 },
  741. resolveId: { invokeCount: 0, totalTime: 0 }
  742. });
  743. config.plugins.forEach((i) => {
  744. map[i.name] = {
  745. ...defaultMetricInfo(),
  746. name: i.name,
  747. enforce: i.enforce
  748. };
  749. });
  750. Object.values(ssr ? transformMapSSR : transformMap).forEach((transformInfos) => {
  751. transformInfos.forEach(({ name, start, end }) => {
  752. if (name === dummyLoadPluginName)
  753. return;
  754. if (!map[name])
  755. map[name] = { ...defaultMetricInfo(), name };
  756. map[name].transform.totalTime += end - start;
  757. map[name].transform.invokeCount += 1;
  758. });
  759. });
  760. Object.values(ssr ? idMapSSR : idMap).forEach((resolveIdInfos) => {
  761. resolveIdInfos.forEach(({ name, start, end }) => {
  762. if (!map[name])
  763. map[name] = { ...defaultMetricInfo(), name };
  764. map[name].resolveId.totalTime += end - start;
  765. map[name].resolveId.invokeCount += 1;
  766. });
  767. });
  768. const metrics = Object.values(map).filter(Boolean).sort((a, b) => a.name.localeCompare(b.name));
  769. return metrics;
  770. }
  771. function configureServer(server) {
  772. const _invalidateModule = server.moduleGraph.invalidateModule;
  773. server.moduleGraph.invalidateModule = function(...args) {
  774. const mod = args[0];
  775. if (mod?.id) {
  776. delete transformMap[mod.id];
  777. delete transformMapSSR[mod.id];
  778. }
  779. return _invalidateModule.apply(this, args);
  780. };
  781. const base = (options.base ?? server.config.base) || "/";
  782. server.middlewares.use(`${base}__inspect`, sirv__default(DIR_CLIENT, {
  783. single: true,
  784. dev: true
  785. }));
  786. const rpcFunctions = {
  787. list,
  788. getIdInfo,
  789. getPluginMetrics,
  790. resolveId,
  791. clear: clearId
  792. };
  793. createRPCServer("vite-plugin-inspect", server.ws, rpcFunctions);
  794. async function getIdInfo(id, ssr = false, clear = false) {
  795. if (clear) {
  796. clearId(id, ssr);
  797. try {
  798. await server.transformRequest(id, { ssr });
  799. } catch {
  800. }
  801. }
  802. const resolvedId = resolveId(id, ssr);
  803. const map = ssr ? transformMapSSR : transformMap;
  804. return {
  805. resolvedId,
  806. transforms: map[resolvedId] || []
  807. };
  808. }
  809. function getModulesInfo(map) {
  810. return Object.keys(map).sort().map((id) => {
  811. const plugins = map[id]?.map((i) => i.name);
  812. const deps = Array.from(server.moduleGraph.getModuleById(id)?.importedModules || []).map((i) => i.id || "").filter(Boolean);
  813. return {
  814. id,
  815. plugins,
  816. deps,
  817. virtual: plugins[0] !== dummyLoadPluginName
  818. };
  819. });
  820. }
  821. function list() {
  822. return {
  823. root: config.root,
  824. modules: getModulesInfo(transformMap),
  825. ssrModules: getModulesInfo(transformMapSSR)
  826. };
  827. }
  828. function clearId(_id, ssr = false) {
  829. const id = resolveId(_id);
  830. if (id) {
  831. const mod = server.moduleGraph.getModuleById(id);
  832. if (mod)
  833. server.moduleGraph.invalidateModule(mod);
  834. const map = ssr ? transformMapSSR : transformMap;
  835. delete map[id];
  836. }
  837. }
  838. const _print = server.printUrls;
  839. server.printUrls = () => {
  840. const colorUrl = (url2) => kolorist.green(url2.replace(/:(\d+)\//, (_, port) => `:${kolorist.bold(port)}/`));
  841. let host = `${config.server.https ? "https" : "http"}://localhost:${config.server.port || "80"}`;
  842. const url = server.resolvedUrls?.local[0];
  843. if (url) {
  844. try {
  845. const u = new URL(url);
  846. host = `${u.protocol}//${u.host}`;
  847. } catch (error) {
  848. console.warn("Parse resolved url failed:", error);
  849. }
  850. }
  851. _print();
  852. console.log(` ${kolorist.green("\u279C")} ${kolorist.bold("Inspect")}: ${colorUrl(`${host}${base}__inspect/`)}`);
  853. };
  854. return rpcFunctions;
  855. }
  856. async function generateBuild() {
  857. const targetDir = node_path.join(config.root, outputDir);
  858. const reportsDir = node_path.join(targetDir, "reports");
  859. await fs__default.mkdir(targetDir, { recursive: true });
  860. await fs__default.copy(DIR_CLIENT, targetDir, { overwrite: true });
  861. await fs__default.writeFile(
  862. node_path.join(targetDir, "index.html"),
  863. (await fs__default.readFile(node_path.join(targetDir, "index.html"), "utf-8")).replace(
  864. 'data-vite-inspect-mode="DEV"',
  865. 'data-vite-inspect-mode="BUILD"'
  866. )
  867. );
  868. await fs__default.rm(reportsDir, {
  869. recursive: true,
  870. force: true
  871. });
  872. await fs__default.mkdir(reportsDir, { recursive: true });
  873. function getModulesInfo(map) {
  874. return Object.keys(map).sort().map((id) => {
  875. const plugins = map[id]?.map((i) => i.name);
  876. return {
  877. id,
  878. deps: [],
  879. plugins,
  880. virtual: plugins[0] !== dummyLoadPluginName && map[id][0].name !== "vite:load-fallback"
  881. };
  882. });
  883. }
  884. function list() {
  885. return {
  886. root: config.root,
  887. modules: getModulesInfo(transformMap),
  888. ssrModules: getModulesInfo(transformMapSSR)
  889. };
  890. }
  891. await fs__default.writeFile(
  892. node_path.join(reportsDir, "list.json"),
  893. JSON.stringify(list(), null, 2),
  894. "utf-8"
  895. );
  896. await fs__default.writeFile(
  897. node_path.join(reportsDir, "metrics.json"),
  898. JSON.stringify(getPluginMetrics(false), null, 2),
  899. "utf-8"
  900. );
  901. await fs__default.writeFile(
  902. node_path.join(reportsDir, "metrics-ssr.json"),
  903. JSON.stringify(getPluginMetrics(true), null, 2),
  904. "utf-8"
  905. );
  906. async function dumpModuleInfo(dir, map, ssr = false) {
  907. await fs__default.ensureDir(dir);
  908. return Promise.all(
  909. Object.entries(map).map(
  910. ([id, info]) => fs__default.writeJSON(
  911. node_path.join(dir, `${hash(id)}.json`),
  912. {
  913. resolvedId: resolveId(id, ssr),
  914. transforms: info
  915. }
  916. )
  917. )
  918. );
  919. }
  920. await dumpModuleInfo(node_path.join(reportsDir, "transform"), transformMap);
  921. await dumpModuleInfo(node_path.join(reportsDir, "transform-ssr"), transformMapSSR, true);
  922. return targetDir;
  923. }
  924. const plugin = {
  925. name: NAME,
  926. enforce: "pre",
  927. apply(_, { command }) {
  928. if (command === "serve" && dev)
  929. return true;
  930. if (command === "build" && build)
  931. return true;
  932. return false;
  933. },
  934. configResolved(_config) {
  935. config = _config;
  936. config.plugins.forEach(hijackPlugin);
  937. const _createResolver = config.createResolver;
  938. config.createResolver = function(...args) {
  939. const _resolver = _createResolver.apply(this, args);
  940. return async function(...args2) {
  941. const id = args2[0];
  942. const aliasOnly = args2[2];
  943. const ssr = args2[3];
  944. const start = Date.now();
  945. const result = await _resolver.apply(this, args2);
  946. const end = Date.now();
  947. const map = ssr ? idMapSSR : idMap;
  948. if (result && result !== id) {
  949. const pluginName = aliasOnly ? "alias" : "vite:resolve (+alias)";
  950. if (!map[id])
  951. map[id] = [];
  952. map[id].push({ name: pluginName, result, start, end });
  953. }
  954. return result;
  955. };
  956. };
  957. },
  958. configureServer(server) {
  959. const rpc = configureServer(server);
  960. plugin.api = {
  961. rpc
  962. };
  963. },
  964. load: {
  965. order: "pre",
  966. handler(id, { ssr } = {}) {
  967. const map = ssr ? transformMapSSR : transformMap;
  968. delete map[id];
  969. return null;
  970. }
  971. },
  972. handleHotUpdate({ modules, server }) {
  973. const ids = modules.map((module) => module.id);
  974. server.ws.send({
  975. type: "custom",
  976. event: "vite-plugin-inspect:update",
  977. data: { ids }
  978. });
  979. },
  980. async buildEnd() {
  981. if (!build)
  982. return;
  983. const dir = await generateBuild();
  984. console.log(kolorist.green("Inspect report generated at"), kolorist.dim(`${dir}`));
  985. }
  986. };
  987. return plugin;
  988. }
  989. PluginInspect.getViteInspectAPI = function(plugins) {
  990. return plugins.find((p) => p.name === NAME)?.api;
  991. };
  992. module.exports = PluginInspect;