vite-node 0.33.0 → 0.34.1

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.
@@ -3,6 +3,7 @@
3
3
  var node_events = require('node:events');
4
4
  var c = require('picocolors');
5
5
  var createDebug = require('debug');
6
+ var utils = require('./utils.cjs');
6
7
 
7
8
  function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
8
9
 
@@ -17,6 +18,18 @@ function viteNodeHmrPlugin() {
17
18
  const emitter = createHmrEmitter();
18
19
  return {
19
20
  name: "vite-node:hmr",
21
+ config() {
22
+ if (process.platform === "darwin" && process.env.VITE_TEST_WATCHER_DEBUG) {
23
+ return {
24
+ server: {
25
+ watch: {
26
+ useFsEvents: false,
27
+ usePolling: false
28
+ }
29
+ }
30
+ };
31
+ }
32
+ },
20
33
  configureServer(server) {
21
34
  const _send = server.ws.send;
22
35
  server.emitter = emitter;
@@ -24,6 +37,11 @@ function viteNodeHmrPlugin() {
24
37
  _send(payload);
25
38
  emitter.emit("message", payload);
26
39
  };
40
+ if (process.env.VITE_TEST_WATCHER_DEBUG) {
41
+ server.watcher.on("ready", () => {
42
+ console.log("[debug] watcher is ready");
43
+ });
44
+ }
27
45
  }
28
46
  };
29
47
  }
@@ -59,11 +77,11 @@ async function reload(runner, files) {
59
77
  });
60
78
  return Promise.all(files.map((file) => runner.executeId(file)));
61
79
  }
