@powerhousedao/reactor-browser 6.2.3-dev.5 → 6.2.3-dev.50

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 (88) hide show
  1. package/dist/{attachment-service-D3EhiAJ7.d.ts → attachment-service-B-nLR114.d.ts} +299 -60
  2. package/dist/attachment-service-B-nLR114.d.ts.map +1 -0
  3. package/dist/{client-BIHN_UyR.d.ts → client-C-tRLfRN.d.ts} +3 -3
  4. package/dist/client-C-tRLfRN.d.ts.map +1 -0
  5. package/dist/{client-D66jVnot.js → client-CZyHv02L.js} +197 -32
  6. package/dist/client-CZyHv02L.js.map +1 -0
  7. package/dist/{client-DjK30EQ-.js → client-Cq5avLW5.js} +35 -22
  8. package/dist/client-Cq5avLW5.js.map +1 -0
  9. package/dist/{document-by-id-B4FIzG1w.js → dispatch-C1VVTn5S.js} +393 -54
  10. package/dist/dispatch-C1VVTn5S.js.map +1 -0
  11. package/dist/document-by-id-BRDkvmpn.js +16 -0
  12. package/dist/document-by-id-BRDkvmpn.js.map +1 -0
  13. package/dist/{document-model-modules-bTP87nyr.js → document-model-modules-Gsh1Xr7j.js} +60 -68
  14. package/dist/document-model-modules-Gsh1Xr7j.js.map +1 -0
  15. package/dist/{document-operations-WeE6wIDt.js → document-operations-CpzMebZ3.js} +595 -126
  16. package/dist/document-operations-CpzMebZ3.js.map +1 -0
  17. package/dist/{global-OuINvEGT.d.ts → global-BvawOKrQ.d.ts} +57 -13
  18. package/dist/global-BvawOKrQ.d.ts.map +1 -0
  19. package/dist/{index-B33TKEqp.d.ts → index-Cjf5TGen.d.ts} +19 -98
  20. package/dist/index-Cjf5TGen.d.ts.map +1 -0
  21. package/dist/{index-BIVDXw3K.d.ts → index-rtDmzViP.d.ts} +3 -3
  22. package/dist/index-rtDmzViP.d.ts.map +1 -0
  23. package/dist/index.d.ts +395 -371
  24. package/dist/index.d.ts.map +1 -1
  25. package/dist/index.js +114 -39
  26. package/dist/index.js.map +1 -1
  27. package/dist/inspector-proxy-DKOjxSGE.d.ts +32 -0
  28. package/dist/inspector-proxy-DKOjxSGE.d.ts.map +1 -0
  29. package/dist/{make-ph-event-functions-DBq3iWYn.js → make-ph-event-functions-CdsvEl5t.js} +4 -2
  30. package/dist/{make-ph-event-functions-DBq3iWYn.js.map → make-ph-event-functions-CdsvEl5t.js.map} +1 -1
  31. package/dist/{pglite-CntadC_p-9NDG14dS.d.ts → pglite-CntadC_p-DTkdF8sr.d.ts} +11 -33
  32. package/dist/pglite-CntadC_p-DTkdF8sr.d.ts.map +1 -0
  33. package/dist/{relational-D1RB45sA.js → relational-DxHuX41f.js} +66 -5
  34. package/dist/relational-DxHuX41f.js.map +1 -0
  35. package/dist/{renown-rqK8sokh.js → renown-CPAeJt5L.js} +7 -8
  36. package/dist/{renown-rqK8sokh.js.map → renown-CPAeJt5L.js.map} +1 -1
  37. package/dist/{renown-BHxwP7xU.js → renown-D05wkobG.js} +2 -2
  38. package/dist/{renown-BHxwP7xU.js.map → renown-D05wkobG.js.map} +1 -1
  39. package/dist/src/ai/index.d.ts +51 -62
  40. package/dist/src/ai/index.d.ts.map +1 -1
  41. package/dist/src/ai/index.js +5 -8
  42. package/dist/src/ai/index.js.map +1 -1
  43. package/dist/src/analytics/index.d.ts +36 -44
  44. package/dist/src/analytics/index.d.ts.map +1 -1
  45. package/dist/src/analytics/index.js +2 -2
  46. package/dist/src/analytics/index.js.map +1 -1
  47. package/dist/src/document-model.d.ts +3 -4
  48. package/dist/src/document-model.d.ts.map +1 -1
  49. package/dist/src/document-model.js.map +1 -1
  50. package/dist/src/graphql/client.d.ts +4 -3
  51. package/dist/src/graphql/client.js +1 -1
  52. package/dist/src/graphql-client/entry.d.ts +5 -4
  53. package/dist/src/graphql-client/entry.js +4 -4
  54. package/dist/src/relational/index.d.ts +15 -9
  55. package/dist/src/relational/index.d.ts.map +1 -1
  56. package/dist/src/relational/index.js +1 -1
  57. package/dist/src/renown/index.d.ts +3 -2
  58. package/dist/src/renown/index.js +2 -2
  59. package/dist/src/rpc/index.d.ts +94 -110
  60. package/dist/src/rpc/index.d.ts.map +1 -1
  61. package/dist/src/rpc/index.js +264 -607
  62. package/dist/src/rpc/index.js.map +1 -1
  63. package/dist/{store-BJYcr_FL.js → store-DInXcjal.js} +1 -1
  64. package/dist/{store-BJYcr_FL.js.map → store-DInXcjal.js.map} +1 -1
  65. package/dist/{switchboard-CaXQ4-5Q.js → switchboard-3vHbIV5W.js} +58 -6
  66. package/dist/switchboard-3vHbIV5W.js.map +1 -0
  67. package/dist/{types-6vDzbRRS.d.ts → types-520nWrB3.d.ts} +2 -2
  68. package/dist/types-520nWrB3.d.ts.map +1 -0
  69. package/dist/{types-Dcv1ZLoW.d.ts → types-D0ugg0E1.d.ts} +224 -17
  70. package/dist/types-D0ugg0E1.d.ts.map +1 -0
  71. package/package.json +19 -20
  72. package/dist/attachment-service-D3EhiAJ7.d.ts.map +0 -1
  73. package/dist/client-BIHN_UyR.d.ts.map +0 -1
  74. package/dist/client-D66jVnot.js.map +0 -1
  75. package/dist/client-DjK30EQ-.js.map +0 -1
  76. package/dist/document-by-id-B4FIzG1w.js.map +0 -1
  77. package/dist/document-model-modules-bTP87nyr.js.map +0 -1
  78. package/dist/document-operations-WeE6wIDt.js.map +0 -1
  79. package/dist/global-OuINvEGT.d.ts.map +0 -1
  80. package/dist/index-B33TKEqp.d.ts.map +0 -1
  81. package/dist/index-BIVDXw3K.d.ts.map +0 -1
  82. package/dist/inspector-proxy-6h5VKAwt.d.ts +0 -257
  83. package/dist/inspector-proxy-6h5VKAwt.d.ts.map +0 -1
  84. package/dist/pglite-CntadC_p-9NDG14dS.d.ts.map +0 -1
  85. package/dist/relational-D1RB45sA.js.map +0 -1
  86. package/dist/switchboard-CaXQ4-5Q.js.map +0 -1
  87. package/dist/types-6vDzbRRS.d.ts.map +0 -1
  88. package/dist/types-Dcv1ZLoW.d.ts.map +0 -1
