@unieai/rabi-client-hmr 0.0.0-stage → 0.2.2-rc.5
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 +21 -0
- package/README.md +7 -2
- package/lib/client.js +11 -0
- package/lib/index.js +172 -0
- package/lib/types/client/index.d.ts +14 -0
- package/lib/types/events.d.ts +44 -0
- package/lib/types/index.d.ts +21 -0
- package/locale/de.json +6 -0
- package/locale/en.json +5 -0
- package/locale/es.json +6 -0
- package/locale/fr.json +6 -0
- package/locale/ja.json +6 -0
- package/locale/pt.json +6 -0
- package/locale/ru.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +48 -4
- package/src/client/index.ts +87 -0
- package/src/events.ts +50 -0
- package/src/index.ts +208 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 DeepSeek
|
|
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,8 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @unieai/rabi-client-hmr
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Web client graph synchronization and rebuilt-bundle reload transport
|
|
4
|
+
|
|
5
|
+
Part of Rabi, the agent harness UnieAI Code runs on. Installed as a dependency of `@unieai/rabi`;
|
|
6
|
+
not meant to be used on its own.
|
|
7
|
+
|
|
8
|
+
See LICENSE for the license and copyright of this package.
|
package/lib/client.js
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
|
|
2
|
+
window.__ModuleLoader__.load({id:`@unieai/rabi-client-hmr`,factory:require=>{var module={exports:{}};var exports=module.exports;Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var ParseError=class extends Error{constructor(message,options){super(message),this.name=`ParseError`,this.type=options.type,this.field=options.field,this.value=options.value,this.line=options.line}};const LF=10,CR=13,SPACE=32;function noop(_arg){}function createParser(config){if(typeof config==`function`)throw new TypeError("`config` must be an object, got a function instead. Did you mean `createParser({onEvent: fn})`?");const{onEvent=noop,onError=noop,onRetry=noop,onComment,maxBufferSize}=config,pendingFragments=[];let pendingFragmentsLength=0,isFirstChunk=!0,id,data=``,dataLines=0,eventType,terminated=!1;function feed(chunk){if(terminated)throw new Error("Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing.");if(isFirstChunk&&(isFirstChunk=!1,chunk.charCodeAt(0)===239&&chunk.charCodeAt(1)===187&&chunk.charCodeAt(2)===191&&(chunk=chunk.slice(3))),pendingFragments.length===0){const trailing2=processLines(chunk);trailing2!==``&&(pendingFragments.push(trailing2),pendingFragmentsLength=trailing2.length),checkBufferSize();return}if(chunk.indexOf(`
|
|
3
|
+
`)===-1&&chunk.indexOf(`\r`)===-1){pendingFragments.push(chunk),pendingFragmentsLength+=chunk.length,checkBufferSize();return}pendingFragments.push(chunk);const input=pendingFragments.join(``);pendingFragments.length=0,pendingFragmentsLength=0;const trailing=processLines(input);trailing!==``&&(pendingFragments.push(trailing),pendingFragmentsLength=trailing.length),checkBufferSize()}function checkBufferSize(){maxBufferSize!==void 0&&(pendingFragmentsLength+data.length<=maxBufferSize||(terminated=!0,pendingFragments.length=0,pendingFragmentsLength=0,id=void 0,data=``,dataLines=0,eventType=void 0,onError(new ParseError(`Buffered data exceeded max buffer size of ${maxBufferSize} characters`,{type:`max-buffer-size-exceeded`}))))}function processLines(chunk){let searchIndex=0;if(chunk.indexOf(`\r`)===-1){let lfIndex=chunk.indexOf(`
|
|
4
|
+
`,searchIndex);for(;lfIndex!==-1;){if(searchIndex===lfIndex){dataLines>0&&onEvent({id,event:eventType,data}),id=void 0,data=``,dataLines=0,eventType=void 0,searchIndex=lfIndex+1,lfIndex=chunk.indexOf(`
|
|
5
|
+
`,searchIndex);continue}const firstCharCode=chunk.charCodeAt(searchIndex);if(isDataPrefix(chunk,searchIndex,firstCharCode)){const valueStart=chunk.charCodeAt(searchIndex+5)===SPACE?searchIndex+6:searchIndex+5,value=chunk.slice(valueStart,lfIndex);if(dataLines===0&&chunk.charCodeAt(lfIndex+1)===LF){onEvent({id,event:eventType,data:value}),id=void 0,data=``,eventType=void 0,searchIndex=lfIndex+2,lfIndex=chunk.indexOf(`
|
|
6
|
+
`,searchIndex);continue}data=dataLines===0?value:`${data}
|
|
7
|
+
${value}`,dataLines++}else isEventPrefix(chunk,searchIndex,firstCharCode)?eventType=chunk.slice(chunk.charCodeAt(searchIndex+6)===SPACE?searchIndex+7:searchIndex+6,lfIndex)||void 0:parseLine(chunk,searchIndex,lfIndex);searchIndex=lfIndex+1,lfIndex=chunk.indexOf(`
|
|
8
|
+
`,searchIndex)}return chunk.slice(searchIndex)}for(;searchIndex<chunk.length;){const crIndex=chunk.indexOf(`\r`,searchIndex),lfIndex=chunk.indexOf(`
|
|
9
|
+
`,searchIndex);let lineEnd=-1;if(crIndex!==-1&&lfIndex!==-1?lineEnd=crIndex<lfIndex?crIndex:lfIndex:crIndex!==-1?crIndex===chunk.length-1?lineEnd=-1:lineEnd=crIndex:lfIndex!==-1&&(lineEnd=lfIndex),lineEnd===-1)break;parseLine(chunk,searchIndex,lineEnd),searchIndex=lineEnd+1,chunk.charCodeAt(searchIndex-1)===CR&&chunk.charCodeAt(searchIndex)===LF&&searchIndex++}return chunk.slice(searchIndex)}function parseLine(chunk,start,end){if(start===end){dispatchEvent();return}const firstCharCode=chunk.charCodeAt(start);if(isDataPrefix(chunk,start,firstCharCode)){const valueStart=chunk.charCodeAt(start+5)===SPACE?start+6:start+5,value2=chunk.slice(valueStart,end);data=dataLines===0?value2:`${data}
|
|
10
|
+
${value2}`,dataLines++;return}if(isEventPrefix(chunk,start,firstCharCode)){eventType=chunk.slice(chunk.charCodeAt(start+6)===SPACE?start+7:start+6,end)||void 0;return}if(firstCharCode===105&&chunk.charCodeAt(start+1)===100&&chunk.charCodeAt(start+2)===58){const value2=chunk.slice(chunk.charCodeAt(start+3)===SPACE?start+4:start+3,end);id=value2.includes(`\0`)?void 0:value2;return}if(firstCharCode===58){if(onComment)onComment(chunk.slice(start,end).slice(chunk.charCodeAt(start+1)===SPACE?2:1));return}const line=chunk.slice(start,end),fieldSeparatorIndex=line.indexOf(`:`);if(fieldSeparatorIndex===-1){processField(line,``,line);return}const field=line.slice(0,fieldSeparatorIndex),offset=line.charCodeAt(fieldSeparatorIndex+1)===SPACE?2:1;processField(field,line.slice(fieldSeparatorIndex+offset),line)}function processField(field,value,line){switch(field){case`event`:eventType=value||void 0;break;case`data`:data=dataLines===0?value:`${data}
|
|
11
|
+
${value}`,dataLines++;break;case`id`:id=value.includes(`\0`)?void 0:value;break;case`retry`:/^\d+$/.test(value)?onRetry(parseInt(value,10)):onError(new ParseError(`Invalid \`retry\` value: "${value}"`,{type:`invalid-retry`,value,line}));break;default:onError(new ParseError(`Unknown field "${field.length>20?`${field.slice(0,20)}\u2026`:field}"`,{type:`unknown-field`,field,value,line}));break}}function dispatchEvent(){dataLines>0&&onEvent({id,event:eventType,data}),id=void 0,data=``,dataLines=0,eventType=void 0}function reset(options={}){if(options.consume&&pendingFragments.length>0){const incompleteLine=pendingFragments.join(``);parseLine(incompleteLine,0,incompleteLine.length)}isFirstChunk=!0,id=void 0,data=``,dataLines=0,eventType=void 0,pendingFragments.length=0,pendingFragmentsLength=0,terminated=!1}return{feed,reset}}function isDataPrefix(chunk,i,firstCharCode){return firstCharCode===100&&chunk.charCodeAt(i+1)===97&&chunk.charCodeAt(i+2)===116&&chunk.charCodeAt(i+3)===97&&chunk.charCodeAt(i+4)===58}function isEventPrefix(chunk,i,firstCharCode){return firstCharCode===101&&chunk.charCodeAt(i+1)===118&&chunk.charCodeAt(i+2)===101&&chunk.charCodeAt(i+3)===110&&chunk.charCodeAt(i+4)===116&&chunk.charCodeAt(i+5)===58}var EventSourceParserStream=class extends TransformStream{constructor({onError,onRetry,onComment,maxBufferSize}={}){let parser;super({start(controller){parser=createParser({onEvent:event=>{controller.enqueue(event)},onError(error){typeof onError==`function`&&onError(error),(onError===`terminate`||error.type===`max-buffer-size-exceeded`)&&controller.error(error)},onRetry,onComment,maxBufferSize})},transform(chunk){parser.feed(chunk)}})}};function parsePluginsEventFrame(value){if(typeof value!==`object`||value===null)return{kind:`invalid`};const record=value;switch(record.type){case`rebuilt`:return typeof record.id===`string`&&typeof record.rev===`string`?{kind:`frame`,frame:{type:`rebuilt`,id:record.id,rev:record.rev}}:{kind:`invalid`};case`graph`:return typeof record.graph===`object`&&record.graph!==null?{kind:`frame`,frame:{type:`graph`,graph:record.graph}}:{kind:`invalid`};default:return typeof record.type===`string`?{kind:`unknown`}:{kind:`invalid`}}}const EVENTS_ENDPOINT=`/plugins/events`;const EVENTS_ROUTE=EVENTS_ENDPOINT.slice(1);const name=`client-hmr`;const inject=[`modules`];async function readPageTransportEvents(fetch,signal,receive){const response=await fetch(EVENTS_ROUTE,{method:`GET`,headers:{accept:`text/event-stream`},signal});if(!response.ok||response.body===null)throw new Error(`client-hmr: ${EVENTS_ROUTE} answered ${String(response.status)}`);const reader=response.body.pipeThrough(new TextDecoderStream).pipeThrough(new EventSourceParserStream).getReader();for(;;){const{done,value}=await reader.read();if(done)break;receive(value.data)}if(!signal.aborted)throw new Error(`client-hmr: ${EVENTS_ROUTE} closed; client graph changes stop until the page reloads`)}function apply(ctx){const entries=ctx.modules.entries;const handle=frame=>{(frame.type===`graph`?Promise.resolve().then(()=>entries.sync(frame.graph)):entries.reload(frame.id,frame.rev)).catch(error=>{ctx.logger.error(error)})};const receive=data=>{let value;try{value=JSON.parse(data)}catch{ctx.logger.warn(`client-hmr: unparseable event frame: ${data}`);return}const parsed=parsePluginsEventFrame(value);if(parsed.kind===`invalid`)ctx.logger.warn(`client-hmr: invalid event frame: ${data}`);else if(parsed.kind===`frame`)handle(parsed.frame)};ctx.effect(()=>{const transport=globalThis.__RABI_TRANSPORT__;if(transport?.fetch!==void 0){const controller=new AbortController;readPageTransportEvents(transport.fetch,controller.signal,receive).catch(error=>{if(!controller.signal.aborted)ctx.logger.error(error)});return()=>{controller.abort()}}const source=new EventSource(EVENTS_ROUTE);source.addEventListener(`message`,event=>{receive(event.data)});return()=>{source.close()}},`client-hmr: event source`)}exports.apply=apply;exports.inject=inject;exports.name=name;return module.exports}});
|
package/lib/index.js
ADDED
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
import { statSync } from "node:fs";
|
|
2
|
+
import z from "@unieai/schemastery";
|
|
3
|
+
//#region lib/types/events.js
|
|
4
|
+
/** System SSE endpoint pushing graph/rebuilt frames (wire protocol constant). */
|
|
5
|
+
const EVENTS_ENDPOINT = "/plugins/events";
|
|
6
|
+
EVENTS_ENDPOINT.slice(1);
|
|
7
|
+
//#endregion
|
|
8
|
+
//#region lib/types/index.js
|
|
9
|
+
/**
|
|
10
|
+
* Host transport for Web client graph changes and rebuilt bundles. One interval
|
|
11
|
+
* stat-polls every graph row's client bundle (polling by design: network mounts
|
|
12
|
+
* deliver no inotify events), reports changes through
|
|
13
|
+
* `clientModules.rebuilt(id)`, and serves the `/plugins/events` SSE channel
|
|
14
|
+
* broadcasting graph/rebuilt frames to the browser half (src/client/).
|
|
15
|
+
* The Web composition mounts this transport for live graph updates;
|
|
16
|
+
* a development rebuild watcher also supplies bundle changes.
|
|
17
|
+
*/
|
|
18
|
+
/** Cordis plugin name. */
|
|
19
|
+
const name = "client-hmr";
|
|
20
|
+
/** Required services: the client graph and Web route registry. */
|
|
21
|
+
const inject = ["clientModules", "webServer"];
|
|
22
|
+
const Config = z.object({ pollIntervalMs: z.number().step(1).min(1).default(500) });
|
|
23
|
+
/** Serialize one frame as an SSE data line. */
|
|
24
|
+
function sseData(frame) {
|
|
25
|
+
return `data: ${JSON.stringify(frame)}\n\n`;
|
|
26
|
+
}
|
|
27
|
+
/** Snapshot the executable bundle metadata that drives reloads. */
|
|
28
|
+
function bundleStat(path) {
|
|
29
|
+
const bundle = statSync(path);
|
|
30
|
+
return {
|
|
31
|
+
mtimeMs: bundle.mtimeMs,
|
|
32
|
+
ctimeMs: bundle.ctimeMs,
|
|
33
|
+
size: bundle.size
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
/** Whether the executable bundle metadata is unchanged since its last publication. */
|
|
37
|
+
function sameBundleStat(left, right) {
|
|
38
|
+
return left.mtimeMs === right.mtimeMs && left.ctimeMs === right.ctimeMs && left.size === right.size;
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Mount bundle watches and graph/rebuilt SSE delivery.
|
|
42
|
+
* @param ctx - host plugin context carrying clientModules and webServer.
|
|
43
|
+
* @param config - validated {@link Config}.
|
|
44
|
+
*/
|
|
45
|
+
function apply(ctx, config) {
|
|
46
|
+
const pollIntervalMs = config.pollIntervalMs;
|
|
47
|
+
const watched = /* @__PURE__ */ new Map();
|
|
48
|
+
const publish = (id, watch, current) => {
|
|
49
|
+
try {
|
|
50
|
+
ctx.clientModules.rebuilt(id);
|
|
51
|
+
} catch (error) {
|
|
52
|
+
if (error.code === "ENOENT") {
|
|
53
|
+
watch.dirty = true;
|
|
54
|
+
return;
|
|
55
|
+
}
|
|
56
|
+
ctx.logger.warn(error);
|
|
57
|
+
}
|
|
58
|
+
watch.mtimeMs = current.mtimeMs;
|
|
59
|
+
watch.ctimeMs = current.ctimeMs;
|
|
60
|
+
watch.size = current.size;
|
|
61
|
+
watch.dirty = false;
|
|
62
|
+
};
|
|
63
|
+
const watchRow = (id, baseline) => {
|
|
64
|
+
const watch = {
|
|
65
|
+
...baseline,
|
|
66
|
+
dirty: false
|
|
67
|
+
};
|
|
68
|
+
watched.set(id, watch);
|
|
69
|
+
let current;
|
|
70
|
+
try {
|
|
71
|
+
current = bundleStat(baseline.path);
|
|
72
|
+
} catch (error) {
|
|
73
|
+
watch.dirty = true;
|
|
74
|
+
if (error.code !== "ENOENT") ctx.logger.warn(error);
|
|
75
|
+
return;
|
|
76
|
+
}
|
|
77
|
+
if (!sameBundleStat(current, watch)) publish(id, watch, current);
|
|
78
|
+
};
|
|
79
|
+
const pollWatches = () => {
|
|
80
|
+
for (const [id, watch] of watched) {
|
|
81
|
+
let current;
|
|
82
|
+
try {
|
|
83
|
+
current = bundleStat(watch.path);
|
|
84
|
+
} catch (error) {
|
|
85
|
+
watch.dirty = true;
|
|
86
|
+
if (error.code !== "ENOENT") ctx.logger.warn(error);
|
|
87
|
+
continue;
|
|
88
|
+
}
|
|
89
|
+
if (!watch.dirty && sameBundleStat(current, watch)) continue;
|
|
90
|
+
publish(id, watch, current);
|
|
91
|
+
}
|
|
92
|
+
};
|
|
93
|
+
const syncWatches = () => {
|
|
94
|
+
const rows = /* @__PURE__ */ new Map();
|
|
95
|
+
for (const row of ctx.clientModules.graph().entries) {
|
|
96
|
+
const watch = ctx.clientModules.artifactBaseline(row.id);
|
|
97
|
+
if (watch !== void 0) rows.set(row.id, watch);
|
|
98
|
+
}
|
|
99
|
+
for (const [id, watch] of watched) {
|
|
100
|
+
if (rows.get(id)?.path === watch.path) continue;
|
|
101
|
+
watched.delete(id);
|
|
102
|
+
}
|
|
103
|
+
for (const [id, watch] of rows) if (!watched.has(id)) watchRow(id, watch);
|
|
104
|
+
};
|
|
105
|
+
ctx.effect(() => {
|
|
106
|
+
syncWatches();
|
|
107
|
+
const unsubscribe = ctx.clientModules.onGraphChanged(syncWatches);
|
|
108
|
+
const timer = setInterval(pollWatches, pollIntervalMs);
|
|
109
|
+
timer.unref();
|
|
110
|
+
return () => {
|
|
111
|
+
unsubscribe();
|
|
112
|
+
clearInterval(timer);
|
|
113
|
+
watched.clear();
|
|
114
|
+
};
|
|
115
|
+
}, "client-hmr: bundle watches");
|
|
116
|
+
const connections = /* @__PURE__ */ new Set();
|
|
117
|
+
const publishGraph = () => {
|
|
118
|
+
const line = sseData({
|
|
119
|
+
type: "graph",
|
|
120
|
+
graph: ctx.clientModules.graph()
|
|
121
|
+
});
|
|
122
|
+
for (const res of connections) res.write(line);
|
|
123
|
+
};
|
|
124
|
+
const connect = (res) => {
|
|
125
|
+
res.writeHead(200, {
|
|
126
|
+
"content-type": "text/event-stream",
|
|
127
|
+
"cache-control": "no-cache",
|
|
128
|
+
"connection": "keep-alive"
|
|
129
|
+
});
|
|
130
|
+
res.write(": connected\n\n");
|
|
131
|
+
connections.add(res);
|
|
132
|
+
res.write(sseData({
|
|
133
|
+
type: "graph",
|
|
134
|
+
graph: ctx.clientModules.graph()
|
|
135
|
+
}));
|
|
136
|
+
res.on("close", () => {
|
|
137
|
+
connections.delete(res);
|
|
138
|
+
});
|
|
139
|
+
};
|
|
140
|
+
ctx.effect(() => {
|
|
141
|
+
const disposeRoute = ctx.webServer.register({
|
|
142
|
+
kind: "exact",
|
|
143
|
+
path: EVENTS_ENDPOINT,
|
|
144
|
+
handler: (req, res) => {
|
|
145
|
+
if (req.method !== "GET" && req.method !== "HEAD") {
|
|
146
|
+
res.writeHead(405);
|
|
147
|
+
res.end();
|
|
148
|
+
return;
|
|
149
|
+
}
|
|
150
|
+
connect(res);
|
|
151
|
+
}
|
|
152
|
+
});
|
|
153
|
+
const unsubscribeGraph = ctx.clientModules.onGraphChanged(publishGraph);
|
|
154
|
+
const unsubscribe = ctx.clientModules.onRebuilt((id, rev) => {
|
|
155
|
+
const line = sseData({
|
|
156
|
+
type: "rebuilt",
|
|
157
|
+
id,
|
|
158
|
+
rev
|
|
159
|
+
});
|
|
160
|
+
for (const res of connections) res.write(line);
|
|
161
|
+
});
|
|
162
|
+
return () => {
|
|
163
|
+
unsubscribeGraph();
|
|
164
|
+
unsubscribe();
|
|
165
|
+
disposeRoute();
|
|
166
|
+
for (const res of connections) res.destroy();
|
|
167
|
+
connections.clear();
|
|
168
|
+
};
|
|
169
|
+
}, "client-hmr: /plugins/events channel");
|
|
170
|
+
}
|
|
171
|
+
//#endregion
|
|
172
|
+
export { Config, EVENTS_ENDPOINT, apply, inject, name };
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/** Web SSE transport for page-owned client entry reconciliation and rebuilt code replacement. */
|
|
2
|
+
import type { Context } from '@unieai/cordis';
|
|
3
|
+
export type { PluginsEventFrame } from '../events.ts';
|
|
4
|
+
/** Cordis plugin name. */
|
|
5
|
+
export declare const name = "client-hmr";
|
|
6
|
+
/** Required service: the client module system whose entry controller handles received frames. */
|
|
7
|
+
export declare const inject: string[];
|
|
8
|
+
/**
|
|
9
|
+
* Forward graph snapshots and rebuilds to the page's shared serial controller. The event stream arrives through the
|
|
10
|
+
* shell transport when the page has one, otherwise through the browser `EventSource`.
|
|
11
|
+
* @param ctx - Plugin context with the client module system.
|
|
12
|
+
*/
|
|
13
|
+
export declare function apply(ctx: Context): void;
|
|
14
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Wire protocol of the `/plugins/events` SSE channel — single source for
|
|
3
|
+
* both halves of this package. Frames still cross a wire boundary: the
|
|
4
|
+
* browser half validates them at its JSON parse point; sharing the type keeps
|
|
5
|
+
* the two ends from drifting, not from parsing.
|
|
6
|
+
*/
|
|
7
|
+
import type { WebBootGraph } from '@unieai/rabi-client-modules';
|
|
8
|
+
/** One SSE frame: the settled graph on connection or change, or one rebuilt bundle notice. */
|
|
9
|
+
export type PluginsEventFrame = {
|
|
10
|
+
type: 'graph';
|
|
11
|
+
graph: WebBootGraph;
|
|
12
|
+
} | {
|
|
13
|
+
type: 'rebuilt';
|
|
14
|
+
id: string;
|
|
15
|
+
rev: string;
|
|
16
|
+
};
|
|
17
|
+
/** Browser wire-parse result: known frame, forward-compatible unknown type, or malformed payload. */
|
|
18
|
+
export type PluginsEventParseResult = {
|
|
19
|
+
kind: 'frame';
|
|
20
|
+
frame: {
|
|
21
|
+
type: 'graph';
|
|
22
|
+
graph: unknown;
|
|
23
|
+
} | Extract<PluginsEventFrame, {
|
|
24
|
+
type: 'rebuilt';
|
|
25
|
+
}>;
|
|
26
|
+
} | {
|
|
27
|
+
kind: 'unknown';
|
|
28
|
+
} | {
|
|
29
|
+
kind: 'invalid';
|
|
30
|
+
};
|
|
31
|
+
/**
|
|
32
|
+
* Validate the frame envelope; the module controller parses the complete graph before updating its index.
|
|
33
|
+
* @param value - Parsed JSON value from the EventSource message.
|
|
34
|
+
* @returns the known frame, an unknown-type marker, or an invalid marker.
|
|
35
|
+
*/
|
|
36
|
+
export declare function parsePluginsEventFrame(value: unknown): PluginsEventParseResult;
|
|
37
|
+
/** System SSE endpoint pushing graph/rebuilt frames (wire protocol constant). */
|
|
38
|
+
export declare const EVENTS_ENDPOINT = "/plugins/events";
|
|
39
|
+
/**
|
|
40
|
+
* Document-relative form of {@link EVENTS_ENDPOINT} used by the browser half.
|
|
41
|
+
* See .agents/notes/implemented/architecture/2026-09-14-web-document-relative-app-routes.md.
|
|
42
|
+
*/
|
|
43
|
+
export declare const EVENTS_ROUTE: string;
|
|
44
|
+
//# sourceMappingURL=events.d.ts.map
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import type { Context } from '@unieai/cordis';
|
|
2
|
+
import z from '@unieai/schemastery';
|
|
3
|
+
export type { PluginsEventFrame } from './events.ts';
|
|
4
|
+
export { EVENTS_ENDPOINT } from './events.ts';
|
|
5
|
+
/** Cordis plugin name. */
|
|
6
|
+
export declare const name = "client-hmr";
|
|
7
|
+
/** Required services: the client graph and Web route registry. */
|
|
8
|
+
export declare const inject: string[];
|
|
9
|
+
/** Plugin config, validated by the same-named schemastery schema. */
|
|
10
|
+
export interface Config {
|
|
11
|
+
/** Bundle stat-poll interval in milliseconds (default 500, the build-side watcher's polling default). */
|
|
12
|
+
pollIntervalMs?: number;
|
|
13
|
+
}
|
|
14
|
+
export declare const Config: z<Config>;
|
|
15
|
+
/**
|
|
16
|
+
* Mount bundle watches and graph/rebuilt SSE delivery.
|
|
17
|
+
* @param ctx - host plugin context carrying clientModules and webServer.
|
|
18
|
+
* @param config - validated {@link Config}.
|
|
19
|
+
*/
|
|
20
|
+
export declare function apply(ctx: Context, config: Config): void;
|
|
21
|
+
//# sourceMappingURL=index.d.ts.map
|
package/locale/de.json
ADDED
package/locale/es.json
ADDED
package/locale/fr.json
ADDED
package/locale/ja.json
ADDED
package/locale/pt.json
ADDED
package/locale/ru.json
ADDED
package/locale/zh.json
ADDED
package/package.json
CHANGED
|
@@ -1,6 +1,50 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@unieai/rabi-client-hmr",
|
|
3
|
-
"
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"description": "Web client graph synchronization and rebuilt-bundle reload transport",
|
|
4
|
+
"version": "0.2.2-rc.5",
|
|
5
|
+
"publishConfig": {
|
|
6
|
+
"access": "public"
|
|
7
|
+
},
|
|
8
|
+
"type": "module",
|
|
9
|
+
"main": "lib/index.js",
|
|
10
|
+
"types": "lib/types/index.d.ts",
|
|
11
|
+
"exports": {
|
|
12
|
+
".": {
|
|
13
|
+
"types": "./lib/types/index.d.ts",
|
|
14
|
+
"default": "./lib/index.js"
|
|
15
|
+
},
|
|
16
|
+
"./client": {
|
|
17
|
+
"types": "./lib/types/client/index.d.ts",
|
|
18
|
+
"default": "./lib/client.js"
|
|
19
|
+
},
|
|
20
|
+
"./src/*": "./src/*",
|
|
21
|
+
"./package.json": "./package.json",
|
|
22
|
+
"./locale/*.json": "./locale/*.json"
|
|
23
|
+
},
|
|
24
|
+
"rabi": {
|
|
25
|
+
"client": {
|
|
26
|
+
"inject": [
|
|
27
|
+
"@unieai/rabi-client-modules"
|
|
28
|
+
],
|
|
29
|
+
"platform": "web",
|
|
30
|
+
"immediately": true
|
|
31
|
+
}
|
|
32
|
+
},
|
|
33
|
+
"license": "MIT",
|
|
34
|
+
"dependencies": {
|
|
35
|
+
"@unieai/schemastery": "3.19.0"
|
|
36
|
+
},
|
|
37
|
+
"peerDependencies": {
|
|
38
|
+
"@unieai/cordis": "4.1.0"
|
|
39
|
+
},
|
|
40
|
+
"files": [
|
|
41
|
+
"locale/*.json",
|
|
42
|
+
"lib/index.js",
|
|
43
|
+
"lib/client.js",
|
|
44
|
+
"lib/types/**/*.d.ts",
|
|
45
|
+
"lib/types/**/*.d.ts.map",
|
|
46
|
+
"lib/**/*.js.map",
|
|
47
|
+
"src",
|
|
48
|
+
"README.md"
|
|
49
|
+
]
|
|
50
|
+
}
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
/** Web SSE transport for page-owned client entry reconciliation and rebuilt code replacement. */
|
|
2
|
+
import type { Context } from '@unieai/cordis'
|
|
3
|
+
import { EventSourceParserStream } from 'eventsource-parser/stream'
|
|
4
|
+
import type { PluginsEventParseResult } from '../events.ts'
|
|
5
|
+
import { EVENTS_ROUTE, parsePluginsEventFrame } from '../events.ts'
|
|
6
|
+
|
|
7
|
+
export type { PluginsEventFrame } from '../events.ts'
|
|
8
|
+
|
|
9
|
+
/** Cordis plugin name. */
|
|
10
|
+
export const name = 'client-hmr'
|
|
11
|
+
|
|
12
|
+
/** Required service: the client module system whose entry controller handles received frames. */
|
|
13
|
+
export const inject = ['modules']
|
|
14
|
+
|
|
15
|
+
/** Request carrier a shell installs when it owns the page transport, such as the worker preview's tunnel. */
|
|
16
|
+
type PageTransportFetch = (input: string, init: RequestInit) => Promise<Response>
|
|
17
|
+
|
|
18
|
+
/** Page global carrying the shell transport; absent in the served web app. */
|
|
19
|
+
interface PageTransportGlobal {
|
|
20
|
+
__RABI_TRANSPORT__?: { fetch?: PageTransportFetch }
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Read the document-relative events route through a shell-owned transport until it closes or `signal` aborts.
|
|
25
|
+
* @param fetch - The shell's request carrier.
|
|
26
|
+
* @param signal - Aborts the stream when the plugin disposes.
|
|
27
|
+
* @param receive - Handles one SSE `data` payload.
|
|
28
|
+
* @throws Error when the Host refuses the stream or the stream ends while the plugin is active.
|
|
29
|
+
*/
|
|
30
|
+
async function readPageTransportEvents(fetch: PageTransportFetch, signal: AbortSignal, receive: (data: string) => void): Promise<void> {
|
|
31
|
+
const response = await fetch(EVENTS_ROUTE, { method: 'GET', headers: { accept: 'text/event-stream' }, signal })
|
|
32
|
+
if (!response.ok || response.body === null) {
|
|
33
|
+
throw new Error(`client-hmr: ${EVENTS_ROUTE} answered ${String(response.status)}`)
|
|
34
|
+
}
|
|
35
|
+
const reader = response.body.pipeThrough(new TextDecoderStream()).pipeThrough(new EventSourceParserStream()).getReader()
|
|
36
|
+
for (;;) {
|
|
37
|
+
const { done, value } = await reader.read()
|
|
38
|
+
if (done) break
|
|
39
|
+
receive(value.data)
|
|
40
|
+
}
|
|
41
|
+
if (!signal.aborted) throw new Error(`client-hmr: ${EVENTS_ROUTE} closed; client graph changes stop until the page reloads`)
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Forward graph snapshots and rebuilds to the page's shared serial controller. The event stream arrives through the
|
|
46
|
+
* shell transport when the page has one, otherwise through the browser `EventSource`.
|
|
47
|
+
* @param ctx - Plugin context with the client module system.
|
|
48
|
+
*/
|
|
49
|
+
export function apply(ctx: Context): void {
|
|
50
|
+
const entries = ctx.modules.entries
|
|
51
|
+
const handle = (frame: Extract<PluginsEventParseResult, { kind: 'frame' }>['frame']): void => {
|
|
52
|
+
const run = frame.type === 'graph'
|
|
53
|
+
? Promise.resolve().then(() => entries.sync(frame.graph))
|
|
54
|
+
: entries.reload(frame.id, frame.rev)
|
|
55
|
+
void run.catch((error: unknown) => { ctx.logger.error(error) })
|
|
56
|
+
}
|
|
57
|
+
const receive = (data: string): void => {
|
|
58
|
+
let value: unknown
|
|
59
|
+
try {
|
|
60
|
+
value = JSON.parse(data)
|
|
61
|
+
} catch {
|
|
62
|
+
// Wire boundary: a malformed transport frame is dropped loudly.
|
|
63
|
+
ctx.logger.warn(`client-hmr: unparseable event frame: ${data}`)
|
|
64
|
+
return
|
|
65
|
+
}
|
|
66
|
+
const parsed = parsePluginsEventFrame(value)
|
|
67
|
+
if (parsed.kind === 'invalid') {
|
|
68
|
+
ctx.logger.warn(`client-hmr: invalid event frame: ${data}`)
|
|
69
|
+
} else if (parsed.kind === 'frame') {
|
|
70
|
+
handle(parsed.frame)
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
ctx.effect(() => {
|
|
75
|
+
const transport = (globalThis as PageTransportGlobal).__RABI_TRANSPORT__
|
|
76
|
+
if (transport?.fetch !== undefined) {
|
|
77
|
+
const controller = new AbortController()
|
|
78
|
+
void readPageTransportEvents(transport.fetch, controller.signal, receive).catch((error: unknown) => {
|
|
79
|
+
if (!controller.signal.aborted) ctx.logger.error(error)
|
|
80
|
+
})
|
|
81
|
+
return () => { controller.abort() }
|
|
82
|
+
}
|
|
83
|
+
const source = new EventSource(EVENTS_ROUTE)
|
|
84
|
+
source.addEventListener('message', (event: MessageEvent<string>) => { receive(event.data) })
|
|
85
|
+
return () => { source.close() }
|
|
86
|
+
}, 'client-hmr: event source')
|
|
87
|
+
}
|
package/src/events.ts
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Wire protocol of the `/plugins/events` SSE channel — single source for
|
|
3
|
+
* both halves of this package. Frames still cross a wire boundary: the
|
|
4
|
+
* browser half validates them at its JSON parse point; sharing the type keeps
|
|
5
|
+
* the two ends from drifting, not from parsing.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import type { WebBootGraph } from '@unieai/rabi-client-modules'
|
|
9
|
+
|
|
10
|
+
/** One SSE frame: the settled graph on connection or change, or one rebuilt bundle notice. */
|
|
11
|
+
export type PluginsEventFrame =
|
|
12
|
+
| { type: 'graph'; graph: WebBootGraph }
|
|
13
|
+
| { type: 'rebuilt'; id: string; rev: string }
|
|
14
|
+
|
|
15
|
+
/** Browser wire-parse result: known frame, forward-compatible unknown type, or malformed payload. */
|
|
16
|
+
export type PluginsEventParseResult =
|
|
17
|
+
| { kind: 'frame'; frame: { type: 'graph'; graph: unknown } | Extract<PluginsEventFrame, { type: 'rebuilt' }> }
|
|
18
|
+
| { kind: 'unknown' }
|
|
19
|
+
| { kind: 'invalid' }
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Validate the frame envelope; the module controller parses the complete graph before updating its index.
|
|
23
|
+
* @param value - Parsed JSON value from the EventSource message.
|
|
24
|
+
* @returns the known frame, an unknown-type marker, or an invalid marker.
|
|
25
|
+
*/
|
|
26
|
+
export function parsePluginsEventFrame(value: unknown): PluginsEventParseResult {
|
|
27
|
+
if (typeof value !== 'object' || value === null) return { kind: 'invalid' }
|
|
28
|
+
const record = value as Record<string, unknown>
|
|
29
|
+
switch (record.type) {
|
|
30
|
+
case 'rebuilt':
|
|
31
|
+
return typeof record.id === 'string' && typeof record.rev === 'string'
|
|
32
|
+
? { kind: 'frame', frame: { type: 'rebuilt', id: record.id, rev: record.rev } }
|
|
33
|
+
: { kind: 'invalid' }
|
|
34
|
+
case 'graph':
|
|
35
|
+
return typeof record.graph === 'object' && record.graph !== null
|
|
36
|
+
? { kind: 'frame', frame: { type: 'graph', graph: record.graph } }
|
|
37
|
+
: { kind: 'invalid' }
|
|
38
|
+
default:
|
|
39
|
+
return typeof record.type === 'string' ? { kind: 'unknown' } : { kind: 'invalid' }
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** System SSE endpoint pushing graph/rebuilt frames (wire protocol constant). */
|
|
44
|
+
export const EVENTS_ENDPOINT = '/plugins/events'
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Document-relative form of {@link EVENTS_ENDPOINT} used by the browser half.
|
|
48
|
+
* See .agents/notes/implemented/architecture/2026-09-14-web-document-relative-app-routes.md.
|
|
49
|
+
*/
|
|
50
|
+
export const EVENTS_ROUTE = EVENTS_ENDPOINT.slice(1)
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Host transport for Web client graph changes and rebuilt bundles. One interval
|
|
3
|
+
* stat-polls every graph row's client bundle (polling by design: network mounts
|
|
4
|
+
* deliver no inotify events), reports changes through
|
|
5
|
+
* `clientModules.rebuilt(id)`, and serves the `/plugins/events` SSE channel
|
|
6
|
+
* broadcasting graph/rebuilt frames to the browser half (src/client/).
|
|
7
|
+
* The Web composition mounts this transport for live graph updates;
|
|
8
|
+
* a development rebuild watcher also supplies bundle changes.
|
|
9
|
+
*/
|
|
10
|
+
import { statSync } from 'node:fs'
|
|
11
|
+
import type { ServerResponse } from 'node:http'
|
|
12
|
+
import type { Context } from '@unieai/cordis'
|
|
13
|
+
import z from '@unieai/schemastery'
|
|
14
|
+
// Type imports carry the clientModules/webServer Context merges.
|
|
15
|
+
import type { ClientArtifactBaseline } from '@unieai/rabi-client-modules'
|
|
16
|
+
import type {} from '@unieai/rabi-host-webserver'
|
|
17
|
+
import type { PluginsEventFrame } from './events.ts'
|
|
18
|
+
import { EVENTS_ENDPOINT } from './events.ts'
|
|
19
|
+
|
|
20
|
+
export type { PluginsEventFrame } from './events.ts'
|
|
21
|
+
export { EVENTS_ENDPOINT } from './events.ts'
|
|
22
|
+
|
|
23
|
+
/** Cordis plugin name. */
|
|
24
|
+
export const name = 'client-hmr'
|
|
25
|
+
|
|
26
|
+
/** Required services: the client graph and Web route registry. */
|
|
27
|
+
export const inject = ['clientModules', 'webServer']
|
|
28
|
+
|
|
29
|
+
/** Plugin config, validated by the same-named schemastery schema. */
|
|
30
|
+
export interface Config {
|
|
31
|
+
/** Bundle stat-poll interval in milliseconds (default 500, the build-side watcher's polling default). */
|
|
32
|
+
pollIntervalMs?: number
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export const Config: z<Config> = z.object({
|
|
36
|
+
pollIntervalMs: z.number().step(1).min(1).default(500),
|
|
37
|
+
})
|
|
38
|
+
|
|
39
|
+
/** Serialize one frame as an SSE data line. */
|
|
40
|
+
function sseData(frame: PluginsEventFrame): string {
|
|
41
|
+
return `data: ${JSON.stringify(frame)}\n\n`
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
type WatchedBundleStat = Omit<ClientArtifactBaseline, 'path'>
|
|
45
|
+
|
|
46
|
+
type WatchedBundle = {
|
|
47
|
+
-readonly [K in keyof ClientArtifactBaseline]: ClientArtifactBaseline[K]
|
|
48
|
+
} & { dirty: boolean }
|
|
49
|
+
|
|
50
|
+
/** Snapshot the executable bundle metadata that drives reloads. */
|
|
51
|
+
function bundleStat(path: string): WatchedBundleStat {
|
|
52
|
+
const bundle = statSync(path)
|
|
53
|
+
return { mtimeMs: bundle.mtimeMs, ctimeMs: bundle.ctimeMs, size: bundle.size }
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** Whether the executable bundle metadata is unchanged since its last publication. */
|
|
57
|
+
function sameBundleStat(left: WatchedBundleStat, right: WatchedBundleStat): boolean {
|
|
58
|
+
return left.mtimeMs === right.mtimeMs
|
|
59
|
+
&& left.ctimeMs === right.ctimeMs
|
|
60
|
+
&& left.size === right.size
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Mount bundle watches and graph/rebuilt SSE delivery.
|
|
65
|
+
* @param ctx - host plugin context carrying clientModules and webServer.
|
|
66
|
+
* @param config - validated {@link Config}.
|
|
67
|
+
*/
|
|
68
|
+
export function apply(ctx: Context, config: Config): void {
|
|
69
|
+
// schemastery's .default() guarantees the field is set after validation.
|
|
70
|
+
const pollIntervalMs = config.pollIntervalMs as number
|
|
71
|
+
|
|
72
|
+
// --- bundle watch: one HMR-owned stat poll ------------------------------
|
|
73
|
+
const watched = new Map<string, WatchedBundle>()
|
|
74
|
+
|
|
75
|
+
const publish = (id: string, watch: WatchedBundle, current: WatchedBundleStat): void => {
|
|
76
|
+
try {
|
|
77
|
+
ctx.clientModules.rebuilt(id)
|
|
78
|
+
} catch (error) {
|
|
79
|
+
const code = (error as NodeJS.ErrnoException).code
|
|
80
|
+
if (code === 'ENOENT') {
|
|
81
|
+
watch.dirty = true
|
|
82
|
+
return
|
|
83
|
+
}
|
|
84
|
+
ctx.logger.warn(error)
|
|
85
|
+
}
|
|
86
|
+
watch.mtimeMs = current.mtimeMs
|
|
87
|
+
watch.ctimeMs = current.ctimeMs
|
|
88
|
+
watch.size = current.size
|
|
89
|
+
watch.dirty = false
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
const watchRow = (id: string, baseline: ClientArtifactBaseline): void => {
|
|
93
|
+
const watch: WatchedBundle = { ...baseline, dirty: false }
|
|
94
|
+
watched.set(id, watch)
|
|
95
|
+
let current: WatchedBundleStat
|
|
96
|
+
try {
|
|
97
|
+
current = bundleStat(baseline.path)
|
|
98
|
+
} catch (error) {
|
|
99
|
+
watch.dirty = true
|
|
100
|
+
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') ctx.logger.warn(error)
|
|
101
|
+
return
|
|
102
|
+
}
|
|
103
|
+
// The module host captured its baseline before reading the bytes in the
|
|
104
|
+
// startup batch. Only a mismatch crosses into generation publication.
|
|
105
|
+
if (!sameBundleStat(current, watch)) publish(id, watch, current)
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
const pollWatches = (): void => {
|
|
109
|
+
for (const [id, watch] of watched) {
|
|
110
|
+
let current: WatchedBundleStat
|
|
111
|
+
try {
|
|
112
|
+
current = bundleStat(watch.path)
|
|
113
|
+
} catch (error) {
|
|
114
|
+
watch.dirty = true
|
|
115
|
+
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') ctx.logger.warn(error)
|
|
116
|
+
continue
|
|
117
|
+
}
|
|
118
|
+
if (!watch.dirty && sameBundleStat(current, watch)) continue
|
|
119
|
+
// Stat-before-publication preserves a detectable older baseline for
|
|
120
|
+
// writes that land during the read. The preset stamps the entry after
|
|
121
|
+
// sibling chunks, so a completed build supplies the final stat change.
|
|
122
|
+
publish(id, watch, current)
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
// Diff the watch set against the current graph: drop watches for removed
|
|
127
|
+
// rows (or rows whose bundle path moved), add watches for new rows.
|
|
128
|
+
const syncWatches = (): void => {
|
|
129
|
+
const rows = new Map<string, ClientArtifactBaseline>()
|
|
130
|
+
for (const row of ctx.clientModules.graph().entries) {
|
|
131
|
+
const watch = ctx.clientModules.artifactBaseline(row.id)
|
|
132
|
+
if (watch !== undefined) rows.set(row.id, watch)
|
|
133
|
+
}
|
|
134
|
+
for (const [id, watch] of watched) {
|
|
135
|
+
if (rows.get(id)?.path === watch.path) continue
|
|
136
|
+
watched.delete(id)
|
|
137
|
+
}
|
|
138
|
+
for (const [id, watch] of rows) {
|
|
139
|
+
if (!watched.has(id)) watchRow(id, watch)
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
ctx.effect(() => {
|
|
144
|
+
// Initial sync covers rows already in the graph; the subscription covers
|
|
145
|
+
// rows arriving later (boot-window activations, including this plugin's
|
|
146
|
+
// own row; bootstrap revisions also reach page diagnostics).
|
|
147
|
+
syncWatches()
|
|
148
|
+
const unsubscribe = ctx.clientModules.onGraphChanged(syncWatches)
|
|
149
|
+
const timer = setInterval(pollWatches, pollIntervalMs)
|
|
150
|
+
timer.unref()
|
|
151
|
+
return () => {
|
|
152
|
+
unsubscribe()
|
|
153
|
+
clearInterval(timer)
|
|
154
|
+
watched.clear()
|
|
155
|
+
}
|
|
156
|
+
}, 'client-hmr: bundle watches')
|
|
157
|
+
|
|
158
|
+
// --- /plugins/events SSE channel ----------------------------------------
|
|
159
|
+
const connections = new Set<ServerResponse>()
|
|
160
|
+
|
|
161
|
+
const publishGraph = (): void => {
|
|
162
|
+
const line = sseData({ type: 'graph', graph: ctx.clientModules.graph() })
|
|
163
|
+
for (const res of connections) res.write(line)
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
const connect = (res: ServerResponse): void => {
|
|
167
|
+
res.writeHead(200, {
|
|
168
|
+
'content-type': 'text/event-stream',
|
|
169
|
+
'cache-control': 'no-cache',
|
|
170
|
+
'connection': 'keep-alive',
|
|
171
|
+
})
|
|
172
|
+
// Comment line on open so clients/proxies see a live channel even when
|
|
173
|
+
// no rebuild ever happens; EventSource frame parsing skips it naturally.
|
|
174
|
+
res.write(': connected\n\n')
|
|
175
|
+
connections.add(res)
|
|
176
|
+
res.write(sseData({ type: 'graph', graph: ctx.clientModules.graph() }))
|
|
177
|
+
res.on('close', () => { connections.delete(res) })
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
ctx.effect(() => {
|
|
181
|
+
const disposeRoute = ctx.webServer.register({
|
|
182
|
+
kind: 'exact',
|
|
183
|
+
path: EVENTS_ENDPOINT,
|
|
184
|
+
handler: (req, res) => {
|
|
185
|
+
// Named routes match ahead of the carrier's method gate; keep the old
|
|
186
|
+
// global 405 semantics for non-GET hits on this endpoint.
|
|
187
|
+
if (req.method !== 'GET' && req.method !== 'HEAD') {
|
|
188
|
+
res.writeHead(405)
|
|
189
|
+
res.end()
|
|
190
|
+
return
|
|
191
|
+
}
|
|
192
|
+
connect(res)
|
|
193
|
+
},
|
|
194
|
+
})
|
|
195
|
+
const unsubscribeGraph = ctx.clientModules.onGraphChanged(publishGraph)
|
|
196
|
+
const unsubscribe = ctx.clientModules.onRebuilt((id, rev) => {
|
|
197
|
+
const line = sseData({ type: 'rebuilt', id, rev })
|
|
198
|
+
for (const res of connections) res.write(line)
|
|
199
|
+
})
|
|
200
|
+
return () => {
|
|
201
|
+
unsubscribeGraph()
|
|
202
|
+
unsubscribe()
|
|
203
|
+
disposeRoute()
|
|
204
|
+
for (const res of connections) res.destroy()
|
|
205
|
+
connections.clear()
|
|
206
|
+
}
|
|
207
|
+
}, 'client-hmr: /plugins/events channel')
|
|
208
|
+
}
|