vite-node 1.2.2 → 1.3.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/README.md CHANGED
@@ -6,7 +6,7 @@
6
6
  vite-node
7
7
  </h1>
8
8
  <p align="center">
9
- Vite as Node runtime.<br>The engine powers <a href="https://github.com/vitest-dev/vitest">Vitest</a> and <a href="https://github.com/nuxt/framework">Nuxt 3 Dev SSR</a>.
9
+ Vite as Node runtime.<br>The engine that powers <a href="https://github.com/vitest-dev/vitest">Vitest</a> and <a href="https://github.com/nuxt/framework">Nuxt 3 Dev SSR</a>.
10
10
  <p>
11
11
  <p align="center">
12
12
  <a href="https://www.npmjs.com/package/vitest"><img src="https://img.shields.io/npm/v/vite-node?color=FCC72B&label="></a>
@@ -0,0 +1,260 @@
1
+ 'use strict';
2
+
3
+ var node_events = require('node:events');
4
+ var c = require('picocolors');
5
+ var createDebug = require('debug');
6
+ var utils = require('./utils.cjs');
7
+
8
+ function createHmrEmitter() {
9
+ const emitter = new node_events.EventEmitter();
10
+ return emitter;
11
+ }
12
+ function viteNodeHmrPlugin() {
13
+ const emitter = createHmrEmitter();
14
+ return {
15
+ name: "vite-node:hmr",
16
+ config() {
17
+ if (process.platform === "darwin" && process.env.VITE_TEST_WATCHER_DEBUG) {
18
+ return {
19
+ server: {
20
+ watch: {
21
+ useFsEvents: false,
22
+ usePolling: false
23
+ }
24
+ }
25
+ };
26
+ }
27
+ },
28
+ configureServer(server) {
29
+ const _send = server.ws.send;
30
+ server.emitter = emitter;
31
+ server.ws.send = function(payload) {
32
+ _send(payload);
33
+ emitter.emit("message", payload);
34
+ };
35
+ if (process.env.VITE_TEST_WATCHER_DEBUG) {
36
+ server.watcher.on("ready", () => {
37
+ console.log("[debug] watcher is ready");
38
+ });
39
+ }
40
+ }
41
+ };
42
+ }
43
+
44
+ const debugHmr = createDebug("vite-node:hmr");
45
+ const cache = /* @__PURE__ */ new WeakMap();
46
+ function getCache(runner) {
47
+ if (!cache.has(runner)) {
48
+ cache.set(runner, {
49
+ hotModulesMap: /* @__PURE__ */ new Map(),
50
+ dataMap: /* @__PURE__ */ new Map(),
51
+ disposeMap: /* @__PURE__ */ new Map(),
52
+ pruneMap: /* @__PURE__ */ new Map(),
53
+ customListenersMap: /* @__PURE__ */ new Map(),
54
+ ctxToListenersMap: /* @__PURE__ */ new Map(),
55
+ messageBuffer: [],
56
+ isFirstUpdate: false,
57
+ pending: false,
58
+ queued: []
59
+ });
60
+ }
61
+ return cache.get(runner);
62
+ }
63
+ function sendMessageBuffer(runner, emitter) {
64
+ const maps = getCache(runner);
65
+ maps.messageBuffer.forEach((msg) => emitter.emit("custom", msg));
66
+ maps.messageBuffer.length = 0;
67
+ }
68
+ async function reload(runner, files) {
69
+ Array.from(runner.moduleCache.keys()).forEach((fsPath) => {
70
+ if (!fsPath.includes("node_modules"))
71
+ runner.moduleCache.delete(fsPath);
72
+ });
73
+ return Promise.all(files.map((file) => runner.executeId(file)));
74
+ }
75
+ async function notifyListeners(runner, event, data) {
76
+ const maps = getCache(runner);
77
+ const cbs = maps.customListenersMap.get(event);
78
+ if (cbs)
79
+ await Promise.all(cbs.map((cb) => cb(data)));
80
+ }
81
+ async function queueUpdate(runner, p) {
82
+ const maps = getCache(runner);
83
+ maps.queued.push(p);
84
+ if (!maps.pending) {
85
+ maps.pending = true;
86
+ await Promise.resolve();
87
+ maps.pending = false;
88
+ const loading = [...maps.queued];
89
+ maps.queued = [];
90
+ (await Promise.all(loading)).forEach((fn) => fn && fn());
91
+ }
92
+ }
93
+ async function fetchUpdate(runner, { path, acceptedPath }) {
94
+ path = utils.normalizeRequestId(path);
95
+ acceptedPath = utils.normalizeRequestId(acceptedPath);
96
+ const maps = getCache(runner);
97
+ const mod = maps.hotModulesMap.get(path);
98
+ if (!mod) {
99
+ return;
100
+ }
101
+ const isSelfUpdate = path === acceptedPath;
102
+ let fetchedModule;
103
+ const qualifiedCallbacks = mod.callbacks.filter(
104
+ ({ deps }) => deps.includes(acceptedPath)
105
+ );
106
+ if (isSelfUpdate || qualifiedCallbacks.length > 0) {
107
+ const disposer = maps.disposeMap.get(acceptedPath);
108
+ if (disposer)
109
+ await disposer(maps.dataMap.get(acceptedPath));
110
+ try {
111
+ [fetchedModule] = await reload(runner, [acceptedPath]);
112
+ } catch (e) {
113
+ warnFailedFetch(e, acceptedPath);
114
+ }
115
+ }
116
+ return () => {
117
+ for (const { deps, fn } of qualifiedCallbacks)
118
+ fn(deps.map((dep) => dep === acceptedPath ? fetchedModule : void 0));
119
+ const loggedPath = isSelfUpdate ? path : `${acceptedPath} via ${path}`;
120
+ console.log(`${c.cyan("[vite-node]")} hot updated: ${loggedPath}`);
121
+ };
122
+ }
123
+ function warnFailedFetch(err, path) {
124
+ if (!err.message.match("fetch"))
125
+ console.error(err);
126
+ console.error(
127
+ `[hmr] Failed to reload ${path}. This could be due to syntax errors or importing non-existent modules. (see errors above)`
128
+ );
129
+ }
130
+ async function handleMessage(runner, emitter, files, payload) {
131
+ const maps = getCache(runner);
132
+ switch (payload.type) {
133
+ case "connected":
134
+ sendMessageBuffer(runner, emitter);
135
+ break;
136
+ case "update":
137
+ await notifyListeners(runner, "vite:beforeUpdate", payload);
138
+ await Promise.all(payload.updates.map((update) => {
139
+ if (update.type === "js-update")
140
+ return queueUpdate(runner, fetchUpdate(runner, update));
141
+ console.error(`${c.cyan("[vite-node]")} no support css hmr.}`);
142
+ return null;
143
+ }));
144
+ await notifyListeners(runner, "vite:afterUpdate", payload);
145
+ break;
146
+ case "full-reload":
147
+ await notifyListeners(runner, "vite:beforeFullReload", payload);
148
+ maps.customListenersMap.delete("vite:beforeFullReload");
149
+ await reload(runner, files);
150
+ break;
151
+ case "custom":
152
+ await notifyListeners(runner, payload.event, payload.data);
153
+ break;
154
+ case "prune":
155
+ await notifyListeners(runner, "vite:beforePrune", payload);
156
+ payload.paths.forEach((path) => {
157
+ const fn = maps.pruneMap.get(path);
158
+ if (fn)
159
+ fn(maps.dataMap.get(path));
160
+ });
161
+ break;
162
+ case "error": {
163
+ await notifyListeners(runner, "vite:error", payload);
164
+ const err = payload.err;
165
+ console.error(`${c.cyan("[vite-node]")} Internal Server Error
166
+ ${err.message}
167
+ ${err.stack}`);
168
+ break;
169
+ }
170
+ }
171
+ }
172
+ function createHotContext(runner, emitter, files, ownerPath) {
173
+ debugHmr("createHotContext", ownerPath);
174
+ const maps = getCache(runner);
175
+ if (!maps.dataMap.has(ownerPath))
176
+ maps.dataMap.set(ownerPath, {});
177
+ const mod = maps.hotModulesMap.get(ownerPath);
178
+ if (mod)
179
+ mod.callbacks = [];
180
+ const newListeners = /* @__PURE__ */ new Map();
181
+ maps.ctxToListenersMap.set(ownerPath, newListeners);
182
+ function acceptDeps(deps, callback = () => {
183
+ }) {
184
+ const mod2 = maps.hotModulesMap.get(ownerPath) || {
185
+ id: ownerPath,
186
+ callbacks: []
187
+ };
188
+ mod2.callbacks.push({
189
+ deps,
190
+ fn: callback
191
+ });
192
+ maps.hotModulesMap.set(ownerPath, mod2);
193
+ }
194
+ const hot = {
195
+ get data() {
196
+ return maps.dataMap.get(ownerPath);
197
+ },
198
+ acceptExports(_, callback) {
199
+ acceptDeps([ownerPath], callback && (([mod2]) => callback(mod2)));
200
+ },
201
+ accept(deps, callback) {
202
+ if (typeof deps === "function" || !deps) {
203
+ acceptDeps([ownerPath], ([mod2]) => deps && deps(mod2));
204
+ } else if (typeof deps === "string") {
205
+ acceptDeps([deps], ([mod2]) => callback && callback(mod2));
206
+ } else if (Array.isArray(deps)) {
207
+ acceptDeps(deps, callback);
208
+ } else {
209
+ throw new TypeError("invalid hot.accept() usage.");
210
+ }
211
+ },
212
+ dispose(cb) {
213
+ maps.disposeMap.set(ownerPath, cb);
214
+ },
215
+ prune(cb) {
216
+ maps.pruneMap.set(ownerPath, cb);
217
+ },
218
+ invalidate() {
219
+ notifyListeners(runner, "vite:invalidate", { path: ownerPath, message: void 0 });
220
+ return reload(runner, files);
221
+ },
222
+ on(event, cb) {
223
+ const addToMap = (map) => {
224
+ const existing = map.get(event) || [];
225
+ existing.push(cb);
226
+ map.set(event, existing);
227
+ };
228
+ addToMap(maps.customListenersMap);
229
+ addToMap(newListeners);
230
+ },
231
+ off(event, cb) {
232
+ const removeFromMap = (map) => {
233
+ const existing = map.get(event);
234
+ if (existing === void 0)
235
+ return;
236
+ const pruned = existing.filter((l) => l !== cb);
237
+ if (pruned.length === 0) {
238
+ map.delete(event);
239
+ return;
240
+ }
241
+ map.set(event, pruned);
242
+ };
243
+ removeFromMap(maps.customListenersMap);
244
+ removeFromMap(newListeners);
245
+ },
246
+ send(event, data) {
247
+ maps.messageBuffer.push(JSON.stringify({ type: "custom", event, data }));
248
+ sendMessageBuffer(runner, emitter);
249
+ }
250
+ };
251
+ return hot;
252
+ }
253
+
254
+ exports.createHmrEmitter = createHmrEmitter;
255
+ exports.createHotContext = createHotContext;
256
+ exports.getCache = getCache;
257
+ exports.handleMessage = handleMessage;
258
+ exports.reload = reload;
259
+ exports.sendMessageBuffer = sendMessageBuffer;
260
+ exports.viteNodeHmrPlugin = viteNodeHmrPlugin;
@@ -0,0 +1,252 @@
1
+ import { EventEmitter } from 'node:events';
2
+ import c from 'picocolors';
3
+ import createDebug from 'debug';
4
+ import { normalizeRequestId } from './utils.mjs';
5
+
6
+ function createHmrEmitter() {
7
+ const emitter = new EventEmitter();
8
+ return emitter;
9
+ }
10
+ function viteNodeHmrPlugin() {
11
+ const emitter = createHmrEmitter();
12
+ return {
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
+ },
26
+ configureServer(server) {
27
+ const _send = server.ws.send;
28
+ server.emitter = emitter;
29
+ server.ws.send = function(payload) {
30
+ _send(payload);
31
+ emitter.emit("message", payload);
32
+ };
33
+ if (process.env.VITE_TEST_WATCHER_DEBUG) {
34
+ server.watcher.on("ready", () => {
35
+ console.log("[debug] watcher is ready");
36
+ });
37
+ }
38
+ }
39
+ };
40
+ }
41
+
42
+ const debugHmr = createDebug("vite-node:hmr");
43
+ const cache = /* @__PURE__ */ new WeakMap();
44
+ function getCache(runner) {
45
+ if (!cache.has(runner)) {
46
+ cache.set(runner, {
47
+ hotModulesMap: /* @__PURE__ */ new Map(),
48
+ dataMap: /* @__PURE__ */ new Map(),
49
+ disposeMap: /* @__PURE__ */ new Map(),
50
+ pruneMap: /* @__PURE__ */ new Map(),
51
+ customListenersMap: /* @__PURE__ */ new Map(),
52
+ ctxToListenersMap: /* @__PURE__ */ new Map(),
53
+ messageBuffer: [],
54
+ isFirstUpdate: false,
55
+ pending: false,
56
+ queued: []
57
+ });
58
+ }
59
+ return cache.get(runner);
60
+ }
61
+ function sendMessageBuffer(runner, emitter) {
62
+ const maps = getCache(runner);
63
+ maps.messageBuffer.forEach((msg) => emitter.emit("custom", msg));
64
+ maps.messageBuffer.length = 0;
65
+ }
66
+ async function reload(runner, files) {
67
+ Array.from(runner.moduleCache.keys()).forEach((fsPath) => {
68
+ if (!fsPath.includes("node_modules"))
69
+ runner.moduleCache.delete(fsPath);
70
+ });
71
+ return Promise.all(files.map((file) => runner.executeId(file)));
72
+ }
73
+ async function notifyListeners(runner, event, data) {
74
+ const maps = getCache(runner);
75
+ const cbs = maps.customListenersMap.get(event);
76
+ if (cbs)
77
+ await Promise.all(cbs.map((cb) => cb(data)));
78
+ }
79
+ async function queueUpdate(runner, p) {
80
+ const maps = getCache(runner);
81
+ maps.queued.push(p);
82
+ if (!maps.pending) {
83
+ maps.pending = true;
84
+ await Promise.resolve();
85
+ maps.pending = false;
86
+ const loading = [...maps.queued];
87
+ maps.queued = [];
88
+ (await Promise.all(loading)).forEach((fn) => fn && fn());
89
+ }
90
+ }
91
+ async function fetchUpdate(runner, { path, acceptedPath }) {
92
+ path = normalizeRequestId(path);
93
+ acceptedPath = normalizeRequestId(acceptedPath);
94
+ const maps = getCache(runner);
95
+ const mod = maps.hotModulesMap.get(path);
96
+ if (!mod) {
97
+ return;
98
+ }
99
+ const isSelfUpdate = path === acceptedPath;
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);
112
+ }
113
+ }
114
+ return () => {
115
+ for (const { deps, fn } of qualifiedCallbacks)
116
+ fn(deps.map((dep) => dep === acceptedPath ? fetchedModule : void 0));
117
+ const loggedPath = isSelfUpdate ? path : `${acceptedPath} via ${path}`;
118
+ console.log(`${c.cyan("[vite-node]")} hot updated: ${loggedPath}`);
119
+ };
120
+ }
121
+ function warnFailedFetch(err, path) {
122
+ if (!err.message.match("fetch"))
123
+ console.error(err);
124
+ console.error(
125
+ `[hmr] Failed to reload ${path}. This could be due to syntax errors or importing non-existent modules. (see errors above)`
126
+ );
127
+ }
128
+ async function handleMessage(runner, emitter, files, payload) {
129
+ const maps = getCache(runner);
130
+ switch (payload.type) {
131
+ case "connected":
132
+ sendMessageBuffer(runner, emitter);
133
+ break;
134
+ case "update":
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);
143
+ break;
144
+ case "full-reload":
145
+ await notifyListeners(runner, "vite:beforeFullReload", payload);
146
+ maps.customListenersMap.delete("vite:beforeFullReload");
147
+ await reload(runner, files);
148
+ break;
149
+ case "custom":
150
+ await notifyListeners(runner, payload.event, payload.data);
151
+ break;
152
+ case "prune":
153
+ await notifyListeners(runner, "vite:beforePrune", payload);
154
+ payload.paths.forEach((path) => {
155
+ const fn = maps.pruneMap.get(path);
156
+ if (fn)
157
+ fn(maps.dataMap.get(path));
158
+ });
159
+ break;
160
+ case "error": {
161
+ await notifyListeners(runner, "vite:error", payload);
162
+ const err = payload.err;
163
+ console.error(`${c.cyan("[vite-node]")} Internal Server Error
164
+ ${err.message}
165
+ ${err.stack}`);
166
+ break;
167
+ }
168
+ }
169
+ }
170
+ function createHotContext(runner, emitter, files, ownerPath) {
171
+ debugHmr("createHotContext", ownerPath);
172
+ const maps = getCache(runner);
173
+ if (!maps.dataMap.has(ownerPath))
174
+ maps.dataMap.set(ownerPath, {});
175
+ const mod = maps.hotModulesMap.get(ownerPath);
176
+ if (mod)
177
+ mod.callbacks = [];
178
+ const newListeners = /* @__PURE__ */ new Map();
179
+ maps.ctxToListenersMap.set(ownerPath, newListeners);
180
+ function acceptDeps(deps, callback = () => {
181
+ }) {
182
+ const mod2 = maps.hotModulesMap.get(ownerPath) || {
183
+ id: ownerPath,
184
+ callbacks: []
185
+ };
186
+ mod2.callbacks.push({
187
+ deps,
188
+ fn: callback
189
+ });
190
+ maps.hotModulesMap.set(ownerPath, mod2);
191
+ }
192
+ const hot = {
193
+ get data() {
194
+ return maps.dataMap.get(ownerPath);
195
+ },
196
+ acceptExports(_, callback) {
197
+ acceptDeps([ownerPath], callback && (([mod2]) => callback(mod2)));
198
+ },
199
+ accept(deps, callback) {
200
+ if (typeof deps === "function" || !deps) {
201
+ acceptDeps([ownerPath], ([mod2]) => deps && deps(mod2));
202
+ } else if (typeof deps === "string") {
203
+ acceptDeps([deps], ([mod2]) => callback && callback(mod2));
204
+ } else if (Array.isArray(deps)) {
205
+ acceptDeps(deps, callback);
206
+ } else {
207
+ throw new TypeError("invalid hot.accept() usage.");
208
+ }
209
+ },
210
+ dispose(cb) {
211
+ maps.disposeMap.set(ownerPath, cb);
212
+ },
213
+ prune(cb) {
214
+ maps.pruneMap.set(ownerPath, cb);
215
+ },
216
+ invalidate() {
217
+ notifyListeners(runner, "vite:invalidate", { path: ownerPath, message: void 0 });
218
+ return reload(runner, files);
219
+ },
220
+ on(event, cb) {
221
+ const addToMap = (map) => {
222
+ const existing = map.get(event) || [];
223
+ existing.push(cb);
224
+ map.set(event, existing);
225
+ };
226
+ addToMap(maps.customListenersMap);
227
+ addToMap(newListeners);
228
+ },
229
+ off(event, cb) {
230
+ const removeFromMap = (map) => {
231
+ const existing = map.get(event);
232
+ if (existing === void 0)
233
+ return;
234
+ const pruned = existing.filter((l) => l !== cb);
235
+ if (pruned.length === 0) {
236
+ map.delete(event);
237
+ return;
238
+ }
239
+ map.set(event, pruned);
240
+ };
241
+ removeFromMap(maps.customListenersMap);
242
+ removeFromMap(newListeners);
243
+ },
244
+ send(event, data) {
245
+ maps.messageBuffer.push(JSON.stringify({ type: "custom", event, data }));
246
+ sendMessageBuffer(runner, emitter);
247
+ }
248
+ };
249
+ return hot;
250
+ }
251
+
252
+ export { createHotContext as a, createHmrEmitter as c, getCache as g, handleMessage as h, reload as r, sendMessageBuffer as s, viteNodeHmrPlugin as v };
package/dist/cli.cjs CHANGED
@@ -7,8 +7,8 @@ var vite = require('vite');
7
7
  var server = require('./server.cjs');