@@ -1,42 +1,7 @@
1
- import { t as RegistryClient } from "../../client-DjK30EQ-.js";
2
- import { normalizeDocumentModelVersion } from "@powerhousedao/shared/document-model";
3
- import { DriveCollectionId, ReactorEventTypes, SyncEventTypes } from "@powerhousedao/reactor";
4
- //#region src/rpc/listeners.ts
5
- var KeyedListeners = class {
6
- map = /* @__PURE__ */ new Map();
7
- add(key, fn) {
8
- let set = this.map.get(key);
9
- if (!set) {
10
- set = /* @__PURE__ */ new Set();
11
- this.map.set(key, set);
12
- }
13
- set.add(fn);
14
- return () => {
15
- const current = this.map.get(key);
16
- if (!current) return;
17
- current.delete(fn);
18
- if (current.size === 0) this.map.delete(key);
19
- };
20
- }
21
- emit(key, ...a) {
22
- const set = this.map.get(key);
23
- if (!set) return;
24
- for (const fn of [...set]) fn(...a);
25
- }
26
- emitAll(...a) {
27
- for (const set of [...this.map.values()]) for (const fn of [...set]) fn(...a);
28
- }
29
- };
30
- var Listeners = class {
31
- keyed = new KeyedListeners();
32
- add(fn) {
33
- return this.keyed.add(null, fn);
34
- }
35
- emit(...a) {
36
- this.keyed.emit(null, ...a);
37
- }
38
- };
39
- //#endregion
1
+ import { t as RegistryClient } from "../../client-Cq5avLW5.js";
2
+ import { DriveCollectionId, ReactorEventTypes, SyncEventTypes, createPeerAgreement } from "@powerhousedao/reactor";
3
+ import { KeyedListeners, KeyedListeners as KeyedListeners$1, Listeners, Listeners as Listeners$1, MessageRouter, RPC_PROTOCOL_VERSION, RPC_PROTOCOL_VERSION as RPC_PROTOCOL_VERSION$1, ReactorHostServer, ReactorHostServer as ReactorHostServer$1, RpcCorrelator, SubscriptionStore, SubscriptionStore as SubscriptionStore$1, createCorrelatedSubscriptions, createCorrelatedSubscriptions as createCorrelatedSubscriptions$1, createPortTransport, createPortTransport as createPortTransport$1, createReactorClientProxy, createReactorClientProxy as createReactorClientProxy$1, fromErrorInfo, fromErrorInfo as fromErrorInfo$1, hostResponder, hostResponder as hostResponder$1, toErrorInfo } from "@powerhousedao/reactor/rpc";
4
+ import { rewritePackageSource } from "@powerhousedao/shared/connect";
40
5
  //#region src/rpc/op-channel.ts
41
6
  const RPC_DEFAULT_TIMEOUT_MS = 3e4;
