@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.
Files changed (54) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +16 -2
  3. package/dist/appearance.d.ts +11 -0
  4. package/dist/appearance.js +11 -0
  5. package/dist/browser/chunks/transitions-3JvGwb-W.js +71 -0
  6. package/dist/browser/demo.js +50 -0
  7. package/dist/browser/lifecycle.js +55 -0
  8. package/dist/client/demo.d.ts +1 -0
  9. package/dist/client/demo.js +46 -0
  10. package/dist/client/lifecycle.d.ts +1 -0
  11. package/dist/client/lifecycle.js +73 -0
  12. package/dist/client/mark.d.ts +2 -0
  13. package/dist/client/mark.js +8 -0
  14. package/dist/client/page.d.ts +14 -0
  15. package/dist/client/page.js +18 -0
  16. package/dist/client/playground.d.ts +5 -0
  17. package/dist/client/playground.js +32 -0
  18. package/dist/client/status.d.ts +3 -0
  19. package/dist/client/status.js +9 -0
  20. package/dist/client/styles.d.ts +2 -0
  21. package/dist/client/styles.js +139 -0
  22. package/dist/client/transitions.d.ts +8 -0
  23. package/dist/client/transitions.js +45 -0
  24. package/dist/config/discovery.d.ts +12 -0
  25. package/dist/config/discovery.js +57 -0
  26. package/dist/config/index.d.ts +4 -0
  27. package/dist/config/index.js +4 -0
  28. package/dist/config/inputs.d.ts +18 -0
  29. package/dist/config/inputs.js +29 -0
  30. package/dist/config/snapshots.d.ts +16 -0
  31. package/dist/config/snapshots.js +25 -0
  32. package/dist/config/watcher.d.ts +12 -0
  33. package/dist/config/watcher.js +108 -0
  34. package/dist/index.d.ts +64 -0
  35. package/dist/index.js +303 -0
  36. package/dist/lifecycle/coordinator.d.ts +51 -0
  37. package/dist/lifecycle/coordinator.js +244 -0
  38. package/dist/lifecycle/index.d.ts +3 -0
  39. package/dist/lifecycle/index.js +2 -0
  40. package/dist/lifecycle/wait.d.ts +2 -0
  41. package/dist/lifecycle/wait.js +22 -0
  42. package/dist/process/child.d.ts +55 -0
  43. package/dist/process/child.js +191 -0
  44. package/dist/protocol.d.ts +182 -0
  45. package/dist/protocol.js +77 -0
  46. package/dist/server/events.d.ts +11 -0
  47. package/dist/server/events.js +37 -0
  48. package/dist/server/http.d.ts +19 -0
  49. package/dist/server/http.js +139 -0
  50. package/dist/server/listener.d.ts +5 -0
  51. package/dist/server/listener.js +53 -0
  52. package/dist/server/observe.d.ts +47 -0
  53. package/dist/server/observe.js +59 -0
  54. package/package.json +58 -3