8
8
  var client = require('./client.cjs');
9
9
  var utils = require('./utils.cjs');
10
+ var hmr = require('./chunk-hmr.cjs');
10
11
  var sourceMap = require('./source-map.cjs');
11
- var hmr = require('./hmr.cjs');
12
12
  require('node:perf_hooks');
13
13
  require('node:fs');
14
14
  require('node:assert');
@@ -20,7 +20,7 @@ require('node:url');
20
20
  require('node:vm');
21
21
  require('node:events');
22
22
 
23
- var version = "1.2.2";
23
+ var version = "1.3.0";
24
24
 
25
25
  const cli = cac("vite-node");
26
26
  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");
package/dist/cli.d.ts CHANGED
@@ -2,14 +2,14 @@ import { V as ViteNodeServerOptions } from './index-WT31LSgS.js';
2
2
  import './trace-mapping.d-xyIfZtPm.js';
3
3
 
4
4
  interface CliOptions {
5
- root?: string;
6
- script?: boolean;
7
- config?: string;
8
- mode?: string;
9
- watch?: boolean;
10
- options?: ViteNodeServerOptionsCLI;
11
- version?: boolean;
12
- help?: boolean;
5
+ 'root'?: string;
6
+ 'script'?: boolean;
7
+ 'config'?: string;
8
+ 'mode'?: string;
9
+ 'watch'?: boolean;
10
+ 'options'?: ViteNodeServerOptionsCLI;
11
+ 'version'?: boolean;
12
+ 'help'?: boolean;
13
13
  '--'?: string[];
14
14
  }