42
7
  function toVoid(promise) {
@@ -59,7 +24,7 @@ function opChannel(router, kind, timeoutMs = RPC_DEFAULT_TIMEOUT_MS) {
59
24
  /** Worker lifecycle channel (info/restart/clearStorage/migrate) over the shared router. */
60
25
  function createWorkerAdminClient(router) {
61
26
  let migrationState = { status: "idle" };
62
- const migrationListeners = new Listeners();
27
+ const migrationListeners = new Listeners$1();
63
28
  router.on("migration", (msg) => {
64
29
  migrationState = msg.state;
65
30
  migrationListeners.emit();
@@ -79,236 +44,6 @@ function createWorkerAdminClient(router) {
79
44
  };
80
45
  }
81
46
  //#endregion
82
- //#region src/rpc/error-info.ts
83
- const MAX_STACK_LENGTH = 8 * 1024;
84
- const MAX_CAUSE_DEPTH = 8;
85
- function toErrorInfo(err, depth = 0) {
86
- if (depth > MAX_CAUSE_DEPTH) return {
87
- name: "Error",
88
- message: "cause chain truncated"
89
- };
90
- if (err instanceof Error) {
91
- const info = {
92
- name: err.name || "Error",
93
- message: err.message
94
- };
95
- if (typeof err.stack === "string") info.stack = err.stack.length > MAX_STACK_LENGTH ? err.stack.slice(0, MAX_STACK_LENGTH) : err.stack;
96
- if (err.cause !== void 0) info.cause = toErrorInfo(err.cause, depth + 1);
97
- return info;
98
- }
99
- if (typeof err === "string") return {
100
- name: "Error",
101
- message: err
102
- };
103
- if (err && typeof err === "object") {
104
- const record = err;
105
- return {
106
- name: typeof record.name === "string" ? record.name : "Error",
107
- message: typeof record.message === "string" ? record.message : safeStringify(err)
108
- };
109
- }
110
- return {
111
- name: "Error",
112
- message: safeStringify(err)
113
- };
114
- }
115
- function safeStringify(value) {
116
- if (value === null || value === void 0) return String(value);
117
- if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") return String(value);
118
- try {
119
- return JSON.stringify(value);
120
- } catch {
121
- return "[unserializable]";
122
- }
123
- }
124
- function fromErrorInfo(info) {
125
- const err = new Error(info.message);
126
- Object.defineProperty(err, "name", {
127
- value: info.name,
128
- configurable: true,
129
- writable: true
130
- });
131
- if (info.stack !== void 0) err.stack = info.stack;
132
- if (info.cause !== void 0) Object.defineProperty(err, "cause", {
133
- value: fromErrorInfo(info.cause),
134
- configurable: true,
135
- writable: true
136
- });
137
- return err;
138
- }
139
- //#endregion
140
- //#region src/rpc/paging.ts
141
- function isPageableResult(value) {
142
- return value !== null && typeof value === "object" && typeof value.next === "function";
143
- }
144
- function hasNextToken(value) {
145
- return value !== null && typeof value === "object" && typeof value.nextToken === "string";
146
- }
147
- function dehydratePage(value, registerCursor) {
148
- if (!isPageableResult(value)) return value;
149
- const { next, ...rest } = value;
150
- return {
151
- ...rest,
152
- nextToken: registerCursor(next)
153
- };
154
- }
155
- function rehydratePage(value, fetchPage) {
156
- if (!hasNextToken(value)) return value;
157
- const { nextToken, ...rest } = value;
158
- return {
159
- ...rest,
160
- next: () => fetchPage(nextToken)
161
- };
162
- }
163
- //#endregion
164
- //#region src/rpc/subscription.ts
165
- var SubscriptionStore = class {
166
- map = /* @__PURE__ */ new Map();
167
- set(id, unsubscribe) {
168
- this.map.set(id, unsubscribe);
169
- }
170
- get(id) {
171
- return this.map.get(id);
172
- }
173
- delete(id) {
174
- this.map.delete(id);
175
- }
176
- end(id) {
177
- const unsubscribe = this.map.get(id);
178
- if (unsubscribe) {
179
- this.map.delete(id);
180
- unsubscribe();
181
- }
182
- }
183
- drain() {
184
- for (const unsubscribe of this.map.values()) unsubscribe();
185
- this.map.clear();
186
- }
187
- };
188
- function createCorrelatedSubscriptions(router, config) {
189
- let counter = 0;
190
- const subs = /* @__PURE__ */ new Map();
191
- router.on(config.eventKind, (message) => {
192
- const sub = subs.get(message.id);
193
- if (sub) config.onEvent(sub, message);
194
- });
195
- router.on(config.errKind, (message) => {
196
- const id = message.id;
197
- const sub = subs.get(id);
198
- if (sub) {
199
- subs.delete(id);
200
- router.post(config.close(id));
201
- config.onError(sub, message);
202
- }
203
- });
204
- return { subscribe(sub, open) {
205
- const id = `${config.idPrefix}${++counter}`;
206
- subs.set(id, sub);
207
- router.post(open(id));
208
- return () => {
209
- subs.delete(id);
210
- router.post(config.close(id));
211
- };
212
- } };
213
- }
214
- //#endregion
215
- //#region src/rpc/client-proxy.ts
216
- function isAbortSignal(value) {
217
- return typeof value === "object" && value !== null && typeof value.aborted === "boolean" && typeof value.addEventListener === "function" && typeof value.removeEventListener === "function";
218
- }
219
- function createReactorClientProxy(router, options = {}) {
220
- const registry = options.registry;
221
- function fetchPage(token) {
222
- return router.request((id) => ({
223
- k: "page",
224
- id,
225
- token
226
- }), { transform: rehydrate });
227
- }
228
- function rehydrate(value) {
229
- return rehydratePage(value, fetchPage);
230
- }
231
- const changeSubs = createCorrelatedSubscriptions(router, {
232
- idPrefix: "sub",
233
- eventKind: "event",
234
- errKind: "sub-err",
235
- onEvent: (callback, msg) => callback(msg.change),
236
- onError: (_callback, msg) => console.error("Reactor subscription failed:", fromErrorInfo(msg.error)),
237
- close: (id) => ({
238
- k: "unsub",
239
- id
240
- })
241
- });
242
- router.on("reload", (msg) => {
243
- options.onReload?.(msg.reason, msg.workerGen);
244
- });
245
- const call = (method, args) => {
246
- let abortAt;
247
- for (let i = 0; i < args.length; i++) if (isAbortSignal(args[i])) abortAt = i;
248
- let wire = args;
249
- if (abortAt !== void 0) {
250
- wire = args.slice();
251
- wire[abortAt] = void 0;
252
- }
253
- return router.request((id) => ({
254
- k: "req",
255
- id,
256
- method,
257
- args: wire,
258
- abortAt
259
- }), {
260
- transform: rehydrate,
261
- setup: (id) => {
262
- if (abortAt === void 0) return;
263
- const signal = args[abortAt];
264
- const sendAbort = () => router.post({
265
- k: "abort",
266
- targetId: id
267
- });
268
- if (signal.aborted) {
269
- sendAbort();
270
- return;
271
- }
272
- signal.addEventListener("abort", sendAbort, { once: true });
273
- return () => signal.removeEventListener("abort", sendAbort);
274
- }
275
- });
276
- };
277
- const subscribe = (search, callback, view) => changeSubs.subscribe(callback, (id) => ({
278
- k: "sub",
279
- id,
280
- search,
281
- view
282
- }));
283
- const forwarders = /* @__PURE__ */ new Map();
284
- const forwarder = (method) => {
285
- let fn = forwarders.get(method);
286
- if (!fn) {
287
- fn = (...args) => call(method, args);
288
- forwarders.set(method, fn);
289
- }
290
- return fn;
291
- };
292
- const drives = new Proxy({}, { get: (_target, prop) => typeof prop === "string" ? forwarder(`drives.${prop}`) : void 0 });
293
- return new Proxy({}, { get(_target, prop) {
294
- if (typeof prop !== "string" || prop === "then") return;
295
- if (prop === "drives") return drives;
296
- if (prop === "subscribe") return subscribe;
297
- if (registry) {
298
- if (prop === "getDocumentModelModule") return (documentType) => Promise.resolve().then(() => registry.getModule(documentType));
299
- if (prop === "getDocumentModelModuleForDocument") return (document) => Promise.resolve().then(() => registry.getModule(document.header.documentType, normalizeDocumentModelVersion(document.state.document?.version)));
300
- if (prop === "getDocumentModelModules") return (_namespace, paging) => Promise.resolve({
301
- results: registry.getAllModules(),
302
- options: paging ?? {
303
- cursor: "",
304
- limit: Number.MAX_SAFE_INTEGER
305
- }
306
- });
307
- }
308
- return forwarder(prop);
309
- } });
310
- }
311
- //#endregion
312
47
  //#region src/rpc/inspector-proxy.ts
313
48
  function createInspectorProxy(router) {
314
49
  const ops = opChannel(router, "inspector-op");
@@ -318,6 +53,8 @@ function createInspectorProxy(router) {
318
53
  resumeQueue: () => ops.callVoid("queue.resume"),
319
54
  getProcessors: () => ops.call("processors.getAll"),
320
55
  retryProcessor: (processorId) => ops.callVoid("processors.retry", [processorId]),
56
+ getCatchUpStatus: () => ops.call("catchUp.status"),
57
+ sweepCatchUp: () => ops.call("catchUp.sweepNow"),
321
58
  validateDocument: (documentId, branch) => ops.call("integrity.validate", [documentId, branch]),
322
59
  rebuildKeyframes: (documentId, branch) => ops.call("integrity.rebuildKeyframes", [documentId, branch]),
323
60
  rebuildSnapshots: (documentId, branch) => ops.call("integrity.rebuildSnapshots", [documentId, branch]),
@@ -325,61 +62,14 @@ function createInspectorProxy(router) {
325
62
  };
326
63
  }
327
64
  //#endregion
328
- //#region src/rpc/protocol.ts
329
- const RPC_PROTOCOL_VERSION = 2;
330
- /** Error reply kind for a client message kind, so it reaches the right registry. */
331
- function responseErrorKind(k) {
332
- if (k === "sub") return "sub-err";
333
- if (k === "sub-live") return "live-err";
334
- return "err";
335
- }
336
- //#endregion
337
- //#region src/rpc/host-reply.ts
338
- const defaultOk = () => ({ ok: true });
339
- function hostResponder(transport) {
340
- const ok = (id, value = { ok: true }) => {
341
- transport.post({
342
- k: "res",
343
- id,
344
- value
345
- });
346
- };
347
- const err = (id, error) => {
348
- transport.post({
349
- k: "err",
350
- id,
351
- error: toErrorInfo(error)
352
- });
353
- };
354
- return {
355
- ok,
356
- err,
357
- errForKind(message, error) {
358
- if (!("id" in message)) return;
359
- transport.post({
360
- k: responseErrorKind(message.k),
361
- id: message.id,
362
- error: toErrorInfo(error)
363
- });
364
- },
365
- async run(id, body, mapOk = defaultOk) {
366
- try {
367
- ok(id, mapOk(await body()));
368
- } catch (error) {
369
- err(id, error);
370
- }
371
- }
372
- };
373
- }
374
- //#endregion
375
65
  //#region src/rpc/live-query-proxy.ts
376
66
  function createLiveQueryProxy(router) {
377
- const subs = createCorrelatedSubscriptions(router, {
67
+ const subs = createCorrelatedSubscriptions$1(router, {
378
68
  idPrefix: "live",
379
69
  eventKind: "event-live",
380
70
  errKind: "live-err",
381
71
  onEvent: (sub, msg) => sub.onResults(msg.results),
382
- onError: (sub, msg) => sub.onError?.(fromErrorInfo(msg.error)),
72
+ onError: (sub, msg) => sub.onError?.(fromErrorInfo$1(msg.error)),
383
73
  close: (id) => ({
384
74
  k: "unsub-live",
385
75
  id
@@ -470,7 +160,8 @@ function rehydrateMeta(wire) {
470
160
  collectionId: DriveCollectionId.forDrive(wire.collectionId.driveId, wire.collectionId.branch),
471
161
  channelConfig: wire.channelConfig,
472
162
  filter: wire.filter,
473
- options: wire.options
163
+ options: wire.options,
164
+ peer: wire.peer
474
165
  };
475
166
  }
476
167
  function channelUrl(meta) {
@@ -480,10 +171,11 @@ function channelUrl(meta) {
480
171
  var SyncManagerProxy = class {
481
172
  ops;
482
173
  connectionStates = /* @__PURE__ */ new Map();
483
- connectionListeners = new KeyedListeners();
174
+ connectionListeners = new KeyedListeners$1();
484
175
  syncStatuses = /* @__PURE__ */ new Map();
485
- syncStatusListeners = new Listeners();
176
+ syncStatusListeners = new Listeners$1();
486
177
  remotes = [];
178
+ basis;
487
179
  seedPromise = null;
488
180
  constructor(router, busProxy) {
489
181
  this.ops = opChannel(router, "sync-op");
@@ -499,16 +191,17 @@ var SyncManagerProxy = class {
499
191
  });
500
192
  this.ensureSeeded();
501
193
  }
502
- async startup() {
503
- let lastError;
504
- for (let attempt = 0; attempt < SEED_MAX_ATTEMPTS; attempt++) try {
194
+ /** Attempts that fail while `isWaiting()` (the worker waits on a store lock) are not counted. */
195
+ async startup({ isWaiting = () => false } = {}) {
196
+ let failures = 0;
197
+ for (;;) try {
505
198
  await this.ensureSeeded();
506
199
  return;
507
200
  } catch (error) {
508
- lastError = error;
509
- if (attempt < SEED_MAX_ATTEMPTS - 1) await new Promise((resolve) => setTimeout(resolve, SEED_RETRY_DELAY_MS));
201
+ if (!isWaiting()) failures++;
202
+ if (failures >= SEED_MAX_ATTEMPTS) throw error;
203
+ await new Promise((resolve) => setTimeout(resolve, SEED_RETRY_DELAY_MS));
510
204
  }
511
- throw lastError;
512
205
  }
513
206
  shutdown() {
514
207
  return {
@@ -537,6 +230,24 @@ var SyncManagerProxy = class {
537
230
  await this.refreshRemotes();
538
231
  return this.getByName(name);
539
232
  }
233
+ async setPeerManifest(id, manifest) {
234
+ await this.callSyncOp("setPeerManifest", [id, manifest]);
235
+ await this.refreshRemotes();
236
+ }
237
+ /** Fetched once; the worker's flags do not change at runtime. */
238
+ localManifest() {
239
+ return this.agreementBasis().local;
240
+ }
241
+ async listHolds(filter) {
242
+ return await this.callSyncOp("listHolds", [filter]);
243
+ }
244
+ agreement() {
245
+ return createPeerAgreement(this.agreementBasis(), this.remotes.map((remote) => remote.meta));
246
+ }
247
+ agreementBasis() {
248
+ if (!this.basis) throw new Error("Peer agreement has not been fetched from the worker yet");
249
+ return this.basis;
250
+ }
540
251
  async bindRemote(id, boundAddress) {
541
252
  await this.callSyncOp("bindRemote", [id, boundAddress]);
542
253
  await this.refreshRemotes();
@@ -591,6 +302,8 @@ var SyncManagerProxy = class {
591
302
  },
592
303
  notePoll: () => {},
593
304
  lastHolderPollUtcMs: () => void 0,
305
+ setLocalManifest: () => {},
306
+ onPeerManifest: () => () => {},
594
307
  config: { url }
595
308
  };
596
309
  }
@@ -610,6 +323,9 @@ var SyncManagerProxy = class {
610
323
  this.notifyConnection();
611
324
  }
612
325
  ensureSeeded() {
326
+ if (!this.basis) this.callSyncOp("peerAgreementBasis", []).then((basis) => {
327
+ this.basis = basis;
328
+ }).catch(() => {});
613
329
  if (!this.seedPromise) {
614
330
  const pending = this.refreshRemotes();
615
331
  this.seedPromise = pending;
@@ -639,7 +355,7 @@ const FORWARDED_BUS_EVENT_TYPES = [...FORWARDED_EVENT_TYPES, SYNC_STATUS_CHANGED
639
355
  /** Tab-side IEventBus over bus-event; emit() is unsupported (the worker emits). */
640
356
  var ReactorEventBusProxy = class {
641
357
  forwardedTypes = new Set(FORWARDED_BUS_EVENT_TYPES);
642
- subscribers = new KeyedListeners();
358
+ subscribers = new KeyedListeners$1();
643
359
  constructor(router) {
644
360
  router.on("bus-event", (msg) => {
645
361
  this.subscribers.emit(msg.eventType, msg.eventType, msg.event);
@@ -660,7 +376,7 @@ function createReactorEventBusProxy(router) {
660
376
  //#endregion
661
377
  //#region src/rpc/connect-reactor.ts
662
378
  function connectReactorClient(router, hello, onReload, registry) {
663
- const client = createReactorClientProxy(router, {
379
+ const client = createReactorClientProxy$1(router, {
664
380
  onReload,
665
381
  registry
666
382
  });
@@ -680,143 +396,6 @@ function postReactorIdentity(router, user) {
680
396
  });
681
397
  }
682
398
  //#endregion
683
- //#region src/rpc/host-server.ts
684
- const MAX_PENDING_PAGES = 1e3;
685
- var ReactorHostServer = class {
686
- client;
687
- transport;
688
- reply;
689
- aborters = /* @__PURE__ */ new Map();
690
- subscriptions = new SubscriptionStore();
691
- pages = /* @__PURE__ */ new Map();
692
- pageCounter = 0;
693
- detach = () => {};
694
- constructor(client, transport) {
695
- this.client = client;
696
- this.transport = transport;
697
- this.reply = hostResponder(transport);
698
- }
699
- start() {
700
- this.detach = this.transport.onMessage((message) => {
701
- this.handleMessage(message);
702
- });
703
- }
704
- stop() {
705
- this.detach();
706
- this.subscriptions.drain();
707
- this.aborters.clear();
708
- this.pages.clear();
709
- }
710
- async handleMessage(message) {
711
- try {
712
- switch (message.k) {
713
- case "req":
714
- await this.handleRequest(message);
715
- return;
716
- case "page":
717
- await this.handlePage(message);
718
- return;
719
- case "abort":
720
- this.aborters.get(message.targetId)?.abort();
721
- return;
722
- case "sub":
723
- this.handleSubscribe(message);
724
- return;
725
- case "unsub":
726
- this.subscriptions.end(message.id);
727
- return;
728
- }
729
- } catch (error) {
730
- this.reply.errForKind(message, error);
731
- }
732
- }
733
- async handleRequest(message) {
734
- let args = message.args;
735
- let controller;
736
- if (message.abortAt !== void 0) {
737
- controller = new AbortController();
738
- this.aborters.set(message.id, controller);
739
- args = message.args.slice();
740
- args[message.abortAt] = controller.signal;
741
- }
742
- try {
743
- const value = await this.resolveMethod(message.method)(...args);
744
- this.reply.ok(message.id, this.prepareResult(value));
745
- } catch (error) {
746
- this.reply.err(message.id, error);
747
- } finally {
748
- if (controller) this.aborters.delete(message.id);
749
- }
750
- }
751
- async handlePage(message) {
752
- const next = this.pages.get(message.token);
753
- this.pages.delete(message.token);
754
- if (!next) {
755
- this.reply.err(message.id, /* @__PURE__ */ new Error("Paged cursor already consumed or expired"));
756
- return;
757
- }
758
- try {
759
- const value = await next();
760
- this.reply.ok(message.id, this.prepareResult(value));
761
- } catch (error) {
762
- this.reply.err(message.id, error);
763
- }
764
- }
765
- handleSubscribe(message) {
766
- const unsubscribe = this.client.subscribe(message.search, (change) => this.transport.post({
767
- k: "event",
768
- id: message.id,
769
- change
770
- }), message.view);
771
- this.subscriptions.set(message.id, unsubscribe);
772
- }
773
- prepareResult(value) {
774
- return dehydratePage(value, (next) => {
775
- const token = `p${++this.pageCounter}`;
776
- this.pages.set(token, next);
777
- if (this.pages.size > MAX_PENDING_PAGES) {
778
- const oldest = this.pages.keys().next().value;
779
- if (oldest !== void 0) this.pages.delete(oldest);
780
- }
781
- return token;
782
- });
783
- }
784
- resolveMethod(path) {
785
- if (path.startsWith("drives.")) {
786
- const name = path.slice(7);
787
- const fn = this.client.drives[name];
788
- if (typeof fn !== "function") throw new Error(`Unknown drive method: ${name}`);
789
- return fn.bind(this.client.drives);
790
- }
791
- const fn = this.client[path];
792
- if (typeof fn !== "function") throw new Error(`Unknown reactor method: ${path}`);
793
- return fn.bind(this.client);
794
- }
795
- };
796
- //#endregion
797
- //#region src/rpc/transport.ts
798
- function createPortTransport(port) {
799
- port.start();
800
- port.addEventListener("messageerror", (event) => {
801
- console.error("[rpc transport] failed to deserialize message", event);
802
- });
803
- return {
804
- post(message) {
805
- port.postMessage(message);
806
- },
807
- onMessage(listener) {
808
- const handler = (event) => {
809
- listener(event.data);
810
- };
811
- port.addEventListener("message", handler);
812
- return () => port.removeEventListener("message", handler);
813
- },
814
- close() {
815
- port.close();
816
- }
817
- };
818
- }
819
- //#endregion
820
399
  //#region src/rpc/reactor-host.ts
821
400
  function isDataMessage(msg) {
822
401
  return msg.k === "req" || msg.k === "sub" || msg.k === "page" || msg.k === "sync-op" || msg.k === "db-op" || msg.k === "inspector-op" || msg.k === "sub-live";
@@ -829,25 +408,38 @@ function workerGenForVersion(version) {
829
408
  const suffix = flags === "" ? "" : `-${hashFlags(flags)}`;
830
409
  return `v${version.rpcProtocolVersion}-${version.appBuildId}${suffix}`;
831
410
  }
411
+ const VERSION_MISMATCH = "reactor version mismatch";
412
+ const FLAGS_CHANGED = "reactor enforcement flags changed";
413
+ /** Whether a reload reason comes from a build fingerprint mismatch. */
414
+ function isFingerprintMismatchReload(reason) {
415
+ return reason === VERSION_MISMATCH || reason.startsWith(FLAGS_CHANGED);
416
+ }
832
417
  /** Names what differs, so a reload is diagnosable from the tab's console. */
833
418
  function mismatchReason(baseline, incoming) {
834
- if ((baseline.featureFlags ?? "") !== (incoming.featureFlags ?? "")) return `reactor enforcement flags changed (worker: ${baseline.featureFlags || "none"}, tab: ${incoming.featureFlags || "none"})`;
835
- return "reactor version mismatch";
419
+ if ((baseline.featureFlags ?? "") !== (incoming.featureFlags ?? "")) return `${FLAGS_CHANGED} (worker: ${baseline.featureFlags || "none"}, tab: ${incoming.featureFlags || "none"})`;
420
+ return VERSION_MISMATCH;
836
421
  }
837
422
  function hashFlags(flags) {
838
423
  let hash = 0;
839
424
  for (let i = 0; i < flags.length; i++) hash = hash * 31 + flags.charCodeAt(i) | 0;
840
425
  return (hash >>> 0).toString(36);
841
426
  }
427
+ const RETIRED_WORKER_RELOAD_REASON = "worker retired";
428
+ function retiredError() {
429
+ return /* @__PURE__ */ new Error("This worker was retired; reloading into the current one");
430
+ }
842
431
  var ReactorHost = class {
843
432
  options;
844
433
  disposers = /* @__PURE__ */ new Set();
845
434
  clients = /* @__PURE__ */ new Set();
846
435
  clientPromise = null;
436
+ buildFailure = null;
847
437
  baseline = null;
848
438
  ownerId;
849
439
  bootedAtMs;
850
440
  migrationState = null;
441
+ retirement = null;
442
+ reloadSent = false;
851
443
  constructor(options) {
852
444
  this.options = options;
853
445
  this.ownerId = options.ownerId ?? crypto.randomUUID();
@@ -858,11 +450,12 @@ var ReactorHost = class {
858
450
  let server = null;
859
451
  let ready = false;
860
452
  const buffer = [];
861
- const liveSubs = new SubscriptionStore();
862
- const reply = hostResponder(transport);
453
+ const liveSubs = new SubscriptionStore$1();
454
+ const reply = hostResponder$1(transport);
863
455
  const ensureServer = async (construct) => {
864
456
  if (server) return;
865
- server = new ReactorHostServer(await this.resolveClient(construct), transport);
457
+ const client = await this.resolveClient(construct);
458
+ server = new ReactorHostServer$1(client, transport);
866
459
  };
867
460
  const drainBuffer = async () => {
868
461
  while (buffer.length > 0) {
@@ -886,6 +479,10 @@ var ReactorHost = class {
886
479
  reply.errForKind(msg, /* @__PURE__ */ new Error("migration in progress"));
887
480
  return;
888
481
  }
482
+ if (this.retirement && isDataMessage(msg)) {
483
+ reply.errForKind(msg, retiredError());
484
+ return;
485
+ }
889
486
  if (msg.k === "hello") {
890
487
  this.handleHello(msg, transport, reply, ensureServer, drainBuffer);
891
488
  return;
@@ -923,7 +520,7 @@ var ReactorHost = class {
923
520
  return;
924
521
  }
925
522
  if (msg.k === "admin") {
926
- this.handleAdmin(msg, reply);
523
+ this.handleAdmin(msg, reply, transport);
927
524
  return;
928
525
  }
929
526
  if (ready && server) server.handleMessage(msg);
@@ -934,6 +531,10 @@ var ReactorHost = class {
934
531
  k: "migration",
935
532
  state: this.migrationState
936
533
  });
534
+ if (this.retirement && this.reloadSent) transport.post({
535
+ k: "reload",
536
+ ...this.retirement
537
+ });
937
538
  if (this.options.client) ensureServer().then(drainBuffer).catch((error) => {
938
539
  console.error("ReactorHost buffer drain failed", error);
939
540
  });
@@ -948,7 +549,7 @@ var ReactorHost = class {
948
549
  return dispose;
949
550
  }
950
551
  connectPort(port) {
951
- return this.connect(createPortTransport(port));
552
+ return this.connect(createPortTransport$1(port));
952
553
  }
953
554
  broadcastBusEvent(eventType, event) {
954
555
  for (const transport of this.clients) transport.post({
@@ -964,6 +565,37 @@ var ReactorHost = class {
964
565
  workerGen
965
566
  });
966
567
  }
568
+ retireAndReload(reason, workerGen) {
569
+ if (this.retirement) return;
570
+ this.retirement = {
571
+ reason,
572
+ workerGen
573
+ };
574
+ const drain = this.options.drainBeforeReload;
575
+ if (!drain || !isFingerprintMismatchReload(reason)) {
576
+ this.sendReload(reason, workerGen);
577
+ return;
578
+ }
579
+ this.drainThenReload(drain, reason, workerGen);
580
+ }
581
+ async drainThenReload(drain, reason, workerGen) {
582
+ try {
583
+ await drain();
584
+ } catch (error) {
585
+ console.error("ReactorHost drain before reload failed", error);
586
+ }
587
+ this.sendReload(reason, workerGen);
588
+ }
589
+ sendReload(reason, workerGen) {
590
+ this.reloadSent = true;
591
+ this.broadcastReload(reason, workerGen);
592
+ this.stopRetired(reason);
593
+ }
594
+ stopRetired(reason) {
595
+ this.options.onRetire?.(reason).catch((error) => {
596
+ console.error("ReactorHost retirement cleanup failed", error);
597
+ });
598
+ }
967
599
  setMigrationState(state) {
968
600
  this.migrationState = state;
969
601
  for (const transport of this.clients) transport.post({
@@ -971,10 +603,22 @@ var ReactorHost = class {
971
603
  state
972
604
  });
973
605
  }
606
+ get retired() {
607
+ return this.retirement !== null;
608
+ }
974
609
  get connectionCount() {
975
610
  return this.disposers.size;
976
611
  }
977
- handleAdmin(message, reply) {
612
+ handleAdmin(message, reply, transport) {
613
+ if (this.retirement && message.method !== "info") {
614
+ if (this.reloadSent) transport.post({
615
+ k: "reload",
616
+ reason: RETIRED_WORKER_RELOAD_REASON,
617
+ workerGen: this.retirement.workerGen
618
+ });
619
+ reply.err(message.id, retiredError());
620
+ return;
621
+ }
978
622
  if (message.method === "restart") {
979
623
  this.options.onAdminRestart?.();
980
624
  reply.ok(message.id);
@@ -994,7 +638,7 @@ var ReactorHost = class {
994
638
  bootedAtMs: this.bootedAtMs,
995
639
  connectedClients: this.connectionCount,
996
640
  appBuildId: this.baseline?.appBuildId ?? this.options.appBuildId ?? "unknown",
997
- rpcProtocolVersion: this.baseline?.rpcProtocolVersion ?? 2,
641
+ rpcProtocolVersion: this.baseline?.rpcProtocolVersion ?? RPC_PROTOCOL_VERSION$1,
998
642
  featureFlags: this.baseline?.featureFlags ?? ""
999
643
  };
1000
644
  reply.ok(message.id, info);
@@ -1005,19 +649,31 @@ var ReactorHost = class {
1005
649
  });
1006
650
  }
1007
651
  resolveClient(construct) {
652
+ if (this.retirement) return Promise.reject(retiredError());
1008
653
  if (!this.clientPromise) {
1009
654
  const build = this.options.build;
1010
655
  if (!build) return Promise.reject(/* @__PURE__ */ new Error("ReactorHost has no client or builder"));
1011
656
  const pending = build(construct);
1012
657
  this.clientPromise = pending;
1013
- pending.catch(() => {
1014
- if (this.clientPromise === pending) this.clientPromise = null;
658
+ this.buildFailure = null;
659
+ pending.then(() => {
660
+ if (this.retirement && this.reloadSent) this.stopRetired(this.retirement.reason);
661
+ }, () => void 0);
662
+ pending.catch((error) => {
663
+ if (this.clientPromise === pending) {
664
+ this.clientPromise = null;
665
+ this.buildFailure = { error };
666
+ }
1015
667
  });
1016
668
  }
1017
669
  return this.clientPromise;
1018
670
  }
1019
671
  async awaitClientReady() {
1020
- if (this.clientPromise) await this.clientPromise;
672
+ if (this.clientPromise) {
673
+ await this.clientPromise;
674
+ return;
675
+ }
676
+ if (this.buildFailure) throw this.buildFailure.error;
1021
677
  }
1022
678
  requireHandler(handler, message, reply, label) {
1023
679
  if (handler) return true;
@@ -1027,11 +683,7 @@ var ReactorHost = class {
1027
683
  async handleHello(message, transport, reply, ensureServer, drainBuffer) {
1028
684
  if (this.baseline) {
1029
685
  if (!versionsCompatible(this.baseline, message.version)) {
1030
- transport.post({
1031
- k: "reload",
1032
- reason: mismatchReason(this.baseline, message.version),
1033
- workerGen: workerGenForVersion(message.version)
1034
- });
686
+ this.retireAndReload(mismatchReason(this.baseline, message.version), `${workerGenForVersion(message.version)}-${this.ownerId.slice(0, 8)}`);
1035
687
  reply.ok(message.id, { ok: false });
1036
688
  return;
1037
689
  }
@@ -1044,7 +696,7 @@ var ReactorHost = class {
1044
696
  }
1045
697
  async handleRegister(message, reply) {
1046
698
  await reply.run(message.id, async () => {
1047
- await this.options.registerPackages?.(message.specs);
699
+ await this.options.registerPackages?.(message.specs, message.sources);
1048
700
  });
1049
701
  }
1050
702
  async handleUnregister(message, reply) {
@@ -1086,9 +738,11 @@ var ReactorHost = class {
1086
738
  };
1087
739
  //#endregion
1088
740
  //#region src/rpc/worker-package-loader.ts
1089
- function packageName(spec) {
1090
- const at = spec.lastIndexOf("@");
1091
- return at > 0 ? spec.slice(0, at) : spec;
741
+ const SOURCE_KEY_PREFIX = "src:";
742
+ function packageName(key) {
743
+ if (key.startsWith(SOURCE_KEY_PREFIX)) return key.slice(4);
744
+ const at = key.lastIndexOf("@");
745
+ return at > 0 ? key.slice(0, at) : key;
1092
746
  }
1093
747
  function moduleKey(module) {
1094
748
  return `${module.documentModel.global.id}@${module.version ?? 1}`;
@@ -1098,16 +752,44 @@ function isDocumentModelModule(value) {
1098
752
  const candidate = value;
1099
753
  return typeof candidate.reducer === "function" && typeof candidate.documentModel?.global?.id === "string";
1100
754
  }
755
+ function isUpgradeManifest(value) {
756
+ if (typeof value !== "object" || value === null) return false;
757
+ const candidate = value;
758
+ return typeof candidate.documentType === "string" && typeof candidate.upgrades === "object" && candidate.upgrades !== null;
759
+ }
760
+ function manifestsOf(namespace) {
761
+ const out = [];
762
+ for (const value of Object.values(namespace)) {
763
+ if (isUpgradeManifest(value)) {
764
+ out.push(value);
765
+ continue;
766
+ }
767
+ if (Array.isArray(value)) {
768
+ for (const inner of value) if (isUpgradeManifest(inner)) out.push(inner);
769
+ }
770
+ }
771
+ return out;
772
+ }
1101
773
  var WorkerPackageLoader = class {
1102
774
  cdnUrl;
1103
775
  importPackage;
1104
776
  resolvePackages;
777
+ sharedImports;
778
+ importSource;
1105
779
  modulesByKey = /* @__PURE__ */ new Map();
780
+ manifestsByType = /* @__PURE__ */ new Map();
781
+ keysBySource = /* @__PURE__ */ new Map();
782
+ manifestTypesBySource = /* @__PURE__ */ new Map();
1106
783
  loadedSpecs = /* @__PURE__ */ new Set();
1107
784
  failures = [];
785
+ pendingLoads = /* @__PURE__ */ new Map();
786
+ generationBySource = /* @__PURE__ */ new Map();
787
+ generation = 0;
1108
788
  constructor(options) {
1109
789
  this.cdnUrl = options.cdnUrl.replace(/\/$/, "");
1110
790
  this.importPackage = options.importPackage;
791
+ this.sharedImports = options.sharedImports;
792
+ this.importSource = options.importSource;
1111
793
  const registryClient = new RegistryClient(options.cdnUrl);
1112
794
  this.resolvePackages = options.resolvePackages ?? ((documentType) => registryClient.getPackagesByDocumentType(documentType));
1113
795
  }
@@ -1115,6 +797,29 @@ var WorkerPackageLoader = class {
1115
797
  await Promise.all([...new Set(specs)].map((spec) => this.loadPackage(spec)));
1116
798
  return this.models;
1117
799
  }
800
+ /** Loads URL-addressed packages (local project packages). Idempotent. */
801
+ async loadSources(sources) {
802
+ await Promise.all(sources.map((source) => this.loadFromUrl(sourceKey(source), source.url)));
803
+ }
804
+ /**
805
+ * Replaces previously loaded sources with freshly imported ones (a vetra
806
+ * watch rebuild re-sends the same source under a cache-busted URL). Returns
807
+ * every document type touched - removed, re-added, or new - so the caller
808
+ * can replace the registry's version families. A source whose import fails
809
+ * keeps its previous modules and is reported in `failures`; one superseded
810
+ * by a newer reload of the same source contributes nothing.
811
+ */
812
+ async reloadSources(sources) {
813
+ const results = await Promise.all(sources.map((source) => this.replaceSource(sourceKey(source), source.url)));
814
+ const types = /* @__PURE__ */ new Set();
815
+ const failures = [];
816
+ for (const result of results) if (result.status === "replaced") for (const type of result.types) types.add(type);
817
+ else if (result.status === "failed") failures.push(result.failure);
818
+ return {
819
+ types: [...types],
820
+ failures
821
+ };
822
+ }
1118
823
  async load(documentType) {
1119
824
  const existing = this.latestForType(documentType);
1120
825
  if (existing) return existing;
@@ -1128,6 +833,9 @@ var WorkerPackageLoader = class {
1128
833
  get models() {
1129
834
  return [...new Set(this.modulesByKey.values())];
1130
835
  }
836
+ get upgradeManifests() {
837
+ return [...this.manifestsByType.values()];
838
+ }
1131
839
  get loadFailures() {
1132
840
  return [...this.failures];
1133
841
  }
@@ -1147,137 +855,86 @@ var WorkerPackageLoader = class {
1147
855
  return new Error(`Failed to import package(s) [${packageNames.join(", ")}] for document model: ${documentType}`, { cause });
1148
856
  }
1149
857
  async loadPackage(spec) {
1150
- if (this.loadedSpecs.has(spec)) return;
1151
858
  const name = packageName(spec);
1152
859
  const url = `${this.cdnUrl}/${name}/browser/document-models/index.js`;
860
+ await this.loadFromUrl(spec, url);
861
+ }
862
+ loadFromUrl(key, url) {
863
+ if (this.loadedSpecs.has(key)) return Promise.resolve();
864
+ let pending = this.pendingLoads.get(key);
865
+ if (!pending) {
866
+ pending = this.replaceSource(key, url).finally(() => this.pendingLoads.delete(key)).then(() => void 0);
867
+ this.pendingLoads.set(key, pending);
868
+ }
869
+ return pending;
870
+ }
871
+ async replaceSource(key, url) {
872
+ const generation = ++this.generation;
873
+ this.generationBySource.set(key, generation);
874
+ let namespace;
1153
875
  try {
1154
- const namespace = await this.importPackage(url);
1155
- for (const value of Object.values(namespace)) if (isDocumentModelModule(value)) this.modulesByKey.set(moduleKey(value), value);
1156
- this.loadedSpecs.add(spec);
876
+ namespace = await this.importNamespace(url);
1157
877
  } catch (error) {
1158
- this.failures.push({
1159
- name,
878
+ if (this.generationBySource.get(key) !== generation) return { status: "stale" };
879
+ const failure = {
880
+ name: packageName(key),
1160
881
  url,
1161
882
  error
1162
- });
883
+ };
884
+ this.failures.push(failure);
885
+ return {
886
+ status: "failed",
887
+ failure
888
+ };
1163
889
  }
1164
- }
1165
- };
1166
- //#endregion
1167
- //#region src/rpc/rpc-correlator.ts
1168
- /**
1169
- * Request/response correlation shared by every RPC proxy: one pending map,
1170
- * res/err settlement, and per-request timeout/transform/cleanup.
1171
- */
1172
- var RpcCorrelator = class {
1173
- counter = 0;
1174
- pending = /* @__PURE__ */ new Map();
1175
- constructor(poster, prefix = "r") {
1176
- this.poster = poster;
1177
- this.prefix = prefix;
1178
- }
1179
- nextId() {
1180
- return `${this.prefix}${++this.counter}`;
1181
- }
1182
- /** Settle the pending request a res/err refers to; a missing id is a no-op. */
1183
- handleMessage(message) {
1184
- if (message.k !== "res" && message.k !== "err") return;
1185
- const entry = this.pending.get(message.id);
1186
- if (!entry) return;
1187
- this.pending.delete(message.id);
1188
- if (entry.timer) clearTimeout(entry.timer);
1189
- entry.cleanup?.();
1190
- if (message.k === "res") entry.resolve(entry.transform ? entry.transform(message.value) : message.value);
1191
- else entry.reject(fromErrorInfo(message.error));
1192
- }
1193
- /** Send a request, resolving on its res/err. `build` stamps the generated id. */
1194
- request(build, options = {}) {
1195
- const id = this.nextId();
1196
- const message = build(id);
1197
- const method = message.method;
1198
- const label = typeof method === "string" ? `${message.k} "${method}"` : message.k;
1199
- const promise = new Promise((resolve, reject) => {
1200
- let timer;
1201
- if (options.timeoutMs !== void 0) {
1202
- const timeoutMs = options.timeoutMs;
1203
- timer = setTimeout(() => {
1204
- const entry = this.pending.get(id);
1205
- if (entry) {
1206
- this.pending.delete(id);
1207
- entry.cleanup?.();
1208
- reject(/* @__PURE__ */ new Error(`Reactor worker did not respond to ${label} within ${timeoutMs}ms; the worker may have failed to load`));
1209
- }
1210
- }, timeoutMs);
1211
- }
1212
- this.pending.set(id, {
1213
- resolve,
1214
- reject,
1215
- timer,
1216
- transform: options.transform
1217
- });
1218
- });
1219
- this.poster.post(message);
1220
- const cleanup = options.setup?.(id);
1221
- if (cleanup) {
1222
- const entry = this.pending.get(id);
1223
- if (entry) entry.cleanup = cleanup;
1224
- else cleanup();
890
+ if (this.generationBySource.get(key) !== generation) return { status: "stale" };
891
+ const types = /* @__PURE__ */ new Set();
892
+ for (const removedKey of this.keysBySource.get(key) ?? []) {
893
+ const removed = this.modulesByKey.get(removedKey);
894
+ if (removed) types.add(removed.documentModel.global.id);
895
+ this.modulesByKey.delete(removedKey);
1225
896
  }
1226
- return promise;
1227
- }
1228
- };
1229
- //#endregion
1230
- //#region src/rpc/message-router.ts
1231
- /**
1232
- * Owns the single transport.onMessage and dispatches each message to the one
1233
- * consumer that owns its kind. Composes the shared RpcCorrelator (res/err) and
1234
- * exposes request/nextId; attach/detach swap the transport for reconnect.
1235
- */
1236
- var MessageRouter = class {
1237
- handlers = /* @__PURE__ */ new Map();
1238
- correlator;
1239
- transport = null;
1240
- detachTransport = () => {};
1241
- constructor(prefix = "r") {
1242
- this.correlator = new RpcCorrelator(this, prefix);
1243
- const settle = (message) => this.correlator.handleMessage(message);
1244
- this.handlers.set("res", settle);
1245
- this.handlers.set("err", settle);
1246
- }
1247
- attach(transport) {
1248
- this.detachTransport();
1249
- this.transport = transport;
1250
- this.detachTransport = transport.onMessage((message) => {
1251
- const msg = message;
1252
- this.handlers.get(msg.k)?.(msg);
1253
- });
1254
- }
1255
- detach() {
1256
- this.detachTransport();
1257
- this.detachTransport = () => {};
1258
- this.transport = null;
1259
- }
1260
- post(message) {
1261
- if (!this.transport) throw new Error("MessageRouter.post called before attach");
1262
- this.transport.post(message);
1263
- }
1264
- /** Register the sole owner of a message kind; throws on a duplicate. */
1265
- on(kind, handler) {
1266
- if (this.handlers.has(kind)) throw new Error(`MessageRouter already has a handler for "${kind}"`);
1267
- const route = handler;
1268
- this.handlers.set(kind, route);
1269
- return () => {
1270
- if (this.handlers.get(kind) === route) this.handlers.delete(kind);
897
+ for (const type of this.manifestTypesBySource.get(key) ?? []) this.manifestsByType.delete(type);
898
+ for (const added of this.registerNamespace(key, namespace)) types.add(added);
899
+ this.loadedSpecs.add(key);
900
+ return {
901
+ status: "replaced",
902
+ types
1271
903
  };
1272
904
  }
1273
- request(build, options) {
1274
- return this.correlator.request(build, options);
1275
- }
1276
- nextId() {
1277
- return this.correlator.nextId();
905
+ async importNamespace(url) {
906
+ const source = this.sharedImports !== void 0 && Object.keys(this.sharedImports).length > 0 ? await (await fetch(url)).text() : void 0;
907
+ const rewritten = source !== void 0 ? rewritePackageSource(source, url, this.sharedImports) : source;
908
+ if (rewritten !== void 0 && rewritten !== source) {
909
+ if (!this.importSource) throw new Error("importSource is required to load a package that imports shared deps");
910
+ return this.importSource(rewritten);
911
+ }
912
+ return this.importPackage(url);
913
+ }
914
+ /** Registers a namespace as the key's whole contribution; returns its module types. */
915
+ registerNamespace(key, namespace) {
916
+ const keys = /* @__PURE__ */ new Set();
917
+ const manifestTypes = /* @__PURE__ */ new Set();
918
+ const types = /* @__PURE__ */ new Set();
919
+ for (const value of Object.values(namespace)) if (isDocumentModelModule(value)) {
920
+ const k = moduleKey(value);
921
+ this.modulesByKey.set(k, value);
922
+ keys.add(k);
923
+ types.add(value.documentModel.global.id);
924
+ }
925
+ for (const manifest of manifestsOf(namespace)) {
926
+ this.manifestsByType.set(manifest.documentType, manifest);
927
+ manifestTypes.add(manifest.documentType);
928
+ }
929
+ this.keysBySource.set(key, keys);
930
+ this.manifestTypesBySource.set(key, manifestTypes);
931
+ return types;
1278
932
  }
1279
933
  };
934
+ function sourceKey(source) {
935
+ return `${SOURCE_KEY_PREFIX}${source.name}`;
936
+ }
1280
937
  //#endregion
1281
- export { FORWARDED_BUS_EVENT_TYPES, FORWARDED_EVENT_TYPES, KeyedListeners, Listeners, MessageRouter, RPC_DEFAULT_TIMEOUT_MS, RPC_PROTOCOL_VERSION, ReactorEventBusProxy, ReactorHost, ReactorHostServer, RpcCorrelator, SYNC_STATUS_CHANGED_EVENT, SubscriptionStore, SyncManagerProxy, WorkerPackageLoader, connectReactorClient, createCorrelatedSubscriptions, createInspectorProxy, createLiveQueryProxy, createPortTransport, createReactorClientProxy, createReactorEventBusProxy, createRelationalPgliteProxy, createSyncManagerProxy, createWorkerAdminClient, fromErrorInfo, hostResponder, opChannel, postReactorIdentity, toErrorInfo, toVoid };
938
+ export { FORWARDED_BUS_EVENT_TYPES, FORWARDED_EVENT_TYPES, KeyedListeners, Listeners, MessageRouter, RETIRED_WORKER_RELOAD_REASON, RPC_DEFAULT_TIMEOUT_MS, RPC_PROTOCOL_VERSION, ReactorEventBusProxy, ReactorHost, ReactorHostServer, RpcCorrelator, SYNC_STATUS_CHANGED_EVENT, SubscriptionStore, SyncManagerProxy, WorkerPackageLoader, connectReactorClient, createCorrelatedSubscriptions, createInspectorProxy, createLiveQueryProxy, createPortTransport, createReactorClientProxy, createReactorEventBusProxy, createRelationalPgliteProxy, createSyncManagerProxy, createWorkerAdminClient, fromErrorInfo, hostResponder, isFingerprintMismatchReload, opChannel, postReactorIdentity, toErrorInfo, toVoid };
1282
939
 
1283
940
  //# sourceMappingURL=index.js.map