@xharness/cordis-plugin-hmr 0.0.0-stage → 1.2.0-alpha.2

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2021-present Shigma
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,51 @@
1
- # Temporary Holding Version
1
+ # @cordisjs/plugin-hmr
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Hot module replacement for loader-managed Cordis plugins.
4
+
5
+ The HMR plugin watches source files, traces Node's module graph, clears affected
6
+ module caches, and reloads only the plugin entries that depend on changed
7
+ application files. Changes to framework-level dependencies fall back to
8
+ `loader.exit()`, letting the host process restart.
9
+
10
+ Module watches canonicalize their existing base directory before opening
11
+ Chokidar, so the native backend receives one filesystem spelling even when
12
+ Windows supplied an 8.3 alias.
13
+
14
+ ## Requirements
15
+
16
+ - `@cordisjs/plugin-loader`
17
+ - `@cordisjs/plugin-timer`
18
+ - A runtime that exposes Node's internal module loader. The package throws if
19
+ the loader service has no internal module loader available.
20
+
21
+ ## Usage
22
+
23
+ ```yaml
24
+ - id: timer
25
+ name: '@cordisjs/plugin-timer'
26
+ - id: hmr
27
+ name: '@cordisjs/plugin-hmr'
28
+ config:
29
+ root:
30
+ - src
31
+ ignored:
32
+ - '**/node_modules'
33
+ - '**/.*'
34
+ debounce: 100
35
+ ```
36
+
37
+ ## Config
38
+
39
+ | Field | Description |
40
+ | --- | --- |
41
+ | `base` | Optional base directory resolved from `ctx.baseUrl`. |
42
+ | `root` | Chokidar roots to watch. Defaults to `['.']`. |
43
+ | `ignored` | Picomatch patterns excluded from watch and reload analysis. |
44
+ | `debounce` | Milliseconds to wait before processing a burst of changes. |
45
+
46
+ ## Events
47
+
48
+ | Event | Description |
49
+ | --- | --- |
50
+ | `hmr/change` | Emitted for changed files that are not handled by plugin reload or config reload. |
51
+ | `hmr/reload` | Emitted after one or more plugin entries are reloaded. |
package/lib/index.js ADDED
@@ -0,0 +1,405 @@
1
+ import { createRequire } from "node:module";
2
+ import { Inject, Service } from "@xharness/cordis";
3
+ import { watch } from "chokidar";
4
+ import { relative, resolve } from "node:path";
5
+ import { realpath } from "node:fs/promises";
6
+ import { codeFrameColumns } from "@babel/code-frame";
7
+ import { readFileSync } from "node:fs";
8
+ import { fileURLToPath, pathToFileURL } from "node:url";
9
+ import picomatch from "picomatch";
10
+ import z from "@xharness/schemastery";
11
+ //#region lib/types/error.js
12
+ function isBuildFailure(e) {
13
+ return Array.isArray(e?.errors) && e.errors.every((error) => error.text);
14
+ }
15
+ /** Log HMR build failures with code frames when source locations are available. */
16
+ function handleError(ctx, e) {
17
+ if (!isBuildFailure(e)) {
18
+ ctx.logger.warn(e);
19
+ return;
20
+ }
21
+ for (const error of e.errors) {
22
+ if (!error.location) {
23
+ ctx.logger.warn(error.text);
24
+ continue;
25
+ }
26
+ try {
27
+ const { file, line, column } = error.location;
28
+ const formatted = codeFrameColumns(readFileSync(file, "utf8"), { start: {
29
+ line,
30
+ column
31
+ } }, {
32
+ highlightCode: true,
33
+ message: error.text
34
+ });
35
+ ctx.logger.warn(`File: ${file}:${line}:${column}\n` + formatted);
36
+ } catch (e) {
37
+ ctx.logger.warn(e);
38
+ }
39
+ }
40
+ }
41
+ //#endregion
42
+ //#region lib/types/index.js
43
+ var __esDecorate = function(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
44
+ function accept(f) {
45
+ if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected");
46
+ return f;
47
+ }
48
+ var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
49
+ var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
50
+ var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
51
+ var _, done = false;
52
+ for (var i = decorators.length - 1; i >= 0; i--) {
53
+ var context = {};
54
+ for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p];
55
+ for (var p in contextIn.access) context.access[p] = contextIn.access[p];
56
+ context.addInitializer = function(f) {
57
+ if (done) throw new TypeError("Cannot add initializers after decoration has completed");
58
+ extraInitializers.push(accept(f || null));
59
+ };
60
+ var result = (0, decorators[i])(kind === "accessor" ? {
61
+ get: descriptor.get,
62
+ set: descriptor.set
63
+ } : descriptor[key], context);
64
+ if (kind === "accessor") {
65
+ if (result === void 0) continue;
66
+ if (result === null || typeof result !== "object") throw new TypeError("Object expected");
67
+ if (_ = accept(result.get)) descriptor.get = _;
68
+ if (_ = accept(result.set)) descriptor.set = _;
69
+ if (_ = accept(result.init)) initializers.unshift(_);
70
+ } else if (_ = accept(result)) if (kind === "field") initializers.unshift(_);
71
+ else descriptor[key] = _;
72
+ }
73
+ if (target) Object.defineProperty(target, contextIn.name, descriptor);
74
+ done = true;
75
+ };
76
+ var __runInitializers = function(thisArg, initializers, value) {
77
+ var useValue = arguments.length > 2;
78
+ for (var i = 0; i < initializers.length; i++) value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
79
+ return useValue ? value : void 0;
80
+ };
81
+ /**
82
+ * Recursively collect all module dependencies from a ModuleJob.
83
+ * Skips node: builtins and node_modules to focus on user code.
84
+ */
85
+ async function loadDependencies(job, ignored = /* @__PURE__ */ new Set()) {
86
+ const dependencies = /* @__PURE__ */ new Set();
87
+ async function traverse(job) {
88
+ if (ignored.has(job.url) || dependencies.has(job.url)) return;
89
+ if (job.url.startsWith("node:") || job.url.includes("/node_modules/")) return;
90
+ dependencies.add(job.url);
91
+ const children = await job.linked;
92
+ await Promise.all(Array.prototype.map.call(children, traverse));
93
+ }
94
+ await traverse(job);
95
+ return dependencies;
96
+ }
97
+ let Hmr = (() => {
98
+ let _classDecorators = [Inject("loader"), Inject("timer")];
99
+ let _classDescriptor;
100
+ let _classExtraInitializers = [];
101
+ let _classThis;
102
+ let _classSuper = Service;
103
+ var Hmr = class extends _classSuper {
104
+ static {
105
+ _classThis = this;
106
+ }
107
+ static {
108
+ const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
109
+ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, {
110
+ kind: "class",
111
+ name: _classThis.name,
112
+ metadata: _metadata
113
+ }, null, _classExtraInitializers);
114
+ Hmr = _classThis = _classDescriptor.value;
115
+ if (_metadata) Object.defineProperty(_classThis, Symbol.metadata, {
116
+ enumerable: true,
117
+ configurable: true,
118
+ writable: true,
119
+ value: _metadata
120
+ });
121
+ __runInitializers(_classThis, _classExtraInitializers);
122
+ }
123
+ config;
124
+ baseDir;
125
+ internal;
126
+ watcher;
127
+ /**
128
+ * Changes from externals will always trigger a full reload.
129
+ * Externals are the dependency tree of the CLI worker entry point.
130
+ */
131
+ externals;
132
+ /**
133
+ * Files that should be reloaded (accepted changes).
134
+ * Includes all stashed files and their dependents.
135
+ */
136
+ accepted;
137
+ /**
138
+ * Files that should NOT be reloaded.
139
+ * Includes externals and files whose dependents are all declined.
140
+ */
141
+ declined;
142
+ /** Stashed file changes waiting to be processed */
143
+ stashed = /* @__PURE__ */ new Set();
144
+ constructor(ctx, config) {
145
+ super(ctx, "hmr");
146
+ this.config = config;
147
+ if (!this.ctx.loader.internal) throw new Error("--expose-internals is required for HMR service");
148
+ this.internal = this.ctx.loader.internal;
149
+ this.baseDir = fileURLToPath(new URL(config.base || ".", ctx.baseUrl));
150
+ }
151
+ /**
152
+ * Resolve a module specifier to a URL, compatible with Node 22-24.
153
+ */
154
+ async _resolve(specifier, parentURL, attrs) {
155
+ switch (this.internal.version) {
156
+ case "v1": return await this.internal.resolve(specifier, parentURL, attrs);
157
+ case "v2": return this.internal.resolveSync(parentURL, {
158
+ specifier,
159
+ attributes: attrs
160
+ });
161
+ }
162
+ }
163
+ async *[Service.init]() {
164
+ yield () => this.watcher?.close();
165
+ const { loader } = this.ctx;
166
+ const { root, ignored } = this.config;
167
+ if (!this.config.base) this.ctx.logger.info("watching %o", root);
168
+ else this.ctx.logger.info("watching %o in %s", root, this.baseDir);
169
+ const match = picomatch(ignored);
170
+ const watchBaseDir = await realpath(this.baseDir);
171
+ const mainUrl = pathToFileURL(resolve(process.argv[1])).href;
172
+ const mainJob = this.internal.loadCache.get(mainUrl);
173
+ if (mainJob) this.externals = await loadDependencies(mainJob);
174
+ else this.externals = /* @__PURE__ */ new Set();
175
+ this.watcher = watch(root, {
176
+ ...this.config,
177
+ cwd: watchBaseDir,
178
+ ignored: (path) => match(relative(watchBaseDir, path)),
179
+ ignoreInitial: true
180
+ });
181
+ const partialReload = this.ctx.debounce(() => this.partialReload(), this.config.debounce);
182
+ this.watcher.on("change", async (path) => {
183
+ this.ctx.logger.debug("change detected at %C", path);
184
+ const filename = resolve(watchBaseDir, path);
185
+ const configuredFilename = resolve(this.baseDir, path);
186
+ const url = pathToFileURL(filename).href;
187
+ if (this.externals.has(url)) return loader.exit();
188
+ if (loader.internal.loadCache.has(url)) {
189
+ this.stashed.add(url);
190
+ return partialReload();
191
+ }
192
+ for (const entry of loader.entries()) {
193
+ const include = entry.subtree;
194
+ if (include?.filename !== filename && include?.filename !== configuredFilename) continue;
195
+ try {
196
+ await include.refresh();
197
+ } catch (error) {
198
+ this.ctx.logger.warn(error);
199
+ }
200
+ return;
201
+ }
202
+ this.ctx.emit("hmr/change", url);
203
+ });
204
+ const ready = Promise.withResolvers();
205
+ let readyState = root.length === 0 ? "resolved" : "pending";
206
+ if (root.length === 0) ready.resolve();
207
+ else this.watcher.once("ready", () => {
208
+ readyState = "resolved";
209
+ ready.resolve();
210
+ });
211
+ this.watcher.on("error", (error) => {
212
+ if (readyState === "pending") {
213
+ readyState = "rejected";
214
+ ready.reject(error);
215
+ } else this.ctx.logger.warn(error);
216
+ });
217
+ await ready.promise;
218
+ }
219
+ getOuterStack = () => [];
220
+ async getLinked(url) {
221
+ const job = this.internal.loadCache.get(url);
222
+ if (!job) return [];
223
+ const linked = await job.linked;
224
+ return Array.prototype.map.call(linked, (job) => job.url);
225
+ }
226
+ /**
227
+ * Classify changed files into accepted (should reload) and declined (should not).
228
+ *
229
+ * A file is accepted if it's directly changed (stashed) or if any of its
230
+ * dependents are accepted. A file is declined if all its dependents are
231
+ * declined or if it's an external.
232
+ */
233
+ async analyzeChanges() {
234
+ const pending = [];
235
+ this.accepted = new Set(this.stashed);
236
+ this.declined = new Set(this.externals);
237
+ const isExcluded = (url) => url.startsWith("node:") || url.includes("/node_modules/");
238
+ await Promise.all([...this.stashed].map(async (url) => {
239
+ const children = await this.getLinked(url);
240
+ for (const child of children) {
241
+ if (this.accepted.has(child) || this.declined.has(child) || isExcluded(child)) continue;
242
+ pending.push(child);
243
+ }
244
+ }));
245
+ while (pending.length) {
246
+ let index = 0, hasUpdate = false;
247
+ while (index < pending.length) {
248
+ const url = pending[index];
249
+ const children = await this.getLinked(url);
250
+ let isDeclined = true, isAccepted = false;
251
+ for (const child of children) {
252
+ if (this.declined.has(child) || isExcluded(child)) continue;
253
+ if (this.accepted.has(child)) {
254
+ isAccepted = true;
255
+ break;
256
+ } else {
257
+ isDeclined = false;
258
+ if (!pending.includes(child)) {
259
+ hasUpdate = true;
260
+ pending.push(child);
261
+ }
262
+ }
263
+ }
264
+ if (isAccepted || isDeclined) {
265
+ hasUpdate = true;
266
+ pending.splice(index, 1);
267
+ if (isAccepted) this.accepted.add(url);
268
+ else this.declined.add(url);
269
+ } else index++;
270
+ }
271
+ if (!hasUpdate) break;
272
+ }
273
+ for (const url of pending) this.declined.add(url);
274
+ }
275
+ async partialReload() {
276
+ await this.analyzeChanges();
277
+ const pending = /* @__PURE__ */ new Map();
278
+ const reloads = /* @__PURE__ */ new Map();
279
+ const nameMap = Object.create(null);
280
+ for (const entry of this.ctx.loader.entries()) (nameMap[entry.parent.tree.ctx.baseUrl] ??= /* @__PURE__ */ new Set()).add(entry.options.name);
281
+ for (const baseUrl in nameMap) for (const name of nameMap[baseUrl]) try {
282
+ const { url } = await this._resolve(name, baseUrl, {});
283
+ if (this.declined.has(url)) continue;
284
+ const job = this.internal.loadCache.get(url);
285
+ const plugin = this.ctx.loader.unwrapExports(job?.module?.getNamespace());
286
+ if (!job || !plugin) continue;
287
+ pending.set(job, plugin);
288
+ this.declined.add(url);
289
+ } catch (err) {
290
+ this.ctx.logger.warn(err);
291
+ }
292
+ for (const [job, plugin] of pending) {
293
+ this.declined.delete(job.url);
294
+ const dependencies = [...await loadDependencies(job, this.declined)];
295
+ this.declined.add(job.url);
296
+ if (!dependencies.some((dep) => this.accepted.has(dep))) continue;
297
+ dependencies.forEach((dep) => this.accepted.add(dep));
298
+ reloads.set(plugin, {
299
+ filename: job.url,
300
+ runtime: this.ctx.registry.get(plugin)
301
+ });
302
+ }
303
+ /**
304
+ * Clear module caches for all accepted files before re-importing.
305
+ *
306
+ * We need to clear both:
307
+ * 1. ESM loadCache — managed by Node's internal ModuleLoader
308
+ * 2. CJS Module._cache — for CJS modules that were imported via import()
309
+ *
310
+ * In Node 24, CJS modules loaded via import() appear in both caches.
311
+ * If we only clear loadCache, the CJS cache may serve stale modules.
312
+ *
313
+ * We use Map.prototype methods directly on loadCache because:
314
+ * - In Node 22/23, loadCache is a plain Map<url, ModuleJob>
315
+ * - In Node 24, loadCache is a LoadCache extends Map<url, { [type]: ModuleJob }>
316
+ * where .delete() only sets the type slot to undefined (doesn't remove the entry)
317
+ * Using Map.prototype.delete ensures complete removal in both versions.
318
+ */
319
+ const esmBackup = Object.create(null);
320
+ const cjsBackup = Object.create(null);
321
+ const require = createRequire(import.meta.url);
322
+ for (const filename of this.accepted) {
323
+ esmBackup[filename] = Map.prototype.get.call(this.internal.loadCache, filename);
324
+ Map.prototype.delete.call(this.internal.loadCache, filename);
325
+ try {
326
+ const filepath = fileURLToPath(filename);
327
+ if (require.cache[filepath]) {
328
+ cjsBackup[filepath] = require.cache[filepath];
329
+ delete require.cache[filepath];
330
+ }
331
+ } catch {}
332
+ }
333
+ const rollback = () => {
334
+ for (const filename in esmBackup) Map.prototype.set.call(this.internal.loadCache, filename, esmBackup[filename]);
335
+ for (const filepath in cjsBackup) require.cache[filepath] = cjsBackup[filepath];
336
+ };
337
+ const attempts = {};
338
+ try {
339
+ for (const [, { filename }] of reloads) attempts[filename] = this.ctx.loader.unwrapExports(await this.ctx.loader.import(filename, this.getOuterStack));
340
+ } catch (e) {
341
+ handleError(this.ctx, e);
342
+ return rollback();
343
+ }
344
+ const reload = (plugin, runtime) => {
345
+ if (!runtime) return;
346
+ for (const oldFiber of runtime.fibers) {
347
+ const fiber = oldFiber.parent.registry.plugin(plugin, oldFiber.rawConfig, this.getOuterStack);
348
+ fiber.entry = oldFiber.entry;
349
+ if (fiber.entry) fiber.entry.fiber = fiber;
350
+ }
351
+ };
352
+ try {
353
+ for (const [plugin, { filename, runtime }] of reloads) {
354
+ if (!runtime) continue;
355
+ const path = relative(this.baseDir, fileURLToPath(filename));
356
+ try {
357
+ this.ctx.registry.delete(plugin);
358
+ } catch (err) {
359
+ this.ctx.logger.warn("failed to dispose plugin at %C", path);
360
+ this.ctx.logger.warn(err);
361
+ }
362
+ try {
363
+ reload(attempts[filename], runtime);
364
+ this.ctx.logger.info("reload plugin at %C", path);
365
+ } catch (err) {
366
+ this.ctx.logger.warn("failed to reload plugin at %C", path);
367
+ this.ctx.logger.warn(err);
368
+ throw err;
369
+ }
370
+ }
371
+ } catch {
372
+ rollback();
373
+ for (const [plugin, { filename, runtime }] of reloads) {
374
+ if (!runtime) continue;
375
+ try {
376
+ this.ctx.registry.delete(attempts[filename]);
377
+ reload(plugin, runtime);
378
+ } catch (err) {
379
+ this.ctx.logger.warn(err);
380
+ }
381
+ }
382
+ return;
383
+ }
384
+ this.ctx.emit("hmr/reload", reloads);
385
+ this.stashed = /* @__PURE__ */ new Set();
386
+ }
387
+ };
388
+ return _classThis;
389
+ })();
390
+ (function(Hmr) {
391
+ Hmr.Config = z.object({
392
+ base: z.string(),
393
+ root: z.array(String).role("table").default(["."]),
394
+ ignored: z.array(String).role("table").default([
395
+ "**/node_modules",
396
+ "**/.*",
397
+ "cache",
398
+ "data"
399
+ ]),
400
+ debounce: z.natural().role("ms").default(100)
401
+ });
402
+ })(Hmr || (Hmr = {}));
403
+ var types_default = Hmr;
404
+ //#endregion
405
+ export { types_default as default };
@@ -0,0 +1,4 @@
1
+ import { Context } from '@xharness/cordis';
2
+ /** Log HMR build failures with code frames when source locations are available. */
3
+ export declare function handleError(ctx: Context, e: any): void;
4
+ //# sourceMappingURL=error.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"error.d.ts","sourceRoot":"","sources":["../../src/error.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,kBAAkB,CAAA;AAS1C,mFAAmF;AACnF,wBAAgB,WAAW,CAAC,GAAG,EAAE,OAAO,EAAE,CAAC,EAAE,GAAG,QAyB/C"}
@@ -0,0 +1,67 @@
1
+ import { Context, Service, type Plugin } from '@xharness/cordis';
2
+ import { type ChokidarOptions } from 'chokidar';
3
+ import z from '@xharness/schemastery';
4
+ declare module '@xharness/cordis' {
5
+ interface Context {
6
+ hmr: Hmr;
7
+ }
8
+ interface Events {
9
+ 'hmr/change'(url: string): void;
10
+ 'hmr/reload'(reloads: Map<Plugin, Reload>): void;
11
+ }
12
+ }
13
+ interface Reload {
14
+ filename: string;
15
+ runtime?: Plugin.Runtime;
16
+ }
17
+ declare class Hmr extends Service {
18
+ config: Hmr.Config;
19
+ baseDir: string;
20
+ private internal;
21
+ private watcher;
22
+ /**
23
+ * Changes from externals will always trigger a full reload.
24
+ * Externals are the dependency tree of the CLI worker entry point.
25
+ */
26
+ private externals;
27
+ /**
28
+ * Files that should be reloaded (accepted changes).
29
+ * Includes all stashed files and their dependents.
30
+ */
31
+ private accepted;
32
+ /**
33
+ * Files that should NOT be reloaded.
34
+ * Includes externals and files whose dependents are all declined.
35
+ */
36
+ private declined;
37
+ /** Stashed file changes waiting to be processed */
38
+ private stashed;
39
+ constructor(ctx: Context, config: Hmr.Config);
40
+ /**
41
+ * Resolve a module specifier to a URL, compatible with Node 22-24.
42
+ */
43
+ private _resolve;
44
+ [Service.init](): AsyncGenerator<() => Promise<void>, void, unknown>;
45
+ getOuterStack: () => string[];
46
+ getLinked(url: string): Promise<string[]>;
47
+ /**
48
+ * Classify changed files into accepted (should reload) and declined (should not).
49
+ *
50
+ * A file is accepted if it's directly changed (stashed) or if any of its
51
+ * dependents are accepted. A file is declined if all its dependents are
52
+ * declined or if it's an external.
53
+ */
54
+ private analyzeChanges;
55
+ private partialReload;
56
+ }
57
+ declare namespace Hmr {
58
+ interface Config extends ChokidarOptions {
59
+ base?: string;
60
+ root: string[];
61
+ debounce: number;
62
+ ignored: string[];
63
+ }
64
+ const Config: z<Config>;
65
+ }
66
+ export default Hmr;
67
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAU,OAAO,EAAE,KAAK,MAAM,EAAE,MAAM,kBAAkB,CAAA;AAIxE,OAAO,EAAoB,KAAK,eAAe,EAAE,MAAM,UAAU,CAAA;AAQjE,OAAO,CAAC,MAAM,uBAAuB,CAAA;AAErC,OAAO,QAAQ,kBAAkB,CAAC;IAChC,UAAU,OAAO;QACf,GAAG,EAAE,GAAG,CAAA;KACT;IAED,UAAU,MAAM;QACd,YAAY,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI,CAAA;QAC/B,YAAY,CAAC,OAAO,EAAE,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,IAAI,CAAA;KACjD;CACF;AAmBD,UAAU,MAAM;IACd,QAAQ,EAAE,MAAM,CAAA;IAChB,OAAO,CAAC,EAAE,MAAM,CAAC,OAAO,CAAA;CACzB;AAED,cAEM,GAAI,SAAQ,OAAO;IA2BU,MAAM,EAAE,GAAG,CAAC,MAAM;IA1B5C,OAAO,EAAE,MAAM,CAAA;IAEtB,OAAO,CAAC,QAAQ,CAAc;IAC9B,OAAO,CAAC,OAAO,CAAY;IAE3B;;;OAGG;IACH,OAAO,CAAC,SAAS,CAAc;IAE/B;;;OAGG;IACH,OAAO,CAAC,QAAQ,CAAc;IAE9B;;;OAGG;IACH,OAAO,CAAC,QAAQ,CAAc;IAE9B,mDAAmD;IACnD,OAAO,CAAC,OAAO,CAAoB;gBAEvB,GAAG,EAAE,OAAO,EAAS,MAAM,EAAE,GAAG,CAAC,MAAM;IASnD;;OAEG;YACW,QAAQ;IAOf,CAAC,OAAO,CAAC,IAAI,CAAC;IAmFrB,aAAa,QAAO,MAAM,EAAE,CAE3B;IAEK,SAAS,CAAC,GAAG,EAAE,MAAM;IAO3B;;;;;;OAMG;YACW,cAAc;YAuDd,aAAa;CAsJ5B;AAED,kBAAU,GAAG,CAAC;IACZ,UAAiB,MAAO,SAAQ,eAAe;QAC7C,IAAI,CAAC,EAAE,MAAM,CAAA;QACb,IAAI,EAAE,MAAM,EAAE,CAAA;QACd,QAAQ,EAAE,MAAM,CAAA;QAChB,OAAO,EAAE,MAAM,EAAE,CAAA;KAClB;IAEM,MAAM,MAAM,EAAE,CAAC,CAAC,MAAM,CAU3B,CAAA;CAIH;AAED,eAAe,GAAG,CAAA"}
package/package.json CHANGED
@@ -1,6 +1,59 @@
1
1
  {
2
2
  "name": "@xharness/cordis-plugin-hmr",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "description": "Hot Module Replacement Plugin for Cordis",
4
+ "version": "1.2.0-alpha.2",
5
+ "publishConfig": {
6
+ "access": "public"
7
+ },
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/Kuner/XHarness.git",
11
+ "directory": "vendor/hmr"
12
+ },
13
+ "type": "module",
14
+ "main": "lib/index.js",
15
+ "types": "lib/types/index.d.ts",
16
+ "exports": {
17
+ ".": {
18
+ "types": "./lib/types/index.d.ts",
19
+ "default": "./lib/index.js"
20
+ },
21
+ "./src/*": "./src/*",
22
+ "./package.json": "./package.json"
23
+ },
24
+ "files": [
25
+ "lib/index.js",
26
+ "lib/types/**/*.d.ts",
27
+ "lib/types/**/*.d.ts.map",
28
+ "src"
29
+ ],
30
+ "author": "Shigma <shigma10826@gmail.com>",
31
+ "license": "MIT",
32
+ "@xharness/cordis": {
33
+ "services": {
34
+ "required": [
35
+ "timer"
36
+ ]
37
+ },
38
+ "description": {
39
+ "en": "Hot Module Replacement",
40
+ "zh": "模块热替换"
41
+ }
42
+ },
43
+ "peerDependencies": {
44
+ "@xharness/cordis-plugin-timer": "~1.3.0-alpha.2",
45
+ "@xharness/cordis": "~4.2.0-alpha.2"
46
+ },
47
+ "dependencies": {
48
+ "@babel/code-frame": "^7.29.0",
49
+ "chokidar": "^4.0.3",
50
+ "@xharness/cosmokit": "~1.10.0-alpha.2",
51
+ "picomatch": "^4.0.3",
52
+ "@xharness/schemastery": "~3.20.0-alpha.2"
53
+ },
54
+ "devDependencies": {
55
+ "@types/babel__code-frame": "^7.27.0",
56
+ "@types/picomatch": "^3.0.2",
57
+ "esbuild": "^0.28.1"
58
+ }
6
59
  }