15
15
  type Optional<T> = T | undefined;
package/dist/cli.mjs CHANGED
@@ -6,7 +6,7 @@ import { ViteNodeServer } from './server.mjs';
6
6
  import { ViteNodeRunner } from './client.mjs';
7
7
  import { toArray } from './utils.mjs';
8
8
  import { installSourcemapsSupport } from './source-map.mjs';
9
- import { viteNodeHmrPlugin, createHotContext, handleMessage } from './hmr.mjs';
9
+ import { v as viteNodeHmrPlugin, a as createHotContext, h as handleMessage } from './chunk-hmr.mjs';
10
10
  import 'node:perf_hooks';
11
11
  import 'node:fs';
12
12
  import 'node:assert';
@@ -18,7 +18,7 @@ import 'node:url';
18
18
  import 'node:vm';
19
19
  import 'node:events';
20
20
 
21
- var version = "1.2.2";
21
+ var version = "1.3.0";
22
22
 
23
23
  const cli = cac("vite-node");
24
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");
package/dist/hmr.cjs CHANGED
@@ -1,264 +1,21 @@
1
1
  'use strict';
2
2
 
3
- var node_events = require('node:events');
4
- var c = require('picocolors');
5
- var createDebug = require('debug');
6
- var utils = require('./utils.cjs');
3
+ var hmr = require('./chunk-hmr.cjs');
4
+ require('node:events');
5
+ require('picocolors');
6
+ require('debug');
7
+ require('./utils.cjs');
7
8
  require('node:url');
