vite-node 4.0.0-beta.9 → 5.0.0

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 DELETED
@@ -1,382 +0,0 @@
1
- 'use strict';
2
-
3
- var assert = require('node:assert');
4
- var fs = require('node:fs');
5
- var node_perf_hooks = require('node:perf_hooks');
6
- var node_url = require('node:url');
7
- var createDebug = require('debug');
8
- var pathe = require('pathe');
9
- var vite = require('vite');
10
- var browser = require('./chunk-browser.cjs');
11
- var esModuleLexer = require('es-module-lexer');
12
- var constants = require('./constants.cjs');
13
- var utils = require('./utils.cjs');
14
- var sourceMap = require('./source-map.cjs');
15
- require('node:module');
16
- require('node:path');
17
-
18
- function _interopNamespaceDefault(e) {
19
- var n = Object.create(null);
20
- if (e) {
21
- Object.keys(e).forEach(function (k) {
22
- if (k !== 'default') {
23
- var d = Object.getOwnPropertyDescriptor(e, k);
24
- Object.defineProperty(n, k, d.get ? d : {
25
- enumerable: true,
26
- get: function () { return e[k]; }
27
- });
28
- }
29
- });
30
- }
31
- n.default = e;
32
- return Object.freeze(n);
33
- }
34
-
35
- var esModuleLexer__namespace = /*#__PURE__*/_interopNamespaceDefault(esModuleLexer);
36
-
37
- /* eslint-disable no-console */
38
- function hashCode(s) {
39
- return s.split("").reduce((a, b) => {
40
- return a = (a << 5) - a + b.charCodeAt(0), a & a;
41
- }, 0);
42
- }
43
- class Debugger {
44
- dumpDir;
45
- initPromise;
46
- externalizeMap = /* @__PURE__ */ new Map();
47
- constructor(root, options) {
48
- if (this.options = options, options.dumpModules) this.dumpDir = pathe.resolve(root, options.dumpModules === true ? ".vite-node/dump" : options.dumpModules);
49
- if (this.dumpDir) if (options.loadDumppedModules) console.info(browser.s.gray(`[vite-node] [debug] load modules from ${this.dumpDir}`));
50
- else console.info(browser.s.gray(`[vite-node] [debug] dump modules to ${this.dumpDir}`));
51
- this.initPromise = this.clearDump();
52
- }
53
- async clearDump() {
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
- }
61
- }
62
- encodeId(id) {
63
- return `${id.replace(/[^\w@\-]/g, "_").replace(/_+/g, "_")}-${hashCode(id)}.js`;
64
- }
65
- async recordExternalize(id, path) {
66
- this.dumpDir && (this.externalizeMap.set(id, path), await this.writeInfo());
67
- }
68
- async dumpFile(id, result) {
69
- if (!result || !this.dumpDir) return;
70
- await this.initPromise;
71
- const name = this.encodeId(id);
72
- return await fs.promises.writeFile(pathe.join(this.dumpDir, name), `// ${id.replace(/\0/g, "\\0")}\n${result.code}`, "utf-8");
73
- }
74
- async loadDump(id) {
75
- if (!this.dumpDir) return null;
76
- await this.initPromise;
77
- const name = this.encodeId(id), path = pathe.join(this.dumpDir, name);
78
- if (!fs.existsSync(path)) return null;
79
- const code = await fs.promises.readFile(path, "utf-8");
80
- return {
81
- code: code.replace(/^\/\/.*\n/, ""),
82
- map: void 0
83
- };
84
- }
85
- async writeInfo() {
86
- if (!this.dumpDir) return;
87
- const info = JSON.stringify({
88
- time: (/* @__PURE__ */ new Date()).toLocaleString(),
89
- externalize: Object.fromEntries(this.externalizeMap.entries())
90
- }, null, 2);
91
- return fs.promises.writeFile(pathe.join(this.dumpDir, "info.json"), info, "utf-8");
92
- }
93
- }
94
-
95
- const BUILTIN_EXTENSIONS = new Set([
96
- ".mjs",
97
- ".cjs",
98
- ".node",
99
- ".wasm"
100
- ]), ESM_EXT_RE = /\.(es|esm|esm-browser|esm-bundler|es6|module)\.js$/, ESM_FOLDER_RE = /\/(es|esm)\/(.*\.js)$/, defaultInline = [
101
- /virtual:/,
102
- /\.[mc]?ts$/,
103
- /[?&](init|raw|url|inline)\b/,
104
- constants.KNOWN_ASSET_RE
105
- ], depsExternal = [/\/node_modules\/.*\.cjs\.js$/, /\/node_modules\/.*\.mjs$/];
106
- function guessCJSversion(id) {
107
- if (id.match(ESM_EXT_RE)) {
108
- for (const i of [
109
- id.replace(ESM_EXT_RE, ".mjs"),
110
- id.replace(ESM_EXT_RE, ".umd.js"),
111
- id.replace(ESM_EXT_RE, ".cjs.js"),
112
- id.replace(ESM_EXT_RE, ".js")
113
- ]) if (fs.existsSync(i)) return i;
114
- }
115
- if (id.match(ESM_FOLDER_RE)) {
116
- for (const i of [
117
- id.replace(ESM_FOLDER_RE, "/umd/$1"),
118
- id.replace(ESM_FOLDER_RE, "/cjs/$1"),
119
- id.replace(ESM_FOLDER_RE, "/lib/$1"),
120
- id.replace(ESM_FOLDER_RE, "/$1")
121
- ]) if (fs.existsSync(i)) return i;
122
- }
123
- }
124
- // The code from https://github.com/unjs/mlly/blob/c5bcca0cda175921344fd6de1bc0c499e73e5dac/src/syntax.ts#L51-L98
125
- async function isValidNodeImport(id) {
126
- const extension = pathe.extname(id);
127
- if (BUILTIN_EXTENSIONS.has(extension)) return true;
128
- if (extension !== ".js") return false;
129
- id = id.replace("file:///", "");
130
- const package_ = await utils.findNearestPackageData(pathe.dirname(id));
131
- if (package_.type === "module") return true;
132
- if (/\.(?:\w+-)?esm?(?:-\w+)?\.js$|\/esm?\//.test(id)) return false;
133
- try {
134
- await esModuleLexer__namespace.init;
135
- const code = await fs.promises.readFile(id, "utf8"), [, , , hasModuleSyntax] = esModuleLexer__namespace.parse(code);
136
- return !hasModuleSyntax;
137
- } catch {
138
- return false;
139
- }
140
- }
141
- const _defaultExternalizeCache = /* @__PURE__ */ new Map();
142
- async function shouldExternalize(id, options, cache = _defaultExternalizeCache) {
143
- if (!cache.has(id)) cache.set(id, _shouldExternalize(id, options));
144
- return cache.get(id);
145
- }
146
- async function _shouldExternalize(id, options) {
147
- // data: should be processed by native import,
148
- // since it is a feature of ESM.
149
- // also externalize network imports since nodejs allows it when --experimental-network-imports
150
- if (utils.isNodeBuiltin(id) || id.startsWith("data:") || /^(?:https?:)?\/\//.test(id)) return id;
151
- id = patchWindowsImportPath(id);
152
- const moduleDirectories = (options === null || options === void 0 ? void 0 : options.moduleDirectories) || ["/node_modules/"];
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;
154
- // Unless the user explicitly opted to inline them, externalize Vite deps.
155
- // They are too big to inline by default.
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;
159
- }
160
- function matchExternalizePattern(id, moduleDirectories, patterns) {
161
- if (patterns == null) return false;
162
- if (patterns === true) return true;
163
- for (const ex of patterns) if (typeof ex === "string") {
164
- if (moduleDirectories.some((dir) => id.includes(pathe.join(dir, ex)))) return true;
165
- } else if (ex.test(id)) return true;
166
- return false;
167
- }
168
- function patchWindowsImportPath(path) {
169
- return path.match(/^\w:\\/) ? `file:///${utils.slash(path)}` : path.match(/^\w:\//) ? `file:///${path}` : path;
170
- }
171
-
172
- const debugRequest = createDebug("vite-node:server:request");
173
- class ViteNodeServer {
174
- fetchPromiseMap = {
175
- ssr: /* @__PURE__ */ new Map(),
176
- web: /* @__PURE__ */ new Map()
177
- };
178
- transformPromiseMap = {
179
- ssr: /* @__PURE__ */ new Map(),
180
- web: /* @__PURE__ */ new Map()
181
- };
182
- durations = {
183
- ssr: /* @__PURE__ */ new Map(),
184
- web: /* @__PURE__ */ new Map()
185
- };
186
- existingOptimizedDeps = /* @__PURE__ */ new Set();
187
- fetchCaches = {
188
- ssr: /* @__PURE__ */ new Map(),
189
- web: /* @__PURE__ */ new Map()
190
- };
191
- fetchCache = /* @__PURE__ */ new Map();
192
- externalizeCache = /* @__PURE__ */ new Map();
193
- debugger;
194
- constructor(server, options = {}) {
195
- var _options$deps3;
196
- this.server = server, this.options = options;
197
- const ssrOptions = server.config.ssr;
198
- if (options.deps ?? (options.deps = {}), options.deps.cacheDir = pathe.relative(server.config.root, options.deps.cacheDir || server.config.cacheDir), ssrOptions) {
199
- // we don't externalize ssr, because it has different semantics in Vite
200
- // if (ssrOptions.external) {
201
- // options.deps.external ??= []
202
- // options.deps.external.push(...ssrOptions.external)
203
- // }
204
- if (ssrOptions.noExternal === true) {
205
- var _options$deps;
206
- (_options$deps = options.deps).inline ?? (_options$deps.inline = true);
207
- } else if (options.deps.inline !== true) {
208
- var _options$deps2;
209
- (_options$deps2 = options.deps).inline ?? (_options$deps2.inline = []);
210
- const inline = options.deps.inline;
211
- options.deps.inline.push(...utils.toArray(ssrOptions.noExternal).filter((dep) => !inline.includes(dep)));
212
- }
213
- }
214
- if (process.env.VITE_NODE_DEBUG_DUMP) options.debug = Object.assign({
215
- dumpModules: !!process.env.VITE_NODE_DEBUG_DUMP,
216
- loadDumppedModules: process.env.VITE_NODE_DEBUG_DUMP === "load"
217
- }, options.debug ?? {});
218
- if (options.debug) this.debugger = new Debugger(server.config.root, options.debug);
219
- if (options.deps.inlineFiles) options.deps.inlineFiles = options.deps.inlineFiles.flatMap((file) => {
220
- if (file.startsWith("file://")) return file;
221
- const resolvedId = pathe.resolve(file);
222
- return [resolvedId, node_url.pathToFileURL(resolvedId).href];
223
- });
224
- (_options$deps3 = options.deps).moduleDirectories ?? (_options$deps3.moduleDirectories = []);
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(",");
226
- if (customModuleDirectories) options.deps.moduleDirectories.push(...customModuleDirectories);
227
- // always add node_modules as a module directory
228
- if (options.deps.moduleDirectories = options.deps.moduleDirectories.map((dir) => {
229
- if (!dir.startsWith("/")) dir = `/${dir}`;
230
- if (!dir.endsWith("/")) dir += "/";
231
- return pathe.normalize(dir);
232
- }), !options.deps.moduleDirectories.includes("/node_modules/")) options.deps.moduleDirectories.push("/node_modules/");
233
- }
234
- shouldExternalize(id) {
235
- return shouldExternalize(id, this.options.deps, this.externalizeCache);
236
- }
237
- getTotalDuration() {
238
- const ssrDurations = [...this.durations.ssr.values()].flat(), webDurations = [...this.durations.web.values()].flat();
239
- return [...ssrDurations, ...webDurations].reduce((a, b) => a + b, 0);
240
- }
241
- async ensureExists(id) {
242
- return this.existingOptimizedDeps.has(id) ? true : fs.existsSync(id) ? (this.existingOptimizedDeps.add(id), true) : new Promise((resolve) => {
243
- setTimeout(() => {
244
- this.ensureExists(id).then(() => {
245
- resolve(true);
246
- });
247
- });
248
- });
249
- }
250
- async resolveId(id, importer, transformMode) {
251
- if (importer && !importer.startsWith(utils.withTrailingSlash(this.server.config.root))) 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 _this$fetchCache$get, _this$server$moduleGr;
257
- source = utils.normalizeModuleId(source);
258
- const fetchResult = (_this$fetchCache$get = this.fetchCache.get(source)) === null || _this$fetchCache$get === void 0 ? void 0 : _this$fetchCache$get.result;
259
- if (fetchResult === null || fetchResult === void 0 ? void 0 : fetchResult.map) return fetchResult.map;
260
- const ssrTransformResult = (_this$server$moduleGr = this.server.moduleGraph.getModuleById(source)) === null || _this$server$moduleGr === void 0 ? void 0 : _this$server$moduleGr.ssrTransformResult;
261
- return (ssrTransformResult === null || ssrTransformResult === void 0 ? void 0 : ssrTransformResult.map) || null;
262
- }
263
- assertMode(mode) {
264
- assert(mode === "web" || mode === "ssr", `"transformMode" can only be "web" or "ssr", received "${mode}".`);
265
- }
266
- async fetchModule(id, transformMode) {
267
- const mode = transformMode || this.getTransformMode(id);
268
- return this.fetchResult(id, mode).then((r) => {
269
- return this.options.sourcemap !== true ? {
270
- ...r,
271
- map: void 0
272
- } : r;
273
- });
274
- }
275
- async fetchResult(id, mode) {
276
- const moduleId = utils.normalizeModuleId(id);
277
- this.assertMode(mode);
278
- const promiseMap = this.fetchPromiseMap[mode];
279
- // reuse transform for concurrent requests
280
- if (!promiseMap.has(moduleId)) promiseMap.set(moduleId, this._fetchModule(moduleId, mode).finally(() => {
281
- promiseMap.delete(moduleId);
282
- }));
283
- return promiseMap.get(moduleId);
284
- }
285
- async transformRequest(id, filepath = id, transformMode) {
286
- const mode = transformMode || this.getTransformMode(id);
287
- this.assertMode(mode);
288
- const promiseMap = this.transformPromiseMap[mode];
289
- // reuse transform for concurrent requests
290
- if (!promiseMap.has(id)) promiseMap.set(id, this._transformRequest(id, filepath, mode).finally(() => {
291
- promiseMap.delete(id);
292
- }));
293
- return promiseMap.get(id);
294
- }
295
- async transformModule(id, transformMode) {
296
- if (transformMode !== "web") throw new Error("`transformModule` only supports `transformMode: \"web\"`.");
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);
298
- return { code: result === null || result === void 0 ? void 0 : result.code };
299
- }
300
- getTransformMode(id) {
301
- var _this$options$transfo, _this$options$transfo2;
302
- const withoutQuery = id.split("?")[0];
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) && _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) && _this$options$transfo2.some((r) => withoutQuery.match(r)) || withoutQuery.match(/\.([cm]?[jt]sx?|json)$/) ? "ssr" : "web";
304
- }
305
- getChangedModule(id, file) {
306
- const module = this.server.moduleGraph.getModuleById(id) || this.server.moduleGraph.getModuleById(file);
307
- if (module) return module;
308
- const _modules = this.server.moduleGraph.getModulesByFile(file);
309
- if (!_modules || !_modules.size) return null;
310
- // find the latest changed module
311
- const modules = [..._modules];
312
- let mod = modules[0], latestMax = -1;
313
- for (const m of _modules) {
314
- const timestamp = Math.max(m.lastHMRTimestamp, m.lastInvalidationTimestamp);
315
- if (timestamp > latestMax) latestMax = timestamp, mod = m;
316
- }
317
- return mod;
318
- }
319
- async _fetchModule(id, transformMode) {
320
- var _this$options$deps;
321
- let result;
322
- const cacheDir = (_this$options$deps = this.options.deps) === null || _this$options$deps === void 0 ? void 0 : _this$options$deps.cacheDir;
323
- if (cacheDir && id.includes(cacheDir)) {
324
- if (!id.startsWith(utils.withTrailingSlash(this.server.config.root))) id = pathe.join(this.server.config.root, id);
325
- const timeout = setTimeout(() => {
326
- throw new Error(`ViteNodeServer: ${id} not found. This is a bug, please report it.`);
327
- }, 5e3);
328
- await this.ensureExists(id), clearTimeout(timeout);
329
- }
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;
331
- if (cache && (timestamp === 0 || cache.timestamp >= timestamp)) return cache.result;
332
- const time = Date.now(), externalize = await this.shouldExternalize(filePath);
333
- let duration;
334
- if (externalize) {
335
- var _this$debugger;
336
- result = { externalize }, (_this$debugger = this.debugger) === null || _this$debugger === void 0 || _this$debugger.recordExternalize(id, externalize);
337
- } else {
338
- const start = node_perf_hooks.performance.now(), r = await this._transformRequest(id, filePath, transformMode);
339
- duration = node_perf_hooks.performance.now() - start, result = {
340
- code: r === null || r === void 0 ? void 0 : r.code,
341
- map: r === null || r === void 0 ? void 0 : r.map
342
- };
343
- }
344
- const cacheEntry = {
345
- duration,
346
- timestamp: time,
347
- 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;
350
- }
351
- async processTransformResult(filepath, result) {
352
- const mod = this.server.moduleGraph.getModuleById(filepath);
353
- return sourceMap.withInlineSourcemap(result, {
354
- filepath: (mod === null || mod === void 0 ? void 0 : mod.file) || filepath,
355
- root: this.server.config.root,
356
- noFirstLineMapping: Number(vite.version.split(".")[0]) >= 6
357
- });
358
- }
359
- async _transformRequest(id, filepath, transformMode) {
360
- var _this$options$debug, _this$options$debug2;
361
- debugRequest(id);
362
- let result = null;
363
- if ((_this$options$debug = this.options.debug) === null || _this$options$debug === void 0 ? void 0 : _this$options$debug.loadDumppedModules) {
364
- var _this$debugger2;
365
- if (result = await ((_this$debugger2 = this.debugger) === null || _this$debugger2 === void 0 ? void 0 : _this$debugger2.loadDump(id)) ?? null, result) return result;
366
- }
367
- if (transformMode === "web") {
368
- if (result = await this.server.transformRequest(id), result) result = await this.server.ssrTransform(result.code, result.map, id);
369
- } else result = await this.server.transformRequest(id, { ssr: true });
370
- const sourcemap = this.options.sourcemap ?? "inline";
371
- if (sourcemap === "inline" && result) result = await this.processTransformResult(filepath, result);
372
- if ((_this$options$debug2 = this.options.debug) === null || _this$options$debug2 === void 0 ? void 0 : _this$options$debug2.dumpModules) {
373
- var _this$debugger3;
374
- await ((_this$debugger3 = this.debugger) === null || _this$debugger3 === void 0 ? void 0 : _this$debugger3.dumpFile(id, result));
375
- }
376
- return result;
377
- }
378
- }
379
-
380
- exports.ViteNodeServer = ViteNodeServer;
381
- exports.guessCJSversion = guessCJSversion;
382
- exports.shouldExternalize = shouldExternalize;