vite-node 3.2.4 → 4.0.0-beta.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/server.cjs CHANGED
@@ -37,8 +37,7 @@ var esModuleLexer__namespace = /*#__PURE__*/_interopNamespaceDefault(esModuleLex
37
37
  /* eslint-disable no-console */
38
38
  function hashCode(s) {
39
39
  return s.split("").reduce((a, b) => {
40
- a = (a << 5) - a + b.charCodeAt(0);
41
- return a & a;
40
+ return a = (a << 5) - a + b.charCodeAt(0), a & a;
42
41
  }, 0);
43
42
  }
44
43
  class Debugger {
@@ -46,27 +45,25 @@ class Debugger {
46
45
  initPromise;
47
46
  externalizeMap = /* @__PURE__ */ new Map();
48
47
  constructor(root, options) {
49
- this.options = options;
50
- if (options.dumpModules) this.dumpDir = pathe.resolve(root, options.dumpModules === true ? ".vite-node/dump" : options.dumpModules);
48
+ if (this.options = options, options.dumpModules) this.dumpDir = pathe.resolve(root, options.dumpModules === true ? ".vite-node/dump" : options.dumpModules);
51
49
  if (this.dumpDir) if (options.loadDumppedModules) console.info(browser.s.gray(`[vite-node] [debug] load modules from ${this.dumpDir}`));
52
50
  else console.info(browser.s.gray(`[vite-node] [debug] dump modules to ${this.dumpDir}`));
53
51
  this.initPromise = this.clearDump();
54
52
  }
55
53
  async clearDump() {
56
- if (!this.dumpDir) return;
57
- if (!this.options.loadDumppedModules && fs.existsSync(this.dumpDir)) await fs.promises.rm(this.dumpDir, {
58
- recursive: true,
59
- force: true
60
- });
61
- await fs.promises.mkdir(this.dumpDir, { recursive: true });
54
+ if (this.dumpDir) {
55
+ if (!this.options.loadDumppedModules && fs.existsSync(this.dumpDir)) await fs.promises.rm(this.dumpDir, {
56
+ recursive: true,
57
+ force: true
58
+ });
59
+ await fs.promises.mkdir(this.dumpDir, { recursive: true });
60
+ }
62
61
  }
63
62
  encodeId(id) {
64
63
  return `${id.replace(/[^\w@\-]/g, "_").replace(/_+/g, "_")}-${hashCode(id)}.js`;
65
64
  }
66
65
  async recordExternalize(id, path) {
67
- if (!this.dumpDir) return;
68
- this.externalizeMap.set(id, path);
69
- await this.writeInfo();
66
+ this.dumpDir && (this.externalizeMap.set(id, path), await this.writeInfo());
70
67
  }
71
68
  async dumpFile(id, result) {
72
69
  if (!result || !this.dumpDir) return;
@@ -77,8 +74,7 @@ class Debugger {
77
74
  async loadDump(id) {
78
75
  if (!this.dumpDir) return null;
79
76
  await this.initPromise;
80
- const name = this.encodeId(id);
81
- const path = pathe.join(this.dumpDir, name);
77
+ const name = this.encodeId(id), path = pathe.join(this.dumpDir, name);
82
78
  if (!fs.existsSync(path)) return null;
83
79
  const code = await fs.promises.readFile(path, "utf-8");
84
80
  return {
@@ -101,16 +97,12 @@ const BUILTIN_EXTENSIONS = new Set([
101
97
  ".cjs",
102
98
  ".node",
103
99
  ".wasm"
104
- ]);
105
- const ESM_EXT_RE = /\.(es|esm|esm-browser|esm-bundler|es6|module)\.js$/;
106
- const ESM_FOLDER_RE = /\/(es|esm)\/(.*\.js)$/;
107
- const defaultInline = [
100
+ ]), ESM_EXT_RE = /\.(es|esm|esm-browser|esm-bundler|es6|module)\.js$/, ESM_FOLDER_RE = /\/(es|esm)\/(.*\.js)$/, defaultInline = [
108
101
  /virtual:/,
109
102
  /\.[mc]?ts$/,
110
103
  /[?&](init|raw|url|inline)\b/,
111
104
  constants.KNOWN_ASSET_RE
112
- ];
113
- const depsExternal = [/\/node_modules\/.*\.cjs\.js$/, /\/node_modules\/.*\.mjs$/];
105
+ ], depsExternal = [/\/node_modules\/.*\.cjs\.js$/, /\/node_modules\/.*\.mjs$/];
114
106
  function guessCJSversion(id) {
115
107
  if (id.match(ESM_EXT_RE)) {
116
108
  for (const i of [
@@ -140,8 +132,7 @@ async function isValidNodeImport(id) {
140
132
  if (/\.(?:\w+-)?esm?(?:-\w+)?\.js$|\/esm?\//.test(id)) return false;
141
133
  try {
142
134
  await esModuleLexer__namespace.init;
143
- const code = await fs.promises.readFile(id, "utf8");
144
- const [, , , hasModuleSyntax] = esModuleLexer__namespace.parse(code);
135
+ const code = await fs.promises.readFile(id, "utf8"), [, , , hasModuleSyntax] = esModuleLexer__namespace.parse(code);
145
136
  return !hasModuleSyntax;
146
137
  } catch {
147
138
  return false;
@@ -153,26 +144,18 @@ async function shouldExternalize(id, options, cache = _defaultExternalizeCache)
153
144
  return cache.get(id);
154
145
  }
155
146
  async function _shouldExternalize(id, options) {
156
- if (utils.isNodeBuiltin(id)) return id;
157
147
  // data: should be processed by native import,
158
148
  // since it is a feature of ESM.
159
149
  // also externalize network imports since nodejs allows it when --experimental-network-imports
160
- if (id.startsWith("data:") || /^(?:https?:)?\/\//.test(id)) return id;
150
+ if (utils.isNodeBuiltin(id) || id.startsWith("data:") || /^(?:https?:)?\/\//.test(id)) return id;
161
151
  id = patchWindowsImportPath(id);
162
152
  const moduleDirectories = (options === null || options === void 0 ? void 0 : options.moduleDirectories) || ["/node_modules/"];
163
- if (matchExternalizePattern(id, moduleDirectories, options === null || options === void 0 ? void 0 : options.inline)) return false;
164
- if ((options === null || options === void 0 ? void 0 : options.inlineFiles) && (options === null || options === void 0 ? void 0 : options.inlineFiles.includes(id))) return false;
165
- if (matchExternalizePattern(id, moduleDirectories, options === null || options === void 0 ? void 0 : options.external)) return id;
153
+ if (matchExternalizePattern(id, moduleDirectories, options === null || options === void 0 ? void 0 : options.inline) || (options === null || options === void 0 ? void 0 : options.inlineFiles) && (options === null || options === void 0 ? void 0 : options.inlineFiles.includes(id))) return false;
166
154
  // Unless the user explicitly opted to inline them, externalize Vite deps.
167
155
  // They are too big to inline by default.
168
- if ((options === null || options === void 0 ? void 0 : options.cacheDir) && id.includes(options.cacheDir)) return id;
169
- const isLibraryModule = moduleDirectories.some((dir) => id.includes(dir));
170
- const guessCJS = isLibraryModule && (options === null || options === void 0 ? void 0 : options.fallbackCJS);
171
- id = guessCJS ? guessCJSversion(id) || id : id;
172
- if (matchExternalizePattern(id, moduleDirectories, defaultInline)) return false;
173
- if (matchExternalizePattern(id, moduleDirectories, depsExternal)) return id;
174
- if (isLibraryModule && await isValidNodeImport(id)) return id;
175
- return false;
156
+ if (matchExternalizePattern(id, moduleDirectories, options === null || options === void 0 ? void 0 : options.external) || (options === null || options === void 0 ? void 0 : options.cacheDir) && id.includes(options.cacheDir)) return id;
157
+ const isLibraryModule = moduleDirectories.some((dir) => id.includes(dir)), guessCJS = isLibraryModule && (options === null || options === void 0 ? void 0 : options.fallbackCJS);
158
+ return id = guessCJS ? guessCJSversion(id) || id : id, matchExternalizePattern(id, moduleDirectories, defaultInline) ? false : matchExternalizePattern(id, moduleDirectories, depsExternal) || isLibraryModule && await isValidNodeImport(id) ? id : false;
176
159
  }
177
160
  function matchExternalizePattern(id, moduleDirectories, patterns) {
178
161
  if (patterns == null) return false;
@@ -183,9 +166,7 @@ function matchExternalizePattern(id, moduleDirectories, patterns) {
183
166
  return false;
184
167
  }
185
168
  function patchWindowsImportPath(path) {
186
- if (path.match(/^\w:\\/)) return `file:///${utils.slash(path)}`;
187
- else if (path.match(/^\w:\//)) return `file:///${path}`;
188
- else return path;
169
+ return path.match(/^\w:\\/) ? `file:///${utils.slash(path)}` : path.match(/^\w:\//) ? `file:///${path}` : path;
189
170
  }
190
171
 
191
172
  const debugRequest = createDebug("vite-node:server:request");
@@ -212,12 +193,9 @@ class ViteNodeServer {
212
193
  debugger;
213
194
  constructor(server, options = {}) {
214
195
  var _options$deps3;
215
- this.server = server;
216
- this.options = options;
196
+ this.server = server, this.options = options;
217
197
  const ssrOptions = server.config.ssr;
218
- options.deps ?? (options.deps = {});
219
- options.deps.cacheDir = pathe.relative(server.config.root, options.deps.cacheDir || server.config.cacheDir);
220
- if (ssrOptions) {
198
+ if (options.deps ?? (options.deps = {}), options.deps.cacheDir = pathe.relative(server.config.root, options.deps.cacheDir || server.config.cacheDir), ssrOptions) {
221
199
  // we don't externalize ssr, because it has different semantics in Vite
222
200
  // if (ssrOptions.external) {
223
201
  // options.deps.external ??= []
@@ -244,32 +222,24 @@ class ViteNodeServer {
244
222
  return [resolvedId, node_url.pathToFileURL(resolvedId).href];
245
223
  });
246
224
  (_options$deps3 = options.deps).moduleDirectories ?? (_options$deps3.moduleDirectories = []);
247
- const envValue = process.env.VITE_NODE_DEPS_MODULE_DIRECTORIES || process.env.npm_config_VITE_NODE_DEPS_MODULE_DIRECTORIES;
248
- const customModuleDirectories = envValue === null || envValue === void 0 ? void 0 : envValue.split(",");
225
+ const envValue = process.env.VITE_NODE_DEPS_MODULE_DIRECTORIES || process.env.npm_config_VITE_NODE_DEPS_MODULE_DIRECTORIES, customModuleDirectories = envValue === null || envValue === void 0 ? void 0 : envValue.split(",");
249
226
  if (customModuleDirectories) options.deps.moduleDirectories.push(...customModuleDirectories);
250
- options.deps.moduleDirectories = options.deps.moduleDirectories.map((dir) => {
227
+ // always add node_modules as a module directory
228
+ if (options.deps.moduleDirectories = options.deps.moduleDirectories.map((dir) => {
251
229
  if (!dir.startsWith("/")) dir = `/${dir}`;
252
230
  if (!dir.endsWith("/")) dir += "/";
253
231
  return pathe.normalize(dir);
254
- });
255
- // always add node_modules as a module directory
256
- if (!options.deps.moduleDirectories.includes("/node_modules/")) options.deps.moduleDirectories.push("/node_modules/");
232
+ }), !options.deps.moduleDirectories.includes("/node_modules/")) options.deps.moduleDirectories.push("/node_modules/");
257
233
  }
258
234
  shouldExternalize(id) {
259
235
  return shouldExternalize(id, this.options.deps, this.externalizeCache);
260
236
  }
261
237
  getTotalDuration() {
262
- const ssrDurations = [...this.durations.ssr.values()].flat();
263
- const webDurations = [...this.durations.web.values()].flat();
238
+ const ssrDurations = [...this.durations.ssr.values()].flat(), webDurations = [...this.durations.web.values()].flat();
264
239
  return [...ssrDurations, ...webDurations].reduce((a, b) => a + b, 0);
265
240
  }
266
241
  async ensureExists(id) {
267
- if (this.existingOptimizedDeps.has(id)) return true;
268
- if (fs.existsSync(id)) {
269
- this.existingOptimizedDeps.add(id);
270
- return true;
271
- }
272
- return new Promise((resolve) => {
242
+ return this.existingOptimizedDeps.has(id) ? true : fs.existsSync(id) ? (this.existingOptimizedDeps.add(id), true) : new Promise((resolve) => {
273
243
  setTimeout(() => {
274
244
  this.ensureExists(id).then(() => {
275
245
  resolve(true);
@@ -324,18 +294,13 @@ class ViteNodeServer {
324
294
  }
325
295
  async transformModule(id, transformMode) {
326
296
  if (transformMode !== "web") throw new Error("`transformModule` only supports `transformMode: \"web\"`.");
327
- const normalizedId = utils.normalizeModuleId(id);
328
- const mod = this.server.moduleGraph.getModuleById(normalizedId);
329
- const result = (mod === null || mod === void 0 ? void 0 : mod.transformResult) || await this.server.transformRequest(normalizedId);
297
+ const normalizedId = utils.normalizeModuleId(id), mod = this.server.moduleGraph.getModuleById(normalizedId), result = (mod === null || mod === void 0 ? void 0 : mod.transformResult) || await this.server.transformRequest(normalizedId);
330
298
  return { code: result === null || result === void 0 ? void 0 : result.code };
331
299
  }
332
300
  getTransformMode(id) {
333
301
  var _this$options$transfo, _this$options$transfo2;
334
302
  const withoutQuery = id.split("?")[0];
335
- if ((_this$options$transfo = this.options.transformMode) === null || _this$options$transfo === void 0 || (_this$options$transfo = _this$options$transfo.web) === null || _this$options$transfo === void 0 ? void 0 : _this$options$transfo.some((r) => withoutQuery.match(r))) return "web";
336
- if ((_this$options$transfo2 = this.options.transformMode) === null || _this$options$transfo2 === void 0 || (_this$options$transfo2 = _this$options$transfo2.ssr) === null || _this$options$transfo2 === void 0 ? void 0 : _this$options$transfo2.some((r) => withoutQuery.match(r))) return "ssr";
337
- if (withoutQuery.match(/\.([cm]?[jt]sx?|json)$/)) return "ssr";
338
- return "web";
303
+ return ((_this$options$transfo = this.options.transformMode) === null || _this$options$transfo === void 0 || (_this$options$transfo = _this$options$transfo.web) === null || _this$options$transfo === void 0 ? void 0 : _this$options$transfo.some((r) => withoutQuery.match(r))) ? "web" : ((_this$options$transfo2 = this.options.transformMode) === null || _this$options$transfo2 === void 0 || (_this$options$transfo2 = _this$options$transfo2.ssr) === null || _this$options$transfo2 === void 0 ? void 0 : _this$options$transfo2.some((r) => withoutQuery.match(r))) || withoutQuery.match(/\.([cm]?[jt]sx?|json)$/) ? "ssr" : "web";
339
304
  }
340
305
  getChangedModule(id, file) {
341
306
  const module = this.server.moduleGraph.getModuleById(id) || this.server.moduleGraph.getModuleById(file);
@@ -344,14 +309,10 @@ class ViteNodeServer {
344
309
  if (!_modules || !_modules.size) return null;
345
310
  // find the latest changed module
346
311
  const modules = [..._modules];
347
- let mod = modules[0];
348
- let latestMax = -1;
312
+ let mod = modules[0], latestMax = -1;
349
313
  for (const m of _modules) {
350
314
  const timestamp = Math.max(m.lastHMRTimestamp, m.lastInvalidationTimestamp);
351
- if (timestamp > latestMax) {
352
- latestMax = timestamp;
353
- mod = m;
354
- }
315
+ if (timestamp > latestMax) latestMax = timestamp, mod = m;
355
316
  }
356
317
  return mod;
357
318
  }
@@ -364,29 +325,18 @@ class ViteNodeServer {
364
325
  const timeout = setTimeout(() => {
365
326
  throw new Error(`ViteNodeServer: ${id} not found. This is a bug, please report it.`);
366
327
  }, 5e3);
367
- await this.ensureExists(id);
368
- clearTimeout(timeout);
328
+ await this.ensureExists(id), clearTimeout(timeout);
369
329
  }
370
- const { path: filePath } = utils.toFilePath(id, this.server.config.root);
371
- const moduleNode = this.getChangedModule(id, filePath);
372
- const cache = this.fetchCaches[transformMode].get(filePath);
373
- // lastUpdateTimestamp is the timestamp that marks the last time the module was changed
374
- // if lastUpdateTimestamp is 0, then the module was not changed since the server started
375
- // we test "timestamp === 0" for expressiveness, but it's not necessary
376
- const timestamp = moduleNode ? Math.max(moduleNode.lastHMRTimestamp, moduleNode.lastInvalidationTimestamp) : 0;
330
+ const { path: filePath } = utils.toFilePath(id, this.server.config.root), moduleNode = this.getChangedModule(id, filePath), cache = this.fetchCaches[transformMode].get(filePath), timestamp = moduleNode ? Math.max(moduleNode.lastHMRTimestamp, moduleNode.lastInvalidationTimestamp) : 0;
377
331
  if (cache && (timestamp === 0 || cache.timestamp >= timestamp)) return cache.result;
378
- const time = Date.now();
379
- const externalize = await this.shouldExternalize(filePath);
332
+ const time = Date.now(), externalize = await this.shouldExternalize(filePath);
380
333
  let duration;
381
334
  if (externalize) {
382
335
  var _this$debugger;
383
- result = { externalize };
384
- (_this$debugger = this.debugger) === null || _this$debugger === void 0 || _this$debugger.recordExternalize(id, externalize);
336
+ result = { externalize }, (_this$debugger = this.debugger) === null || _this$debugger === void 0 || _this$debugger.recordExternalize(id, externalize);
385
337
  } else {
386
- const start = node_perf_hooks.performance.now();
387
- const r = await this._transformRequest(id, filePath, transformMode);
388
- duration = node_perf_hooks.performance.now() - start;
389
- result = {
338
+ const start = node_perf_hooks.performance.now(), r = await this._transformRequest(id, filePath, transformMode);
339
+ duration = node_perf_hooks.performance.now() - start, result = {
390
340
  code: r === null || r === void 0 ? void 0 : r.code,
391
341
  map: r === null || r === void 0 ? void 0 : r.map
392
342
  };
@@ -395,12 +345,8 @@ class ViteNodeServer {
395
345
  duration,
396
346
  timestamp: time,
397
347
  result
398
- };
399
- const durations = this.durations[transformMode].get(filePath) || [];
400
- this.durations[transformMode].set(filePath, [...durations, duration ?? 0]);
401
- this.fetchCaches[transformMode].set(filePath, cacheEntry);
402
- this.fetchCache.set(filePath, cacheEntry);
403
- return result;
348
+ }, durations = this.durations[transformMode].get(filePath) || [];
349
+ return this.durations[transformMode].set(filePath, [...durations, duration ?? 0]), this.fetchCaches[transformMode].set(filePath, cacheEntry), this.fetchCache.set(filePath, cacheEntry), result;
404
350
  }
405
351
  async processTransformResult(filepath, result) {
406
352
  const mod = this.server.moduleGraph.getModuleById(filepath);
@@ -416,14 +362,10 @@ class ViteNodeServer {
416
362
  let result = null;
417
363
  if ((_this$options$debug = this.options.debug) === null || _this$options$debug === void 0 ? void 0 : _this$options$debug.loadDumppedModules) {
418
364
  var _this$debugger2;
419
- result = await ((_this$debugger2 = this.debugger) === null || _this$debugger2 === void 0 ? void 0 : _this$debugger2.loadDump(id)) ?? null;
420
- if (result) return result;
365
+ if (result = await ((_this$debugger2 = this.debugger) === null || _this$debugger2 === void 0 ? void 0 : _this$debugger2.loadDump(id)) ?? null, result) return result;
421
366
  }
422
367
  if (transformMode === "web") {
423
- // for components like Vue, we want to use the client side
424
- // plugins but then convert the code to be consumed by the server
425
- result = await this.server.transformRequest(id);
426
- if (result) result = await this.server.ssrTransform(result.code, result.map, id);
368
+ if (result = await this.server.transformRequest(id), result) result = await this.server.ssrTransform(result.code, result.map, id);
427
369
  } else result = await this.server.transformRequest(id, { ssr: true });
428
370
  const sourcemap = this.options.sourcemap ?? "inline";
429
371
  if (sourcemap === "inline" && result) result = await this.processTransformResult(filepath, result);
package/dist/server.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { TransformResult, ViteDevServer } from 'vite';
2
- import { D as DebuggerOptions, c as DepsHandlingOptions, V as ViteNodeServerOptions, F as FetchResult, d as ViteNodeResolveId } from './index.d-DGmxD2U7.js';
3
- import { E as EncodedSourceMap } from './trace-mapping.d-DLVdEqOp.js';
2
+ import { D as DebuggerOptions, c as DepsHandlingOptions, V as ViteNodeServerOptions, F as FetchResult, d as ViteNodeResolveId } from './index.d-uN06xifv.js';
3
+ import { E as EncodedSourceMap } from './trace-mapping.d-BWFx6tPc.js';
4
4
 
5
5
  declare class Debugger {
6
6
  options: DebuggerOptions;
@@ -46,7 +46,7 @@ declare class ViteNodeServer {
46
46
  fetchResult(id: string, mode: "web" | "ssr"): Promise<FetchResult>;
47
47
  transformRequest(id: string, filepath?: string, transformMode?: "web" | "ssr"): Promise<TransformResult | null | undefined>;
48
48
  transformModule(id: string, transformMode?: "web" | "ssr"): Promise<{
49
- code: string | undefined
49
+ code: string | undefined;
50
50
  }>;
51
51
  getTransformMode(id: string): "ssr" | "web";
52
52
  private getChangedModule;
package/dist/server.mjs CHANGED
@@ -16,8 +16,7 @@ import 'node:path';
16
16
  /* eslint-disable no-console */
17
17
  function hashCode(s) {
18
18
  return s.split("").reduce((a, b) => {
19
- a = (a << 5) - a + b.charCodeAt(0);
20
- return a & a;
19
+ return a = (a << 5) - a + b.charCodeAt(0), a & a;
21
20
  }, 0);
22
21
  }
23
22
  class Debugger {
@@ -25,27 +24,25 @@ class Debugger {
25
24
  initPromise;
26
25
  externalizeMap = /* @__PURE__ */ new Map();
27
26
  constructor(root, options) {
28
- this.options = options;
29
- if (options.dumpModules) this.dumpDir = resolve(root, options.dumpModules === true ? ".vite-node/dump" : options.dumpModules);
27
+ if (this.options = options, options.dumpModules) this.dumpDir = resolve(root, options.dumpModules === true ? ".vite-node/dump" : options.dumpModules);
30
28
  if (this.dumpDir) if (options.loadDumppedModules) console.info(s.gray(`[vite-node] [debug] load modules from ${this.dumpDir}`));
31
29
  else console.info(s.gray(`[vite-node] [debug] dump modules to ${this.dumpDir}`));
32
30
  this.initPromise = this.clearDump();
33
31
  }
34
32
  async clearDump() {
35
- if (!this.dumpDir) return;
36
- if (!this.options.loadDumppedModules && existsSync(this.dumpDir)) await promises.rm(this.dumpDir, {
37
- recursive: true,
38
- force: true
39
- });
40
- await promises.mkdir(this.dumpDir, { recursive: true });
33
+ if (this.dumpDir) {
34
+ if (!this.options.loadDumppedModules && existsSync(this.dumpDir)) await promises.rm(this.dumpDir, {
35
+ recursive: true,
36
+ force: true
37
+ });
38
+ await promises.mkdir(this.dumpDir, { recursive: true });
39
+ }
41
40
  }
42
41
  encodeId(id) {
43
42
  return `${id.replace(/[^\w@\-]/g, "_").replace(/_+/g, "_")}-${hashCode(id)}.js`;
44
43
  }
45
44
  async recordExternalize(id, path) {
46
- if (!this.dumpDir) return;
47
- this.externalizeMap.set(id, path);
48
- await this.writeInfo();
45
+ this.dumpDir && (this.externalizeMap.set(id, path), await this.writeInfo());
49
46
  }
50
47
  async dumpFile(id, result) {
51
48
  if (!result || !this.dumpDir) return;
@@ -56,8 +53,7 @@ class Debugger {
56
53
  async loadDump(id) {
57
54
  if (!this.dumpDir) return null;
58
55
  await this.initPromise;
59
- const name = this.encodeId(id);
60
- const path = join(this.dumpDir, name);
56
+ const name = this.encodeId(id), path = join(this.dumpDir, name);
61
57
  if (!existsSync(path)) return null;
62
58
  const code = await promises.readFile(path, "utf-8");
63
59
  return {
@@ -80,16 +76,12 @@ const BUILTIN_EXTENSIONS = new Set([
80
76
  ".cjs",
81
77
  ".node",
82
78
  ".wasm"
83
- ]);
84
- const ESM_EXT_RE = /\.(es|esm|esm-browser|esm-bundler|es6|module)\.js$/;
85
- const ESM_FOLDER_RE = /\/(es|esm)\/(.*\.js)$/;
86
- const defaultInline = [
79
+ ]), ESM_EXT_RE = /\.(es|esm|esm-browser|esm-bundler|es6|module)\.js$/, ESM_FOLDER_RE = /\/(es|esm)\/(.*\.js)$/, defaultInline = [
87
80
  /virtual:/,
88
81
  /\.[mc]?ts$/,
89
82
  /[?&](init|raw|url|inline)\b/,
90
83
  KNOWN_ASSET_RE
91
- ];
92
- const depsExternal = [/\/node_modules\/.*\.cjs\.js$/, /\/node_modules\/.*\.mjs$/];
84
+ ], depsExternal = [/\/node_modules\/.*\.cjs\.js$/, /\/node_modules\/.*\.mjs$/];
93
85
  function guessCJSversion(id) {
94
86
  if (id.match(ESM_EXT_RE)) {
95
87
  for (const i of [
@@ -119,8 +111,7 @@ async function isValidNodeImport(id) {
119
111
  if (/\.(?:\w+-)?esm?(?:-\w+)?\.js$|\/esm?\//.test(id)) return false;
120
112
  try {
121
113
  await esModuleLexer.init;
122
- const code = await promises.readFile(id, "utf8");
123
- const [, , , hasModuleSyntax] = esModuleLexer.parse(code);
114
+ const code = await promises.readFile(id, "utf8"), [, , , hasModuleSyntax] = esModuleLexer.parse(code);
124
115
  return !hasModuleSyntax;
125
116
  } catch {
126
117
  return false;
@@ -132,26 +123,18 @@ async function shouldExternalize(id, options, cache = _defaultExternalizeCache)
132
123
  return cache.get(id);
133
124
  }
134
125
  async function _shouldExternalize(id, options) {
135
- if (isNodeBuiltin(id)) return id;
136
126
  // data: should be processed by native import,
137
127
  // since it is a feature of ESM.
138
128
  // also externalize network imports since nodejs allows it when --experimental-network-imports
139
- if (id.startsWith("data:") || /^(?:https?:)?\/\//.test(id)) return id;
129
+ if (isNodeBuiltin(id) || id.startsWith("data:") || /^(?:https?:)?\/\//.test(id)) return id;
140
130
  id = patchWindowsImportPath(id);
141
131
  const moduleDirectories = (options === null || options === void 0 ? void 0 : options.moduleDirectories) || ["/node_modules/"];
142
- if (matchExternalizePattern(id, moduleDirectories, options === null || options === void 0 ? void 0 : options.inline)) return false;
143
- if ((options === null || options === void 0 ? void 0 : options.inlineFiles) && (options === null || options === void 0 ? void 0 : options.inlineFiles.includes(id))) return false;
144
- if (matchExternalizePattern(id, moduleDirectories, options === null || options === void 0 ? void 0 : options.external)) return id;
132
+ if (matchExternalizePattern(id, moduleDirectories, options === null || options === void 0 ? void 0 : options.inline) || (options === null || options === void 0 ? void 0 : options.inlineFiles) && (options === null || options === void 0 ? void 0 : options.inlineFiles.includes(id))) return false;
145
133
  // Unless the user explicitly opted to inline them, externalize Vite deps.
146
134
  // They are too big to inline by default.
147
- if ((options === null || options === void 0 ? void 0 : options.cacheDir) && id.includes(options.cacheDir)) return id;
148
- const isLibraryModule = moduleDirectories.some((dir) => id.includes(dir));
149
- const guessCJS = isLibraryModule && (options === null || options === void 0 ? void 0 : options.fallbackCJS);
150
- id = guessCJS ? guessCJSversion(id) || id : id;
151
- if (matchExternalizePattern(id, moduleDirectories, defaultInline)) return false;
152
- if (matchExternalizePattern(id, moduleDirectories, depsExternal)) return id;
153
- if (isLibraryModule && await isValidNodeImport(id)) return id;
154
- return false;
135
+ if (matchExternalizePattern(id, moduleDirectories, options === null || options === void 0 ? void 0 : options.external) || (options === null || options === void 0 ? void 0 : options.cacheDir) && id.includes(options.cacheDir)) return id;
136
+ const isLibraryModule = moduleDirectories.some((dir) => id.includes(dir)), guessCJS = isLibraryModule && (options === null || options === void 0 ? void 0 : options.fallbackCJS);
137
+ return id = guessCJS ? guessCJSversion(id) || id : id, matchExternalizePattern(id, moduleDirectories, defaultInline) ? false : matchExternalizePattern(id, moduleDirectories, depsExternal) || isLibraryModule && await isValidNodeImport(id) ? id : false;
155
138
  }
156
139
  function matchExternalizePattern(id, moduleDirectories, patterns) {
157
140
  if (patterns == null) return false;
@@ -162,9 +145,7 @@ function matchExternalizePattern(id, moduleDirectories, patterns) {
162
145
  return false;
163
146
  }
164
147
  function patchWindowsImportPath(path) {
165
- if (path.match(/^\w:\\/)) return `file:///${slash(path)}`;
166
- else if (path.match(/^\w:\//)) return `file:///${path}`;
167
- else return path;
148
+ return path.match(/^\w:\\/) ? `file:///${slash(path)}` : path.match(/^\w:\//) ? `file:///${path}` : path;
168
149
  }
169
150
 
170
151
  const debugRequest = createDebug("vite-node:server:request");
@@ -191,12 +172,9 @@ class ViteNodeServer {
191
172
  debugger;
192
173
  constructor(server, options = {}) {
193
174
  var _options$deps3;
194
- this.server = server;
195
- this.options = options;
175
+ this.server = server, this.options = options;
196
176
  const ssrOptions = server.config.ssr;
197
- options.deps ?? (options.deps = {});
198
- options.deps.cacheDir = relative(server.config.root, options.deps.cacheDir || server.config.cacheDir);
199
- if (ssrOptions) {
177
+ if (options.deps ?? (options.deps = {}), options.deps.cacheDir = relative(server.config.root, options.deps.cacheDir || server.config.cacheDir), ssrOptions) {
200
178
  // we don't externalize ssr, because it has different semantics in Vite
201
179
  // if (ssrOptions.external) {
202
180
  // options.deps.external ??= []
@@ -223,32 +201,24 @@ class ViteNodeServer {
223
201
  return [resolvedId, pathToFileURL(resolvedId).href];
224
202
  });
225
203
  (_options$deps3 = options.deps).moduleDirectories ?? (_options$deps3.moduleDirectories = []);
226
- const envValue = process.env.VITE_NODE_DEPS_MODULE_DIRECTORIES || process.env.npm_config_VITE_NODE_DEPS_MODULE_DIRECTORIES;
227
- const customModuleDirectories = envValue === null || envValue === void 0 ? void 0 : envValue.split(",");
204
+ const envValue = process.env.VITE_NODE_DEPS_MODULE_DIRECTORIES || process.env.npm_config_VITE_NODE_DEPS_MODULE_DIRECTORIES, customModuleDirectories = envValue === null || envValue === void 0 ? void 0 : envValue.split(",");
228
205
  if (customModuleDirectories) options.deps.moduleDirectories.push(...customModuleDirectories);
229
- options.deps.moduleDirectories = options.deps.moduleDirectories.map((dir) => {
206
+ // always add node_modules as a module directory
207
+ if (options.deps.moduleDirectories = options.deps.moduleDirectories.map((dir) => {
230
208
  if (!dir.startsWith("/")) dir = `/${dir}`;
231
209
  if (!dir.endsWith("/")) dir += "/";
232
210
  return normalize(dir);
233
- });
234
- // always add node_modules as a module directory
235
- if (!options.deps.moduleDirectories.includes("/node_modules/")) options.deps.moduleDirectories.push("/node_modules/");
211
+ }), !options.deps.moduleDirectories.includes("/node_modules/")) options.deps.moduleDirectories.push("/node_modules/");
236
212
  }
237
213
  shouldExternalize(id) {
238
214
  return shouldExternalize(id, this.options.deps, this.externalizeCache);
239
215
  }
240
216
  getTotalDuration() {
241
- const ssrDurations = [...this.durations.ssr.values()].flat();
242
- const webDurations = [...this.durations.web.values()].flat();
217
+ const ssrDurations = [...this.durations.ssr.values()].flat(), webDurations = [...this.durations.web.values()].flat();
243
218
  return [...ssrDurations, ...webDurations].reduce((a, b) => a + b, 0);
244
219
  }
245
220
  async ensureExists(id) {
246
- if (this.existingOptimizedDeps.has(id)) return true;
247
- if (existsSync(id)) {
248
- this.existingOptimizedDeps.add(id);
249
- return true;
250
- }
251
- return new Promise((resolve) => {
221
+ return this.existingOptimizedDeps.has(id) ? true : existsSync(id) ? (this.existingOptimizedDeps.add(id), true) : new Promise((resolve) => {
252
222
  setTimeout(() => {
253
223
  this.ensureExists(id).then(() => {
254
224
  resolve(true);
@@ -303,18 +273,13 @@ class ViteNodeServer {
303
273
  }
304
274
  async transformModule(id, transformMode) {
305
275
  if (transformMode !== "web") throw new Error("`transformModule` only supports `transformMode: \"web\"`.");
306
- const normalizedId = normalizeModuleId(id);
307
- const mod = this.server.moduleGraph.getModuleById(normalizedId);
308
- const result = (mod === null || mod === void 0 ? void 0 : mod.transformResult) || await this.server.transformRequest(normalizedId);
276
+ const normalizedId = normalizeModuleId(id), mod = this.server.moduleGraph.getModuleById(normalizedId), result = (mod === null || mod === void 0 ? void 0 : mod.transformResult) || await this.server.transformRequest(normalizedId);
309
277
  return { code: result === null || result === void 0 ? void 0 : result.code };
310
278
  }
311
279
  getTransformMode(id) {
312
280
  var _this$options$transfo, _this$options$transfo2;
313
281
  const withoutQuery = id.split("?")[0];
314
- if ((_this$options$transfo = this.options.transformMode) === null || _this$options$transfo === void 0 || (_this$options$transfo = _this$options$transfo.web) === null || _this$options$transfo === void 0 ? void 0 : _this$options$transfo.some((r) => withoutQuery.match(r))) return "web";
315
- if ((_this$options$transfo2 = this.options.transformMode) === null || _this$options$transfo2 === void 0 || (_this$options$transfo2 = _this$options$transfo2.ssr) === null || _this$options$transfo2 === void 0 ? void 0 : _this$options$transfo2.some((r) => withoutQuery.match(r))) return "ssr";
316
- if (withoutQuery.match(/\.([cm]?[jt]sx?|json)$/)) return "ssr";
317
- return "web";
282
+ return ((_this$options$transfo = this.options.transformMode) === null || _this$options$transfo === void 0 || (_this$options$transfo = _this$options$transfo.web) === null || _this$options$transfo === void 0 ? void 0 : _this$options$transfo.some((r) => withoutQuery.match(r))) ? "web" : ((_this$options$transfo2 = this.options.transformMode) === null || _this$options$transfo2 === void 0 || (_this$options$transfo2 = _this$options$transfo2.ssr) === null || _this$options$transfo2 === void 0 ? void 0 : _this$options$transfo2.some((r) => withoutQuery.match(r))) || withoutQuery.match(/\.([cm]?[jt]sx?|json)$/) ? "ssr" : "web";
318
283
  }
319
284
  getChangedModule(id, file) {
320
285
  const module = this.server.moduleGraph.getModuleById(id) || this.server.moduleGraph.getModuleById(file);
@@ -323,14 +288,10 @@ class ViteNodeServer {
323
288
  if (!_modules || !_modules.size) return null;
324
289
  // find the latest changed module
325
290
  const modules = [..._modules];
326
- let mod = modules[0];
327
- let latestMax = -1;
291
+ let mod = modules[0], latestMax = -1;
328
292
  for (const m of _modules) {
329
293
  const timestamp = Math.max(m.lastHMRTimestamp, m.lastInvalidationTimestamp);
330
- if (timestamp > latestMax) {
331
- latestMax = timestamp;
332
- mod = m;
333
- }
294
+ if (timestamp > latestMax) latestMax = timestamp, mod = m;
334
295
  }
335
296
  return mod;
336
297
  }
@@ -343,29 +304,18 @@ class ViteNodeServer {
343
304
  const timeout = setTimeout(() => {
344
305
  throw new Error(`ViteNodeServer: ${id} not found. This is a bug, please report it.`);
345
306
  }, 5e3);
346
- await this.ensureExists(id);
347
- clearTimeout(timeout);
307
+ await this.ensureExists(id), clearTimeout(timeout);
348
308
  }
349
- const { path: filePath } = toFilePath(id, this.server.config.root);
350
- const moduleNode = this.getChangedModule(id, filePath);
351
- const cache = this.fetchCaches[transformMode].get(filePath);
352
- // lastUpdateTimestamp is the timestamp that marks the last time the module was changed
353
- // if lastUpdateTimestamp is 0, then the module was not changed since the server started
354
- // we test "timestamp === 0" for expressiveness, but it's not necessary
355
- const timestamp = moduleNode ? Math.max(moduleNode.lastHMRTimestamp, moduleNode.lastInvalidationTimestamp) : 0;
309
+ const { path: filePath } = toFilePath(id, this.server.config.root), moduleNode = this.getChangedModule(id, filePath), cache = this.fetchCaches[transformMode].get(filePath), timestamp = moduleNode ? Math.max(moduleNode.lastHMRTimestamp, moduleNode.lastInvalidationTimestamp) : 0;
356
310
  if (cache && (timestamp === 0 || cache.timestamp >= timestamp)) return cache.result;
357
- const time = Date.now();
358
- const externalize = await this.shouldExternalize(filePath);
311
+ const time = Date.now(), externalize = await this.shouldExternalize(filePath);
359
312
  let duration;
360
313
  if (externalize) {
361
314
  var _this$debugger;
362
- result = { externalize };
363
- (_this$debugger = this.debugger) === null || _this$debugger === void 0 || _this$debugger.recordExternalize(id, externalize);
315
+ result = { externalize }, (_this$debugger = this.debugger) === null || _this$debugger === void 0 || _this$debugger.recordExternalize(id, externalize);
364
316
  } else {
365
- const start = performance.now();
366
- const r = await this._transformRequest(id, filePath, transformMode);
367
- duration = performance.now() - start;
368
- result = {
317
+ const start = performance.now(), r = await this._transformRequest(id, filePath, transformMode);
318
+ duration = performance.now() - start, result = {
369
319
  code: r === null || r === void 0 ? void 0 : r.code,
370
320
  map: r === null || r === void 0 ? void 0 : r.map
371
321
  };
@@ -374,12 +324,8 @@ class ViteNodeServer {
374
324
  duration,
375
325
  timestamp: time,
376
326
  result
377
- };
378
- const durations = this.durations[transformMode].get(filePath) || [];
379
- this.durations[transformMode].set(filePath, [...durations, duration ?? 0]);
380
- this.fetchCaches[transformMode].set(filePath, cacheEntry);
381
- this.fetchCache.set(filePath, cacheEntry);
382
- return result;
327
+ }, durations = this.durations[transformMode].get(filePath) || [];
328
+ return this.durations[transformMode].set(filePath, [...durations, duration ?? 0]), this.fetchCaches[transformMode].set(filePath, cacheEntry), this.fetchCache.set(filePath, cacheEntry), result;
383
329
  }
384
330
  async processTransformResult(filepath, result) {
385
331
  const mod = this.server.moduleGraph.getModuleById(filepath);
@@ -395,14 +341,10 @@ class ViteNodeServer {
395
341
  let result = null;
396
342
  if ((_this$options$debug = this.options.debug) === null || _this$options$debug === void 0 ? void 0 : _this$options$debug.loadDumppedModules) {
397
343
  var _this$debugger2;
398
- result = await ((_this$debugger2 = this.debugger) === null || _this$debugger2 === void 0 ? void 0 : _this$debugger2.loadDump(id)) ?? null;
399
- if (result) return result;
344
+ if (result = await ((_this$debugger2 = this.debugger) === null || _this$debugger2 === void 0 ? void 0 : _this$debugger2.loadDump(id)) ?? null, result) return result;
400
345
  }
401
346
  if (transformMode === "web") {
402
- // for components like Vue, we want to use the client side
403
- // plugins but then convert the code to be consumed by the server
404
- result = await this.server.transformRequest(id);
405
- if (result) result = await this.server.ssrTransform(result.code, result.map, id);
347
+ if (result = await this.server.transformRequest(id), result) result = await this.server.ssrTransform(result.code, result.map, id);
406
348
  } else result = await this.server.transformRequest(id, { ssr: true });
407
349
  const sourcemap = this.options.sourcemap ?? "inline";
408
350
  if (sourcemap === "inline" && result) result = await this.processTransformResult(filepath, result);