@histoire/dev-proxy 0.0.0-stage → 1.0.0-beta.3
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 +16 -2
- package/dist/appearance.d.ts +11 -0
- package/dist/appearance.js +11 -0
- package/dist/browser/chunks/transitions-3JvGwb-W.js +71 -0
- package/dist/browser/demo.js +50 -0
- package/dist/browser/lifecycle.js +55 -0
- package/dist/client/demo.d.ts +1 -0
- package/dist/client/demo.js +46 -0
- package/dist/client/lifecycle.d.ts +1 -0
- package/dist/client/lifecycle.js +73 -0
- package/dist/client/mark.d.ts +2 -0
- package/dist/client/mark.js +8 -0
- package/dist/client/page.d.ts +14 -0
- package/dist/client/page.js +18 -0
- package/dist/client/playground.d.ts +5 -0
- package/dist/client/playground.js +32 -0
- package/dist/client/status.d.ts +3 -0
- package/dist/client/status.js +9 -0
- package/dist/client/styles.d.ts +2 -0
- package/dist/client/styles.js +139 -0
- package/dist/client/transitions.d.ts +8 -0
- package/dist/client/transitions.js +45 -0
- package/dist/config/discovery.d.ts +12 -0
- package/dist/config/discovery.js +57 -0
- package/dist/config/index.d.ts +4 -0
- package/dist/config/index.js +4 -0
- package/dist/config/inputs.d.ts +18 -0
- package/dist/config/inputs.js +29 -0
- package/dist/config/snapshots.d.ts +16 -0
- package/dist/config/snapshots.js +25 -0
- package/dist/config/watcher.d.ts +12 -0
- package/dist/config/watcher.js +108 -0
- package/dist/index.d.ts +64 -0
- package/dist/index.js +303 -0
- package/dist/lifecycle/coordinator.d.ts +51 -0
- package/dist/lifecycle/coordinator.js +244 -0
- package/dist/lifecycle/index.d.ts +3 -0
- package/dist/lifecycle/index.js +2 -0
- package/dist/lifecycle/wait.d.ts +2 -0
- package/dist/lifecycle/wait.js +22 -0
- package/dist/process/child.d.ts +55 -0
- package/dist/process/child.js +191 -0
- package/dist/protocol.d.ts +182 -0
- package/dist/protocol.js +77 -0
- package/dist/server/events.d.ts +11 -0
- package/dist/server/events.js +37 -0
- package/dist/server/http.d.ts +19 -0
- package/dist/server/http.js +139 -0
- package/dist/server/listener.d.ts +5 -0
- package/dist/server/listener.js +53 -0
- package/dist/server/observe.d.ts +47 -0
- package/dist/server/observe.js +59 -0
- package/package.json +58 -3
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import type { ConfiguredAddress, RuntimeCommand, RuntimeEvent, RuntimeOutput, RuntimeReply, RuntimeSendResult, WatchInput } from '../protocol.js';
|
|
2
|
+
/** Starts one IPC runtime and joins its entire lifetime before ownership transfer. */
|
|
3
|
+
export declare function startRuntimeChild(options: {
|
|
4
|
+
/** Runtime entry supplied by Histoire, never imported into proxy process. */
|
|
5
|
+
entry: URL;
|
|
6
|
+
/** Existing project directory. */
|
|
7
|
+
root: string;
|
|
8
|
+
/** Opaque identity fixed for this process. */
|
|
9
|
+
generation: string;
|
|
10
|
+
/** External browser origin. */
|
|
11
|
+
publicOrigin: string;
|
|
12
|
+
/** Serializable CLI options. */
|
|
13
|
+
options: Record<string, unknown>;
|
|
14
|
+
/** Private MCP credential, sent only over IPC. */
|
|
15
|
+
token?: string;
|
|
16
|
+
/** Evaluation snapshots must reconcile before readiness publication. */
|
|
17
|
+
onWatch: (inputs: WatchInput[], complete: boolean) => Promise<void>;
|
|
18
|
+
/** Applies the configured public address and returns the origin the runtime must use. */
|
|
19
|
+
onAddress?: (address: ConfiguredAddress) => Promise<string>;
|
|
20
|
+
/** Commit current dependency set before public readiness, if runtime reported one. */
|
|
21
|
+
onReady?: () => Promise<void>;
|
|
22
|
+
/** Reports unexpected exits after readiness. */
|
|
23
|
+
onExit: (error: Error) => void;
|
|
24
|
+
/** Winddown deadline; defaults to ten seconds. */
|
|
25
|
+
shutdownTimeout?: number;
|
|
26
|
+
/** Receives raw stdout/stderr instead of the default piping to this process; each chunk is consumed once. */
|
|
27
|
+
onOutput?: (output: RuntimeOutput) => void;
|
|
28
|
+
/** Receives validated reply/event frames of this generation, independently of readiness. */
|
|
29
|
+
onRuntimeMessage?: (message: RuntimeReply | RuntimeEvent) => void;
|
|
30
|
+
/** Runs once when this runtime stops being usable (winddown start or exit), before cleanup completes. */
|
|
31
|
+
onRetire?: () => void;
|
|
32
|
+
/** Reports observer failures and winddown notices; defaults to `console.error`. */
|
|
33
|
+
onDiagnostic?: (message: string) => void;
|
|
34
|
+
/** Ready runtime asked to be replaced by a new process. */
|
|
35
|
+
onRestartRequest?: (request: {
|
|
36
|
+
source: string;
|
|
37
|
+
fresh: boolean;
|
|
38
|
+
}) => void;
|
|
39
|
+
}): {
|
|
40
|
+
ready: Promise<void>;
|
|
41
|
+
/** Latest backend metadata remains private to parent proxy. */
|
|
42
|
+
readonly backend: {
|
|
43
|
+
type: 'ready';
|
|
44
|
+
generation: string;
|
|
45
|
+
target: string;
|
|
46
|
+
base: string;
|
|
47
|
+
open?: boolean | string;
|
|
48
|
+
} | undefined;
|
|
49
|
+
/** Process identity used only by parent diagnostics and ownership tests. */
|
|
50
|
+
pid: number | undefined;
|
|
51
|
+
/** Hands a command to this process; resolves once IPC accepted the frame. */
|
|
52
|
+
sendRuntimeCommand(command: Omit<RuntimeCommand, 'type' | 'generation'>): Promise<RuntimeSendResult>;
|
|
53
|
+
/** IPC first permits framework cleanup; forced tree termination is last resort. */
|
|
54
|
+
close(): Promise<void>;
|
|
55
|
+
};
|
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
import { fork, spawn } from 'node:child_process';
|
|
2
|
+
import { isChildMessage } from '../protocol.js';
|
|
3
|
+
/** Starts one IPC runtime and joins its entire lifetime before ownership transfer. */
|
|
4
|
+
export function startRuntimeChild(options) {
|
|
5
|
+
const diagnostic = options.onDiagnostic ?? ((message) => console.error(message));
|
|
6
|
+
/** Observer faults must never disturb process ownership. */
|
|
7
|
+
function guarded(action) {
|
|
8
|
+
try {
|
|
9
|
+
action();
|
|
10
|
+
}
|
|
11
|
+
catch (error) {
|
|
12
|
+
try {
|
|
13
|
+
diagnostic(`Histoire runtime observer failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
14
|
+
}
|
|
15
|
+
catch { }
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
let retired = false;
|
|
19
|
+
/** Signals retirement exactly once. */
|
|
20
|
+
function retire() {
|
|
21
|
+
if (retired)
|
|
22
|
+
return;
|
|
23
|
+
retired = true;
|
|
24
|
+
if (options.onRetire)
|
|
25
|
+
guarded(options.onRetire);
|
|
26
|
+
}
|
|
27
|
+
const environment = { ...process.env };
|
|
28
|
+
delete environment.HISTOIRE_MCP_TOKEN;
|
|
29
|
+
const child = fork(options.entry, [], { cwd: options.root, env: environment, detached: process.platform !== 'win32', execArgv: [], stdio: ['ignore', 'pipe', 'pipe', 'ipc'] });
|
|
30
|
+
// Without an observer the streams keep their historical direct piping.
|
|
31
|
+
const outputListeners = [];
|
|
32
|
+
if (options.onOutput) {
|
|
33
|
+
const observe = options.onOutput;
|
|
34
|
+
for (const stream of ['stdout', 'stderr']) {
|
|
35
|
+
const source = child[stream];
|
|
36
|
+
const onData = (chunk) => guarded(() => observe({ stream, generation: options.generation, chunk }));
|
|
37
|
+
const onEnd = () => guarded(() => observe({ stream, generation: options.generation }));
|
|
38
|
+
source.on('data', onData);
|
|
39
|
+
source.once('end', onEnd);
|
|
40
|
+
outputListeners.push(() => {
|
|
41
|
+
source.off('data', onData);
|
|
42
|
+
source.off('end', onEnd);
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
else {
|
|
47
|
+
child.stdout.pipe(process.stdout, { end: false });
|
|
48
|
+
child.stderr.pipe(process.stderr, { end: false });
|
|
49
|
+
}
|
|
50
|
+
let closing;
|
|
51
|
+
let settled = false;
|
|
52
|
+
let backend;
|
|
53
|
+
let resolve;
|
|
54
|
+
let reject;
|
|
55
|
+
const ready = new Promise((yes, no) => {
|
|
56
|
+
resolve = yes;
|
|
57
|
+
reject = no;
|
|
58
|
+
});
|
|
59
|
+
void ready.catch(() => {
|
|
60
|
+
});
|
|
61
|
+
const exited = new Promise(resolve => child.once('exit', () => resolve()));
|
|
62
|
+
let messages = Promise.resolve();
|
|
63
|
+
child.on('error', reject);
|
|
64
|
+
child.on('message', (raw) => {
|
|
65
|
+
if (!isChildMessage(raw) || raw.generation !== options.generation || closing)
|
|
66
|
+
return;
|
|
67
|
+
if (raw.type === 'restart') {
|
|
68
|
+
// Only a served generation may ask; startup failures already report through `failed`.
|
|
69
|
+
if (settled && options.onRestartRequest)
|
|
70
|
+
guarded(() => options.onRestartRequest({ source: raw.source, fresh: raw.fresh === true }));
|
|
71
|
+
return;
|
|
72
|
+
}
|
|
73
|
+
if (raw.type === 'runtime-reply' || raw.type === 'runtime-event') {
|
|
74
|
+
// Runtime traffic is independent of the startup message chain.
|
|
75
|
+
if (options.onRuntimeMessage)
|
|
76
|
+
guarded(() => options.onRuntimeMessage(raw));
|
|
77
|
+
return;
|
|
78
|
+
}
|
|
79
|
+
messages = messages.then(async () => {
|
|
80
|
+
if (closing)
|
|
81
|
+
return;
|
|
82
|
+
if (raw.type === 'watch')
|
|
83
|
+
await options.onWatch(raw.inputs, raw.complete === true);
|
|
84
|
+
if (raw.type === 'address') {
|
|
85
|
+
const publicOrigin = await options.onAddress?.({ port: raw.port, host: raw.host }) ?? options.publicOrigin;
|
|
86
|
+
if (closing || !child.connected)
|
|
87
|
+
return;
|
|
88
|
+
child.send({ type: 'address', generation: options.generation, publicOrigin }, error => error && reject(error));
|
|
89
|
+
}
|
|
90
|
+
if (raw.type === 'failed')
|
|
91
|
+
reject(new Error(raw.error));
|
|
92
|
+
if (raw.type === 'ready') {
|
|
93
|
+
await options.onReady?.();
|
|
94
|
+
if (closing)
|
|
95
|
+
return;
|
|
96
|
+
backend = raw;
|
|
97
|
+
settled = true;
|
|
98
|
+
resolve();
|
|
99
|
+
}
|
|
100
|
+
}).catch(reject);
|
|
101
|
+
});
|
|
102
|
+
child.once('exit', (code, signal) => {
|
|
103
|
+
retire();
|
|
104
|
+
const error = new Error(`Histoire runtime exited (${signal ?? code ?? 'unknown'})`);
|
|
105
|
+
reject(error);
|
|
106
|
+
if (settled && !closing)
|
|
107
|
+
options.onExit(error);
|
|
108
|
+
});
|
|
109
|
+
const message = { type: 'start', generation: options.generation, publicOrigin: options.publicOrigin, options: options.options, token: options.token };
|
|
110
|
+
child.send(message, error => error && reject(error));
|
|
111
|
+
/** Waits bounded time without retaining a timer once process exits. */
|
|
112
|
+
async function wait(milliseconds) {
|
|
113
|
+
if (child.exitCode !== null || child.signalCode !== null)
|
|
114
|
+
return true;
|
|
115
|
+
let timer;
|
|
116
|
+
try {
|
|
117
|
+
return await Promise.race([exited.then(() => true), new Promise((resolve) => {
|
|
118
|
+
timer = setTimeout(() => resolve(false), milliseconds);
|
|
119
|
+
})]);
|
|
120
|
+
}
|
|
121
|
+
finally {
|
|
122
|
+
clearTimeout(timer);
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
/** Kills only this detached ownership group, including ordinary runtime descendants. */
|
|
126
|
+
async function killTree() {
|
|
127
|
+
if (!child.pid)
|
|
128
|
+
return;
|
|
129
|
+
if (process.platform === 'win32') {
|
|
130
|
+
await new Promise((resolve, reject) => {
|
|
131
|
+
const kill = spawn('taskkill', ['/pid', String(child.pid), '/T', '/F'], { stdio: 'ignore' });
|
|
132
|
+
kill.once('error', reject);
|
|
133
|
+
kill.once('exit', code => code === 0 ? resolve() : reject(new Error('Unable to terminate Histoire runtime tree')));
|
|
134
|
+
});
|
|
135
|
+
}
|
|
136
|
+
else {
|
|
137
|
+
try {
|
|
138
|
+
process.kill(-child.pid, 'SIGKILL');
|
|
139
|
+
}
|
|
140
|
+
catch (error) {
|
|
141
|
+
if (error.code !== 'ESRCH')
|
|
142
|
+
throw error;
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
return {
|
|
147
|
+
ready,
|
|
148
|
+
/** Latest backend metadata remains private to parent proxy. */
|
|
149
|
+
get backend() {
|
|
150
|
+
return backend;
|
|
151
|
+
},
|
|
152
|
+
/** Process identity used only by parent diagnostics and ownership tests. */
|
|
153
|
+
pid: child.pid,
|
|
154
|
+
/** Hands a command to this process; resolves once IPC accepted the frame. */
|
|
155
|
+
sendRuntimeCommand(command) {
|
|
156
|
+
if (closing || !settled || !child.connected)
|
|
157
|
+
return Promise.resolve({ ok: false, reason: 'closed' });
|
|
158
|
+
// Envelope fields last: a stray `type` or `generation` on the command can never readdress it.
|
|
159
|
+
const message = { ...command, type: 'runtime-command', generation: options.generation };
|
|
160
|
+
return new Promise((resolve) => {
|
|
161
|
+
child.send(message, error => resolve(error ? { ok: false, reason: 'closed' } : { ok: true, generation: options.generation }));
|
|
162
|
+
});
|
|
163
|
+
},
|
|
164
|
+
/** IPC first permits framework cleanup; forced tree termination is last resort. */
|
|
165
|
+
close() {
|
|
166
|
+
return closing ??= (async () => {
|
|
167
|
+
retire();
|
|
168
|
+
reject(new Error('Histoire runtime closed'));
|
|
169
|
+
if (child.connected) {
|
|
170
|
+
child.send({ type: 'shutdown' }, () => {
|
|
171
|
+
});
|
|
172
|
+
}
|
|
173
|
+
if (!await wait(options.shutdownTimeout ?? 10_000)) {
|
|
174
|
+
diagnostic('Histoire runtime winddown timed out; terminating owned process tree');
|
|
175
|
+
await killTree();
|
|
176
|
+
if (!await wait(3000))
|
|
177
|
+
throw new Error('Histoire runtime termination could not be confirmed');
|
|
178
|
+
}
|
|
179
|
+
// Successful exit must not leave inherited descendants holding ports.
|
|
180
|
+
if (process.platform !== 'win32')
|
|
181
|
+
await killTree();
|
|
182
|
+
child.stdout.unpipe(process.stdout);
|
|
183
|
+
child.stderr.unpipe(process.stderr);
|
|
184
|
+
for (const stop of outputListeners)
|
|
185
|
+
stop();
|
|
186
|
+
if (child.connected)
|
|
187
|
+
child.disconnect();
|
|
188
|
+
})();
|
|
189
|
+
},
|
|
190
|
+
};
|
|
191
|
+
}
|
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
import { Buffer } from 'node:buffer';
|
|
2
|
+
/** Public lifecycle, also used by SDK compatibility adapters. */
|
|
3
|
+
export type RuntimeStatus = 'starting' | 'ready' | 'restarting' | 'failed' | 'closed';
|
|
4
|
+
/** Configuration bytes captured at evaluation, encoded only for private IPC. */
|
|
5
|
+
export interface WatchInput {
|
|
6
|
+
/** Absolute local configuration/dependency path. */
|
|
7
|
+
file: string;
|
|
8
|
+
/** Source shown in terminal diagnostics. */
|
|
9
|
+
source: string;
|
|
10
|
+
/** Base64 bytes; null records a missing file. */
|
|
11
|
+
bytes: string | null;
|
|
12
|
+
}
|
|
13
|
+
/** Browser-safe snapshot; excludes backend address, process IDs and secrets. */
|
|
14
|
+
export interface PublicState {
|
|
15
|
+
/** Current availability. */
|
|
16
|
+
status: RuntimeStatus;
|
|
17
|
+
/** Opaque process generation. */
|
|
18
|
+
generation: string;
|
|
19
|
+
/** Current application mount. */
|
|
20
|
+
base: string;
|
|
21
|
+
/** Short failure detail, when startup failed. */
|
|
22
|
+
error?: string;
|
|
23
|
+
}
|
|
24
|
+
/** Why a runtime generation is being replaced. */
|
|
25
|
+
export type RestartCauseKind =
|
|
26
|
+
/** Explicit request by the embedding application (keyboard, API). */
|
|
27
|
+
'manual'
|
|
28
|
+
/** A watched configuration or dependency file changed; `source` labels it. */
|
|
29
|
+
| 'config'
|
|
30
|
+
/** The served page asked for a restart. */
|
|
31
|
+
| 'browser'
|
|
32
|
+
/** The runtime process exited unexpectedly; `source` carries the exit detail. */
|
|
33
|
+
| 'exit'
|
|
34
|
+
/** The runtime asked to be replaced by a new process (e.g. after a plugin change); `source` labels why. */
|
|
35
|
+
| 'runtime';
|
|
36
|
+
/** Observed reason of one restart transition, delivered once per transition. */
|
|
37
|
+
export interface RestartCause {
|
|
38
|
+
kind: RestartCauseKind;
|
|
39
|
+
/** Short origin label (watched file source or exit detail). */
|
|
40
|
+
source?: string;
|
|
41
|
+
/** The next generation skips cached catalog restoration and forces dependency optimization. */
|
|
42
|
+
fresh: boolean;
|
|
43
|
+
}
|
|
44
|
+
/** Input of a restart request; omitted fields mean an ordinary manual restart. */
|
|
45
|
+
export interface RestartRequest {
|
|
46
|
+
cause?: RestartCauseKind;
|
|
47
|
+
source?: string;
|
|
48
|
+
/** Request a one-shot fresh next generation; never lost when coalesced with another cause. */
|
|
49
|
+
fresh?: boolean;
|
|
50
|
+
}
|
|
51
|
+
/** Frozen bounds for generic runtime frames; payload semantics belong to the framework adapter. */
|
|
52
|
+
export declare const RUNTIME_FRAME_MAX_BYTES: number;
|
|
53
|
+
/** Longest accepted runtime restart label. */
|
|
54
|
+
export declare const RESTART_SOURCE_MAX_LENGTH = 200;
|
|
55
|
+
/** Longest accepted correlation, operation and event identifier. */
|
|
56
|
+
export declare const RUNTIME_ID_MAX_LENGTH = 100;
|
|
57
|
+
/** Framework-neutral request carried to the current generation only. */
|
|
58
|
+
export interface RuntimeCommand {
|
|
59
|
+
type: 'runtime-command';
|
|
60
|
+
/** Generation the sender believes is current; receivers ignore mismatches. */
|
|
61
|
+
generation: string;
|
|
62
|
+
/** Correlation identifier echoed by the matching reply. */
|
|
63
|
+
id: string;
|
|
64
|
+
/** Recognized operation name, validated by the framework adapter. */
|
|
65
|
+
operation: string;
|
|
66
|
+
/** Detached JSON arguments. */
|
|
67
|
+
args?: unknown;
|
|
68
|
+
}
|
|
69
|
+
/** Failure carried by a negative runtime reply. */
|
|
70
|
+
export interface RuntimeFailure {
|
|
71
|
+
/** Stable machine-readable code. */
|
|
72
|
+
code: string;
|
|
73
|
+
/** Short human-readable detail. */
|
|
74
|
+
message: string;
|
|
75
|
+
}
|
|
76
|
+
/** Correlated answer to one runtime command. */
|
|
77
|
+
export type RuntimeReply = {
|
|
78
|
+
type: 'runtime-reply';
|
|
79
|
+
generation: string;
|
|
80
|
+
id: string;
|
|
81
|
+
} & ({
|
|
82
|
+
ok: true;
|
|
83
|
+
result?: unknown;
|
|
84
|
+
} | {
|
|
85
|
+
ok: false;
|
|
86
|
+
error: RuntimeFailure;
|
|
87
|
+
});
|
|
88
|
+
/** Uncorrelated generation-scoped observation. */
|
|
89
|
+
export interface RuntimeEvent {
|
|
90
|
+
type: 'runtime-event';
|
|
91
|
+
generation: string;
|
|
92
|
+
/** Recognized event name. */
|
|
93
|
+
event: string;
|
|
94
|
+
/** Detached JSON payload. */
|
|
95
|
+
data?: unknown;
|
|
96
|
+
}
|
|
97
|
+
/** Why a command could not be handed to a runtime process. */
|
|
98
|
+
export type RuntimeSendFailure = 'starting' | 'restarting' | 'failed' | 'closed';
|
|
99
|
+
/** Outcome of handing a command to the current ready runtime. */
|
|
100
|
+
export type RuntimeSendResult = {
|
|
101
|
+
ok: true;
|
|
102
|
+
generation: string;
|
|
103
|
+
} | {
|
|
104
|
+
ok: false;
|
|
105
|
+
reason: RuntimeSendFailure;
|
|
106
|
+
};
|
|
107
|
+
/** Raw runtime stream observation; an absent chunk marks the end of that stream. */
|
|
108
|
+
export interface RuntimeOutput {
|
|
109
|
+
stream: 'stdout' | 'stderr';
|
|
110
|
+
generation: string;
|
|
111
|
+
chunk?: Buffer;
|
|
112
|
+
}
|
|
113
|
+
/** Parent starts one runtime exactly once and requests graceful winddown. */
|
|
114
|
+
export type ParentMessage = {
|
|
115
|
+
type: 'start';
|
|
116
|
+
generation: string;
|
|
117
|
+
publicOrigin: string;
|
|
118
|
+
options: Record<string, unknown>;
|
|
119
|
+
token?: string;
|
|
120
|
+
} | {
|
|
121
|
+
type: 'address';
|
|
122
|
+
generation: string;
|
|
123
|
+
publicOrigin: string;
|
|
124
|
+
} | {
|
|
125
|
+
type: 'shutdown';
|
|
126
|
+
} | RuntimeCommand;
|
|
127
|
+
/** Public address asked by project configuration; command-line values win. */
|
|
128
|
+
export interface ConfiguredAddress {
|
|
129
|
+
/** Unvalidated project port, checked only if the CLI did not override it. */
|
|
130
|
+
port?: unknown;
|
|
131
|
+
/** Unvalidated project host, checked only if the CLI did not override it. */
|
|
132
|
+
host?: unknown;
|
|
133
|
+
}
|
|
134
|
+
/** Runtime reports observations; only parent decides public availability/restarts. */
|
|
135
|
+
export type ChildMessage = {
|
|
136
|
+
type: 'watch';
|
|
137
|
+
generation: string;
|
|
138
|
+
inputs: WatchInput[];
|
|
139
|
+
complete?: boolean;
|
|
140
|
+
}
|
|
141
|
+
/** Configured public address, sent before the runtime pins its origin; parent answers with the final one. */
|
|
142
|
+
| ({
|
|
143
|
+
type: 'address';
|
|
144
|
+
generation: string;
|
|
145
|
+
} & ConfiguredAddress) | {
|
|
146
|
+
type: 'ready';
|
|
147
|
+
generation: string;
|
|
148
|
+
target: string;
|
|
149
|
+
base: string;
|
|
150
|
+
open?: boolean | string;
|
|
151
|
+
} | {
|
|
152
|
+
type: 'failed';
|
|
153
|
+
generation: string;
|
|
154
|
+
error: string;
|
|
155
|
+
}
|
|
156
|
+
/** Ready runtime asks the parent for a full process replacement; only the parent restarts. */
|
|
157
|
+
| {
|
|
158
|
+
type: 'restart';
|
|
159
|
+
generation: string;
|
|
160
|
+
source: string;
|
|
161
|
+
fresh?: boolean;
|
|
162
|
+
} | RuntimeReply | RuntimeEvent;
|
|
163
|
+
/** Non-empty identifier within the frozen length bound. */
|
|
164
|
+
export declare function isIdentifier(value: unknown): value is string;
|
|
165
|
+
/** Serialized frames above the frozen bound (or unserializable ones) are rejected. */
|
|
166
|
+
export declare function isBoundedFrame(value: unknown): boolean;
|
|
167
|
+
/**
|
|
168
|
+
* Whether the child will accept a command: identifiers within bounds, and the frame still within
|
|
169
|
+
* its bound once wrapped in the `runtime-command` envelope it travels in (generation of the longest
|
|
170
|
+
* accepted length). Senders refuse anything else up front instead of waiting for a dropped reply.
|
|
171
|
+
* @param command Correlation ID, operation and arguments of the command.
|
|
172
|
+
*/
|
|
173
|
+
export declare function isBoundedCommand(command: Omit<RuntimeCommand, 'type' | 'generation'>): boolean;
|
|
174
|
+
/** Accept a finite, bounded command addressed to the receiving generation. */
|
|
175
|
+
export declare function isRuntimeCommand(value: unknown): value is RuntimeCommand;
|
|
176
|
+
/**
|
|
177
|
+
* Whether a child-sent workbench base is a same-origin absolute path. Backslashes are rejected
|
|
178
|
+
* because URL parsers treat them as slashes (`/\\evil.com` resolves to another host).
|
|
179
|
+
*/
|
|
180
|
+
export declare function isSafeBase(base: unknown): base is string;
|
|
181
|
+
/** Accept finite, generation-scoped frames before dispatching across IPC. */
|
|
182
|
+
export declare function isChildMessage(value: unknown): value is ChildMessage;
|
package/dist/protocol.js
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { Buffer } from 'node:buffer';
|
|
2
|
+
/** Frozen bounds for generic runtime frames; payload semantics belong to the framework adapter. */
|
|
3
|
+
export const RUNTIME_FRAME_MAX_BYTES = 256 * 1024;
|
|
4
|
+
/** Longest accepted runtime restart label. */
|
|
5
|
+
export const RESTART_SOURCE_MAX_LENGTH = 200;
|
|
6
|
+
/** Longest accepted correlation, operation and event identifier. */
|
|
7
|
+
export const RUNTIME_ID_MAX_LENGTH = 100;
|
|
8
|
+
/** Non-empty identifier within the frozen length bound. */
|
|
9
|
+
export function isIdentifier(value) {
|
|
10
|
+
return typeof value === 'string' && value.length > 0 && value.length <= RUNTIME_ID_MAX_LENGTH;
|
|
11
|
+
}
|
|
12
|
+
/** Serialized frames above the frozen bound (or unserializable ones) are rejected. */
|
|
13
|
+
export function isBoundedFrame(value) {
|
|
14
|
+
try {
|
|
15
|
+
return Buffer.byteLength(JSON.stringify(value)) <= RUNTIME_FRAME_MAX_BYTES;
|
|
16
|
+
}
|
|
17
|
+
catch {
|
|
18
|
+
return false;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Whether the child will accept a command: identifiers within bounds, and the frame still within
|
|
23
|
+
* its bound once wrapped in the `runtime-command` envelope it travels in (generation of the longest
|
|
24
|
+
* accepted length). Senders refuse anything else up front instead of waiting for a dropped reply.
|
|
25
|
+
* @param command Correlation ID, operation and arguments of the command.
|
|
26
|
+
*/
|
|
27
|
+
export function isBoundedCommand(command) {
|
|
28
|
+
return isIdentifier(command.id) && isIdentifier(command.operation) && isBoundedFrame({ ...command, type: 'runtime-command', generation: 'x'.repeat(RUNTIME_ID_MAX_LENGTH) });
|
|
29
|
+
}
|
|
30
|
+
/** Accept a finite, bounded command addressed to the receiving generation. */
|
|
31
|
+
export function isRuntimeCommand(value) {
|
|
32
|
+
if (!value || typeof value !== 'object')
|
|
33
|
+
return false;
|
|
34
|
+
const message = value;
|
|
35
|
+
return message.type === 'runtime-command' && isIdentifier(message.generation) && isIdentifier(message.id) && isIdentifier(message.operation) && isBoundedFrame(value);
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Whether a child-sent workbench base is a same-origin absolute path. Backslashes are rejected
|
|
39
|
+
* because URL parsers treat them as slashes (`/\\evil.com` resolves to another host).
|
|
40
|
+
*/
|
|
41
|
+
export function isSafeBase(base) {
|
|
42
|
+
if (typeof base !== 'string' || !base.startsWith('/') || base.startsWith('//') || base.includes('\\'))
|
|
43
|
+
return false;
|
|
44
|
+
try {
|
|
45
|
+
return new URL(base, 'http://x').origin === 'http://x';
|
|
46
|
+
}
|
|
47
|
+
catch {
|
|
48
|
+
return false;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
/** Accept finite, generation-scoped frames before dispatching across IPC. */
|
|
52
|
+
export function isChildMessage(value) {
|
|
53
|
+
if (!value || typeof value !== 'object')
|
|
54
|
+
return false;
|
|
55
|
+
const message = value;
|
|
56
|
+
if (typeof message.generation !== 'string' || message.generation.length > 100)
|
|
57
|
+
return false;
|
|
58
|
+
if (message.type === 'runtime-reply') {
|
|
59
|
+
if (!isIdentifier(message.id) || typeof message.ok !== 'boolean')
|
|
60
|
+
return false;
|
|
61
|
+
const error = message.error;
|
|
62
|
+
if (!message.ok && !(error && isIdentifier(error.code) && typeof error.message === 'string' && error.message.length <= 4096))
|
|
63
|
+
return false;
|
|
64
|
+
return isBoundedFrame(value);
|
|
65
|
+
}
|
|
66
|
+
if (message.type === 'runtime-event')
|
|
67
|
+
return isIdentifier(message.event) && isBoundedFrame(value);
|
|
68
|
+
if (message.type === 'address')
|
|
69
|
+
return isBoundedFrame(value);
|
|
70
|
+
if (message.type === 'failed')
|
|
71
|
+
return typeof message.error === 'string' && message.error.length <= 4096;
|
|
72
|
+
if (message.type === 'restart')
|
|
73
|
+
return typeof message.source === 'string' && message.source.length > 0 && message.source.length <= RESTART_SOURCE_MAX_LENGTH && (message.fresh === undefined || typeof message.fresh === 'boolean');
|
|
74
|
+
if (message.type === 'ready')
|
|
75
|
+
return typeof message.target === 'string' && /^http:\/\/127\.0\.0\.1:\d+$/.test(message.target) && isSafeBase(message.base);
|
|
76
|
+
return message.type === 'watch' && Array.isArray(message.inputs) && message.inputs.length <= 10000 && message.inputs.every(input => input && typeof input.file === 'string' && typeof input.source === 'string' && (input.bytes === null || typeof input.bytes === 'string'));
|
|
77
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { IncomingMessage, ServerResponse } from 'node:http';
|
|
2
|
+
import type { PublicState } from '../protocol.js';
|
|
3
|
+
/** SSE channel independent of Vite and runtime process lifetime. */
|
|
4
|
+
export declare function createStatusChannel(read: () => PublicState): {
|
|
5
|
+
/** Immediately publish latest state on reconnect. */
|
|
6
|
+
connect(_request: IncomingMessage, response: ServerResponse): void;
|
|
7
|
+
/** State snapshots supersede previous observations; no event replay buffer needed. */
|
|
8
|
+
publish(): void;
|
|
9
|
+
/** End streams before closing listener. */
|
|
10
|
+
close(): void;
|
|
11
|
+
};
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/** SSE channel independent of Vite and runtime process lifetime. */
|
|
2
|
+
export function createStatusChannel(read) {
|
|
3
|
+
const clients = new Set();
|
|
4
|
+
/** Drop slow/disconnected consumers instead of buffering unbounded state. */
|
|
5
|
+
function write(response, data) {
|
|
6
|
+
if (!response.write(data)) {
|
|
7
|
+
clients.delete(response);
|
|
8
|
+
response.destroy();
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
const heartbeat = setInterval(() => {
|
|
12
|
+
for (const response of clients)
|
|
13
|
+
write(response, ': heartbeat\n\n');
|
|
14
|
+
}, 15_000);
|
|
15
|
+
heartbeat.unref();
|
|
16
|
+
return {
|
|
17
|
+
/** Immediately publish latest state on reconnect. */
|
|
18
|
+
connect(_request, response) {
|
|
19
|
+
response.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-store', 'connection': 'keep-alive', 'x-accel-buffering': 'no' });
|
|
20
|
+
clients.add(response);
|
|
21
|
+
response.once('close', () => clients.delete(response));
|
|
22
|
+
write(response, `data: ${JSON.stringify(read())}\n\n`);
|
|
23
|
+
},
|
|
24
|
+
/** State snapshots supersede previous observations; no event replay buffer needed. */
|
|
25
|
+
publish() {
|
|
26
|
+
for (const response of clients)
|
|
27
|
+
write(response, `data: ${JSON.stringify(read())}\n\n`);
|
|
28
|
+
},
|
|
29
|
+
/** End streams before closing listener. */
|
|
30
|
+
close() {
|
|
31
|
+
clearInterval(heartbeat);
|
|
32
|
+
for (const response of clients)
|
|
33
|
+
response.end();
|
|
34
|
+
clients.clear();
|
|
35
|
+
},
|
|
36
|
+
};
|
|
37
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import type { PublicState } from '../protocol.js';
|
|
2
|
+
import type { ProxyRequestObserver } from './observe.js';
|
|
3
|
+
/** Stable HTTP listener delegates only after coherent generation readiness. */
|
|
4
|
+
export declare function createProxyHttp(read: () => PublicState, restart: () => Promise<void>, observer?: ProxyRequestObserver, readPublicHostname?: () => string | undefined): {
|
|
5
|
+
server: import("http").Server<typeof import("http").IncomingMessage, typeof import("http").ServerResponse>;
|
|
6
|
+
events: {
|
|
7
|
+
connect(_request: import("http").IncomingMessage, response: import("http").ServerResponse): void;
|
|
8
|
+
publish(): void;
|
|
9
|
+
close(): void;
|
|
10
|
+
};
|
|
11
|
+
/** Forwarding library is deliberately absent from initial listener import graph. */
|
|
12
|
+
prepare(): Promise<void>;
|
|
13
|
+
/** Withdraw target synchronously and retire old runtime WebSockets. */
|
|
14
|
+
setTarget(next?: string): void;
|
|
15
|
+
/** Release the bound address while keeping the server reusable for another bind. */
|
|
16
|
+
unlisten(): Promise<void>;
|
|
17
|
+
/** Join listener close after terminating owned streams and idle connections. */
|
|
18
|
+
close(): Promise<void>;
|
|
19
|
+
};
|