8
9
  require('node:module');
9
10
  require('node:fs');
10
11
  require('pathe');
11
12
 
12
- function createHmrEmitter() {
13
- const emitter = new node_events.EventEmitter();
14
- return emitter;
15
- }
16
- function viteNodeHmrPlugin() {
17
- const emitter = createHmrEmitter();
18
- return {
19
- name: "vite-node:hmr",
20
- config() {
21
- if (process.platform === "darwin" && process.env.VITE_TEST_WATCHER_DEBUG) {
22
- return {
23
- server: {
24
- watch: {
25
- useFsEvents: false,
26
- usePolling: false
27
- }
28
- }
29
- };
30
- }
31
- },
32
- configureServer(server) {
33
- const _send = server.ws.send;
34
- server.emitter = emitter;
35
- server.ws.send = function(payload) {
36
- _send(payload);
37
- emitter.emit("message", payload);
38
- };
39
- if (process.env.VITE_TEST_WATCHER_DEBUG) {
40
- server.watcher.on("ready", () => {
41
- console.log("[debug] watcher is ready");
42
- });
43
- }
44
- }
45
- };
46
- }
47
13
 
48
- const debugHmr = createDebug("vite-node:hmr");
49
- const cache = /* @__PURE__ */ new WeakMap();
50
- function getCache(runner) {
51
- if (!cache.has(runner)) {
52
- cache.set(runner, {
53
- hotModulesMap: /* @__PURE__ */ new Map(),
54
- dataMap: /* @__PURE__ */ new Map(),
55
- disposeMap: /* @__PURE__ */ new Map(),
56
- pruneMap: /* @__PURE__ */ new Map(),
57
- customListenersMap: /* @__PURE__ */ new Map(),
58
- ctxToListenersMap: /* @__PURE__ */ new Map(),
59
- messageBuffer: [],
60
- isFirstUpdate: false,
61
- pending: false,
62
- queued: []
63
- });
64
- }
65
- return cache.get(runner);
66
- }
67
- function sendMessageBuffer(runner, emitter) {
68
- const maps = getCache(runner);
69
- maps.messageBuffer.forEach((msg) => emitter.emit("custom", msg));
70
- maps.messageBuffer.length = 0;
71
- }
72
- async function reload(runner, files) {
73
- Array.from(runner.moduleCache.keys()).forEach((fsPath) => {
74
- if (!fsPath.includes("node_modules"))
75
- runner.moduleCache.delete(fsPath);
76
- });
77
- return Promise.all(files.map((file) => runner.executeId(file)));
78
- }
79
- async function notifyListeners(runner, event, data) {
80
- const maps = getCache(runner);
81
- const cbs = maps.customListenersMap.get(event);
82
- if (cbs)
83
- await Promise.all(cbs.map((cb) => cb(data)));
84
- }
85
- async function queueUpdate(runner, p) {
86
- const maps = getCache(runner);
87
- maps.queued.push(p);
88
- if (!maps.pending) {
89
- maps.pending = true;
90
- await Promise.resolve();
91
- maps.pending = false;
92
- const loading = [...maps.queued];
93
- maps.queued = [];
94
- (await Promise.all(loading)).forEach((fn) => fn && fn());
95
- }
96
- }
97
- async function fetchUpdate(runner, { path, acceptedPath }) {
98
- path = utils.normalizeRequestId(path);
99
- acceptedPath = utils.normalizeRequestId(acceptedPath);
100
- const maps = getCache(runner);
101
- const mod = maps.hotModulesMap.get(path);
102
- if (!mod) {
103
- return;
104
- }
105
- const isSelfUpdate = path === acceptedPath;
106
- let fetchedModule;
107
- const qualifiedCallbacks = mod.callbacks.filter(
108
- ({ deps }) => deps.includes(acceptedPath)
109
- );
110
- if (isSelfUpdate || qualifiedCallbacks.length > 0) {
111
- const disposer = maps.disposeMap.get(acceptedPath);
112
- if (disposer)
113
- await disposer(maps.dataMap.get(acceptedPath));
114
- try {
115
- [fetchedModule] = await reload(runner, [acceptedPath]);
116
- } catch (e) {
117
- warnFailedFetch(e, acceptedPath);
118
- }
119
- }
120
- return () => {
121
- for (const { deps, fn } of qualifiedCallbacks)
122
- fn(deps.map((dep) => dep === acceptedPath ? fetchedModule : void 0));
123
- const loggedPath = isSelfUpdate ? path : `${acceptedPath} via ${path}`;
124
- console.log(`${c.cyan("[vite-node]")} hot updated: ${loggedPath}`);
125
- };
126
- }
127
- function warnFailedFetch(err, path) {
128
- if (!err.message.match("fetch"))
129
- console.error(err);
130
- console.error(
131
- `[hmr] Failed to reload ${path}. This could be due to syntax errors or importing non-existent modules. (see errors above)`
132
- );
133
- }
134
- async function handleMessage(runner, emitter, files, payload) {
135
- const maps = getCache(runner);
136
- switch (payload.type) {
137
- case "connected":
138
- sendMessageBuffer(runner, emitter);
139
- break;
140
- case "update":
141
- await notifyListeners(runner, "vite:beforeUpdate", payload);
142
- await Promise.all(payload.updates.map((update) => {
143
- if (update.type === "js-update")
144
- return queueUpdate(runner, fetchUpdate(runner, update));
145
- console.error(`${c.cyan("[vite-node]")} no support css hmr.}`);
146
- return null;
147
- }));
148
- await notifyListeners(runner, "vite:afterUpdate", payload);
149
- break;
150
- case "full-reload":
151
- await notifyListeners(runner, "vite:beforeFullReload", payload);
152
- maps.customListenersMap.delete("vite:beforeFullReload");
153
- await reload(runner, files);
154
- break;
155
- case "custom":
156
- await notifyListeners(runner, payload.event, payload.data);
157
- break;
158
- case "prune":
159
- await notifyListeners(runner, "vite:beforePrune", payload);
160
- payload.paths.forEach((path) => {
161
- const fn = maps.pruneMap.get(path);
162
- if (fn)
163
- fn(maps.dataMap.get(path));
164
- });
165
- break;
166
- case "error": {
167
- await notifyListeners(runner, "vite:error", payload);
168
- const err = payload.err;
169
- console.error(`${c.cyan("[vite-node]")} Internal Server Error
170
- ${err.message}
171
- ${err.stack}`);
172
- break;
173
- }
174
- }
175
- }
176
- function createHotContext(runner, emitter, files, ownerPath) {
177
- debugHmr("createHotContext", ownerPath);
178
- const maps = getCache(runner);
179
- if (!maps.dataMap.has(ownerPath))
180
- maps.dataMap.set(ownerPath, {});
181
- const mod = maps.hotModulesMap.get(ownerPath);
182
- if (mod)
183
- mod.callbacks = [];
184
- const newListeners = /* @__PURE__ */ new Map();
185
- maps.ctxToListenersMap.set(ownerPath, newListeners);
186
- function acceptDeps(deps, callback = () => {
187
- }) {
188
- const mod2 = maps.hotModulesMap.get(ownerPath) || {
189
- id: ownerPath,
190
- callbacks: []
191
- };
192
- mod2.callbacks.push({
193
- deps,
194
- fn: callback
195
- });
196
- maps.hotModulesMap.set(ownerPath, mod2);
197
- }
198
- const hot = {
199
- get data() {
200
- return maps.dataMap.get(ownerPath);
201
- },
202
- acceptExports(_, callback) {
203
- acceptDeps([ownerPath], callback && (([mod2]) => callback(mod2)));
204
- },
205
- accept(deps, callback) {
206
- if (typeof deps === "function" || !deps) {
207
- acceptDeps([ownerPath], ([mod2]) => deps && deps(mod2));
208
- } else if (typeof deps === "string") {
209
- acceptDeps([deps], ([mod2]) => callback && callback(mod2));
210
- } else if (Array.isArray(deps)) {
211
- acceptDeps(deps, callback);
212
- } else {
213
- throw new TypeError("invalid hot.accept() usage.");
214
- }
215
- },
216
- dispose(cb) {
217
- maps.disposeMap.set(ownerPath, cb);
218
- },
219
- prune(cb) {
220
- maps.pruneMap.set(ownerPath, cb);
221
- },
222
- invalidate() {
223
- notifyListeners(runner, "vite:invalidate", { path: ownerPath, message: void 0 });
224
- return reload(runner, files);
225
- },
226
- on(event, cb) {
227
- const addToMap = (map) => {
228
- const existing = map.get(event) || [];
229
- existing.push(cb);
230
- map.set(event, existing);
231
- };
232
- addToMap(maps.customListenersMap);
233
- addToMap(newListeners);
234
- },
235
- off(event, cb) {
236
- const removeFromMap = (map) => {
237
- const existing = map.get(event);
238
- if (existing === void 0)
239
- return;
240
- const pruned = existing.filter((l) => l !== cb);
241
- if (pruned.length === 0) {
242
- map.delete(event);
243
- return;
244
- }
245
- map.set(event, pruned);
246
- };
247
- removeFromMap(maps.customListenersMap);
248
- removeFromMap(newListeners);
249
- },
250
- send(event, data) {
251
- maps.messageBuffer.push(JSON.stringify({ type: "custom", event, data }));
252
- sendMessageBuffer(runner, emitter);
253
- }
254
- };
255
- return hot;
256
- }
257
14
 