62
- function notifyListeners(runner, event, data) {
80
+ async function notifyListeners(runner, event, data) {
63
81
  const maps = getCache(runner);
64
82
  const cbs = maps.customListenersMap.get(event);
65
83
  if (cbs)
66
- cbs.forEach((cb) => cb(data));
84
+ await Promise.all(cbs.map((cb) => cb(data)));
67
85
  }
68
86
  async function queueUpdate(runner, p) {
69
87
  const maps = getCache(runner);
@@ -78,43 +96,31 @@ async function queueUpdate(runner, p) {
78
96
  }
79
97
  }
80
98
  async function fetchUpdate(runner, { path, acceptedPath }) {
99
+ path = utils.normalizeRequestId(path);
100
+ acceptedPath = utils.normalizeRequestId(acceptedPath);
81
101
  const maps = getCache(runner);
82
102
  const mod = maps.hotModulesMap.get(path);
83
103
  if (!mod) {
84
104
  return;
85
105
  }
86
- const moduleMap = /* @__PURE__ */ new Map();
87
106
  const isSelfUpdate = path === acceptedPath;
88
- const modulesToUpdate = /* @__PURE__ */ new Set();
89
- if (isSelfUpdate) {
90
- modulesToUpdate.add(path);
91
- } else {
92
- for (const { deps } of mod.callbacks) {
93
- deps.forEach((dep) => {
94
- if (acceptedPath === dep)
95
- modulesToUpdate.add(dep);
96
- });
107
+ let fetchedModule;
108
+ const qualifiedCallbacks = mod.callbacks.filter(
109
+ ({ deps }) => deps.includes(acceptedPath)
110
+ );
111
+ if (isSelfUpdate || qualifiedCallbacks.length > 0) {
112
+ const disposer = maps.disposeMap.get(acceptedPath);
113
+ if (disposer)
114
+ await disposer(maps.dataMap.get(acceptedPath));
115
+ try {
116
+ [fetchedModule] = await reload(runner, [acceptedPath]);
117
+ } catch (e) {
118
+ warnFailedFetch(e, acceptedPath);
97
119
  }
98
120
  }
99
- const qualifiedCallbacks = mod.callbacks.filter(({ deps }) => {
100
- return deps.some((dep) => modulesToUpdate.has(dep));
101
- });
102
- await Promise.all(
103
- Array.from(modulesToUpdate).map(async (dep) => {
104
- const disposer = maps.disposeMap.get(dep);
105
- if (disposer)
106
- await disposer(maps.dataMap.get(dep));
107
- try {
108
- const newMod = await reload(runner, [dep]);
109
- moduleMap.set(dep, newMod);
110
- } catch (e) {
111
- warnFailedFetch(e, dep);
112
- }
113
- })
114
- );
115
121
  return () => {
116
122
  for (const { deps, fn } of qualifiedCallbacks)
117
- fn(deps.map((dep) => moduleMap.get(dep)));
123
+ fn(deps.map((dep) => dep === acceptedPath ? fetchedModule : void 0));
118
124
  const loggedPath = isSelfUpdate ? path : `${acceptedPath} via ${path}`;
119
125
  console.log(`${c__default["default"].cyan("[vite-node]")} hot updated: ${loggedPath}`);
120
126
  };
@@ -133,26 +139,25 @@ async function handleMessage(runner, emitter, files, payload) {
133
139
  sendMessageBuffer(runner, emitter);
134
140
  break;
135
141
  case "update":
136
- notifyListeners(runner, "vite:beforeUpdate", payload);
137
- if (maps.isFirstUpdate) {
138
- reload(runner, files);
139
- maps.isFirstUpdate = true;
140
- }
141
- payload.updates.forEach((update) => {
142
- if (update.type === "js-update") {
143
- queueUpdate(runner, fetchUpdate(runner, update));
144
- } else {
145
- console.error(`${c__default["default"].cyan("[vite-node]")} no support css hmr.}`);
146
- }
147
- });
142
+ await notifyListeners(runner, "vite:beforeUpdate", payload);
143
+ await Promise.all(payload.updates.map((update) => {
144
+ if (update.type === "js-update")
145
+ return queueUpdate(runner, fetchUpdate(runner, update));
146
+ console.error(`${c__default["default"].cyan("[vite-node]")} no support css hmr.}`);
147
+ return null;
148
+ }));
149
+ await notifyListeners(runner, "vite:afterUpdate", payload);
148
150
  break;
149
151
  case "full-reload":
150
- notifyListeners(runner, "vite:beforeFullReload", payload);
152
+ await notifyListeners(runner, "vite:beforeFullReload", payload);
151
153
  maps.customListenersMap.delete("vite:beforeFullReload");
152
- reload(runner, files);
154
+ await reload(runner, files);
155
+ break;
156
+ case "custom":
157
+ await notifyListeners(runner, payload.event, payload.data);
153
158
  break;
154
159
  case "prune":
155
- notifyListeners(runner, "vite:beforePrune", payload);
160
+ await notifyListeners(runner, "vite:beforePrune", payload);
156
161
  payload.paths.forEach((path) => {
157
162
  const fn = maps.pruneMap.get(path);
158
163
  if (fn)
@@ -160,7 +165,7 @@ async function handleMessage(runner, emitter, files, payload) {
160
165
  });
161
166
  break;
162
167
  case "error": {
163
- notifyListeners(runner, "vite:error", payload);
168
+ await notifyListeners(runner, "vite:error", payload);
164
169
  const err = payload.err;
165
170
  console.error(`${c__default["default"].cyan("[vite-node]")} Internal Server Error
166
171
  ${err.message}
@@ -1,6 +1,7 @@
1
1
  import { EventEmitter } from 'node:events';
2
2
  import c from 'picocolors';
3
3
  import createDebug from 'debug';
4
+ import { normalizeRequestId } from './utils.mjs';
4
5
 
5
6
  function createHmrEmitter() {
6
7
  const emitter = new EventEmitter();
@@ -10,6 +11,18 @@ function viteNodeHmrPlugin() {
10
11
  const emitter = createHmrEmitter();
11
12
  return {
12
13
  name: "vite-node:hmr",
14
+ config() {
15
+ if (process.platform === "darwin" && process.env.VITE_TEST_WATCHER_DEBUG) {
16
+ return {
17
+ server: {
18
+ watch: {
19
+ useFsEvents: false,
20
+ usePolling: false
21
+ }
22
+ }
23
+ };
24
+ }
25
+ },
13
26
  configureServer(server) {
14
27
  const _send = server.ws.send;
15
28
  server.emitter = emitter;
@@ -17,6 +30,11 @@ function viteNodeHmrPlugin() {
17
30
  _send(payload);
18
31
  emitter.emit("message", payload);
19
32
  };
33
+ if (process.env.VITE_TEST_WATCHER_DEBUG) {
34
+ server.watcher.on("ready", () => {
35
+ console.log("[debug] watcher is ready");
36
+ });
37
+ }
20
38
  }
21
39
  };
22
40
  }
@@ -52,11 +70,11 @@ async function reload(runner, files) {
52
70
  });
53
71
  return Promise.all(files.map((file) => runner.executeId(file)));
54
72
  }
55
- function notifyListeners(runner, event, data) {
73
+ async function notifyListeners(runner, event, data) {
56
74
  const maps = getCache(runner);
57
75
  const cbs = maps.customListenersMap.get(event);
58
76
  if (cbs)
59
- cbs.forEach((cb) => cb(data));
77
+ await Promise.all(cbs.map((cb) => cb(data)));
60
78
  }
61
79
  async function queueUpdate(runner, p) {
62
80
  const maps = getCache(runner);
@@ -71,43 +89,31 @@ async function queueUpdate(runner, p) {
71
89
  }
72
90
  }
73
91
  async function fetchUpdate(runner, { path, acceptedPath }) {
92
+ path = normalizeRequestId(path);
93
+ acceptedPath = normalizeRequestId(acceptedPath);
74
94
  const maps = getCache(runner);
75
95
  const mod = maps.hotModulesMap.get(path);
76
96
  if (!mod) {
77
97
  return;
78
98
  }
79
- const moduleMap = /* @__PURE__ */ new Map();
80
99
  const isSelfUpdate = path === acceptedPath;
81
- const modulesToUpdate = /* @__PURE__ */ new Set();
82
- if (isSelfUpdate) {
83
- modulesToUpdate.add(path);
84
- } else {
85
- for (const { deps } of mod.callbacks) {
86
- deps.forEach((dep) => {
87
- if (acceptedPath === dep)
88
- modulesToUpdate.add(dep);
89
- });
100
+ let fetchedModule;
101
+ const qualifiedCallbacks = mod.callbacks.filter(
102
+ ({ deps }) => deps.includes(acceptedPath)
103
+ );
104
+ if (isSelfUpdate || qualifiedCallbacks.length > 0) {
105
+ const disposer = maps.disposeMap.get(acceptedPath);
106
+ if (disposer)
107
+ await disposer(maps.dataMap.get(acceptedPath));
108
+ try {
109
+ [fetchedModule] = await reload(runner, [acceptedPath]);
110
+ } catch (e) {
111
+ warnFailedFetch(e, acceptedPath);
90
112
  }
91
113
  }
92
- const qualifiedCallbacks = mod.callbacks.filter(({ deps }) => {
93
- return deps.some((dep) => modulesToUpdate.has(dep));
94
- });
95
- await Promise.all(
96
- Array.from(modulesToUpdate).map(async (dep) => {
97
- const disposer = maps.disposeMap.get(dep);
98
- if (disposer)
99
- await disposer(maps.dataMap.get(dep));
100
- try {
101
- const newMod = await reload(runner, [dep]);
102
- moduleMap.set(dep, newMod);
103
- } catch (e) {
104
- warnFailedFetch(e, dep);
105
- }
106
- })
107
- );
108
114
  return () => {
109
115
  for (const { deps, fn } of qualifiedCallbacks)
110
- fn(deps.map((dep) => moduleMap.get(dep)));
116
+ fn(deps.map((dep) => dep === acceptedPath ? fetchedModule : void 0));
111
117
  const loggedPath = isSelfUpdate ? path : `${acceptedPath} via ${path}`;
112
118
  console.log(`${c.cyan("[vite-node]")} hot updated: ${loggedPath}`);
113
119
  };
@@ -126,26 +132,25 @@ async function handleMessage(runner, emitter, files, payload) {
126
132
  sendMessageBuffer(runner, emitter);
127
133
  break;
128
134
  case "update":
129
- notifyListeners(runner, "vite:beforeUpdate", payload);
130
- if (maps.isFirstUpdate) {
131
- reload(runner, files);
132
- maps.isFirstUpdate = true;
133
- }
134
- payload.updates.forEach((update) => {
135
- if (update.type === "js-update") {
136
- queueUpdate(runner, fetchUpdate(runner, update));
137
- } else {
138
- console.error(`${c.cyan("[vite-node]")} no support css hmr.}`);
139
- }
140
- });
135
+ await notifyListeners(runner, "vite:beforeUpdate", payload);
136
+ await Promise.all(payload.updates.map((update) => {
137
+ if (update.type === "js-update")
138
+ return queueUpdate(runner, fetchUpdate(runner, update));
139
+ console.error(`${c.cyan("[vite-node]")} no support css hmr.}`);
140
+ return null;
141
+ }));
142
+ await notifyListeners(runner, "vite:afterUpdate", payload);
141
143
  break;
142
144
  case "full-reload":
143
- notifyListeners(runner, "vite:beforeFullReload", payload);
145
+ await notifyListeners(runner, "vite:beforeFullReload", payload);
144
146
  maps.customListenersMap.delete("vite:beforeFullReload");
145
- reload(runner, files);
147
+ await reload(runner, files);
148
+ break;
149
+ case "custom":
150
+ await notifyListeners(runner, payload.event, payload.data);
146
151
  break;
147
152
  case "prune":
148
- notifyListeners(runner, "vite:beforePrune", payload);
153
+ await notifyListeners(runner, "vite:beforePrune", payload);
149
154
  payload.paths.forEach((path) => {
150
155
  const fn = maps.pruneMap.get(path);
151
156
  if (fn)
@@ -153,7 +158,7 @@ async function handleMessage(runner, emitter, files, payload) {
153
158
  });
154
159
  break;
155
160
  case "error": {
156
- notifyListeners(runner, "vite:error", payload);
161
+ await notifyListeners(runner, "vite:error", payload);
157
162
  const err = payload.err;
158
163
  console.error(`${c.cyan("[vite-node]")} Internal Server Error
159
164
  ${err.message}
package/dist/cli.cjs CHANGED
@@ -6,17 +6,18 @@ var vite = require('vite');
6
6
  var server = require('./server.cjs');
7
7
  var client = require('./client.cjs');
8
8
  var utils = require('./utils.cjs');
9
- var sourceMap = require('./source-map.cjs');
10
9
  var hmr = require('./chunk-hmr.cjs');
10
+ var sourceMap = require('./source-map.cjs');
11
11
  require('perf_hooks');
12
12
  require('fs');
13
13
  require('pathe');
14
14
  require('debug');
15
15
  require('mlly');
16
+ require('./constants.cjs');
16
17
  require('node:url');
17
18
  require('module');
18
19
  require('path');
19
- require('vm');
20
+ require('node:vm');
20
21
  require('node:events');
21
22
 
22
23
  function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
@@ -24,12 +25,20 @@ function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'defau
24
25
  var cac__default = /*#__PURE__*/_interopDefaultLegacy(cac);
25
26
  var c__default = /*#__PURE__*/_interopDefaultLegacy(c);
26
27
 
27
- var version = "0.33.0";
28
+ var version = "0.34.1";
28
29
 
29
30
  const cli = cac__default["default"]("vite-node");
30
- cli.version(version).option("-r, --root <path>", "Use specified root directory").option("-c, --config <path>", "Use specified config file").option("-m, --mode <mode>", "Set env mode").option("-w, --watch", 'Restart on file changes, similar to "nodemon"').option("--script", "Use vite-node as a script runner").option("--options <options>", "Use specified Vite server options").help();
31
+ cli.option("-r, --root <path>", "Use specified root directory").option("-c, --config <path>", "Use specified config file").option("-m, --mode <mode>", "Set env mode").option("-w, --watch", 'Restart on file changes, similar to "nodemon"').option("--script", "Use vite-node as a script runner").option("--options <options>", "Use specified Vite server options").option("-v, --version", "Output the version number").option("-h, --help", "Display help for command");
31
32
  cli.command("[...files]").allowUnknownOptions().action(run);
32
- cli.parse();
33
+ cli.parse(process.argv, { run: false });
34
+ if (cli.args.length === 0) {
35
+ cli.runMatchedCommand();
36
+ } else {
37
+ const i = cli.rawArgs.indexOf(cli.args[0]) + 1;
38
+ const scriptArgs = cli.rawArgs.slice(i).filter((it) => it !== "--");
39
+ const executeArgs = [...cli.rawArgs.slice(0, i), "--", ...scriptArgs];
40
+ cli.parse(executeArgs);
41
+ }
33
42
  async function run(files, options = {}) {
34
43
  var _a;
35
44
  if (options.script) {
@@ -39,9 +48,18 @@ async function run(files, options = {}) {
39
48
  } else {
40
49
  process.argv = [...process.argv.slice(0, 2), ...options["--"] || []];
41
50
  }
51
+ if (options.version) {
52
+ cli.version(version);
53
+ cli.outputVersion();
54
+ process.exit(0);
55
+ }
56
+ if (options.help) {
57
+ cli.version(version).outputHelp();
58
+ process.exit(0);
59
+ }
42
60
  if (!files.length) {
43
61
  console.error(c__default["default"].red("No files specified."));
44
- cli.outputHelp();
62
+ cli.version(version).outputHelp();
45
63
  process.exit(1);
46
64
  }
47
65
  const serverOptions = options.options ? parseServerOptions(options.options) : {};
@@ -50,6 +68,9 @@ async function run(files, options = {}) {
50
68
  configFile: options.config,
51
69
  root: options.root,
52
70
  mode: options.mode,
71
+ server: {
72
+ hmr: !!options.watch
73
+ },
53
74
  plugins: [
54
75
  options.watch && hmr.viteNodeHmrPlugin()
55
76
  ]
package/dist/cli.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { f as ViteNodeServerOptions } from './types-516036fa.js';
1
+ import { f as ViteNodeServerOptions } from './types-e8623e9c.js';
2
2
  import 'vite/types/hot';
3
3
  import './types.d-7442d07f.js';
4
4
 
@@ -9,6 +9,8 @@ interface CliOptions {
9
9
  mode?: string;
10
10
  watch?: boolean;
11
11
  options?: ViteNodeServerOptionsCLI;
12
+ version?: boolean;
13
+ help?: boolean;
12
14
  '--'?: string[];
13
15
  }
14
16
  type Optional<T> = T | undefined;
package/dist/cli.mjs CHANGED
@@ -11,18 +11,27 @@ import 'node:fs';
11
11
  import 'pathe';
12
12
  import 'debug';
13
13
  import 'mlly';
14
+ import './constants.mjs';
14
15
  import 'node:url';
15
16
  import 'node:module';
16
17
  import 'node:path';
17
18
  import 'node:vm';
18
19
  import 'node:events';
19
20
 
20
- var version = "0.33.0";
21
+ var version = "0.34.1";
21
22
 
22
23
  const cli = cac("vite-node");
23
- cli.version(version).option("-r, --root <path>", "Use specified root directory").option("-c, --config <path>", "Use specified config file").option("-m, --mode <mode>", "Set env mode").option("-w, --watch", 'Restart on file changes, similar to "nodemon"').option("--script", "Use vite-node as a script runner").option("--options <options>", "Use specified Vite server options").help();
24
+ cli.option("-r, --root <path>", "Use specified root directory").option("-c, --config <path>", "Use specified config file").option("-m, --mode <mode>", "Set env mode").option("-w, --watch", 'Restart on file changes, similar to "nodemon"').option("--script", "Use vite-node as a script runner").option("--options <options>", "Use specified Vite server options").option("-v, --version", "Output the version number").option("-h, --help", "Display help for command");
24
25
  cli.command("[...files]").allowUnknownOptions().action(run);
25
- cli.parse();
26
+ cli.parse(process.argv, { run: false });
27
+ if (cli.args.length === 0) {
28
+ cli.runMatchedCommand();
29
+ } else {
30
+ const i = cli.rawArgs.indexOf(cli.args[0]) + 1;
31
+ const scriptArgs = cli.rawArgs.slice(i).filter((it) => it !== "--");
32
+ const executeArgs = [...cli.rawArgs.slice(0, i), "--", ...scriptArgs];
33
+ cli.parse(executeArgs);
34
+ }
26
35
  async function run(files, options = {}) {
27
36
  var _a;
28
37
  if (options.script) {
@@ -32,9 +41,18 @@ async function run(files, options = {}) {
32
41
  } else {
33
42
  process.argv = [...process.argv.slice(0, 2), ...options["--"] || []];
34
43
  }
44
+ if (options.version) {
45
+ cli.version(version);
46
+ cli.outputVersion();
47
+ process.exit(0);
48
+ }
49
+ if (options.help) {
50
+ cli.version(version).outputHelp();
51
+ process.exit(0);
52
+ }
35
53
  if (!files.length) {
36
54
  console.error(c.red("No files specified."));
37
- cli.outputHelp();
55
+ cli.version(version).outputHelp();
38
56
  process.exit(1);
39
57
  }
40
58
  const serverOptions = options.options ? parseServerOptions(options.options) : {};
@@ -43,6 +61,9 @@ async function run(files, options = {}) {
43
61
  configFile: options.config,
44
62
  root: options.root,
45
63
  mode: options.mode,
64
+ server: {
65
+ hmr: !!options.watch
66
+ },
46
67
  plugins: [
47
68
  options.watch && viteNodeHmrPlugin()
48
69
  ]
package/dist/client.cjs CHANGED
@@ -5,7 +5,7 @@ Object.defineProperty(exports, '__esModule', { value: true });
5
5
  var module$1 = require('module');
6
6
  var path = require('path');
7
7
  var node_url = require('node:url');
8
- var vm = require('vm');
8
+ var vm = require('node:vm');
9
9
  var pathe = require('pathe');
10
10
  var createDebug = require('debug');
11
11
  var utils = require('./utils.cjs');
@@ -40,7 +40,7 @@ const debugExecute = createDebug__default["default"]("vite-node:client:execute")
40
40
  const debugNative = createDebug__default["default"]("vite-node:client:native");
41
41
  const clientStub = {
42
42
  injectQuery: (id) => id,
43
- createHotContext() {
43
+ createHotContext: () => {
44
44
  return {
45
45
  accept: () => {
46
46
  },
@@ -58,18 +58,9 @@ const clientStub = {
58
58
  }
59
59
  };
60
60
  },
61
- updateStyle(id, css) {
62
- if (typeof document === "undefined")
63
- return;
64
- const element = document.getElementById(id);
65
- if (element)
66
- element.remove();
67
- const head = document.querySelector("head");
68
- const style = document.createElement("style");
69
- style.setAttribute("type", "text/css");
70
- style.id = id;
71
- style.innerHTML = css;
72
- head == null ? void 0 : head.appendChild(style);
61
+ updateStyle: () => {
62
+ },
63
+ removeStyle: () => {
73
64
  }
74
65
  };
75
66
  const DEFAULT_REQUEST_STUBS = {
@@ -281,29 +272,30 @@ ${getStack()}`), 2e3);
281
272
  }
282
273
  if (transformed == null)
283
274
  throw new Error(`[vite-node] Failed to load "${id}" imported from ${callstack[callstack.length - 2]}`);
275
+ const { Object: Object2, Reflect: Reflect2, Symbol: Symbol2 } = this.getContextPrimitives();
284
276
  const modulePath = utils.cleanUrl(moduleId);
285
277
  const href = node_url.pathToFileURL(modulePath).href;
286
278
  const meta = { url: href };
287
- const exports = /* @__PURE__ */ Object.create(null);
288
- Object.defineProperty(exports, Symbol.toStringTag, {
279
+ const exports = Object2.create(null);
280
+ Object2.defineProperty(exports, Symbol2.toStringTag, {
289
281
  value: "Module",
290
282
  enumerable: false,
291
283
  configurable: false
292
284
  });
293
285
  const cjsExports = new Proxy(exports, {
294
286
  get: (target, p, receiver) => {
295
- if (Reflect.has(target, p))
296
- return Reflect.get(target, p, receiver);
297
- return Reflect.get(Object.prototype, p, receiver);
287
+ if (Reflect2.has(target, p))
288
+ return Reflect2.get(target, p, receiver);
289
+ return Reflect2.get(Object2.prototype, p, receiver);
298
290
  },
299
- getPrototypeOf: () => Object.prototype,
291
+ getPrototypeOf: () => Object2.prototype,
300
292
  set: (_, p, value) => {
301
293
  if (p === "default" && this.shouldInterop(modulePath, { default: value }) && cjsExports !== value) {
302
294
  exportAll(cjsExports, value);
303
295
  exports.default = value;
304
296
  return true;
305
297
  }
306
- if (!Reflect.has(exports, "default"))
298
+ if (!Reflect2.has(exports, "default"))
307
299
  exports.default = {};
308
300
  if (utils.isPrimitive(exports.default)) {
309
301
  defineExport(exports, p, () => void 0);
@@ -315,7 +307,7 @@ ${getStack()}`), 2e3);
315
307
  return true;
316
308
  }
317
309
  });
318
- Object.assign(mod, { code: transformed, exports });
310
+ Object2.assign(mod, { code: transformed, exports });
319
311
  const __filename = node_url.fileURLToPath(href);
320
312
  const moduleProxy = {
321
313
  set exports(value) {
@@ -328,11 +320,11 @@ ${getStack()}`), 2e3);
328
320
  };
329
321
  let hotContext;
330
322
  if (this.options.createHotContext) {
331
- Object.defineProperty(meta, "hot", {
323
+ Object2.defineProperty(meta, "hot", {
332
324
  enumerable: true,
333
325
  get: () => {
334
326
  var _a, _b;
335
- hotContext || (hotContext = (_b = (_a = this.options).createHotContext) == null ? void 0 : _b.call(_a, this, `/@fs/${fsPath}`));
327
+ hotContext || (hotContext = (_b = (_a = this.options).createHotContext) == null ? void 0 : _b.call(_a, this, moduleId));
336
328
  return hotContext;
337
329
  },
338
330
  set: (value) => {
@@ -357,16 +349,23 @@ ${getStack()}`), 2e3);
357
349
  debugExecute(__filename);
358
350
  if (transformed[0] === "#")
359
351
  transformed = transformed.replace(/^\#\!.*/, (s) => " ".repeat(s.length));
352
+ await this.runModule(context, transformed);
353
+ return exports;
354
+ }
355
+ getContextPrimitives() {
356
+ return { Object, Reflect, Symbol };
357
+ }
358
+ async runModule(context, transformed) {
360
359
  const codeDefinition = `'use strict';async (${Object.keys(context).join(",")})=>{{`;
361
360
  const code = `${codeDefinition}${transformed}
362
361
  }}`;
363
- const fn = vm__default["default"].runInThisContext(code, {
364
- filename: __filename,
362
+ const options = {
363
+ filename: context.__filename,
365
364
  lineOffset: 0,
366
365
  columnOffset: -codeDefinition.length
367
- });
366
+ };
367
+ const fn = vm__default["default"].runInThisContext(code, options);
368
368
  await fn(...Object.values(context));
369
- return exports;
370
369
  }
371
370
  prepareContext(context) {
372
371
  return context;
@@ -380,11 +379,14 @@ ${getStack()}`), 2e3);
380
379
  return false;
381
380
  return !path.endsWith(".mjs") && "default" in mod;
382
381
  }
382
+ importExternalModule(path) {
383
+ return (function (t) { return Promise.resolve().then(function () { return /*#__PURE__*/_interopNamespace(require(t)); }); })(path);
384
+ }
383
385
  /**
384
386
  * Import a module and interop it
385
387
  */
386
388
  async interopedImport(path) {
387
- const importedModule = await (function (t) { return Promise.resolve().then(function () { return /*#__PURE__*/_interopNamespace(require(t)); }); })(path);
389
+ const importedModule = await this.importExternalModule(path);
388
390
  if (!this.shouldInterop(path, importedModule))
389
391
  return importedModule;
390
392
  const { mod, defaultExport } = interopModule(importedModule);
package/dist/client.d.ts CHANGED
@@ -1,3 +1,3 @@
1
1
  import './types.d-7442d07f.js';
2
- export { i as DEFAULT_REQUEST_STUBS, M as ModuleCacheMap, h as ViteNodeRunner } from './types-516036fa.js';
2
+ export { i as DEFAULT_REQUEST_STUBS, M as ModuleCacheMap, h as ViteNodeRunner } from './types-e8623e9c.js';
3
3
  import 'vite/types/hot';
package/dist/client.mjs CHANGED
@@ -13,7 +13,7 @@ const debugExecute = createDebug("vite-node:client:execute");
13
13
  const debugNative = createDebug("vite-node:client:native");
14
14
  const clientStub = {
15
15
  injectQuery: (id) => id,
16
- createHotContext() {
16
+ createHotContext: () => {
17
17
  return {
18
18
  accept: () => {
19
19
  },
@@ -31,18 +31,9 @@ const clientStub = {
31
31
  }
32
32
  };
33
33
  },
34
- updateStyle(id, css) {
35
- if (typeof document === "undefined")
36
- return;
37
- const element = document.getElementById(id);
38
- if (element)
39
- element.remove();
40
- const head = document.querySelector("head");
41
- const style = document.createElement("style");
42
- style.setAttribute("type", "text/css");
43
- style.id = id;
44
- style.innerHTML = css;
45
- head == null ? void 0 : head.appendChild(style);
34
+ updateStyle: () => {
35
+ },
36
+ removeStyle: () => {
46
37
  }
47
38
  };
48
39
  const DEFAULT_REQUEST_STUBS = {
@@ -254,29 +245,30 @@ ${getStack()}`), 2e3);
254
245
  }
255
246
  if (transformed == null)
256
247
  throw new Error(`[vite-node] Failed to load "${id}" imported from ${callstack[callstack.length - 2]}`);
248
+ const { Object: Object2, Reflect: Reflect2, Symbol: Symbol2 } = this.getContextPrimitives();
257
249
  const modulePath = cleanUrl(moduleId);
258
250
  const href = pathToFileURL(modulePath).href;
259
251
  const meta = { url: href };
260
- const exports = /* @__PURE__ */ Object.create(null);
261
- Object.defineProperty(exports, Symbol.toStringTag, {
252
+ const exports = Object2.create(null);
253
+ Object2.defineProperty(exports, Symbol2.toStringTag, {
262
254
  value: "Module",
263
255
  enumerable: false,
264
256
  configurable: false
265
257
  });
266
258
  const cjsExports = new Proxy(exports, {
267
259
  get: (target, p, receiver) => {
268
- if (Reflect.has(target, p))
269
- return Reflect.get(target, p, receiver);
270
- return Reflect.get(Object.prototype, p, receiver);
260
+ if (Reflect2.has(target, p))
261
+ return Reflect2.get(target, p, receiver);
262
+ return Reflect2.get(Object2.prototype, p, receiver);
271
263
  },
272
- getPrototypeOf: () => Object.prototype,
264
+ getPrototypeOf: () => Object2.prototype,
273
265
  set: (_, p, value) => {
274
266
  if (p === "default" && this.shouldInterop(modulePath, { default: value }) && cjsExports !== value) {
275
267
  exportAll(cjsExports, value);
276
268
  exports.default = value;
277
269
  return true;
278
270
  }
279
- if (!Reflect.has(exports, "default"))
271
+ if (!Reflect2.has(exports, "default"))
280
272
  exports.default = {};
281
273
  if (isPrimitive(exports.default)) {
282
274
  defineExport(exports, p, () => void 0);
@@ -288,7 +280,7 @@ ${getStack()}`), 2e3);
288
280
  return true;
289
281
  }
290
282
  });
291
- Object.assign(mod, { code: transformed, exports });
283
+ Object2.assign(mod, { code: transformed, exports });
292
284
  const __filename = fileURLToPath(href);
293
285
  const moduleProxy = {
294
286
  set exports(value) {
@@ -301,11 +293,11 @@ ${getStack()}`), 2e3);
301
293
  };
302
294
  let hotContext;
303
295
  if (this.options.createHotContext) {
304
- Object.defineProperty(meta, "hot", {
296
+ Object2.defineProperty(meta, "hot", {
305
297
  enumerable: true,
306
298
  get: () => {
307
299
  var _a, _b;
308
- hotContext || (hotContext = (_b = (_a = this.options).createHotContext) == null ? void 0 : _b.call(_a, this, `/@fs/${fsPath}`));
300
+ hotContext || (hotContext = (_b = (_a = this.options).createHotContext) == null ? void 0 : _b.call(_a, this, moduleId));
309
301
  return hotContext;
310
302
  },
311
303
  set: (value) => {
@@ -330,16 +322,23 @@ ${getStack()}`), 2e3);
330
322
  debugExecute(__filename);
331
323
  if (transformed[0] === "#")
332
324
  transformed = transformed.replace(/^\#\!.*/, (s) => " ".repeat(s.length));
325
+ await this.runModule(context, transformed);
326
+ return exports;
327
+ }
328
+ getContextPrimitives() {
329
+ return { Object, Reflect, Symbol };
330
+ }
331
+ async runModule(context, transformed) {
333
332
  const codeDefinition = `'use strict';async (${Object.keys(context).join(",")})=>{{`;
334
333
  const code = `${codeDefinition}${transformed}
335
334
  }}`;
336
- const fn = vm.runInThisContext(code, {
337
- filename: __filename,
335
+ const options = {
336
+ filename: context.__filename,
338
337
  lineOffset: 0,
339
338
  columnOffset: -codeDefinition.length
340
- });
339
+ };
340
+ const fn = vm.runInThisContext(code, options);
341
341
  await fn(...Object.values(context));
342
- return exports;
343
342
  }
344
343
  prepareContext(context) {
345
344
  return context;
@@ -353,11 +352,14 @@ ${getStack()}`), 2e3);
353
352
  return false;
354
353
  return !path.endsWith(".mjs") && "default" in mod;
355
354
  }
355
+ importExternalModule(path) {
356
+ return import(path);
357
+ }
356
358
  /**
357
359
  * Import a module and interop it
358
360
  */
359
361
  async interopedImport(path) {
360
- const importedModule = await import(path);
362
+ const importedModule = await this.importExternalModule(path);
361
363
  if (!this.shouldInterop(path, importedModule))
362
364
  return importedModule;
363
365
  const { mod, defaultExport } = interopModule(importedModule);
@@ -0,0 +1,41 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ const KNOWN_ASSET_TYPES = [
6
+ // images
7
+ "apng",
8
+ "png",
9
+ "jpe?g",
10
+ "jfif",
11
+ "pjpeg",
12
+ "pjp",
13
+ "gif",
14
+ "svg",
15
+ "ico",
16
+ "webp",
17
+ "avif",
18
+ // media
19
+ "mp4",
20
+ "webm",
21
+ "ogg",
22
+ "mp3",
23
+ "wav",
24
+ "flac",
25
+ "aac",
26
+ // fonts
27
+ "woff2?",
28
+ "eot",
29
+ "ttf",
30
+ "otf",
31
+ // other
32
+ "webmanifest",
33
+ "pdf",
34
+ "txt"
35
+ ];
36
+ const KNOWN_ASSET_RE = new RegExp(`\\.(${KNOWN_ASSET_TYPES.join("|")})$`);
37
+ const CSS_LANGS_RE = /\.(css|less|sass|scss|styl|stylus|pcss|postcss|sss)(?:$|\?)/;
38
+
39
+ exports.CSS_LANGS_RE = CSS_LANGS_RE;
40
+ exports.KNOWN_ASSET_RE = KNOWN_ASSET_RE;
41
+ exports.KNOWN_ASSET_TYPES = KNOWN_ASSET_TYPES;
@@ -0,0 +1,5 @@
1
+ declare const KNOWN_ASSET_TYPES: string[];
2
+ declare const KNOWN_ASSET_RE: RegExp;
3
+ declare const CSS_LANGS_RE: RegExp;
4
+
5
+ export { CSS_LANGS_RE, KNOWN_ASSET_RE, KNOWN_ASSET_TYPES };
@@ -0,0 +1,35 @@
1
+ const KNOWN_ASSET_TYPES = [
2
+ // images
3
+ "apng",
4
+ "png",
5
+ "jpe?g",
6
+ "jfif",
7
+ "pjpeg",
8
+ "pjp",
9
+ "gif",
10
+ "svg",
11
+ "ico",
12
+ "webp",
13
+ "avif",
14
+ // media
15
+ "mp4",
16
+ "webm",
17
+ "ogg",
18
+ "mp3",
19
+ "wav",
20
+ "flac",
21
+ "aac",
22
+ // fonts
23
+ "woff2?",
24
+ "eot",
25
+ "ttf",
26
+ "otf",
27
+ // other
28
+ "webmanifest",
29
+ "pdf",
30
+ "txt"
31
+ ];
32
+ const KNOWN_ASSET_RE = new RegExp(`\\.(${KNOWN_ASSET_TYPES.join("|")})$`);
33
+ const CSS_LANGS_RE = /\.(css|less|sass|scss|styl|stylus|pcss|postcss|sss)(?:$|\?)/;
34
+
35
+ export { CSS_LANGS_RE, KNOWN_ASSET_RE, KNOWN_ASSET_TYPES };
package/dist/hmr.cjs CHANGED
@@ -6,6 +6,11 @@ var hmr = require('./chunk-hmr.cjs');
6
6
  require('node:events');
7
7
  require('picocolors');
8
8
  require('debug');
9
+ require('./utils.cjs');
10
+ require('node:url');
11
+ require('module');
12
+ require('fs');
13
+ require('pathe');
9
14
 
10
15
 
11
16
 
package/dist/hmr.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { EventEmitter } from 'node:events';
2
2
  import { HMRPayload as HMRPayload$1, Plugin } from 'vite';
3
- import { h as ViteNodeRunner, H as HotContext } from './types-516036fa.js';
3
+ import { h as ViteNodeRunner, H as HotContext } from './types-e8623e9c.js';
4
4
  import 'vite/types/hot';
5
5
  import './types.d-7442d07f.js';
6
6
 
@@ -99,6 +99,9 @@ interface InvalidatePayload {
99
99
  message: string | undefined
100
100
  }
101
101
 
102
+ type ModuleNamespace = Record<string, any> & {
103
+ [Symbol.toStringTag]: 'Module';
104
+ };
102
105
  type InferCustomEventPayload<T extends string> = T extends keyof CustomEventMap ? CustomEventMap[T] : any;
103
106
  interface HotModule {
104
107
  id: string;
@@ -106,7 +109,7 @@ interface HotModule {
106
109
  }
107
110
  interface HotCallback {
108
111
  deps: string[];
109
- fn: (modules: object[]) => void;
112
+ fn: (modules: (ModuleNamespace | undefined)[]) => void;
110
113
  }
111
114
  interface CacheData {
112
115
  hotModulesMap: Map<string, HotModule>;
@@ -126,4 +129,4 @@ declare function reload(runner: ViteNodeRunner, files: string[]): Promise<any[]>
126
129
  declare function handleMessage(runner: ViteNodeRunner, emitter: HMREmitter, files: string[], payload: HMRPayload): Promise<void>;
127
130
  declare function createHotContext(runner: ViteNodeRunner, emitter: HMREmitter, files: string[], ownerPath: string): HotContext;
128
131
 
129
- export { Emitter, EventType, HMREmitter, Handler, HotCallback, HotModule, InferCustomEventPayload, createHmrEmitter, createHotContext, getCache, handleMessage, reload, sendMessageBuffer, viteNodeHmrPlugin };
132
+ export { Emitter, EventType, HMREmitter, Handler, HotCallback, HotModule, InferCustomEventPayload, ModuleNamespace, createHmrEmitter, createHotContext, getCache, handleMessage, reload, sendMessageBuffer, viteNodeHmrPlugin };
package/dist/hmr.mjs CHANGED
@@ -2,3 +2,8 @@ export { a as createHmrEmitter, c as createHotContext, g as getCache, h as handl
2
2
  import 'node:events';
3
3
  import 'picocolors';
4
4
  import 'debug';
5
+ import './utils.mjs';
6
+ import 'node:url';
7
+ import 'node:module';
8
+ import 'node:fs';
9
+ import 'pathe';
package/dist/index.d.ts CHANGED
@@ -1,3 +1,3 @@
1
- export { A as Arrayable, a as Awaitable, C as CreateHotContextFunction, g as DebuggerOptions, D as DepsHandlingOptions, b as FetchFunction, F as FetchResult, H as HotContext, d as ModuleCache, M as ModuleCacheMap, N as Nullable, R as RawSourceMap, c as ResolveIdFunction, S as StartOfSourceMap, e as ViteNodeResolveId, V as ViteNodeRunnerOptions, f as ViteNodeServerOptions } from './types-516036fa.js';
1
+ export { A as Arrayable, a as Awaitable, C as CreateHotContextFunction, g as DebuggerOptions, D as DepsHandlingOptions, b as FetchFunction, F as FetchResult, H as HotContext, d as ModuleCache, M as ModuleCacheMap, N as Nullable, R as RawSourceMap, c as ResolveIdFunction, S as StartOfSourceMap, e as ViteNodeResolveId, V as ViteNodeRunnerOptions, f as ViteNodeServerOptions } from './types-e8623e9c.js';
2
2
  export { D as DecodedSourceMap, E as EncodedSourceMap } from './types.d-7442d07f.js';
3
3
  import 'vite/types/hot';
package/dist/server.cjs CHANGED
@@ -8,6 +8,7 @@ var pathe = require('pathe');
8
8
  var createDebug = require('debug');
9
9
  var mlly = require('mlly');
10
10
  var utils = require('./utils.cjs');
11
+ var constants = require('./constants.cjs');
11
12
  var c = require('picocolors');
12
13
  var sourceMap = require('./source-map.cjs');
13
14
  require('node:url');
@@ -19,37 +20,6 @@ function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'defau
19
20
  var createDebug__default = /*#__PURE__*/_interopDefaultLegacy(createDebug);
20
21
  var c__default = /*#__PURE__*/_interopDefaultLegacy(c);
21
22
 
22
- const KNOWN_ASSET_TYPES = [
23
- // images
24
- "apng",
25
- "png",
26
- "jpe?g",
27
- "jfif",
28
- "pjpeg",
29
- "pjp",
30
- "gif",
31
- "svg",
32
- "ico",
33
- "webp",
34
- "avif",
35
- // media
36
- "mp4",
37
- "webm",
38
- "ogg",
39
- "mp3",
40
- "wav",
41
- "flac",
42
- "aac",
43
- // fonts
44
- "woff2?",
45
- "eot",
46
- "ttf",
47
- "otf",
48
- // other
49
- "webmanifest",
50
- "pdf",
51
- "txt"
52
- ];
53
23
  const ESM_EXT_RE = /\.(es|esm|esm-browser|esm-bundler|es6|module)\.js$/;
54
24
  const ESM_FOLDER_RE = /\/(es|esm)\/(.*\.js)$/;
55
25
  const defaultInline = [
@@ -58,7 +28,7 @@ const defaultInline = [
58
28
  // special Vite query strings
59
29
  /[?&](init|raw|url|inline)\b/,
60
30
  // Vite returns a string for assets imports, even if it's inside "node_modules"
61
- new RegExp(`\\.(${KNOWN_ASSET_TYPES.join("|")})$`)
31
+ new RegExp(`\\.(${constants.KNOWN_ASSET_TYPES.join("|")})$`)
62
32
  ];
63
33
  const depsExternal = [
64
34
  /\.cjs\.js$/,
@@ -222,7 +192,7 @@ class ViteNodeServer {
222
192
  var _a, _b, _c;
223
193
  const ssrOptions = server.config.ssr;
224
194
  options.deps ?? (options.deps = {});
225
- options.deps.cacheDir = pathe.relative(server.config.root, server.config.cacheDir);
195
+ options.deps.cacheDir = pathe.relative(server.config.root, options.deps.cacheDir || server.config.cacheDir);
226
196
  if (ssrOptions) {
227
197
  if (ssrOptions.noExternal === true) {
228
198
  (_a = options.deps).inline ?? (_a.inline = true);
@@ -244,6 +214,15 @@ class ViteNodeServer {
244
214
  const customModuleDirectories = envValue == null ? void 0 : envValue.split(",");
245
215
  if (customModuleDirectories)
246
216
  options.deps.moduleDirectories.push(...customModuleDirectories);
217
+ options.deps.moduleDirectories = options.deps.moduleDirectories.map((dir) => {
218
+ if (!dir.startsWith("/"))
219
+ dir = `/${dir}`;
220
+ if (!dir.endsWith("/"))
221
+ dir += "/";
222
+ return pathe.normalize(dir);
223
+ });
224
+ if (!options.deps.moduleDirectories.includes("/node_modules/"))
225
+ options.deps.moduleDirectories.push("/node_modules/");
247
226
  }
248
227
  fetchPromiseMap = /* @__PURE__ */ new Map();
249
228
  transformPromiseMap = /* @__PURE__ */ new Map();
package/dist/server.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { TransformResult, ViteDevServer } from 'vite';
2
2
  import { E as EncodedSourceMap } from './types.d-7442d07f.js';
3
- import { g as DebuggerOptions, D as DepsHandlingOptions, f as ViteNodeServerOptions, F as FetchResult, e as ViteNodeResolveId } from './types-516036fa.js';
3
+ import { g as DebuggerOptions, D as DepsHandlingOptions, f as ViteNodeServerOptions, F as FetchResult, e as ViteNodeResolveId } from './types-e8623e9c.js';
4
4
  import 'vite/types/hot';
5
5
 
6
6
  declare class Debugger {
package/dist/server.mjs CHANGED
@@ -1,46 +1,16 @@
1
1
  import { performance } from 'node:perf_hooks';
2
2
  import { existsSync, promises } from 'node:fs';
3
- import { join, resolve, relative } from 'pathe';
3
+ import { join, resolve, relative, normalize } from 'pathe';
4
4
  import createDebug from 'debug';
5
5
  import { isValidNodeImport } from 'mlly';
6
6
  import { isNodeBuiltin, slash, toArray, normalizeModuleId, toFilePath } from './utils.mjs';
7
+ import { KNOWN_ASSET_TYPES } from './constants.mjs';
7
8
  import c from 'picocolors';
8
9
  import { withInlineSourcemap } from './source-map.mjs';
9
10
  import 'node:url';
10
11
  import 'node:module';
11
12
  import 'node:path';
12
13
 
13
- const KNOWN_ASSET_TYPES = [
14
- // images
15
- "apng",
16
- "png",
17
- "jpe?g",
18
- "jfif",
19
- "pjpeg",
20
- "pjp",
21
- "gif",
22
- "svg",
23
- "ico",
24
- "webp",
25
- "avif",
26
- // media
27
- "mp4",
28
- "webm",
29
- "ogg",
30
- "mp3",
31
- "wav",
32
- "flac",
33
- "aac",
34
- // fonts
35
- "woff2?",
36
- "eot",
37
- "ttf",
38
- "otf",
39
- // other
40
- "webmanifest",
41
- "pdf",
42
- "txt"
43
- ];
44
14
  const ESM_EXT_RE = /\.(es|esm|esm-browser|esm-bundler|es6|module)\.js$/;
45
15
  const ESM_FOLDER_RE = /\/(es|esm)\/(.*\.js)$/;
46
16
  const defaultInline = [
@@ -213,7 +183,7 @@ class ViteNodeServer {
213
183
  var _a, _b, _c;
214
184
  const ssrOptions = server.config.ssr;
215
185
  options.deps ?? (options.deps = {});
216
- options.deps.cacheDir = relative(server.config.root, server.config.cacheDir);
186
+ options.deps.cacheDir = relative(server.config.root, options.deps.cacheDir || server.config.cacheDir);
217
187
  if (ssrOptions) {
218
188
  if (ssrOptions.noExternal === true) {
219
189
  (_a = options.deps).inline ?? (_a.inline = true);
@@ -235,6 +205,15 @@ class ViteNodeServer {
235
205
  const customModuleDirectories = envValue == null ? void 0 : envValue.split(",");
236
206
  if (customModuleDirectories)
237
207
  options.deps.moduleDirectories.push(...customModuleDirectories);
208
+ options.deps.moduleDirectories = options.deps.moduleDirectories.map((dir) => {
209
+ if (!dir.startsWith("/"))
210
+ dir = `/${dir}`;
211
+ if (!dir.endsWith("/"))
212
+ dir += "/";
213
+ return normalize(dir);
214
+ });
215
+ if (!options.deps.moduleDirectories.includes("/node_modules/"))
216
+ options.deps.moduleDirectories.push("/node_modules/");
238
217
  }
239
218
  fetchPromiseMap = /* @__PURE__ */ new Map();
240
219
  transformPromiseMap = /* @__PURE__ */ new Map();
@@ -1,7 +1,7 @@
1
1
  import { ViteHotContext } from 'vite/types/hot';
2
2
  import { E as EncodedSourceMap } from './types.d-7442d07f.js';
3
3
 
4
- declare const DEFAULT_REQUEST_STUBS: Record<string, unknown>;
4
+ declare const DEFAULT_REQUEST_STUBS: Record<string, Record<string, unknown>>;
5
5
  declare class ModuleCacheMap extends Map<string, ModuleCache> {
6
6
  normalizePath(fsPath: string): string;
7
7
  /**
@@ -49,12 +49,19 @@ declare class ViteNodeRunner {
49
49
  dependencyRequest(id: string, fsPath: string, callstack: string[]): Promise<any>;
50
50
  /** @internal */
51
51
  directRequest(id: string, fsPath: string, _callstack: string[]): Promise<any>;
52
+ protected getContextPrimitives(): {
53
+ Object: ObjectConstructor;
54
+ Reflect: typeof Reflect;
55
+ Symbol: SymbolConstructor;
56
+ };
57
+ protected runModule(context: Record<string, any>, transformed: string): Promise<void>;
52
58
  prepareContext(context: Record<string, any>): Record<string, any>;
53
59
  /**
54
60
  * Define if a module should be interop-ed
55
61
  * This function mostly for the ability to override by subclass
56
62
  */
57
63
  shouldInterop(path: string, mod: any): boolean;
64
+ protected importExternalModule(path: string): Promise<any>;
58
65
  /**
59
66
  * Import a module and interop it
60
67
  */
package/dist/types.d.ts CHANGED
@@ -1,3 +1,3 @@
1
1
  import 'vite/types/hot';
2
2
  export { D as DecodedSourceMap, E as EncodedSourceMap } from './types.d-7442d07f.js';
3
- export { A as Arrayable, a as Awaitable, C as CreateHotContextFunction, g as DebuggerOptions, D as DepsHandlingOptions, b as FetchFunction, F as FetchResult, H as HotContext, d as ModuleCache, M as ModuleCacheMap, N as Nullable, R as RawSourceMap, c as ResolveIdFunction, S as StartOfSourceMap, e as ViteNodeResolveId, V as ViteNodeRunnerOptions, f as ViteNodeServerOptions } from './types-516036fa.js';
3
+ export { A as Arrayable, a as Awaitable, C as CreateHotContextFunction, g as DebuggerOptions, D as DepsHandlingOptions, b as FetchFunction, F as FetchResult, H as HotContext, d as ModuleCache, M as ModuleCacheMap, N as Nullable, R as RawSourceMap, c as ResolveIdFunction, S as StartOfSourceMap, e as ViteNodeResolveId, V as ViteNodeRunnerOptions, f as ViteNodeServerOptions } from './types-e8623e9c.js';
package/dist/utils.cjs CHANGED
@@ -8,6 +8,10 @@ var fs = require('fs');
8
8
  var pathe = require('pathe');
9
9
 
10
10
  const isWindows = process.platform === "win32";
11
+ const drive = isWindows ? process.cwd()[0] : null;
12
+ const driveOpposite = drive ? drive === drive.toUpperCase() ? drive.toLowerCase() : drive.toUpperCase() : null;
13
+ const driveRegexp = drive ? new RegExp(`(?:^|/@fs/)${drive}(:[\\/])`) : null;
14
+ const driveOppositeRegext = driveOpposite ? new RegExp(`(?:^|/@fs/)${driveOpposite}(:[\\/])`) : null;
11
15
  function slash(str) {
12
16
  return str.replace(/\\/g, "/");
13
17
  }
@@ -15,6 +19,8 @@ const VALID_ID_PREFIX = "/@id/";
15
19
  function normalizeRequestId(id, base) {
16
20
  if (base && id.startsWith(base))
17
21
  id = `/${id.slice(base.length)}`;
22
+ if (driveRegexp && !(driveRegexp == null ? void 0 : driveRegexp.test(id)) && (driveOppositeRegext == null ? void 0 : driveOppositeRegext.test(id)))
23
+ id = id.replace(driveOppositeRegext, `${drive}$1`);
18
24
  return id.replace(/^\/@id\/__x00__/, "\0").replace(/^\/@id\//, "").replace(/^__vite-browser-external:/, "").replace(/^file:/, "").replace(/^\/+/, "/").replace(/\?v=\w+/, "?").replace(/&v=\w+/, "").replace(/\?t=\w+/, "?").replace(/&t=\w+/, "").replace(/\?import/, "?").replace(/&import/, "").replace(/\?&/, "?").replace(/\?+$/, "");
19
25
  }
20
26
  const queryRE = /\?.*$/s;
@@ -92,9 +98,34 @@ function toArray(array) {
92
98
  return array;
93
99
  return [array];
94
100
  }
101
+ function getCachedData(cache, basedir, originalBasedir) {
102
+ const pkgData = cache.get(getFnpdCacheKey(basedir));
103
+ if (pkgData) {
104
+ traverseBetweenDirs(originalBasedir, basedir, (dir) => {
105
+ cache.set(getFnpdCacheKey(dir), pkgData);
106
+ });
107
+ return pkgData;
108
+ }
109
+ }
110
+ function setCacheData(cache, data, basedir, originalBasedir) {
111
+ cache.set(getFnpdCacheKey(basedir), data);
112
+ traverseBetweenDirs(originalBasedir, basedir, (dir) => {
113
+ cache.set(getFnpdCacheKey(dir), data);
114
+ });
115
+ }
116
+ function getFnpdCacheKey(basedir) {
117
+ return `fnpd_${basedir}`;
118
+ }
119
+ function traverseBetweenDirs(longerDir, shorterDir, cb) {
120
+ while (longerDir !== shorterDir) {
121
+ cb(longerDir);
122
+ longerDir = pathe.dirname(longerDir);
123
+ }
124
+ }
95
125
 
96
126
  exports.VALID_ID_PREFIX = VALID_ID_PREFIX;
97
127
  exports.cleanUrl = cleanUrl;
128
+ exports.getCachedData = getCachedData;
98
129
  exports.hashRE = hashRE;
99
130
  exports.isInternalRequest = isInternalRequest;
100
131
  exports.isNodeBuiltin = isNodeBuiltin;
@@ -103,6 +134,7 @@ exports.isWindows = isWindows;
103
134
  exports.normalizeModuleId = normalizeModuleId;
104
135
  exports.normalizeRequestId = normalizeRequestId;
105
136
  exports.queryRE = queryRE;
137
+ exports.setCacheData = setCacheData;
106
138
  exports.slash = slash;
107
139
  exports.toArray = toArray;
108
140
  exports.toFilePath = toFilePath;
package/dist/utils.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { N as Nullable, A as Arrayable } from './types-516036fa.js';
1
+ import { N as Nullable, A as Arrayable } from './types-e8623e9c.js';
2
2
  import 'vite/types/hot';
3
3
  import './types.d-7442d07f.js';
4
4
 
@@ -23,5 +23,7 @@ declare function isNodeBuiltin(id: string): boolean;
23
23
  * @category Array
24
24
  */
25
25
  declare function toArray<T>(array?: Nullable<Arrayable<T>>): Array<T>;
26
+ declare function getCachedData<T>(cache: Map<string, T>, basedir: string, originalBasedir: string): NonNullable<T> | undefined;
27
+ declare function setCacheData<T>(cache: Map<string, T>, data: T, basedir: string, originalBasedir: string): void;
26
28
 
27
- export { VALID_ID_PREFIX, cleanUrl, hashRE, isInternalRequest, isNodeBuiltin, isPrimitive, isWindows, normalizeModuleId, normalizeRequestId, queryRE, slash, toArray, toFilePath };
29
+ export { VALID_ID_PREFIX, cleanUrl, getCachedData, hashRE, isInternalRequest, isNodeBuiltin, isPrimitive, isWindows, normalizeModuleId, normalizeRequestId, queryRE, setCacheData, slash, toArray, toFilePath };
package/dist/utils.mjs CHANGED
@@ -1,9 +1,13 @@
1
1
  import { fileURLToPath, pathToFileURL } from 'node:url';
2
2
  import { builtinModules } from 'node:module';
3
3
  import { existsSync } from 'node:fs';
4
- import { resolve } from 'pathe';
4
+ import { resolve, dirname } from 'pathe';
5
5
 
6
6
  const isWindows = process.platform === "win32";
7
+ const drive = isWindows ? process.cwd()[0] : null;
8
+ const driveOpposite = drive ? drive === drive.toUpperCase() ? drive.toLowerCase() : drive.toUpperCase() : null;
9
+ const driveRegexp = drive ? new RegExp(`(?:^|/@fs/)${drive}(:[\\/])`) : null;
10
+ const driveOppositeRegext = driveOpposite ? new RegExp(`(?:^|/@fs/)${driveOpposite}(:[\\/])`) : null;
7
11
  function slash(str) {
8
12
  return str.replace(/\\/g, "/");
9
13
  }
@@ -11,6 +15,8 @@ const VALID_ID_PREFIX = "/@id/";
11
15
  function normalizeRequestId(id, base) {
12
16
  if (base && id.startsWith(base))
13
17
  id = `/${id.slice(base.length)}`;
18
+ if (driveRegexp && !(driveRegexp == null ? void 0 : driveRegexp.test(id)) && (driveOppositeRegext == null ? void 0 : driveOppositeRegext.test(id)))
19
+ id = id.replace(driveOppositeRegext, `${drive}$1`);
14
20
  return id.replace(/^\/@id\/__x00__/, "\0").replace(/^\/@id\//, "").replace(/^__vite-browser-external:/, "").replace(/^file:/, "").replace(/^\/+/, "/").replace(/\?v=\w+/, "?").replace(/&v=\w+/, "").replace(/\?t=\w+/, "?").replace(/&t=\w+/, "").replace(/\?import/, "?").replace(/&import/, "").replace(/\?&/, "?").replace(/\?+$/, "");
15
21
  }
16
22
  const queryRE = /\?.*$/s;
@@ -88,5 +94,29 @@ function toArray(array) {
88
94
  return array;
89
95
  return [array];
90
96
  }
97
+ function getCachedData(cache, basedir, originalBasedir) {
98
+ const pkgData = cache.get(getFnpdCacheKey(basedir));
99
+ if (pkgData) {
100
+ traverseBetweenDirs(originalBasedir, basedir, (dir) => {
101
+ cache.set(getFnpdCacheKey(dir), pkgData);
102
+ });
103
+ return pkgData;
104
+ }
105
+ }
106
+ function setCacheData(cache, data, basedir, originalBasedir) {
107
+ cache.set(getFnpdCacheKey(basedir), data);
108
+ traverseBetweenDirs(originalBasedir, basedir, (dir) => {
109
+ cache.set(getFnpdCacheKey(dir), data);
110
+ });
111
+ }
112
+ function getFnpdCacheKey(basedir) {
113
+ return `fnpd_${basedir}`;
114
+ }
115
+ function traverseBetweenDirs(longerDir, shorterDir, cb) {
116
+ while (longerDir !== shorterDir) {
117
+ cb(longerDir);
118
+ longerDir = dirname(longerDir);
119
+ }
120
+ }
91
121
 
92
- export { VALID_ID_PREFIX, cleanUrl, hashRE, isInternalRequest, isNodeBuiltin, isPrimitive, isWindows, normalizeModuleId, normalizeRequestId, queryRE, slash, toArray, toFilePath };
122
+ export { VALID_ID_PREFIX, cleanUrl, getCachedData, hashRE, isInternalRequest, isNodeBuiltin, isPrimitive, isWindows, normalizeModuleId, normalizeRequestId, queryRE, setCacheData, slash, toArray, toFilePath };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vite-node",
3
- "version": "0.33.0",
3
+ "version": "0.34.1",
4
4
  "description": "Vite as Node.js runtime",
5
5
  "author": "Anthony Fu <anthonyfu117@hotmail.com>",
6
6
  "license": "MIT",
@@ -45,7 +45,13 @@
45
45
  "types": "./dist/source-map.d.ts",
46
46
  "require": "./dist/source-map.cjs",
47
47
  "import": "./dist/source-map.mjs"
48
- }
48
+ },
49
+ "./constants": {
50
+ "types": "./dist/constants.d.ts",
51
+ "require": "./dist/constants.cjs",
52
+ "import": "./dist/constants.mjs"
53
+ },
54
+ "./*": "./*"
49
55
  },
50
56
  "main": "./dist/index.mjs",
51
57
  "module": "./dist/index.mjs",