版博士V2.0程序
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

пре 1 година
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  1. 'use strict';
  2. Object.defineProperty(exports, '__esModule', { value: true });
  3. var perf_hooks = require('perf_hooks');
  4. var fs = require('fs');
  5. var pathe = require('pathe');
  6. var createDebug = require('debug');
  7. var mlly = require('mlly');
  8. var utils = require('./utils.cjs');
  9. var c = require('picocolors');
  10. var sourceMap = require('./source-map.cjs');
  11. require('node:url');
  12. require('path');
  13. function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
  14. var createDebug__default = /*#__PURE__*/_interopDefaultLegacy(createDebug);
  15. var c__default = /*#__PURE__*/_interopDefaultLegacy(c);
  16. const KNOWN_ASSET_TYPES = [
  17. "png",
  18. "jpe?g",
  19. "jfif",
  20. "pjpeg",
  21. "pjp",
  22. "gif",
  23. "svg",
  24. "ico",
  25. "webp",
  26. "avif",
  27. "mp4",
  28. "webm",
  29. "ogg",
  30. "mp3",
  31. "wav",
  32. "flac",
  33. "aac",
  34. "woff2?",
  35. "eot",
  36. "ttf",
  37. "otf",
  38. "webmanifest",
  39. "pdf",
  40. "txt"
  41. ];
  42. const ESM_EXT_RE = /\.(es|esm|esm-browser|esm-bundler|es6|module)\.js$/;
  43. const ESM_FOLDER_RE = /\/(es|esm)\/(.*\.js)$/;
  44. const defaultInline = [
  45. /virtual:/,
  46. /\.[mc]?ts$/,
  47. /[?&](init|raw|url|inline)\b/,
  48. new RegExp(`\\.(${KNOWN_ASSET_TYPES.join("|")})$`)
  49. ];
  50. const depsExternal = [
  51. /\.cjs\.js$/,
  52. /\.mjs$/
  53. ];
  54. function guessCJSversion(id) {
  55. if (id.match(ESM_EXT_RE)) {
  56. for (const i of [
  57. id.replace(ESM_EXT_RE, ".mjs"),
  58. id.replace(ESM_EXT_RE, ".umd.js"),
  59. id.replace(ESM_EXT_RE, ".cjs.js"),
  60. id.replace(ESM_EXT_RE, ".js")
  61. ]) {
  62. if (fs.existsSync(i))
  63. return i;
  64. }
  65. }
  66. if (id.match(ESM_FOLDER_RE)) {
  67. for (const i of [
  68. id.replace(ESM_FOLDER_RE, "/umd/$1"),
  69. id.replace(ESM_FOLDER_RE, "/cjs/$1"),
  70. id.replace(ESM_FOLDER_RE, "/lib/$1"),
  71. id.replace(ESM_FOLDER_RE, "/$1")
  72. ]) {
  73. if (fs.existsSync(i))
  74. return i;
  75. }
  76. }
  77. }
  78. const _defaultExternalizeCache = /* @__PURE__ */ new Map();
  79. async function shouldExternalize(id, options, cache = _defaultExternalizeCache) {
  80. if (!cache.has(id))
  81. cache.set(id, _shouldExternalize(id, options));
  82. return cache.get(id);
  83. }
  84. async function _shouldExternalize(id, options) {
  85. if (mlly.isNodeBuiltin(id))
  86. return id;
  87. if (id.startsWith("data:"))
  88. return id;
  89. id = patchWindowsImportPath(id);
  90. if ((options == null ? void 0 : options.cacheDir) && id.includes(options.cacheDir))
  91. return id;
  92. if (matchExternalizePattern(id, options == null ? void 0 : options.inline))
  93. return false;
  94. if (matchExternalizePattern(id, options == null ? void 0 : options.external))
  95. return id;
  96. const isNodeModule = id.includes("/node_modules/");
  97. const guessCJS = isNodeModule && (options == null ? void 0 : options.fallbackCJS);
  98. id = guessCJS ? guessCJSversion(id) || id : id;
  99. if (matchExternalizePattern(id, defaultInline))
  100. return false;
  101. if (matchExternalizePattern(id, depsExternal))
  102. return id;
  103. const isDist = id.includes("/dist/");
  104. if ((isNodeModule || isDist) && await mlly.isValidNodeImport(id))
  105. return id;
  106. return false;
  107. }
  108. function matchExternalizePattern(id, patterns) {
  109. if (patterns == null)
  110. return false;
  111. if (patterns === true)
  112. return true;
  113. for (const ex of patterns) {
  114. if (typeof ex === "string") {
  115. if (id.includes(`/node_modules/${ex}/`))
  116. return true;
  117. } else {
  118. if (ex.test(id))
  119. return true;
  120. }
  121. }
  122. return false;
  123. }
  124. function patchWindowsImportPath(path) {
  125. if (path.match(/^\w:\\/))
  126. return `file:///${utils.slash(path)}`;
  127. else if (path.match(/^\w:\//))
  128. return `file:///${path}`;
  129. else
  130. return path;
  131. }
  132. function hashCode(s) {
  133. return s.split("").reduce((a, b) => {
  134. a = (a << 5) - a + b.charCodeAt(0);
  135. return a & a;
  136. }, 0);
  137. }
  138. class Debugger {
  139. constructor(root, options) {
  140. this.options = options;
  141. this.externalizeMap = /* @__PURE__ */ new Map();
  142. if (options.dumpModules)
  143. this.dumpDir = pathe.resolve(root, options.dumpModules === true ? ".vite-node/dump" : options.dumpModules);
  144. if (this.dumpDir) {
  145. if (options.loadDumppedModules)
  146. console.info(c__default["default"].gray(`[vite-node] [debug] load modules from ${this.dumpDir}`));
  147. else
  148. console.info(c__default["default"].gray(`[vite-node] [debug] dump modules to ${this.dumpDir}`));
  149. }
  150. this.initPromise = this.clearDump();
  151. }
  152. async clearDump() {
  153. if (!this.dumpDir)
  154. return;
  155. if (!this.options.loadDumppedModules && fs.existsSync(this.dumpDir))
  156. await fs.promises.rm(this.dumpDir, { recursive: true, force: true });
  157. await fs.promises.mkdir(this.dumpDir, { recursive: true });
  158. }
  159. encodeId(id) {
  160. return `${id.replace(/[^\w@_-]/g, "_").replace(/_+/g, "_")}-${hashCode(id)}.js`;
  161. }
  162. async recordExternalize(id, path) {
  163. if (!this.dumpDir)
  164. return;
  165. this.externalizeMap.set(id, path);
  166. await this.writeInfo();
  167. }
  168. async dumpFile(id, result) {
  169. if (!result || !this.dumpDir)
  170. return;
  171. await this.initPromise;
  172. const name = this.encodeId(id);
  173. return await fs.promises.writeFile(pathe.join(this.dumpDir, name), `// ${id.replace(/\0/g, "\\0")}
  174. ${result.code}`, "utf-8");
  175. }
  176. async loadDump(id) {
  177. if (!this.dumpDir)
  178. return null;
  179. await this.initPromise;
  180. const name = this.encodeId(id);
  181. const path = pathe.join(this.dumpDir, name);
  182. if (!fs.existsSync(path))
  183. return null;
  184. const code = await fs.promises.readFile(path, "utf-8");
  185. return {
  186. code: code.replace(/^\/\/.*?\n/, ""),
  187. map: void 0
  188. };
  189. }
  190. async writeInfo() {
  191. if (!this.dumpDir)
  192. return;
  193. const info = JSON.stringify({
  194. time: new Date().toLocaleString(),
  195. externalize: Object.fromEntries(this.externalizeMap.entries())
  196. }, null, 2);
  197. return fs.promises.writeFile(pathe.join(this.dumpDir, "info.json"), info, "utf-8");
  198. }
  199. }
  200. const debugRequest = createDebug__default["default"]("vite-node:server:request");
  201. class ViteNodeServer {
  202. constructor(server, options = {}) {
  203. this.server = server;
  204. this.options = options;
  205. this.fetchPromiseMap = /* @__PURE__ */ new Map();
  206. this.transformPromiseMap = /* @__PURE__ */ new Map();
  207. this.existingOptimizedDeps = /* @__PURE__ */ new Set();
  208. this.fetchCache = /* @__PURE__ */ new Map();
  209. this.externalizeCache = /* @__PURE__ */ new Map();
  210. var _a, _b;
  211. const ssrOptions = server.config.ssr;
  212. options.deps ?? (options.deps = {});
  213. options.deps.cacheDir = pathe.relative(server.config.root, server.config.cacheDir);
  214. if (ssrOptions) {
  215. if (ssrOptions.noExternal === true) {
  216. (_a = options.deps).inline ?? (_a.inline = true);
  217. } else if (options.deps.inline !== true) {
  218. (_b = options.deps).inline ?? (_b.inline = []);
  219. options.deps.inline.push(...utils.toArray(ssrOptions.noExternal));
  220. }
  221. }
  222. if (process.env.VITE_NODE_DEBUG_DUMP) {
  223. options.debug = Object.assign({
  224. dumpModules: !!process.env.VITE_NODE_DEBUG_DUMP,
  225. loadDumppedModules: process.env.VITE_NODE_DEBUG_DUMP === "load"
  226. }, options.debug ?? {});
  227. }
  228. if (options.debug)
  229. this.debugger = new Debugger(server.config.root, options.debug);
  230. }
  231. shouldExternalize(id) {
  232. return shouldExternalize(id, this.options.deps, this.externalizeCache);
  233. }
  234. async ensureExists(id) {
  235. if (this.existingOptimizedDeps.has(id))
  236. return true;
  237. if (fs.existsSync(id)) {
  238. this.existingOptimizedDeps.add(id);
  239. return true;
  240. }
  241. return new Promise((resolve2) => {
  242. setTimeout(() => {
  243. this.ensureExists(id).then(() => {
  244. resolve2(true);
  245. });
  246. });
  247. });
  248. }
  249. async resolveId(id, importer, transformMode) {
  250. if (importer && !importer.startsWith(this.server.config.root))
  251. importer = pathe.resolve(this.server.config.root, importer);
  252. const mode = transformMode ?? (importer && this.getTransformMode(importer) || "ssr");
  253. return this.server.pluginContainer.resolveId(id, importer, { ssr: mode === "ssr" });
  254. }
  255. getSourceMap(source) {
  256. var _a, _b;
  257. const fetchResult = (_a = this.fetchCache.get(source)) == null ? void 0 : _a.result;
  258. if (fetchResult == null ? void 0 : fetchResult.map)
  259. return fetchResult.map;
  260. const ssrTransformResult = (_b = this.server.moduleGraph.getModuleById(source)) == null ? void 0 : _b.ssrTransformResult;
  261. return (ssrTransformResult == null ? void 0 : ssrTransformResult.map) || null;
  262. }
  263. async fetchModule(id, transformMode) {
  264. id = utils.normalizeModuleId(id);
  265. if (!this.fetchPromiseMap.has(id)) {
  266. this.fetchPromiseMap.set(
  267. id,
  268. this._fetchModule(id, transformMode).then((r) => {
  269. return this.options.sourcemap !== true ? { ...r, map: void 0 } : r;
  270. }).finally(() => {
  271. this.fetchPromiseMap.delete(id);
  272. })
  273. );
  274. }
  275. return this.fetchPromiseMap.get(id);
  276. }
  277. async transformRequest(id) {
  278. if (!this.transformPromiseMap.has(id)) {
  279. this.transformPromiseMap.set(
  280. id,
  281. this._transformRequest(id).finally(() => {
  282. this.transformPromiseMap.delete(id);
  283. })
  284. );
  285. }
  286. return this.transformPromiseMap.get(id);
  287. }
  288. getTransformMode(id) {
  289. var _a, _b, _c, _d;
  290. const withoutQuery = id.split("?")[0];
  291. if ((_b = (_a = this.options.transformMode) == null ? void 0 : _a.web) == null ? void 0 : _b.some((r) => withoutQuery.match(r)))
  292. return "web";
  293. if ((_d = (_c = this.options.transformMode) == null ? void 0 : _c.ssr) == null ? void 0 : _d.some((r) => withoutQuery.match(r)))
  294. return "ssr";
  295. if (withoutQuery.match(/\.([cm]?[jt]sx?|json)$/))
  296. return "ssr";
  297. return "web";
  298. }
  299. async _fetchModule(id, transformMode) {
  300. var _a, _b;
  301. let result;
  302. const cacheDir = (_a = this.options.deps) == null ? void 0 : _a.cacheDir;
  303. if (cacheDir && id.includes(cacheDir)) {
  304. if (!id.startsWith(this.server.config.root))
  305. id = pathe.join(this.server.config.root, id);
  306. const timeout = setTimeout(() => {
  307. throw new Error(`ViteNodeServer: ${id} not found. This is a bug, please report it.`);
  308. }, 5e3);
  309. await this.ensureExists(id);
  310. clearTimeout(timeout);
  311. }
  312. const { path: filePath } = utils.toFilePath(id, this.server.config.root);
  313. const module = this.server.moduleGraph.getModuleById(id);
  314. const timestamp = module ? module.lastHMRTimestamp : null;
  315. const cache = this.fetchCache.get(filePath);
  316. if (timestamp && cache && cache.timestamp >= timestamp)
  317. return cache.result;
  318. const time = Date.now();
  319. const externalize = await this.shouldExternalize(filePath);
  320. let duration;
  321. if (externalize) {
  322. result = { externalize };
  323. (_b = this.debugger) == null ? void 0 : _b.recordExternalize(id, externalize);
  324. } else {
  325. const start = perf_hooks.performance.now();
  326. const r = await this._transformRequest(id, transformMode);
  327. duration = perf_hooks.performance.now() - start;
  328. result = { code: r == null ? void 0 : r.code, map: r == null ? void 0 : r.map };
  329. }
  330. this.fetchCache.set(filePath, {
  331. duration,
  332. timestamp: time,
  333. result
  334. });
  335. return result;
  336. }
  337. async processTransformResult(result) {
  338. return sourceMap.withInlineSourcemap(result);
  339. }
  340. async _transformRequest(id, customTransformMode) {
  341. var _a, _b, _c, _d;
  342. debugRequest(id);
  343. let result = null;
  344. if ((_a = this.options.debug) == null ? void 0 : _a.loadDumppedModules) {
  345. result = await ((_b = this.debugger) == null ? void 0 : _b.loadDump(id)) ?? null;
  346. if (result)
  347. return result;
  348. }
  349. const transformMode = customTransformMode ?? this.getTransformMode(id);
  350. if (transformMode === "web") {
  351. result = await this.server.transformRequest(id);
  352. if (result)
  353. result = await this.server.ssrTransform(result.code, result.map, id);
  354. } else {
  355. result = await this.server.transformRequest(id, { ssr: true });
  356. }
  357. const sourcemap = this.options.sourcemap ?? "inline";
  358. if (sourcemap === "inline" && result && !id.includes("node_modules"))
  359. result = await this.processTransformResult(result);
  360. if ((_c = this.options.debug) == null ? void 0 : _c.dumpModules)
  361. await ((_d = this.debugger) == null ? void 0 : _d.dumpFile(id, result));
  362. return result;
  363. }
  364. }
  365. exports.ViteNodeServer = ViteNodeServer;
  366. exports.guessCJSversion = guessCJSversion;
  367. exports.shouldExternalize = shouldExternalize;