258
- exports.createHmrEmitter = createHmrEmitter;
259
- exports.createHotContext = createHotContext;
260
- exports.getCache = getCache;
261
- exports.handleMessage = handleMessage;
262
- exports.reload = reload;
263
- exports.sendMessageBuffer = sendMessageBuffer;
264
- exports.viteNodeHmrPlugin = viteNodeHmrPlugin;
15
+ exports.createHmrEmitter = hmr.createHmrEmitter;
16
+ exports.createHotContext = hmr.createHotContext;
17
+ exports.getCache = hmr.getCache;
18
+ exports.handleMessage = hmr.handleMessage;
19
+ exports.reload = hmr.reload;
20
+ exports.sendMessageBuffer = hmr.sendMessageBuffer;
21
+ exports.viteNodeHmrPlugin = hmr.viteNodeHmrPlugin;
package/dist/hmr.d.ts CHANGED
@@ -6,13 +6,12 @@ import './trace-mapping.d-xyIfZtPm.js';
6
6
  type EventType = string | symbol;
7
7
  type Handler<T = unknown> = (event: T) => void;
8
8
  interface Emitter<Events extends Record<EventType, unknown>> {
9
- on<Key extends keyof Events>(type: Key, handler: Handler<Events[Key]>): void;
10
- off<Key extends keyof Events>(type: Key, handler?: Handler<Events[Key]>): void;
11
- emit<Key extends keyof Events>(type: Key, event: Events[Key]): void;
12
- emit<Key extends keyof Events>(type: undefined extends Events[Key] ? Key : never): void;
9
+ on: <Key extends keyof Events>(type: Key, handler: Handler<Events[Key]>) => void;
10
+ off: <Key extends keyof Events>(type: Key, handler?: Handler<Events[Key]>) => void;
11
+ emit: (<Key extends keyof Events>(type: Key, event: Events[Key]) => void) & (<Key extends keyof Events>(type: undefined extends Events[Key] ? Key : never) => void);
13
12
  }
