@zenbujs/core 0.0.1

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 (94) hide show
  1. package/LICENSE +11 -0
  2. package/dist/advice-config-CjgkEf2E.mjs +135 -0
  3. package/dist/advice-config-Cy133IQP.mjs +2 -0
  4. package/dist/advice-runtime.d.mts +35 -0
  5. package/dist/advice-runtime.mjs +131 -0
  6. package/dist/advice.d.mts +36 -0
  7. package/dist/advice.mjs +2 -0
  8. package/dist/base-window-BUt8pwbw.mjs +94 -0
  9. package/dist/base-window-DEIAk618.mjs +2 -0
  10. package/dist/build-config-pbv0w4oN.mjs +17 -0
  11. package/dist/build-electron-B4Gd0Gi4.mjs +516 -0
  12. package/dist/build-source-_q1n1zTV.mjs +162 -0
  13. package/dist/chunk-Dm34NbLt.mjs +6 -0
  14. package/dist/cli/bin.d.mts +1 -0
  15. package/dist/cli/bin.mjs +88 -0
  16. package/dist/cli/build.d.mts +53 -0
  17. package/dist/cli/build.mjs +48 -0
  18. package/dist/cli-BLbQQIVB.mjs +8054 -0
  19. package/dist/config-CdVrW85P.mjs +59 -0
  20. package/dist/config-LK73dJmO.mjs +2 -0
  21. package/dist/db-ByKPbnP6.mjs +2 -0
  22. package/dist/db-DhuAJrye.mjs +531 -0
  23. package/dist/db.d.mts +16 -0
  24. package/dist/db.mjs +16 -0
  25. package/dist/dev-BuqklM0k.mjs +85 -0
  26. package/dist/env-bootstrap-BtVME-CU.d.mts +16 -0
  27. package/dist/env-bootstrap-rj7I-59x.mjs +53 -0
  28. package/dist/env-bootstrap.d.mts +2 -0
  29. package/dist/env-bootstrap.mjs +2 -0
  30. package/dist/http-IBcLzbYu.mjs +2 -0
  31. package/dist/index-Bhlbyrn7.d.mts +63 -0
  32. package/dist/index-CPZ5d6Hl.d.mts +442 -0
  33. package/dist/index-FtE8MXJ_.d.mts +1 -0
  34. package/dist/index.d.mts +6 -0
  35. package/dist/index.mjs +5 -0
  36. package/dist/launcher.mjs +173 -0
  37. package/dist/link-6roQ7Cn6.mjs +580 -0
  38. package/dist/loaders/zenbu.d.mts +22 -0
  39. package/dist/loaders/zenbu.mjs +267 -0
  40. package/dist/log-CyKv8hQg.mjs +20 -0
  41. package/dist/mirror-sync-CodOnwkD.mjs +332 -0
  42. package/dist/monorepo-CmGPHsVm.mjs +119 -0
  43. package/dist/node-D4M19_mV.mjs +5 -0
  44. package/dist/node-loader.d.mts +17 -0
  45. package/dist/node-loader.mjs +33 -0
  46. package/dist/pause-DvAUNmKn.mjs +52 -0
  47. package/dist/publish-source-BVgB62Zj.mjs +131 -0
  48. package/dist/react.d.mts +76 -0
  49. package/dist/react.mjs +291 -0
  50. package/dist/registry-Dh_e7HU1.d.mts +61 -0
  51. package/dist/registry.d.mts +2 -0
  52. package/dist/registry.mjs +1 -0
  53. package/dist/reloader-BCkLjDhS.mjs +2 -0
  54. package/dist/reloader-lLAJ3lqg.mjs +164 -0
  55. package/dist/renderer-host-Bg8QdeeH.mjs +1508 -0
  56. package/dist/renderer-host-DpvBPTHJ.mjs +2 -0
  57. package/dist/rpc-BwwQK6hD.mjs +71 -0
  58. package/dist/rpc-CqitnyR4.mjs +2 -0
  59. package/dist/rpc.d.mts +2 -0
  60. package/dist/rpc.mjs +2 -0
  61. package/dist/runtime-CjqDr8Yf.d.mts +109 -0
  62. package/dist/runtime-DUFKDIe4.mjs +409 -0
  63. package/dist/runtime.d.mts +2 -0
  64. package/dist/runtime.mjs +2 -0
  65. package/dist/schema-CIg4GzHQ.mjs +100 -0
  66. package/dist/schema-DMoSkwUx.d.mts +62 -0
  67. package/dist/schema-dGK6qkfR.mjs +28 -0
  68. package/dist/schema.d.mts +2 -0
  69. package/dist/schema.mjs +2 -0
  70. package/dist/server-BXwZEQ-n.mjs +66 -0
  71. package/dist/server-DjrZUbbu.mjs +2 -0
  72. package/dist/services/default.d.mts +11 -0
  73. package/dist/services/default.mjs +22 -0
  74. package/dist/services/index.d.mts +276 -0
  75. package/dist/services/index.mjs +7 -0
  76. package/dist/setup-gate-BeD6WS6d.mjs +110 -0
  77. package/dist/setup-gate-BqOzm7zp.d.mts +4 -0
  78. package/dist/setup-gate.d.mts +2 -0
  79. package/dist/setup-gate.mjs +2 -0
  80. package/dist/src-pELM4_iH.mjs +376 -0
  81. package/dist/trace-DCB7qFzT.mjs +10 -0
  82. package/dist/transform-DJH3vN4b.mjs +84041 -0
  83. package/dist/transport-BMSzG2-F.mjs +1045 -0
  84. package/dist/view-registry-BualWgAf.mjs +2 -0
  85. package/dist/vite-plugins-Bh3SCOw-.mjs +331 -0
  86. package/dist/vite.d.mts +68 -0
  87. package/dist/vite.mjs +2 -0
  88. package/dist/window-CM2a9Kyc.mjs +2 -0
  89. package/dist/window-CmmpCVX6.mjs +156 -0
  90. package/dist/write-9dRFczGJ.mjs +1248 -0
  91. package/migrations/0000_migration.ts +34 -0
  92. package/migrations/meta/0000_snapshot.json +18 -0
  93. package/migrations/meta/_journal.json +10 -0
  94. package/package.json +124 -0