package/src/error.ts ADDED
@@ -0,0 +1,36 @@
1
+ import { Context } from '@xharness/cordis'
2
+ import type { BuildFailure } from 'esbuild'
3
+ import { codeFrameColumns } from '@babel/code-frame'
4
+ import { readFileSync } from 'node:fs'
5
+
6
+ function isBuildFailure(e: any): e is BuildFailure {
7
+ return Array.isArray(e?.errors) && e.errors.every((error: any) => error.text)
8
+ }
9
+
10
+ /** Log HMR build failures with code frames when source locations are available. */
11
+ export function handleError(ctx: Context, e: any) {
12
+ if (!isBuildFailure(e)) {
13
+ ctx.logger.warn(e)
14
+ return
15
+ }
16
+
17
+ for (const error of e.errors) {
18
+ if (!error.location) {
19
+ ctx.logger.warn(error.text)
20
+ continue
21
+ }
22
+ try {
23
+ const { file, line, column } = error.location
24
+ const source = readFileSync(file, 'utf8')
25
+ const formatted = codeFrameColumns(source, {
26
+ start: { line, column },
27
+ }, {
28
+ highlightCode: true,
29
+ message: error.text,
30
+ })
31
+ ctx.logger.warn(`File: ${file}:${line}:${column}\n` + formatted)
32
+ } catch (e) {
33
+ ctx.logger.warn(e)
34
+ }
35
+ }
36
+ }
package/src/index.ts ADDED
@@ -0,0 +1,428 @@
1
+ import { Context, Inject, Service, type Plugin } from '@xharness/cordis'
2
+ import type { Dict } from '@xharness/cosmokit'
3
+ import { ModuleLoader, type ModuleJob, type ResolveResult } from '@xharness/cordis-plugin-loader'
4
+ import type { Include } from '@xharness/cordis-plugin-include'
5
+ import { FSWatcher, watch, type ChokidarOptions } from 'chokidar'
6
+ import { relative, resolve } from 'node:path'
7
+ import { realpath } from 'node:fs/promises'
8
+ import { handleError } from './error.ts'
9
+ import type {} from '@xharness/cordis-plugin-timer'
10
+ import { fileURLToPath, pathToFileURL } from 'node:url'
11
+ import { createRequire } from 'node:module'
12
+ import picomatch from 'picomatch'
13
+ import z from '@xharness/schemastery'
14
+
15
+ declare module '@xharness/cordis' {
16
+ interface Context {
17
+ hmr: Hmr
18
+ }
19
+
20
+ interface Events {
21
+ 'hmr/change'(url: string): void
22
+ 'hmr/reload'(reloads: Map<Plugin, Reload>): void
23
+ }
24
+ }
25
+
26
+ /**
27
+ * Recursively collect all module dependencies from a ModuleJob.
28
+ * Skips node: builtins and node_modules to focus on user code.
29
+ */
30
+ async function loadDependencies(job: ModuleJob, ignored = new Set<string>()) {
31
+ const dependencies = new Set<string>()
32
+ async function traverse(job: ModuleJob) {
33
+ if (ignored.has(job.url) || dependencies.has(job.url)) return
34
+ if (job.url.startsWith('node:') || job.url.includes('/node_modules/')) return
35
+ dependencies.add(job.url)
36
+ const children = await job.linked
37
+ await Promise.all(Array.prototype.map.call(children, traverse))
38
+ }
39
+ await traverse(job)
40
+ return dependencies
41
+ }
42
+
43
+ interface Reload {
44
+ filename: string
45
+ runtime?: Plugin.Runtime
46
+ }
47
+
48
+ @Inject('loader')
49
+ @Inject('timer')
50
+ class Hmr extends Service {
51
+ public baseDir: string
52
+
53
+ private internal: ModuleLoader
54
+ private watcher!: FSWatcher
55
+
56
+ /**
57
+ * Changes from externals will always trigger a full reload.
58
+ * Externals are the dependency tree of the CLI worker entry point.
59
+ */
60
+ private externals!: Set<string>
61
+
62
+ /**
63
+ * Files that should be reloaded (accepted changes).
64
+ * Includes all stashed files and their dependents.
65
+ */
66
+ private accepted!: Set<string>
67
+
68
+ /**
69
+ * Files that should NOT be reloaded.
70
+ * Includes externals and files whose dependents are all declined.
71
+ */
72
+ private declined!: Set<string>
73
+
74
+ /** Stashed file changes waiting to be processed */
75
+ private stashed = new Set<string>()
76
+
77
+ constructor(ctx: Context, public config: Hmr.Config) {
78
+ super(ctx, 'hmr')
79
+ if (!this.ctx.loader.internal) {
80
+ throw new Error('--expose-internals is required for HMR service')
81
+ }
82
+ this.internal = this.ctx.loader.internal
83
+ this.baseDir = fileURLToPath(new URL(config.base || '.', ctx.baseUrl))
84
+ }
85
+
86
+ /**
87
+ * Resolve a module specifier to a URL, compatible with Node 22-24.
88
+ */
89
+ private async _resolve(specifier: string, parentURL: string, attrs: ImportAttributes): Promise<ResolveResult> {
90
+ switch (this.internal.version) {
91
+ case 'v1': return await this.internal.resolve(specifier, parentURL, attrs)
92
+ case 'v2': return this.internal.resolveSync(parentURL, { specifier, attributes: attrs })
93
+ }
94
+ }
95
+
96
+ async* [Service.init]() {
97
+ yield () => this.watcher?.close()
98
+
99
+ const { loader } = this.ctx
100
+ const { root, ignored } = this.config
101
+ if (!this.config.base) {
102
+ this.ctx.logger.info('watching %o', root)
103
+ } else {
104
+ this.ctx.logger.info('watching %o in %s', root, this.baseDir)
105
+ }
106
+
107
+ const match = picomatch(ignored)
108
+ const watchBaseDir = await realpath(this.baseDir)
109
+
110
+ // Collect externals before opening the watcher so every post-ready change
111
+ // is observed by listeners that already have their classification state.
112
+ const mainUrl = pathToFileURL(resolve(process.argv[1])).href
113
+ const mainJob = this.internal.loadCache.get(mainUrl)
114
+ if (mainJob) {
115
+ this.externals = await loadDependencies(mainJob)
116
+ } else {
117
+ this.externals = new Set()
118
+ }
119
+
120
+ this.watcher = watch(root, {
121
+ ...this.config,
122
+ cwd: watchBaseDir,
123
+ ignored: path => match(relative(watchBaseDir, path)),
124
+ ignoreInitial: true,
125
+ })
126
+
127
+ const partialReload = this.ctx.debounce(() => this.partialReload(), this.config.debounce)
128
+
129
+ this.watcher.on('change', async (path) => {
130
+ this.ctx.logger.debug('change detected at %C', path)
131
+ const filename = resolve(watchBaseDir, path)
132
+ const configuredFilename = resolve(this.baseDir, path)
133
+ const url = pathToFileURL(filename).href
134
+
135
+ // Full reload: the changed file is part of the framework
136
+ if (this.externals.has(url)) return loader.exit()
137
+
138
+ // Partial reload: the file is in the ESM loadCache
139
+ // In Node 24, both CJS and ESM modules imported via import() end up
140
+ // in loadCache, so this check covers all module formats.
141
+ if (loader.internal!.loadCache.has(url)) {
142
+ this.stashed.add(url)
143
+ return partialReload()
144
+ }
145
+
146
+ for (const entry of loader.entries()) {
147
+ const include = entry.subtree as Include | undefined
148
+ if (include?.filename !== filename && include?.filename !== configuredFilename) continue
149
+ // A rejected refresh reports unsaved runtime changes; Include keeps its running tree.
150
+ try { await include.refresh() } catch (error) { this.ctx.logger.warn(error) }
151
+ return
152
+ }
153
+
154
+ this.ctx.emit('hmr/change', url)
155
+ })
156
+
157
+ const ready = Promise.withResolvers<void>()
158
+ let readyState: 'pending' | 'resolved' | 'rejected' = root.length === 0 ? 'resolved' : 'pending'
159
+ if (root.length === 0) {
160
+ ready.resolve()
161
+ } else {
162
+ this.watcher.once('ready', () => {
163
+ readyState = 'resolved'
164
+ ready.resolve()
165
+ })
166
+ }
167
+ this.watcher.on('error', (error) => {
168
+ if (readyState === 'pending') {
169
+ readyState = 'rejected'
170
+ ready.reject(error)
171
+ } else {
172
+ this.ctx.logger.warn(error)
173
+ }
174
+ })
175
+ await ready.promise
176
+ }
177
+
178
+ // hide stack trace from HMR
179
+ getOuterStack = (): string[] => [
180
+ // ' at HMR.partialReload (<anonymous>)',
181
+ ]
182
+
183
+ async getLinked(url: string) {
184
+ const job = this.internal.loadCache.get(url)
185
+ if (!job) return []
186
+ const linked = await job.linked
187
+ return Array.prototype.map.call(linked, (job: ModuleJob) => job.url) as string[]
188
+ }
189
+
190
+ /**
191
+ * Classify changed files into accepted (should reload) and declined (should not).
192
+ *
193
+ * A file is accepted if it's directly changed (stashed) or if any of its
194
+ * dependents are accepted. A file is declined if all its dependents are
195
+ * declined or if it's an external.
196
+ */
197
+ private async analyzeChanges() {
198
+ const pending: string[] = []
199
+
200
+ this.accepted = new Set(this.stashed)
201
+ this.declined = new Set(this.externals)
202
+
203
+ const isExcluded = (url: string) => url.startsWith('node:') || url.includes('/node_modules/')
204
+
205
+ await Promise.all([...this.stashed].map(async (url) => {
206
+ const children = await this.getLinked(url)
207
+ for (const child of children) {
208
+ if (this.accepted.has(child) || this.declined.has(child) || isExcluded(child)) continue
209
+ pending.push(child)
210
+ }
211
+ }))
212
+
213
+ while (pending.length) {
214
+ let index = 0, hasUpdate = false
215
+ while (index < pending.length) {
216
+ const url = pending[index]
217
+ const children = await this.getLinked(url)
218
+ let isDeclined = true, isAccepted = false
219
+ for (const child of children) {
220
+ if (this.declined.has(child) || isExcluded(child)) continue
221
+ if (this.accepted.has(child)) {
222
+ isAccepted = true
223
+ break
224
+ } else {
225
+ isDeclined = false
226
+ if (!pending.includes(child)) {
227
+ hasUpdate = true
228
+ pending.push(child)
229
+ }
230
+ }
231
+ }
232
+ if (isAccepted || isDeclined) {
233
+ hasUpdate = true
234
+ pending.splice(index, 1)
235
+ if (isAccepted) {
236
+ this.accepted.add(url)
237
+ } else {
238
+ this.declined.add(url)
239
+ }
240
+ } else {
241
+ index++
242
+ }
243
+ }
244
+ if (!hasUpdate) break
245
+ }
246
+
247
+ for (const url of pending) {
248
+ this.declined.add(url)
249
+ }
250
+ }
251
+
252
+ private async partialReload() {
253
+ await this.analyzeChanges()
254
+
255
+ const pending = new Map<ModuleJob, Plugin>()
256
+ const reloads = new Map<Plugin, Reload>()
257
+
258
+ // Build a map of plugin names per config tree URL.
259
+ // Plugin entry files are treated as atomic reload units.
260
+ const nameMap: Dict<Set<string>> = Object.create(null)
261
+ for (const entry of this.ctx.loader.entries()) {
262
+ (nameMap[entry.parent.tree.ctx.baseUrl!] ??= new Set()).add(entry.options.name)
263
+ }
264
+
265
+ // Resolve each plugin name to its file URL and check if it needs reload
266
+ for (const baseUrl in nameMap) {
267
+ for (const name of nameMap[baseUrl]) {
268
+ try {
269
+ const { url } = await this._resolve(name, baseUrl, {})
270
+ if (this.declined.has(url)) continue
271
+ const job = this.internal.loadCache.get(url)
272
+ const plugin = this.ctx.loader.unwrapExports(job?.module?.getNamespace())
273
+ if (!job || !plugin) continue
274
+ pending.set(job, plugin)
275
+ this.declined.add(url)
276
+ } catch (err) {
277
+ this.ctx.logger.warn(err)
278
+ }
279
+ }
280
+ }
281
+
282
+ // Check each pending plugin's dependency tree for accepted files
283
+ for (const [job, plugin] of pending) {
284
+ this.declined.delete(job.url)
285
+ const dependencies = [...await loadDependencies(job, this.declined)]
286
+ this.declined.add(job.url)
287
+
288
+ if (!dependencies.some(dep => this.accepted.has(dep))) continue
289
+ dependencies.forEach(dep => this.accepted.add(dep))
290
+
291
+ reloads.set(plugin, {
292
+ filename: job.url,
293
+ runtime: this.ctx.registry.get(plugin),
294
+ })
295
+ }
296
+
297
+ /**
298
+ * Clear module caches for all accepted files before re-importing.
299
+ *
300
+ * We need to clear both:
301
+ * 1. ESM loadCache — managed by Node's internal ModuleLoader
302
+ * 2. CJS Module._cache — for CJS modules that were imported via import()
303
+ *
304
+ * In Node 24, CJS modules loaded via import() appear in both caches.
305
+ * If we only clear loadCache, the CJS cache may serve stale modules.
306
+ *
307
+ * We use Map.prototype methods directly on loadCache because:
308
+ * - In Node 22/23, loadCache is a plain Map<url, ModuleJob>
309
+ * - In Node 24, loadCache is a LoadCache extends Map<url, { [type]: ModuleJob }>
310
+ * where .delete() only sets the type slot to undefined (doesn't remove the entry)
311
+ * Using Map.prototype.delete ensures complete removal in both versions.
312
+ */
313
+ const esmBackup: Dict = Object.create(null)
314
+ const cjsBackup: Dict = Object.create(null)
315
+ const require = createRequire(import.meta.url)
316
+ for (const filename of this.accepted) {
317
+ // Backup and clear ESM loadCache
318
+ const job = Map.prototype.get.call(this.internal.loadCache, filename)
319
+ esmBackup[filename] = job
320
+ Map.prototype.delete.call(this.internal.loadCache, filename)
321
+
322
+ // Backup and clear CJS Module._cache
323
+ try {
324
+ const filepath = fileURLToPath(filename)
325
+ if (require.cache[filepath]) {
326
+ cjsBackup[filepath] = require.cache[filepath]
327
+ delete require.cache[filepath]
328
+ }
329
+ } catch {
330
+ // filename might not be a file: URL (e.g. node: protocol), ignore
331
+ }
332
+ }
333
+
334
+ const rollback = () => {
335
+ for (const filename in esmBackup) {
336
+ Map.prototype.set.call(this.internal.loadCache, filename, esmBackup[filename])
337
+ }
338
+ for (const filepath in cjsBackup) {
339
+ require.cache[filepath] = cjsBackup[filepath]
340
+ }
341
+ }
342
+
343
+ // Attempt to re-import all plugin entry files
344
+ const attempts: Dict = {}
345
+ try {
346
+ for (const [, { filename }] of reloads) {
347
+ attempts[filename] = this.ctx.loader.unwrapExports(await this.ctx.loader.import(filename, this.getOuterStack))
348
+ }
349
+ } catch (e) {
350
+ handleError(this.ctx, e)
351
+ return rollback()
352
+ }
353
+
354
+ const reload = (plugin: any, runtime: Plugin.Runtime) => {
355
+ if (!runtime) return
356
+ for (const oldFiber of runtime.fibers) {
357
+ const fiber = oldFiber.parent.registry.plugin(plugin, oldFiber.rawConfig, this.getOuterStack)
358
+ fiber.entry = oldFiber.entry
359
+ if (fiber.entry) fiber.entry.fiber = fiber
360
+ }
361
+ }
362
+
363
+ try {
364
+ for (const [plugin, { filename, runtime }] of reloads) {
365
+ if (!runtime) continue
366
+ const path = relative(this.baseDir, fileURLToPath(filename))
367
+
368
+ try {
369
+ this.ctx.registry.delete(plugin)
370
+ } catch (err) {
371
+ this.ctx.logger.warn('failed to dispose plugin at %C', path)
372
+ this.ctx.logger.warn(err)
373
+ }
374
+
375
+ try {
376
+ reload(attempts[filename], runtime)
377
+ this.ctx.logger.info('reload plugin at %C', path)
378
+ } catch (err) {
379
+ this.ctx.logger.warn('failed to reload plugin at %C', path)
380
+ this.ctx.logger.warn(err)
381
+ throw err
382
+ }
383
+ }
384
+ } catch {
385
+ // Rollback: restore caches and re-register old plugins
386
+ rollback()
387
+ for (const [plugin, { filename, runtime }] of reloads) {
388
+ if (!runtime) continue
389
+ try {
390
+ this.ctx.registry.delete(attempts[filename])
391
+ reload(plugin, runtime)
392
+ } catch (err) {
393
+ this.ctx.logger.warn(err)
394
+ }
395
+ }
396
+ return
397
+ }
398
+
399
+ this.ctx.emit('hmr/reload', reloads)
400
+ this.stashed = new Set()
401
+ }
402
+ }
403
+
404
+ namespace Hmr {
405
+ export interface Config extends ChokidarOptions {
406
+ base?: string
407
+ root: string[]
408
+ debounce: number
409
+ ignored: string[]
410
+ }
411
+
412
+ export const Config: z<Config> = z.object({
413
+ base: z.string(),
414
+ root: z.array(String).role('table').default(['.']),
415
+ ignored: z.array(String).role('table').default([
416
+ '**/node_modules',
417
+ '**/.*',
418
+ 'cache',
419
+ 'data',
420
+ ]),
421
+ debounce: z.natural().role('ms').default(100),
422
+ })
423
+ // [deepseek-harness] vendored modification: removed `.i18n({ 'en-US': enUS, 'zh-CN': zhCN })`
424
+ // and the corresponding `./locales/*.yml` imports, to avoid a runtime YAML import hook
425
+ // (@cordisjs/unyaml) that we don't vendor. See vendor/README.md.
426
+ }
427
+
428
+ export default Hmr