14
13
  type HMREmitter = Emitter<{
15
- 'message': HMRPayload;
14
+ message: HMRPayload;
16
15
  }> & EventEmitter;
17
16
  declare module 'vite' {
18
17
  interface ViteDevServer {
package/dist/hmr.mjs CHANGED
@@ -1,256 +1,9 @@
1
- import { EventEmitter } from 'node:events';
2
- import c from 'picocolors';
3
- import createDebug from 'debug';
4
- import { normalizeRequestId } from './utils.mjs';
1
+ export { c as createHmrEmitter, a as createHotContext, g as getCache, h as handleMessage, r as reload, s as sendMessageBuffer, v as viteNodeHmrPlugin } from './chunk-hmr.mjs';
2
+ import 'node:events';
3
+ import 'picocolors';
4
+ import 'debug';
5
+ import './utils.mjs';
5
6
  import 'node:url';
6
7
  import 'node:module';
7
8
  import 'node:fs';
8
9
  import 'pathe';
9
-
10
- function createHmrEmitter() {
11
- const emitter = new EventEmitter();
12
- return emitter;
13
- }
14
- function viteNodeHmrPlugin() {
15
- const emitter = createHmrEmitter();
16
- return {
17
- name: "vite-node:hmr",
18
- config() {
19
- if (process.platform === "darwin" && process.env.VITE_TEST_WATCHER_DEBUG) {
20
- return {
21
- server: {
22
- watch: {
23
- useFsEvents: false,
24
- usePolling: false
25
- }
26
- }
27
- };
28
- }
29
- },
30
- configureServer(server) {
31
- const _send = server.ws.send;
32
- server.emitter = emitter;
33
- server.ws.send = function(payload) {
34
- _send(payload);
35
- emitter.emit("message", payload);
36
- };
37
- if (process.env.VITE_TEST_WATCHER_DEBUG) {
38
- server.watcher.on("ready", () => {
39
- console.log("[debug] watcher is ready");
40
- });
41
- }
42
- }
43
- };
44
- }
45
-
46
- const debugHmr = createDebug("vite-node:hmr");
47
- const cache = /* @__PURE__ */ new WeakMap();
48
- function getCache(runner) {
49
- if (!cache.has(runner)) {
50
- cache.set(runner, {
51
- hotModulesMap: /* @__PURE__ */ new Map(),
52
- dataMap: /* @__PURE__ */ new Map(),
53
- disposeMap: /* @__PURE__ */ new Map(),
54
- pruneMap: /* @__PURE__ */ new Map(),
55
- customListenersMap: /* @__PURE__ */ new Map(),
56
- ctxToListenersMap: /* @__PURE__ */ new Map(),
57
- messageBuffer: [],
58
- isFirstUpdate: false,
59
- pending: false,
60
- queued: []
61
- });
62
- }
63
- return cache.get(runner);
64
- }
65
- function sendMessageBuffer(runner, emitter) {
66
- const maps = getCache(runner);
67
- maps.messageBuffer.forEach((msg) => emitter.emit("custom", msg));
68
- maps.messageBuffer.length = 0;
69
- }
70
- async function reload(runner, files) {
71
- Array.from(runner.moduleCache.keys()).forEach((fsPath) => {
72
- if (!fsPath.includes("node_modules"))
73
- runner.moduleCache.delete(fsPath);
74
- });
75
- return Promise.all(files.map((file) => runner.executeId(file)));
76
- }
77
- async function notifyListeners(runner, event, data) {
78
- const maps = getCache(runner);
79
- const cbs = maps.customListenersMap.get(event);
80
- if (cbs)
81
- await Promise.all(cbs.map((cb) => cb(data)));
82
- }
83
- async function queueUpdate(runner, p) {
84
- const maps = getCache(runner);
85
- maps.queued.push(p);
86
- if (!maps.pending) {
87
- maps.pending = true;
88
- await Promise.resolve();
89
- maps.pending = false;
90
- const loading = [...maps.queued];
91
- maps.queued = [];
92
- (await Promise.all(loading)).forEach((fn) => fn && fn());
93
- }
94
- }
95
- async function fetchUpdate(runner, { path, acceptedPath }) {
96
- path = normalizeRequestId(path);
97
- acceptedPath = normalizeRequestId(acceptedPath);
98
- const maps = getCache(runner);
99
- const mod = maps.hotModulesMap.get(path);
100
- if (!mod) {
101
- return;
102
- }
103
- const isSelfUpdate = path === acceptedPath;
104
- let fetchedModule;
105
- const qualifiedCallbacks = mod.callbacks.filter(
106
- ({ deps }) => deps.includes(acceptedPath)
107
- );
108
- if (isSelfUpdate || qualifiedCallbacks.length > 0) {
109
- const disposer = maps.disposeMap.get(acceptedPath);
110
- if (disposer)
111
- await disposer(maps.dataMap.get(acceptedPath));
112
- try {
113
- [fetchedModule] = await reload(runner, [acceptedPath]);
114
- } catch (e) {
115
- warnFailedFetch(e, acceptedPath);
116
- }
117
- }
118
- return () => {
119
- for (const { deps, fn } of qualifiedCallbacks)
120
- fn(deps.map((dep) => dep === acceptedPath ? fetchedModule : void 0));
121
- const loggedPath = isSelfUpdate ? path : `${acceptedPath} via ${path}`;
122
- console.log(`${c.cyan("[vite-node]")} hot updated: ${loggedPath}`);
123
- };
124
- }
125
- function warnFailedFetch(err, path) {
126
- if (!err.message.match("fetch"))
127
- console.error(err);
128
- console.error(
129
- `[hmr] Failed to reload ${path}. This could be due to syntax errors or importing non-existent modules. (see errors above)`
130
- );
131
- }
132
- async function handleMessage(runner, emitter, files, payload) {
133
- const maps = getCache(runner);
134
- switch (payload.type) {
135
- case "connected":
136
- sendMessageBuffer(runner, emitter);
137
- break;
138
- case "update":
139
- await notifyListeners(runner, "vite:beforeUpdate", payload);
140
- await Promise.all(payload.updates.map((update) => {
141
- if (update.type === "js-update")
142
- return queueUpdate(runner, fetchUpdate(runner, update));
143
- console.error(`${c.cyan("[vite-node]")} no support css hmr.}`);
144
- return null;
145
- }));
146
- await notifyListeners(runner, "vite:afterUpdate", payload);
147
- break;
148
- case "full-reload":
149
- await notifyListeners(runner, "vite:beforeFullReload", payload);
150
- maps.customListenersMap.delete("vite:beforeFullReload");
151
- await reload(runner, files);
152
- break;
153
- case "custom":
154
- await notifyListeners(runner, payload.event, payload.data);
155
- break;
156
- case "prune":
157
- await notifyListeners(runner, "vite:beforePrune", payload);
158
- payload.paths.forEach((path) => {
159
- const fn = maps.pruneMap.get(path);
160
- if (fn)
161
- fn(maps.dataMap.get(path));
162
- });
163
- break;
164
- case "error": {
165
- await notifyListeners(runner, "vite:error", payload);
166
- const err = payload.err;
167
- console.error(`${c.cyan("[vite-node]")} Internal Server Error
168
- ${err.message}
169
- ${err.stack}`);
170
- break;
171
- }
172
- }
173
- }
174
- function createHotContext(runner, emitter, files, ownerPath) {
175
- debugHmr("createHotContext", ownerPath);
176
- const maps = getCache(runner);
177
- if (!maps.dataMap.has(ownerPath))
178
- maps.dataMap.set(ownerPath, {});
179
- const mod = maps.hotModulesMap.get(ownerPath);
180
- if (mod)
181
- mod.callbacks = [];
182
- const newListeners = /* @__PURE__ */ new Map();
183
- maps.ctxToListenersMap.set(ownerPath, newListeners);
184
- function acceptDeps(deps, callback = () => {
185
- }) {
186
- const mod2 = maps.hotModulesMap.get(ownerPath) || {
187
- id: ownerPath,
188
- callbacks: []
189
- };
190
- mod2.callbacks.push({
191
- deps,
192
- fn: callback
193
- });
194
- maps.hotModulesMap.set(ownerPath, mod2);
195
- }
196
- const hot = {
197
- get data() {
198
- return maps.dataMap.get(ownerPath);
199
- },
200
- acceptExports(_, callback) {
201
- acceptDeps([ownerPath], callback && (([mod2]) => callback(mod2)));
202
- },
203
- accept(deps, callback) {
204
- if (typeof deps === "function" || !deps) {
205
- acceptDeps([ownerPath], ([mod2]) => deps && deps(mod2));
206
- } else if (typeof deps === "string") {
207
- acceptDeps([deps], ([mod2]) => callback && callback(mod2));
208
- } else if (Array.isArray(deps)) {
209
- acceptDeps(deps, callback);
210
- } else {
211
- throw new TypeError("invalid hot.accept() usage.");
212
- }
213
- },
214
- dispose(cb) {
215
- maps.disposeMap.set(ownerPath, cb);
216
- },
217
- prune(cb) {
218
- maps.pruneMap.set(ownerPath, cb);
219
- },
220
- invalidate() {
221
- notifyListeners(runner, "vite:invalidate", { path: ownerPath, message: void 0 });
222
- return reload(runner, files);
223
- },
224
- on(event, cb) {
225
- const addToMap = (map) => {
226
- const existing = map.get(event) || [];
227
- existing.push(cb);
228
- map.set(event, existing);
229
- };
230
- addToMap(maps.customListenersMap);
231
- addToMap(newListeners);
232
- },
233
- off(event, cb) {
234
- const removeFromMap = (map) => {
235
- const existing = map.get(event);
236
- if (existing === void 0)
237
- return;
238
- const pruned = existing.filter((l) => l !== cb);
239
- if (pruned.length === 0) {
240
- map.delete(event);
241
- return;
242
- }
243
- map.set(event, pruned);
244
- };
245
- removeFromMap(maps.customListenersMap);
246
- removeFromMap(newListeners);
247
- },
248
- send(event, data) {
249
- maps.messageBuffer.push(JSON.stringify({ type: "custom", event, data }));
250
- sendMessageBuffer(runner, emitter);
251
- }
252
- };
253
- return hot;
254
- }
255
-
256
- export { createHmrEmitter, createHotContext, getCache, handleMessage, reload, sendMessageBuffer, viteNodeHmrPlugin };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "vite-node",
3
3
  "type": "module",
4
- "version": "1.2.2",
4
+ "version": "1.3.0",
5
5
  "description": "Vite as Node.js runtime",
6
6
  "author": "Anthony Fu <anthonyfu117@hotmail.com>",
7
7
  "license": "MIT",