@@ -0,0 +1,2 @@
1
+ import "./renderer-host-Bg8QdeeH.mjs";
2
+ export {};
@@ -0,0 +1,71 @@
1
+ import { i as runtime, t as Service } from "./runtime-DUFKDIe4.mjs";
2
+ import { t as createLogger } from "./log-CyKv8hQg.mjs";
3
+ import { o as HttpService } from "./renderer-host-Bg8QdeeH.mjs";
4
+ import { n as createRpcRouter, r as createServer } from "./src-pELM4_iH.mjs";
5
+ //#region src/services/rpc.ts
6
+ const log = createLogger("rpc");
7
+ var RpcService = class extends Service {
8
+ static key = "rpc";
9
+ static deps = { http: HttpService };
10
+ _emit = null;
11
+ get emit() {
12
+ if (!this._emit) throw new Error("RpcService not yet evaluated");
13
+ return this._emit;
14
+ }
15
+ evaluate() {
16
+ const { http } = this.ctx;
17
+ this.setup("rpc-wiring", () => {
18
+ const rpcRouter = createRpcRouter();
19
+ const rpcServer = createServer({
20
+ router: () => runtime.buildRouter(),
21
+ version: "0",
22
+ send: rpcRouter.send
23
+ });
24
+ this._emit = rpcServer.emit;
25
+ const wsRpcConnections = /* @__PURE__ */ new Map();
26
+ const onConnected = (id, ws) => {
27
+ const rpcConn = rpcRouter.connection({
28
+ send: (data) => {
29
+ if (ws.readyState === ws.OPEN) ws.send(JSON.stringify({
30
+ ch: "rpc",
31
+ data
32
+ }));
33
+ },
34
+ postMessage: rpcServer.postMessage,
35
+ removeClient: rpcServer.removeClient
36
+ });
37
+ wsRpcConnections.set(id, {
38
+ rpcConn,
39
+ ws
40
+ });
41
+ ws.on("message", (raw) => {
42
+ const msg = JSON.parse(String(raw));
43
+ if (msg.ch === "rpc") rpcConn.receive(msg.data);
44
+ });
45
+ };
46
+ const onDisconnected = (id) => {
47
+ const entry = wsRpcConnections.get(id);
48
+ if (entry) {
49
+ entry.rpcConn.close();
50
+ wsRpcConnections.delete(id);
51
+ }
52
+ };
53
+ const unsubConnected = http.onConnected(onConnected);
54
+ const unsubDisconnected = http.onDisconnected(onDisconnected);
55
+ return () => {
56
+ this._emit = null;
57
+ unsubConnected();
58
+ unsubDisconnected();
59
+ for (const { rpcConn, ws } of wsRpcConnections.values()) {
60
+ rpcConn.close();
61
+ ws.close();
62
+ }
63
+ wsRpcConnections.clear();
64
+ };
65
+ });
66
+ log.verbose("service ready");
67
+ }
68
+ };
69
+ runtime.register(RpcService, import.meta);
70
+ //#endregion
71
+ export { RpcService as t };
@@ -0,0 +1,2 @@
1
+ import "./rpc-BwwQK6hD.mjs";
2
+ export {};
package/dist/rpc.d.mts ADDED
@@ -0,0 +1,2 @@
1
+ import { n as EventProxy, r as RouterProxy, t as connectRpc } from "./index-Bhlbyrn7.mjs";
2
+ export { type EventProxy, type RouterProxy, connectRpc };
package/dist/rpc.mjs ADDED
@@ -0,0 +1,2 @@
1
+ import { t as connectRpc } from "./src-pELM4_iH.mjs";
2
+ export { connectRpc };
@@ -0,0 +1,109 @@
1
+ //#region src/runtime.d.ts
2
+ type CleanupReason = "reload" | "shutdown";
3
+ type SetupCleanup = ((reason: CleanupReason) => void | Promise<void>) | void;
4
+ type SetupFn = () => SetupCleanup;
5
+ interface ServiceSlot {
6
+ error: unknown | null;
7
+ instance: Service | null;
8
+ ServiceClass: typeof Service;
9
+ status: "blocked" | "evaluating" | "ready" | "failed";
10
+ }
11
+ type AnyServiceClass = abstract new (...args: any[]) => Service;
12
+ type DepRef = AnyServiceClass | string;
13
+ type OptionalDep<R extends DepRef = DepRef> = {
14
+ __optional: true;
15
+ ref: R;
16
+ };
17
+ type DepEntry = DepRef | OptionalDep;
18
+ type DepInstance<D> = D extends OptionalDep<infer R> ? R extends AnyServiceClass ? InstanceType<R> | undefined : unknown : D extends AnyServiceClass ? InstanceType<D> : unknown;
19
+ type ResolveCtx<TDeps> = { [K in keyof TDeps]: DepInstance<TDeps[K]> };
20
+ declare function optional<R extends DepRef>(ref: R): OptionalDep<R>;
21
+ declare abstract class Service {
22
+ static key: string;
23
+ static deps: Record<string, DepEntry>;
24
+ ctx: any;
25
+ /** @internal */
26
+ __setupCleanups: Map<string, (reason: CleanupReason) => void | Promise<void>>;
27
+ evaluate(): void | Promise<void>;
28
+ setup(key: string, fn: SetupFn): void;
29
+ /**
30
+ * Run `fn` and return its result. Historically reported a boot-trace span;
31
+ * now a thin wrapper preserved for caller ergonomics inside service
32
+ * `evaluate()` bodies.
33
+ */
34
+ trace<T>(_name: string, fn: () => T | Promise<T>, _meta?: Record<string, unknown>): Promise<T>;
35
+ traceSync<T>(_name: string, fn: () => T, _meta?: Record<string, unknown>): T;
36
+ /** @internal */
37
+ __cleanupAllSetups(reason?: CleanupReason): Promise<void>;
38
+ }
39
+ /**
40
+ * Declare a Service base class with typed deps. The returned class has
41
+ * `static deps = <your map>` already set, and `this.ctx` is auto-typed
42
+ * from the dep classes — no `declare ctx` needed in the subclass.
43
+ *
44
+ * export class WindowService extends serviceWithDeps({
45
+ * baseWindow: BaseWindowService,
46
+ * http: HttpService,
47
+ * }) {
48
+ * static key = "window"
49
+ * evaluate() {
50
+ * this.ctx.baseWindow // BaseWindowService
51
+ * this.ctx.http // HttpService
52
+ * }
53
+ * }
54
+ *
55
+ * `optional(SomeService)` is supported and produces `Instance | undefined`.
56
+ */
57
+ declare function serviceWithDeps<TDeps extends Record<string, DepEntry>>(deps: TDeps): (abstract new () => {
58
+ ctx: ResolveCtx<TDeps>; /** @internal */
59
+ __setupCleanups: Map<string, (reason: CleanupReason) => void | Promise<void>>;
60
+ evaluate(): void | Promise<void>;
61
+ setup(key: string, fn: SetupFn): void;
62
+ /**
63
+ * Run `fn` and return its result. Historically reported a boot-trace span;
64
+ * now a thin wrapper preserved for caller ergonomics inside service
65
+ * `evaluate()` bodies.
66
+ */
67
+ trace<T>(_name: string, fn: () => T | Promise<T>, _meta?: Record<string, unknown>): Promise<T>;
68
+ traceSync<T>(_name: string, fn: () => T, _meta?: Record<string, unknown>): T; /** @internal */
69
+ __cleanupAllSetups(reason?: CleanupReason): Promise<void>;
70
+ }) & {
71
+ deps: Record<string, DepEntry>;
72
+ key: string;
73
+ };
74
+ declare class ServiceRuntime {
75
+ private definitions;
76
+ private dependentsIndex;
77
+ private dirtyKeys;
78
+ private drainError;
79
+ private draining;
80
+ private registrationTokens;
81
+ private slots;
82
+ private onReconciledCallbacks;
83
+ register(ServiceClass: typeof Service, importMeta?: ImportMeta | null): void;
84
+ getAllKeys(): string[];
85
+ getSlot(key: string): ServiceSlot | undefined;
86
+ whenIdle(): Promise<void>;
87
+ reloadAll(): Promise<void>;
88
+ shutdown(): Promise<void>;
89
+ get<T extends Service>(ref: {
90
+ key: string;
91
+ }): T;
92
+ buildRouter(): Record<string, Record<string, (...args: any[]) => any>>;
93
+ onReconciled(cb: (changedKeys: string[]) => void): () => void;
94
+ private resolveDepSlot;
95
+ private injectCtx;
96
+ private rebuildDependentsIndex;
97
+ private getAffectedKeys;
98
+ private listMissingDeps;
99
+ private ensureSlot;
100
+ private teardownService;
101
+ private unregister;
102
+ private scheduleReconcile;
103
+ private reconcileBatch;
104
+ private reconcileKey;
105
+ private topologicalLevels;
106
+ }
107
+ declare const runtime: ServiceRuntime;
108
+ //#endregion
109
+ export { runtime as a, optional as i, Service as n, serviceWithDeps as o, ServiceRuntime as r, CleanupReason as t };
@@ -0,0 +1,409 @@
1
+ //#region src/runtime.ts
2
+ function optional(ref) {
3
+ return {
4
+ __optional: true,
5
+ ref
6
+ };
7
+ }
8
+ function resolveDep(entry) {
9
+ if (typeof entry === "string") return {
10
+ key: entry,
11
+ optional: false
12
+ };
13
+ if (typeof entry === "object" && entry !== null && "__optional" in entry) {
14
+ const ref = entry.ref;
15
+ return {
16
+ key: typeof ref === "string" ? ref : ref.key,
17
+ optional: true
18
+ };
19
+ }
20
+ return {
21
+ key: entry.key,
22
+ optional: false
23
+ };
24
+ }
25
+ var Service = class {
26
+ static key;
27
+ static deps;
28
+ ctx;
29
+ /** @internal */
30
+ __setupCleanups = /* @__PURE__ */ new Map();
31
+ evaluate() {}
32
+ setup(key, fn) {
33
+ const existing = this.__setupCleanups.get(key);
34
+ if (existing) try {
35
+ existing("reload");
36
+ } catch (e) {
37
+ console.error(`[hot] setup cleanup "${key}" failed:`, e);
38
+ }
39
+ const cleanup = fn();
40
+ if (cleanup) this.__setupCleanups.set(key, cleanup);
41
+ else this.__setupCleanups.delete(key);
42
+ }
43
+ /**
44
+ * Run `fn` and return its result. Historically reported a boot-trace span;
45
+ * now a thin wrapper preserved for caller ergonomics inside service
46
+ * `evaluate()` bodies.
47
+ */
48
+ trace(_name, fn, _meta) {
49
+ return Promise.resolve(fn());
50
+ }
51
+ traceSync(_name, fn, _meta) {
52
+ return fn();
53
+ }
54
+ /** @internal */
55
+ async __cleanupAllSetups(reason = "shutdown") {
56
+ for (const [key, cleanup] of this.__setupCleanups) try {
57
+ await cleanup(reason);
58
+ } catch (e) {
59
+ console.error(`[hot] setup cleanup "${key}" failed:`, e);
60
+ }
61
+ this.__setupCleanups.clear();
62
+ }
63
+ };
64
+ /**
65
+ * Declare a Service base class with typed deps. The returned class has
66
+ * `static deps = <your map>` already set, and `this.ctx` is auto-typed
67
+ * from the dep classes — no `declare ctx` needed in the subclass.
68
+ *
69
+ * export class WindowService extends serviceWithDeps({
70
+ * baseWindow: BaseWindowService,
71
+ * http: HttpService,
72
+ * }) {
73
+ * static key = "window"
74
+ * evaluate() {
75
+ * this.ctx.baseWindow // BaseWindowService
76
+ * this.ctx.http // HttpService
77
+ * }
78
+ * }
79
+ *
80
+ * `optional(SomeService)` is supported and produces `Instance | undefined`.
81
+ */
82
+ function serviceWithDeps(deps) {
83
+ class ServiceWithDeps extends Service {
84
+ static deps = deps;
85
+ }
86
+ return ServiceWithDeps;
87
+ }
88
+ const SERVICE_BASE_METHODS = new Set(Object.getOwnPropertyNames(Service.prototype));
89
+ var ServiceRuntime = class {
90
+ definitions = /* @__PURE__ */ new Map();
91
+ dependentsIndex = /* @__PURE__ */ new Map();
92
+ dirtyKeys = /* @__PURE__ */ new Set();
93
+ drainError = null;
94
+ draining = null;
95
+ registrationTokens = /* @__PURE__ */ new Map();
96
+ slots = /* @__PURE__ */ new Map();
97
+ onReconciledCallbacks = [];
98
+ register(ServiceClass, importMeta) {
99
+ const hot = importMeta?.hot ?? null;
100
+ const baseKey = ServiceClass.key;
101
+ if (!baseKey) throw new Error("Service must have a static key property");
102
+ const slotKey = baseKey;
103
+ this.definitions.set(slotKey, ServiceClass);
104
+ const slot = this.slots.get(slotKey);
105
+ if (slot) slot.ServiceClass = ServiceClass;
106
+ else this.slots.set(slotKey, {
107
+ error: null,
108
+ instance: null,
109
+ ServiceClass,
110
+ status: "blocked"
111
+ });
112
+ this.rebuildDependentsIndex();
113
+ hot?.accept();
114
+ const token = Symbol(slotKey);
115
+ this.registrationTokens.set(slotKey, token);
116
+ hot?.prune?.(() => {
117
+ this.unregister(slotKey, token);
118
+ });
119
+ this.scheduleReconcile([slotKey]);
120
+ }
121
+ getAllKeys() {
122
+ return [...this.slots.keys()];
123
+ }
124
+ getSlot(key) {
125
+ return this.slots.get(key);
126
+ }
127
+ async whenIdle() {
128
+ while (this.draining) await this.draining;
129
+ if (this.drainError) {
130
+ const error = this.drainError;
131
+ this.drainError = null;
132
+ throw error;
133
+ }
134
+ }
135
+ async reloadAll() {
136
+ const keys = [...this.slots.keys()];
137
+ if (keys.length === 0) return;
138
+ await this.scheduleReconcile(keys);
139
+ await this.whenIdle();
140
+ }
141
+ async shutdown() {
142
+ try {
143
+ await this.whenIdle();
144
+ } catch (error) {
145
+ console.error("[hot] runtime idle wait failed during shutdown:", error);
146
+ }
147
+ const keys = [...this.slots.keys()].reverse();
148
+ for (const key of keys) await this.teardownService(key, { removeSlot: true });
149
+ this.definitions.clear();
150
+ this.dependentsIndex.clear();
151
+ this.dirtyKeys.clear();
152
+ this.registrationTokens.clear();
153
+ }
154
+ get(ref) {
155
+ const slot = this.slots.get(ref.key);
156
+ if (!slot || slot.status !== "ready" || !slot.instance) throw new Error(`Service "${ref.key}" not ready. Is it registered and evaluated?`);
157
+ return slot.instance;
158
+ }
159
+ buildRouter() {
160
+ const router = {};
161
+ for (const [slotKey, slot] of this.slots) {
162
+ if (slot.status !== "ready" || !slot.instance) continue;
163
+ const proto = Object.getPrototypeOf(slot.instance);
164
+ const methods = {};
165
+ for (const name of Object.getOwnPropertyNames(proto)) {
166
+ if (SERVICE_BASE_METHODS.has(name)) continue;
167
+ if (name.startsWith("_")) continue;
168
+ const desc = Object.getOwnPropertyDescriptor(proto, name);
169
+ if (!desc || typeof desc.value !== "function") continue;
170
+ const instance = slot.instance;
171
+ methods[name] = (...args) => instance[name](...args);
172
+ }
173
+ if (Object.keys(methods).length > 0) router[slotKey] = methods;
174
+ }
175
+ return router;
176
+ }
177
+ onReconciled(cb) {
178
+ this.onReconciledCallbacks.push(cb);
179
+ return () => {
180
+ const idx = this.onReconciledCallbacks.indexOf(cb);
181
+ if (idx >= 0) this.onReconciledCallbacks.splice(idx, 1);
182
+ };
183
+ }
184
+ resolveDepSlot(depKey) {
185
+ return this.slots.get(depKey);
186
+ }
187
+ injectCtx(instance, ServiceClass) {
188
+ const deps = ServiceClass.deps ?? {};
189
+ const ctx = {};
190
+ for (const [name, entry] of Object.entries(deps)) {
191
+ const { key, optional: isOptional } = resolveDep(entry);
192
+ const slot = this.resolveDepSlot(key);
193
+ if (!slot || slot.status !== "ready" || !slot.instance) {
194
+ if (isOptional) {
195
+ ctx[name] = void 0;
196
+ continue;
197
+ }
198
+ throw new Error(`Dependency "${key}" not ready for "${ServiceClass.key}"`);
199
+ }
200
+ ctx[name] = slot.instance;
201
+ }
202
+ instance.ctx = ctx;
203
+ }
204
+ rebuildDependentsIndex() {
205
+ const next = /* @__PURE__ */ new Map();
206
+ for (const [slotKey, ServiceClass] of this.definitions) {
207
+ const deps = ServiceClass.deps ?? {};
208
+ for (const entry of Object.values(deps)) {
209
+ const { key: depKey } = resolveDep(entry);
210
+ const dependents = next.get(depKey) ?? /* @__PURE__ */ new Set();
211
+ dependents.add(slotKey);
212
+ next.set(depKey, dependents);
213
+ }
214
+ }
215
+ this.dependentsIndex = next;
216
+ }
217
+ getAffectedKeys(changedKeys) {
218
+ const affected = /* @__PURE__ */ new Set();
219
+ const visit = (key) => {
220
+ if (affected.has(key)) return;
221
+ affected.add(key);
222
+ for (const dependent of this.dependentsIndex.get(key) ?? []) visit(dependent);
223
+ };
224
+ for (const key of changedKeys) visit(key);
225
+ return [...affected].filter((key) => this.definitions.has(key));
226
+ }
227
+ listMissingDeps(ServiceClass) {
228
+ const deps = ServiceClass.deps ?? {};
229
+ const missing = [];
230
+ for (const entry of Object.values(deps)) {
231
+ const { key, optional: isOptional } = resolveDep(entry);
232
+ if (isOptional) continue;
233
+ const slot = this.resolveDepSlot(key);
234
+ if (!slot || slot.status !== "ready" || !slot.instance) missing.push(key);
235
+ }
236
+ return missing;
237
+ }
238
+ ensureSlot(key, ServiceClass) {
239
+ const existing = this.slots.get(key);
240
+ if (existing) return existing;
241
+ const slot = {
242
+ error: null,
243
+ instance: null,
244
+ ServiceClass,
245
+ status: "blocked"
246
+ };
247
+ this.slots.set(key, slot);
248
+ return slot;
249
+ }
250
+ async teardownService(key, options = {}) {
251
+ const slot = this.slots.get(key);
252
+ if (!slot) return;
253
+ const instance = slot.instance;
254
+ slot.instance = null;
255
+ slot.status = "blocked";
256
+ slot.error = null;
257
+ if (instance) await instance.__cleanupAllSetups(options.reason ?? "shutdown");
258
+ if (options.removeSlot) this.slots.delete(key);
259
+ }
260
+ async unregister(key, token) {
261
+ if (this.registrationTokens.get(key) !== token) return;
262
+ this.registrationTokens.delete(key);
263
+ this.definitions.delete(key);
264
+ await this.teardownService(key, { removeSlot: true });
265
+ this.rebuildDependentsIndex();
266
+ await this.scheduleReconcile([key]);
267
+ }
268
+ async scheduleReconcile(keys) {
269
+ for (const key of keys) this.dirtyKeys.add(key);
270
+ if (this.draining) return this.draining;
271
+ this.draining = (async () => {
272
+ try {
273
+ while (this.dirtyKeys.size > 0) {
274
+ const batch = [...this.dirtyKeys];
275
+ this.dirtyKeys.clear();
276
+ await this.reconcileBatch(batch);
277
+ }
278
+ } catch (error) {
279
+ this.drainError = error;
280
+ console.error("[hot] runtime reconcile failed:", error);
281
+ } finally {
282
+ this.draining = null;
283
+ if (this.dirtyKeys.size > 0) this.scheduleReconcile([]);
284
+ }
285
+ })();
286
+ return this.draining;
287
+ }
288
+ async reconcileBatch(changedKeys) {
289
+ const affectedKeys = this.getAffectedKeys(changedKeys);
290
+ if (affectedKeys.length === 0) return;
291
+ const affected = /* @__PURE__ */ new Map();
292
+ for (const key of affectedKeys) {
293
+ const ServiceClass = this.definitions.get(key);
294
+ if (ServiceClass) affected.set(key, ServiceClass);
295
+ }
296
+ const levels = this.topologicalLevels(affected);
297
+ for (const level of [...levels].reverse()) await Promise.all(level.map(async (key) => {
298
+ const slot = this.slots.get(key);
299
+ if (slot?.instance) await slot.instance.__cleanupAllSetups("reload");
300
+ }));
301
+ for (const level of levels) await Promise.all(level.map((key) => this.reconcileKey(key)));
302
+ if (affectedKeys.length > 0) for (const cb of this.onReconciledCallbacks) try {
303
+ cb(affectedKeys);
304
+ } catch (e) {
305
+ console.error("[hot] onReconciled callback failed:", e);
306
+ }
307
+ }
308
+ async reconcileKey(key) {
309
+ const ServiceClass = this.definitions.get(key);
310
+ if (!ServiceClass) return;
311
+ const slot = this.ensureSlot(key, ServiceClass);
312
+ slot.ServiceClass = ServiceClass;
313
+ const missingDeps = this.listMissingDeps(ServiceClass);
314
+ if (missingDeps.length > 0) {
315
+ const shouldLog = slot.instance !== null || slot.status !== "blocked";
316
+ await this.teardownService(key, { reason: "reload" });
317
+ if (shouldLog) console.log(`[hot] ${key} waiting on: ${missingDeps.join(", ")}`);
318
+ return;
319
+ }
320
+ let instance = slot.instance;
321
+ if (!instance) {
322
+ instance = new ServiceClass();
323
+ slot.instance = instance;
324
+ } else Object.setPrototypeOf(instance, ServiceClass.prototype);
325
+ slot.status = "evaluating";
326
+ slot.error = null;
327
+ try {
328
+ await instance.__cleanupAllSetups("reload");
329
+ this.injectCtx(instance, ServiceClass);
330
+ await instance.evaluate();
331
+ slot.status = "ready";
332
+ } catch (e) {
333
+ slot.status = "failed";
334
+ slot.error = e;
335
+ console.error(`[hot] ${key} failed to evaluate:`, e);
336
+ }
337
+ }
338
+ topologicalLevels(services) {
339
+ const keys = new Set(services.keys());
340
+ const inDegree = /* @__PURE__ */ new Map();
341
+ const dependents = /* @__PURE__ */ new Map();
342
+ for (const key of keys) {
343
+ inDegree.set(key, 0);
344
+ dependents.set(key, []);
345
+ }
346
+ for (const [slotKey, ServiceClass] of services) {
347
+ const deps = ServiceClass.deps ?? {};
348
+ let degree = 0;
349
+ for (const entry of Object.values(deps)) {
350
+ const { key: depKey, optional: isOptional } = resolveDep(entry);
351
+ if (keys.has(depKey)) {
352
+ degree++;
353
+ dependents.get(depKey).push(slotKey);
354
+ } else if (isOptional) continue;
355
+ }
356
+ inDegree.set(slotKey, degree);
357
+ }
358
+ const levels = [];
359
+ let queue = [...keys].filter((k) => inDegree.get(k) === 0);
360
+ while (queue.length > 0) {
361
+ levels.push(queue);
362
+ const next = [];
363
+ for (const key of queue) for (const dep of dependents.get(key)) {
364
+ const d = inDegree.get(dep) - 1;
365
+ inDegree.set(dep, d);
366
+ if (d === 0) next.push(dep);
367
+ }
368
+ queue = next;
369
+ }
370
+ const resolved = levels.flat();
371
+ if (resolved.length !== keys.size) {
372
+ const missing = [...keys].filter((k) => !resolved.includes(k));
373
+ throw new Error(`Circular dependency detected involving: ${missing.join(", ")}`);
374
+ }
375
+ return levels;
376
+ }
377
+ };
378
+ /**
379
+ * Devtools-only handles, attached to the global so they aren't part of the
380
+ * public `ServiceRuntime` autocomplete surface. Same shape React DevTools
381
+ * uses (`__REACT_DEVTOOLS_GLOBAL_HOOK__`): user code reading
382
+ * `runtime.<...>` never lands on these methods; you only find them if you
383
+ * specifically type `globalThis.__zenbu_dev__`. Kept here (next to the
384
+ * runtime that owns the state) because the hook reaches into private
385
+ * implementation details — `scheduleReconcile` stays `private` on the
386
+ * class; the cast lives inside the encapsulation boundary.
387
+ */
388
+ function installDevHook(rt) {
389
+ const internals = rt;
390
+ globalThis.__zenbu_dev__ = { reloadService: async (key) => {
391
+ if (!internals.definitions.has(key)) throw new Error(`No service registered for key "${key}"`);
392
+ await internals.scheduleReconcile([key]);
393
+ await rt.whenIdle();
394
+ } };
395
+ }
396
+ const runtime = (() => {
397
+ const existing = globalThis.__zenbu_service_runtime__;
398
+ if (existing) {
399
+ Object.setPrototypeOf(existing, ServiceRuntime.prototype);
400
+ installDevHook(existing);
401
+ return existing;
402
+ }
403
+ const fresh = new ServiceRuntime();
404
+ globalThis.__zenbu_service_runtime__ = fresh;
405
+ installDevHook(fresh);
406
+ return fresh;
407
+ })();
408
+ //#endregion
409
+ export { serviceWithDeps as a, runtime as i, ServiceRuntime as n, optional as r, Service as t };
@@ -0,0 +1,2 @@
1
+ import { a as runtime, i as optional, n as Service, o as serviceWithDeps, r as ServiceRuntime, t as CleanupReason } from "./runtime-CjqDr8Yf.mjs";
2
+ export { CleanupReason, Service, ServiceRuntime, optional, runtime, serviceWithDeps };
@@ -0,0 +1,2 @@
1
+ import { a as serviceWithDeps, i as runtime, n as ServiceRuntime, r as optional, t as Service } from "./runtime-DUFKDIe4.mjs";
2
+ export { Service, ServiceRuntime, optional, runtime, serviceWithDeps };