package/dist/index.js ADDED
@@ -0,0 +1,303 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { relative, resolve } from 'node:path';
3
+ import { inspect } from 'node:util';
4
+ import { createRestartCoordinator } from './lifecycle/index.js';
5
+ import { startRuntimeChild } from './process/child.js';
6
+ import { createProxyHttp } from './server/http.js';
7
+ import { assertValidPort, listen } from './server/listener.js';
8
+ /** Public port used when neither the command line nor project config names one. */
9
+ const DEFAULT_PORT = 6006;
10
+ /** Bind first; child startup and project imports happen after handle is available. */
11
+ export async function startDevProxy(options) {
12
+ const root = resolve(options.root ?? process.cwd());
13
+ let state = { status: 'starting', generation: randomUUID(), base: '/' };
14
+ let url;
15
+ let bound = { port: options.port ?? DEFAULT_PORT, host: options.host };
16
+ const http = createProxyHttp(() => state, () => restart({ cause: 'browser' }), options.onRequest, () => url ? new URL(url).hostname : undefined);
17
+ try {
18
+ url = `${await listen(http.server, bound.port, bound.host)}/`;
19
+ }
20
+ catch (error) {
21
+ await http.close();
22
+ throw error;
23
+ }
24
+ /** Moves the public listener to the address project config asks for. */
25
+ async function relocate(configured) {
26
+ const port = options.port ?? (configured.port === undefined ? DEFAULT_PORT : configured.port);
27
+ const host = options.host ?? configured.host;
28
+ assertValidPort(port);
29
+ if (host !== undefined && typeof host !== 'boolean' && (typeof host !== 'string' || !host.length || host.length > 255)) {
30
+ throw new Error('Host must be a boolean or a non-empty hostname of at most 255 characters');
31
+ }
32
+ const next = { port, host };
33
+ if (next.port !== bound.port || next.host !== bound.host) {
34
+ await http.unlisten();
35
+ try {
36
+ url = `${await listen(http.server, next.port, next.host)}/`;
37
+ bound = next;
38
+ }
39
+ catch (error) {
40
+ url = `${await listen(http.server, bound.port, bound.host)}/`;
41
+ throw error;
42
+ }
43
+ options.onListening?.(url);
44
+ }
45
+ if (options.open)
46
+ void open().catch(diagnostic);
47
+ return new URL(url).origin;
48
+ }
49
+ /** Proxy notices reach the observer when present, otherwise the console. */
50
+ function diagnostic(error) {
51
+ const text = typeof error === 'string' ? error : inspect(error);
52
+ if (!options.onDiagnostic) {
53
+ console.error(error);
54
+ return;
55
+ }
56
+ try {
57
+ options.onDiagnostic(text);
58
+ }
59
+ catch { }
60
+ }
61
+ let active;
62
+ let watcher;
63
+ let closed = false;
64
+ let opened = false;
65
+ let closing;
66
+ /** Causes the next announced restart transition will carry, merged. */
67
+ let requested;
68
+ /**
69
+ * An announced transition is still tearing down the previous generation. Requests landing now are
70
+ * coalesced into it (the coordinator acquires after teardown), so they must not name a later transition.
71
+ */
72
+ let releasing = false;
73
+ /** A fresh generation is owed; consumed by the next spawn and re-armed if that one is abandoned before ready. */
74
+ let freshPending = false;
75
+ /** Records a restart request before the coordinator can publish `restarting`. */
76
+ function record(request) {
77
+ const fresh = request.fresh === true;
78
+ if (fresh)
79
+ freshPending = true;
80
+ // Served by the transition already announced: its acquisition consumes `freshPending`.
81
+ if (releasing)
82
+ return;
83
+ // First cause names the transition; a coalesced fresh request upgrades it without replacing the label.
84
+ requested = requested ? { ...requested, fresh: requested.fresh || fresh } : { kind: request.cause ?? 'manual', ...(request.source ? { source: request.source } : {}), fresh };
85
+ }
86
+ /** Delivers the merged cause exactly once for the transition that just began. */
87
+ function announceRestart() {
88
+ const cause = requested;
89
+ requested = undefined;
90
+ releasing = true;
91
+ if (!cause || !options.onRestart)
92
+ return;
93
+ try {
94
+ options.onRestart(cause);
95
+ }
96
+ catch { }
97
+ }
98
+ /** Central publication always withdraws unavailable targets first. */
99
+ function publish(status, error) {
100
+ if (status !== 'ready')
101
+ http.setTarget();
102
+ let detail = error === undefined ? undefined : String(error instanceof Error ? error.message : error).split('\n')[0].slice(0, 512);
103
+ if (detail && options.token)
104
+ detail = detail.replaceAll(options.token, '[credential]');
105
+ state = { ...state, status, ...(detail ? { error: detail } : {}) };
106
+ if (!detail)
107
+ delete state.error;
108
+ http.events.publish();
109
+ options.onStatus?.({ ...state });
110
+ }
111
+ /** Browser opener loads only after initial public listener exists. */
112
+ async function open(path = '/') {
113
+ if (opened || closed)
114
+ return;
115
+ opened = true;
116
+ const { default: openBrowser } = await import('open');
117
+ if (!closed)
118
+ await openBrowser(new URL(path, url).href);
119
+ }
120
+ const controller = createRestartCoordinator({
121
+ interruptStartup: true,
122
+ acquire: async (_signal, isActive) => {
123
+ state = { ...state, generation: randomUUID() };
124
+ http.events.publish();
125
+ let completeInputs;
126
+ const generation = state.generation;
127
+ // Teardown is over: requests from here on schedule another transition, which owns their cause.
128
+ releasing = false;
129
+ const fresh = freshPending;
130
+ freshPending = false;
131
+ options.onRuntimeStart?.({ generation, fresh });
132
+ const child = startRuntimeChild({
133
+ entry: options.runtime,
134
+ root,
135
+ generation: state.generation,
136
+ publicOrigin: new URL(url).origin,
137
+ options: fresh ? { ...options.runtimeOptions, fresh: true } : options.runtimeOptions ?? {},
138
+ token: options.token,
139
+ shutdownTimeout: options.shutdownTimeout,
140
+ onOutput: options.onOutput,
141
+ onRuntimeMessage: options.onRuntimeMessage,
142
+ onRetire: options.onRuntimeRetired && (() => options.onRuntimeRetired(generation)),
143
+ onAddress: async (address) => closed || !isActive() ? new URL(url).origin : relocate(address),
144
+ onDiagnostic: options.onDiagnostic && (message => diagnostic(message)),
145
+ onWatch: async (inputs, complete) => {
146
+ if (complete)
147
+ completeInputs = inputs;
148
+ await watcher?.update(inputs, isActive);
149
+ },
150
+ onReady: async () => {
151
+ if (completeInputs)
152
+ await watcher?.replace(completeInputs, isActive);
153
+ },
154
+ onRestartRequest: ({ source, fresh }) => {
155
+ // A retired generation can't schedule the successor of its replacement.
156
+ if (closed || !isActive())
157
+ return;
158
+ record({ cause: 'runtime', source, fresh });
159
+ void controller.restart().catch(error => publish('failed', error));
160
+ },
161
+ onExit: (error) => {
162
+ if (closed || !isActive())
163
+ return;
164
+ // Coordinator still owns crashed child as ready; replace it instead of serving dead handle.
165
+ diagnostic(error.message);
166
+ publish('failed', error);
167
+ record({ cause: 'exit', source: error.message });
168
+ void controller.restart().catch(failure => publish('failed', failure));
169
+ },
170
+ });
171
+ // A fresh generation superseded before readiness never delivered its fresh work: owe it again.
172
+ const close = child.close;
173
+ child.close = () => {
174
+ if (fresh && !child.backend)
175
+ freshPending = true;
176
+ return close();
177
+ };
178
+ return child;
179
+ },
180
+ isUnsafeCleanup: () => false,
181
+ quarantineCleanupFailures: false,
182
+ withDeadline: promise => promise,
183
+ });
184
+ const off = controller.subscribe((status, runtime) => {
185
+ if (closed)
186
+ return;
187
+ active = status === 'ready' ? runtime : undefined;
188
+ if (status === 'restarting') {
189
+ announceRestart();
190
+ }
191
+ else if (status === 'ready' || status === 'failed') {
192
+ releasing = false;
193
+ // Only a terminal failure strands recorded causes: no further transition will announce them.
194
+ // After `ready`, causes recorded during acquisition belong to the transition that follows.
195
+ if (status === 'failed')
196
+ requested = undefined;
197
+ }
198
+ if (status === 'ready' && runtime?.backend) {
199
+ state = { ...state, base: runtime.backend.base };
200
+ http.setTarget(runtime.backend.target);
201
+ if (runtime.backend.open)
202
+ void open(typeof runtime.backend.open === 'string' ? runtime.backend.open : runtime.backend.base).catch(diagnostic);
203
+ }
204
+ if (options.open && (status === 'ready' || status === 'failed'))
205
+ void open().catch(diagnostic);
206
+ publish(status);
207
+ });
208
+ const prepared = (async () => {
209
+ options.onListening?.(url);
210
+ const config = await import('./config/index.js');
211
+ if (closed)
212
+ return;
213
+ watcher = await config.watchConfiguration([], (source, file) => {
214
+ if (closed)
215
+ return;
216
+ // Label with the origin kind and the project-relative file, so the notice names what changed.
217
+ record({ cause: 'config', source: `${source}: ${relative(root, file).replaceAll('\\', '/')}` });
218
+ void controller.restart().catch(error => publish('failed', error));
219
+ });
220
+ if (closed) {
221
+ await watcher.close();
222
+ return;
223
+ }
224
+ try {
225
+ const revision = await config.captureProjectConfigurationRevision(root, options.config);
226
+ await watcher.update(await config.configurationWatchInputs({ root, config: options.config, revision }));
227
+ }
228
+ catch (error) {
229
+ // Runtime still reports its own inputs; an unreadable candidate must not disable watching.
230
+ diagnostic(error);
231
+ }
232
+ if (closed)
233
+ return;
234
+ await http.prepare();
235
+ })();
236
+ const boot = prepared.then(async () => {
237
+ if (!closed)
238
+ await controller.start();
239
+ });
240
+ const ready = boot.catch((error) => {
241
+ if (!closed)
242
+ publish('failed', error);
243
+ throw error;
244
+ });
245
+ void ready.catch(() => {
246
+ });
247
+ /** Manual replacement uses same serialized winddown as configuration changes. */
248
+ async function restart(request = {}) {
249
+ if (closed)
250
+ throw new Error('Histoire proxy closed');
251
+ await prepared;
252
+ record(request);
253
+ await controller.restart().catch((error) => {
254
+ publish('failed', error);
255
+ throw error;
256
+ });
257
+ }
258
+ return {
259
+ /** Actual public address, including OS-selected or fallback port; project config can move it. */
260
+ get url() {
261
+ return url;
262
+ },
263
+ /** Initial runtime acquisition; watcher remains live after rejection. */
264
+ ready,
265
+ /** Latest public availability, independent of any runtime process. */
266
+ get status() {
267
+ return state.status;
268
+ },
269
+ restart,
270
+ /** Opens an absolute URL in the default browser on demand (terminal action); unrelated to the one-shot `open` option. */
271
+ async openBrowser(target) {
272
+ if (closed)
273
+ return;
274
+ const { default: openBrowser } = await import('open');
275
+ await openBrowser(target);
276
+ },
277
+ /** Delivers a command to the current ready runtime; never queues for an unknown successor. */
278
+ async sendRuntimeCommand(command) {
279
+ if (closed)
280
+ return { ok: false, reason: 'closed' };
281
+ if (state.status !== 'ready' || !active)
282
+ return { ok: false, reason: state.status === 'ready' || state.status === 'closed' ? 'closed' : state.status };
283
+ return active.sendRuntimeCommand(command);
284
+ },
285
+ /** Stop observation/admission synchronously before joining child shutdown. */
286
+ close() {
287
+ return closing ??= (async () => {
288
+ closed = true;
289
+ publish('closed');
290
+ const stop = controller.close();
291
+ await Promise.allSettled([boot]);
292
+ try {
293
+ await stop;
294
+ }
295
+ finally {
296
+ off();
297
+ await watcher?.close();
298
+ await http.close();
299
+ }
300
+ })();
301
+ },
302
+ };
303
+ }
@@ -0,0 +1,51 @@
1
+ import type { RuntimeStatus } from '../protocol.js';
2
+ /** Minimal resource required by shared restart ownership. */
3
+ export interface LifecycleGeneration {
4
+ /** Initial work whose completion permits publication. */
5
+ ready: Promise<void>;
6
+ /** Releases all acquired resources. */
7
+ close: () => Promise<void>;
8
+ /** Optional live collection metadata retained by Histoire adapters. */
9
+ collectionOutcomes?: unknown;
10
+ }
11
+ /** A resource fenced by coordinator generation identity. */
12
+ export type LifecycleHandle<G> = G & {
13
+ epoch: string;
14
+ isActive: () => boolean;
15
+ };
16
+ /** Framework-neutral acquisition, observation and cleanup policy. */
17
+ export interface CoordinatorOptions<G extends LifecycleGeneration> {
18
+ /** CLI process owner can cancel acquisition; SDK compatibility keeps historical joining. */
19
+ interruptStartup?: boolean;
20
+ /** Acquires one runtime, responding to cancellation. */
21
+ acquire: (signal: AbortSignal, isActive: () => boolean) => Promise<G>;
22
+ /** Optional compatibility adapter; CLI proxy supplies its persistent watcher separately. */
23
+ watch?: (runtime: G, restart: (source: string) => void) => Promise<() => Promise<void>>;
24
+ /** Attaches generation-owned services before readiness. */
25
+ onGeneration?: (handle: LifecycleHandle<G>) => void | Promise<void>;
26
+ /** Drains dependents after ownership invalidation. */
27
+ onBeforeRelease?: (handle: LifecycleHandle<G>) => void | Promise<void>;
28
+ /** Reports asynchronous watcher failures. */
29
+ onError?: (error: unknown) => void;
30
+ /** Quarantines controller after failed resource release; process-isolated owners opt out. Default true. */
31
+ quarantineCleanupFailures?: boolean;
32
+ /** Marks failures after which ownership cannot safely transfer. */
33
+ isUnsafeCleanup: (error: unknown) => boolean;
34
+ /** Bounds cleanup using owning framework's error contract. */
35
+ withDeadline: <T>(promise: Promise<T>) => Promise<T>;
36
+ }
37
+ /** Serializes startup/restart and suppresses feedback from superseded generations. */
38
+ export declare function createRestartCoordinator<G extends LifecycleGeneration>(options: CoordinatorOptions<G>): {
39
+ /** Current lifecycle state, usable before a catalog exists. */
40
+ readonly status: RuntimeStatus;
41
+ /** Current private handle; undefined during teardown or after failure. */
42
+ readonly current: LifecycleHandle<G> | undefined;
43
+ start: () => Promise<LifecycleHandle<G>>;
44
+ restart: (_source?: string) => Promise<LifecycleHandle<G>>;
45
+ /** Joins the next completed ready generation. */
46
+ waitForReady: () => Promise<LifecycleHandle<G>>;
47
+ /** Registers lifecycle observations; caller owns returned disposer. */
48
+ subscribe(listener: (status: RuntimeStatus, handle?: LifecycleHandle<G>) => void): () => void;
49
+ /** Stops admission immediately and releases acquired resources once. */
50
+ close(): Promise<void>;
51
+ };
@@ -0,0 +1,244 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { waitForRuntimeWork } from './wait.js';
3
+ /** Serializes startup/restart and suppresses feedback from superseded generations. */
4
+ export function createRestartCoordinator(options) {
5
+ const acquire = options.acquire;
6
+ const watch = options.watch ?? (async () => () => Promise.resolve());
7
+ const listeners = new Set();
8
+ let status = 'starting';
9
+ let current;
10
+ let generation;
11
+ let disposeWatch;
12
+ let abort;
13
+ let transition;
14
+ let closing;
15
+ let pendingRestart = false;
16
+ let acquiring = false;
17
+ let unsafeCleanupError;
18
+ let version = 0;
19
+ /** Records a release failure that blocks later generations, unless owner opted out. */
20
+ function quarantine(error) {
21
+ if (options.quarantineCleanupFailures !== false)
22
+ unsafeCleanupError = error;
23
+ }
24
+ /** Announces lifecycle changes after state has been updated. */
25
+ function publish(next) {
26
+ status = next;
27
+ for (const listener of listeners)
28
+ listener(status, current);
29
+ }
30
+ /** Invalidates ownership before closing watchers and server resources. */
31
+ async function release() {
32
+ acquiring = false;
33
+ version++;
34
+ abort?.abort(new Error('Project runtime closed'));
35
+ const oldHandle = current;
36
+ current = undefined;
37
+ const oldGeneration = generation;
38
+ const oldWatch = disposeWatch;
39
+ generation = undefined;
40
+ disposeWatch = undefined;
41
+ try {
42
+ if (oldHandle)
43
+ await options.onBeforeRelease?.(oldHandle);
44
+ }
45
+ catch (error) {
46
+ quarantine(error);
47
+ // Quarantine this controller after unknown runner teardown; closing
48
+ // remaining project resources still avoids watcher/server leaks.
49
+ await Promise.allSettled([oldWatch?.(), oldGeneration?.close()]);
50
+ throw error;
51
+ }
52
+ const results = await Promise.allSettled([oldWatch?.(), oldGeneration?.close()]);
53
+ const failure = results.find((result) => result.status === 'rejected');
54
+ if (failure) {
55
+ quarantine(failure.reason);
56
+ throw failure.reason;
57
+ }
58
+ }
59
+ /** Creates a fresh generation; late acquisition is closed before returning. */
60
+ async function initialize() {
61
+ acquiring = true;
62
+ const capturedVersion = ++version;
63
+ const active = () => status !== 'closed' && capturedVersion === version;
64
+ const localAbort = new AbortController();
65
+ abort = localAbort;
66
+ let runtime;
67
+ try {
68
+ runtime = await acquire(localAbort.signal, active);
69
+ if (!active()) {
70
+ try {
71
+ await runtime.close();
72
+ }
73
+ catch (error) {
74
+ quarantine(error);
75
+ throw error;
76
+ }
77
+ throw new Error('Project runtime closed');
78
+ }
79
+ generation = runtime;
80
+ // Preserve live getters (backend handoff/catalog outcomes) instead of
81
+ // freezing their acquisition-time values through object spread.
82
+ const handle = Object.defineProperties({}, {
83
+ ...Object.getOwnPropertyDescriptors(runtime),
84
+ epoch: { value: randomUUID(), enumerable: true },
85
+ isActive: { value: active, enumerable: true },
86
+ });
87
+ current = handle;
88
+ await options.onGeneration?.(handle);
89
+ if (!active())
90
+ throw new Error('Project runtime closed');
91
+ const stopWatch = await watch(runtime, (source) => {
92
+ void restart(source).catch(error => options.onError?.(error));
93
+ });
94
+ if (!active()) {
95
+ try {
96
+ await stopWatch();
97
+ }
98
+ catch (error) {
99
+ quarantine(error);
100
+ throw error;
101
+ }
102
+ throw new Error('Project runtime closed');
103
+ }
104
+ disposeWatch = stopWatch;
105
+ // Abort wins even if project execution never settles its readiness work.
106
+ await waitForRuntimeWork(runtime.ready, localAbort.signal);
107
+ if (!active())
108
+ throw new Error('Project runtime closed');
109
+ // Reconciliation may have queued a successor while this watcher became
110
+ // ready. Let finishTransitions retire this stale generation unexposed.
111
+ if (!pendingRestart)
112
+ publish('ready');
113
+ return handle;
114
+ }
115
+ catch (error) {
116
+ if (options.isUnsafeCleanup(error))
117
+ unsafeCleanupError = error;
118
+ if (active()) {
119
+ let cleanupError;
120
+ try {
121
+ await release();
122
+ }
123
+ catch (failure) {
124
+ cleanupError = failure;
125
+ }
126
+ finally {
127
+ publish(pendingRestart ? 'restarting' : 'failed');
128
+ }
129
+ if (cleanupError)
130
+ throw new AggregateError([error, cleanupError], String(error));
131
+ }
132
+ throw error;
133
+ }
134
+ finally {
135
+ if (capturedVersion === version)
136
+ acquiring = false;
137
+ }
138
+ }
139
+ /** Repeats once when a config edit lands after the next config was acquired. */
140
+ async function finishTransitions(first) {
141
+ let handle;
142
+ let next = first;
143
+ for (;;) {
144
+ try {
145
+ handle = await next;
146
+ }
147
+ catch (error) {
148
+ if (!pendingRestart || unsafeCleanupError || status === 'closed')
149
+ throw error;
150
+ }
151
+ if (!pendingRestart || status === 'closed')
152
+ return handle;
153
+ pendingRestart = false;
154
+ const released = release();
155
+ publish('restarting');
156
+ next = released.then(() => initialize());
157
+ }
158
+ }
159
+ /** Records teardown failures as terminal lifecycle failures, including restarts. */
160
+ function observeTransition(work) {
161
+ return work.catch((error) => {
162
+ if (status !== 'closed' && status !== 'failed')
163
+ publish('failed');
164
+ throw error;
165
+ }).finally(() => {
166
+ transition = undefined;
167
+ });
168
+ }
169
+ /** Starts once, or joins an in-progress generation transition. */
170
+ function start() {
171
+ if (status === 'closed')
172
+ return Promise.reject(new Error('Project runtime closed'));
173
+ if (unsafeCleanupError)
174
+ return Promise.reject(unsafeCleanupError);
175
+ if (current && status === 'ready')
176
+ return Promise.resolve(current);
177
+ if (transition)
178
+ return transition;
179
+ publish('starting');
180
+ transition = observeTransition(finishTransitions(initialize()));
181
+ return transition;
182
+ }
183
+ /** Coalesces edits received during one teardown/startup into one restart. */
184
+ function restart(_source) {
185
+ if (status === 'closed')
186
+ return Promise.reject(new Error('Project runtime closed'));
187
+ if (unsafeCleanupError)
188
+ return Promise.reject(unsafeCleanupError);
189
+ if (transition) {
190
+ // Edits before a next generation is acquired already use its fresh config.
191
+ // Edits after acquisition must restart again to avoid losing a config edit.
192
+ if (current || (options.interruptStartup && acquiring))
193
+ pendingRestart = true;
194
+ if (options.interruptStartup && acquiring)
195
+ abort?.abort(new Error('Runtime superseded by config change'));
196
+ return transition;
197
+ }
198
+ const released = release();
199
+ publish('restarting');
200
+ transition = observeTransition(finishTransitions((async () => {
201
+ await released;
202
+ return initialize();
203
+ })()));
204
+ return transition;
205
+ }
206
+ return {
207
+ /** Current lifecycle state, usable before a catalog exists. */
208
+ get status() {
209
+ return status;
210
+ },
211
+ /** Current private handle; undefined during teardown or after failure. */
212
+ get current() {
213
+ return current;
214
+ },
215
+ start,
216
+ restart,
217
+ /** Joins the next completed ready generation. */
218
+ waitForReady: start,
219
+ /** Registers lifecycle observations; caller owns returned disposer. */
220
+ subscribe(listener) {
221
+ listeners.add(listener);
222
+ return () => {
223
+ listeners.delete(listener);
224
+ };
225
+ },
226
+ /** Stops admission immediately and releases acquired resources once. */
227
+ close() {
228
+ if (!closing) {
229
+ publish('closed');
230
+ const released = release();
231
+ // Acquisition may ignore its signal. Join late acquisition until its
232
+ // resources close, while unrelated project controllers remain usable.
233
+ closing = options.withDeadline(Promise.all([released, transition?.catch(() => {
234
+ })])).then(() => {
235
+ if (unsafeCleanupError)
236
+ throw unsafeCleanupError;
237
+ }).finally(() => {
238
+ listeners.clear();
239
+ });
240
+ }
241
+ return closing;
242
+ },
243
+ };
244
+ }
@@ -0,0 +1,3 @@
1
+ export { createRestartCoordinator } from './coordinator.js';
2
+ export type { CoordinatorOptions, LifecycleGeneration, LifecycleHandle } from './coordinator.js';
3
+ export { waitForRuntimeWork } from './wait.js';
@@ -0,0 +1,2 @@
1
+ export { createRestartCoordinator } from './coordinator.js';
2
+ export { waitForRuntimeWork } from './wait.js';
@@ -0,0 +1,2 @@
1
+ /** Waits for owned work or cancellation, removing its listener on either result. */
2
+ export declare function waitForRuntimeWork<T>(work: Promise<T>, signal?: AbortSignal): Promise<T>;
@@ -0,0 +1,22 @@
1
+ /** Waits for owned work or cancellation, removing its listener on either result. */
2
+ export async function waitForRuntimeWork(work, signal) {
3
+ if (!signal)
4
+ return work;
5
+ let onAbort = () => {
6
+ };
7
+ try {
8
+ return await Promise.race([
9
+ work,
10
+ new Promise((_, reject) => {
11
+ onAbort = () => reject(signal.reason ?? new Error('Project runtime closed'));
12
+ if (signal.aborted)
13
+ onAbort();
14
+ else
15
+ signal.addEventListener('abort', onAbort, { once: true });
16
+ }),
17
+ ]);
18
+ }
19
+ finally {
20
+ signal.removeEventListener('abort', onAbort);
21
+ }
22
+ }