@graview/ship 0.1.2 → 0.1.4

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 (46) hide show
  1. package/README.md +312 -13
  2. package/dist/browser.d.ts +4 -4
  3. package/dist/browser.d.ts.map +1 -1
  4. package/dist/browser.js +2 -2
  5. package/dist/browser.js.map +1 -1
  6. package/dist/handler.d.ts +192 -26
  7. package/dist/handler.d.ts.map +1 -1
  8. package/dist/handler.js +383 -340
  9. package/dist/handler.js.map +1 -1
  10. package/dist/health.d.ts +12 -1
  11. package/dist/health.d.ts.map +1 -1
  12. package/dist/health.js +15 -4
  13. package/dist/health.js.map +1 -1
  14. package/dist/index.d.ts +7 -5
  15. package/dist/index.d.ts.map +1 -1
  16. package/dist/index.js +3 -2
  17. package/dist/index.js.map +1 -1
  18. package/dist/live-protocol.d.ts +451 -0
  19. package/dist/live-protocol.d.ts.map +1 -0
  20. package/dist/live-protocol.js +957 -0
  21. package/dist/live-protocol.js.map +1 -0
  22. package/dist/live.d.ts +156 -9
  23. package/dist/live.d.ts.map +1 -1
  24. package/dist/live.js +31 -1
  25. package/dist/live.js.map +1 -1
  26. package/dist/remote.d.ts +180 -5
  27. package/dist/remote.d.ts.map +1 -1
  28. package/dist/remote.js +793 -76
  29. package/dist/remote.js.map +1 -1
  30. package/dist/runtime.d.ts +7 -5
  31. package/dist/runtime.d.ts.map +1 -1
  32. package/dist/runtime.js +3 -2
  33. package/dist/runtime.js.map +1 -1
  34. package/dist/seat-headers.d.ts +6 -0
  35. package/dist/seat-headers.d.ts.map +1 -1
  36. package/dist/seat-headers.js +6 -0
  37. package/dist/seat-headers.js.map +1 -1
  38. package/dist/serve.d.ts +5 -3
  39. package/dist/serve.d.ts.map +1 -1
  40. package/dist/serve.js +18 -4
  41. package/dist/serve.js.map +1 -1
  42. package/dist/websocket.d.ts +1 -1
  43. package/dist/websocket.d.ts.map +1 -1
  44. package/dist/websocket.js +10 -2
  45. package/dist/websocket.js.map +1 -1
  46. package/package.json +3 -3
package/dist/remote.js CHANGED
@@ -1,6 +1,46 @@
1
- import { FieldRevisions, foldPresence, PRESENCE_TTL_MS, REMOTE_PRESENCE_TTL_MS, samePresence, Store, WIRE_PROTOCOL, writtenBy, } from "@graview/core";
2
- import { LIVE_PATH } from "./live.js";
1
+ import { FieldRevisions, foldPresence, ReceiveError, refusalOf, REMOTE_PRESENCE_TTL_MS, samePresence, Store, WIRE_PROTOCOL, writtenBy, } from "@graview/core";
2
+ import { LIVE_PATH, LIVE_SUBPROTOCOL, LIVE_WIRE } from "./live.js";
3
3
  import { SEAT_HEADERS } from "./seat-headers.js";
4
+ /** A call this client let go of for a new declaration or a reload: not refused, so nothing is taken back or said. */
5
+ class Superseded extends Error {
6
+ constructor(message) {
7
+ super(message);
8
+ this.name = "Superseded";
9
+ }
10
+ }
11
+ /** "rename (Version 2 has no …)": a call that no longer fits, named in a sentence. */
12
+ const named = (carried, error) => `${carried.calls.map((call) => call.name.replace(/-/g, " ")).join(", ")} (${error instanceof Error ? (error.message.split("\n")[0] ?? "") : String(error)})`;
13
+ /** Calls kept across a reload, as the next page reads them: read once, then forgotten. */
14
+ function takeCarried(carry) {
15
+ if (!carry)
16
+ return [];
17
+ try {
18
+ const raw = carry.storage.getItem(carry.key);
19
+ if (raw === null)
20
+ return [];
21
+ carry.storage.removeItem(carry.key);
22
+ const parsed = JSON.parse(raw);
23
+ return Array.isArray(parsed) ? parsed.filter((one) => !!one && Array.isArray(one.calls)) : [];
24
+ }
25
+ catch {
26
+ return [];
27
+ }
28
+ }
29
+ /**
30
+ * WHAT `send` THROWS, AND WHAT A TAKEN-BACK CHANGE WAS REFUSED WITH: the
31
+ * server's sentence as the message, and `refusal` for a program to branch
32
+ * on (FR-46).
33
+ */
34
+ export class RemoteRefusedError extends Error {
35
+ refusal;
36
+ constructor(refusal) {
37
+ super(refusal.sentence);
38
+ this.refusal = refusal;
39
+ this.name = "RemoteRefusedError";
40
+ }
41
+ }
42
+ /** A server before FR-46 says no reason: read one from the status it answered with. */
43
+ const REASON_BY_STATUS = { 401: "forbidden", 403: "forbidden", 404: "missing", 413: "limit" };
4
44
  /** A refusal that is a stale write: the server's sentence, and the fields that moved. */
5
45
  class StaleWrite extends Error {
6
46
  conflicts;
@@ -10,6 +50,24 @@ class StaleWrite extends Error {
10
50
  this.name = "StaleWrite";
11
51
  }
12
52
  }
53
+ /** A request that never reached the server: the network refused it, or a gateway said the server is away. */
54
+ class Unreached extends Error {
55
+ constructor(message) {
56
+ super(message);
57
+ this.name = "Unreached";
58
+ }
59
+ }
60
+ /** What a gateway in front of a server says when the server behind it is not there. */
61
+ const AWAY = new Set([502, 503, 504]);
62
+ /** A 503 that is the host saying it takes no changes for a while (reason `unavailable`), not a gateway saying it is away. */
63
+ async function unavailableSaid(response) {
64
+ try {
65
+ return (await response.clone().json()).reason === "unavailable";
66
+ }
67
+ catch {
68
+ return false;
69
+ }
70
+ }
13
71
  /**
14
72
  * Opens a store from a server and keeps it in step with it.
15
73
  *
@@ -24,24 +82,105 @@ function localIds() {
24
82
  return () => `local-${who}-${++at}`;
25
83
  }
26
84
  const OPEN = 1;
85
+ const freshWiring = () => ({
86
+ refusals: new Set(),
87
+ conflicts: new Set(),
88
+ statuses: new Set(),
89
+ builds: new Set(),
90
+ who: new Set(),
91
+ declarations: new Set(),
92
+ tally: { reconnects: 0, rebases: 0, conflicts: 0, resyncs: 0 },
93
+ });
27
94
  export async function openRemote(options) {
95
+ return (await opening(options, takeCarried(options.carry), "This app was updated while your changes were on the way.", freshWiring())).remote;
96
+ }
97
+ /**
98
+ * The remote store, and what the store it replaces needs from it: the
99
+ * sentences about carried calls nobody has heard yet, for it to tell
100
+ * when the new store's own listeners are not there (FR-43).
101
+ */
102
+ async function opening(options, offered, lostSaid, wiring) {
28
103
  const call = options.fetch ?? fetch;
29
104
  const headers = { "content-type": "application/json", ...(options.headers ?? {}) };
30
- Object.assign(headers, seatHeaders(options.principal));
105
+ // Who, and through what: a claim only a server that trusts the seat headers believes (FR-06, FR-52).
106
+ const seat = { ...seatHeaders(options.principal), [SEAT_HEADERS.via]: options.via ?? "web" };
107
+ Object.assign(headers, seat);
31
108
  const live = options.live === true;
32
- const reached = await call(`${options.url}/graview/state`, { headers });
33
- if (!reached.ok)
34
- throw new Error((await reached.json().catch(() => ({}))).error ?? `The server refused (${reached.status})`);
35
- const state = (await reached.json());
109
+ /** Undefined: the socket says `here` only on a change, because the server holds it while the socket is open. */
110
+ const presenceEveryMs = options.presenceEveryMs;
111
+ const visible = options.visible ?? pageVisible;
112
+ /*
113
+ * WHETHER THE SERVER IS BEING REACHED (FR-49), for a host's banner. Every
114
+ * request after the first goes through `reach`, which says so either way;
115
+ * the socket says so on its welcome and when a welcomed socket drops.
116
+ */
117
+ let status = "connecting";
118
+ const statusListeners = wiring.statuses;
119
+ const tally = wiring.tally;
120
+ /** Calls that could not reach the server, each waiting to be sent again once it is back. */
121
+ const held = [];
122
+ const become = (next) => {
123
+ if (next === status || retiring)
124
+ return;
125
+ if (status === "offline" && next === "online")
126
+ tally.reconnects++;
127
+ status = next;
128
+ // A store that replaced another and comes online says nothing its listeners were not already told.
129
+ if (wiring.told !== next) {
130
+ wiring.told = next;
131
+ for (const told of [...statusListeners])
132
+ told(next);
133
+ }
134
+ if (next === "online")
135
+ for (const waiting of held.splice(0))
136
+ waiting.again();
137
+ };
138
+ const reach = async (url, init) => {
139
+ let response;
140
+ try {
141
+ response = await call(url, init);
142
+ }
143
+ catch (error) {
144
+ // A live client whose socket is up is reaching the server, whatever one request met.
145
+ if (!socketReady())
146
+ become("offline");
147
+ throw new Unreached(error instanceof Error ? error.message : String(error));
148
+ }
149
+ // A host that takes no changes for a while is reached, and says so: not away (FR-46).
150
+ if (response.status === 503 && (await unavailableSaid(response))) {
151
+ become("online");
152
+ return response;
153
+ }
154
+ if (AWAY.has(response.status)) {
155
+ if (!socketReady())
156
+ become("offline");
157
+ throw new Unreached(`The server is away (${response.status})`);
158
+ }
159
+ become("online");
160
+ return response;
161
+ };
162
+ const fetchState = async (first = false) => {
163
+ const url = `${options.url}/graview/state`;
164
+ const reached = first ? await call(url, { headers }) : await reach(url, { headers });
165
+ if (!reached.ok)
166
+ throw new Error((await reached.json().catch(() => ({}))).error ?? `The server refused (${reached.status})`);
167
+ return (await reached.json());
168
+ };
169
+ const state = await fetchState(true);
170
+ // A polling client has its first answer; a live one is connecting until its socket is welcomed.
171
+ if (!live)
172
+ status = "online";
36
173
  const enabledModules = state.enabledModules ?? options.enabledModules;
174
+ // The app as the host judges it (`localApp`), so the browser refuses only what the server would.
175
+ const app = (options.localApp ? options.localApp(options.app) : options.app);
37
176
  const store = new Store({
38
- schema: options.app.schema,
39
- mutations: options.app.mutations ?? [],
40
- invariants: options.app.invariants ?? [],
41
- ...(options.app.policy ? { policy: options.app.policy } : {}),
42
- ...(options.app.modules ? { modules: options.app.modules } : {}),
177
+ schema: app.schema,
178
+ mutations: app.mutations ?? [],
179
+ invariants: app.invariants ?? [],
180
+ ...(app.policy ? { policy: app.policy } : {}),
181
+ ...(app.modules ? { modules: app.modules } : {}),
43
182
  ...(enabledModules ? { enabledModules } : {}),
44
- ...(options.app.intelligence ? { intelligence: options.app.intelligence } : {}),
183
+ ...(app.intelligence ? { intelligence: app.intelligence } : {}),
45
184
  /*
46
185
  * The snapshot AND the log: the snapshot is the graph, the log is the
47
186
  * history that led to it. Folding the log alone would lose whatever the
@@ -70,7 +209,7 @@ export async function openRemote(options) {
70
209
  });
71
210
  let seen = state.log.at(-1)?.seq ?? (state.horizon ?? 0) - 1;
72
211
  /** Every field's revision as the server's ops this client has say it (FR-05). */
73
- const revisions = FieldRevisions.of(state.log);
212
+ let revisions = FieldRevisions.of(state.log);
74
213
  /*
75
214
  * PRESENCE, beside the log and never in it. `mine` is the last word this
76
215
  * browser said about itself; it goes out with every poll (or down the
@@ -78,10 +217,20 @@ export async function openRemote(options) {
78
217
  * whoever is listening.
79
218
  */
80
219
  let mine = null;
220
+ /** The key the server holds this client under, as its welcome or its last `here` said (FR-47). */
221
+ let self;
81
222
  let known = new Map();
82
- const whoListeners = new Set();
223
+ const whoListeners = wiring.who;
224
+ /** Set when a list of who is here arrives; read when a dropped socket's held presences lapse. */
225
+ let heardWho = false;
83
226
  const heard = (who) => {
227
+ if (retiring)
228
+ return;
229
+ heardWho = true;
84
230
  const next = foldPresence(new Map(), who, Date.now(), REMOTE_PRESENCE_TTL_MS, mine?.participant);
231
+ // Never yourself, under the key you made or the one the server built for you.
232
+ if (self !== undefined)
233
+ next.delete(self);
85
234
  let changed = next.size !== known.size;
86
235
  if (!changed)
87
236
  for (const [participant, presence] of next)
@@ -90,7 +239,7 @@ export async function openRemote(options) {
90
239
  known = next;
91
240
  if (!changed)
92
241
  return;
93
- for (const listener of whoListeners)
242
+ for (const listener of [...whoListeners])
94
243
  listener([...known.values()]);
95
244
  };
96
245
  /*
@@ -103,7 +252,7 @@ export async function openRemote(options) {
103
252
  * never sits in the log beside the server's op for the same press.
104
253
  *
105
254
  * `provisional` is every batch whose provisional ops may still be in the
106
- * log: a batch is dropped once, and only while it is, because a live
255
+ * log: a batch is dropped once, and only while it is, because a
107
256
  * client's batch id is the one the server's op lands in too, and
108
257
  * dropping it again would cut the server's op.
109
258
  */
@@ -116,48 +265,166 @@ export async function openRemote(options) {
116
265
  };
117
266
  /** Socket calls not yet answered, by cid: what was sent, and how to tell the sender. */
118
267
  const waiting = new Map();
268
+ /** Tells whoever sent a batch the server has now answered, with the ops it landed as. */
269
+ const tellAnswered = (batch, ops) => {
270
+ const answered = waiting.get(batch);
271
+ if (!answered)
272
+ return;
273
+ waiting.delete(batch);
274
+ answered.resolve({ ops: ops.filter((op) => op.batch === batch), batch });
275
+ };
276
+ /** Set while the client takes the server's whole state; what arrives meanwhile waits for it, in order. */
277
+ let resyncing;
278
+ let meanwhile = [];
119
279
  const land = (ops, drop = []) => {
120
280
  if (ops.length === 0 && drop.length === 0)
121
281
  return [];
282
+ if (resyncing) {
283
+ meanwhile.push({ ops, drop });
284
+ return [];
285
+ }
286
+ /*
287
+ * NEVER NUMBERED OUT OF THE SERVER'S ORDER (FR-53). `rebase` lands each
288
+ * op at the end of this log, so ops that begin past the next seq this
289
+ * client has would be numbered as if the ones between never happened.
290
+ * They begin there when the server compacted past where this client
291
+ * left off: `/graview/since` and the welcome begin at the horizon, and
292
+ * the ops between are in no answer. The client takes the state instead.
293
+ */
294
+ const first = Math.min(...ops.filter((op) => op.seq > seen).map((op) => op.seq));
295
+ if (Number.isFinite(first) && first > seen + 1) {
296
+ meanwhile.push({ ops, drop });
297
+ resync();
298
+ return [];
299
+ }
122
300
  /*
123
- * A live client names the batch its call lands in, so an op of the
301
+ * A client names the batch its call lands in (FR-49), so an op of the
124
302
  * server's in one of its pending batches IS that batch's answer —
125
- * pushed, or caught up on after a reconnect, before its ack arrived.
303
+ * pushed, polled, or caught up on after a reconnect, before its answer arrived.
126
304
  */
127
- const echoed = live ? pending.filter((batch) => ops.some((op) => op.batch === batch)) : [];
305
+ const echoed = pending.filter((batch) => ops.some((op) => op.batch === batch));
306
+ const dropping = [...new Set([...drop, ...echoed])].filter((batch) => provisional.has(batch));
307
+ let landed;
308
+ const under = pending.filter((batch) => !echoed.includes(batch));
309
+ try {
310
+ landed = store.rebase({ confirmed: ops, pending: under, drop: dropping }).confirmed;
311
+ }
312
+ catch (error) {
313
+ // An op of the server's that does not fit here: this copy drifted, and is as it was. The server's state is the truth.
314
+ if (!(error instanceof ReceiveError))
315
+ throw error;
316
+ meanwhile.push({ ops, drop });
317
+ resync();
318
+ return [];
319
+ }
128
320
  for (const batch of echoed)
129
321
  settle(batch);
130
- const dropping = [...new Set([...drop, ...echoed])].filter((batch) => provisional.has(batch));
322
+ if (ops.some((op) => op.seq > seen) && under.some((batch) => !dropping.includes(batch)))
323
+ tally.rebases++;
131
324
  if (ops.length > 0) {
132
325
  seen = Math.max(seen, ...ops.map((op) => op.seq));
133
326
  revisions.note(ops);
134
327
  }
135
- const landed = store.rebase({ confirmed: ops, pending: [...pending], drop: dropping }).confirmed;
136
328
  for (const batch of dropping)
137
329
  provisional.delete(batch);
138
- for (const batch of echoed) {
139
- const answered = waiting.get(batch);
140
- if (!answered)
141
- continue;
142
- waiting.delete(batch);
143
- answered.resolve({ ops: ops.filter((op) => op.batch === batch), batch });
144
- }
330
+ for (const batch of echoed)
331
+ tellAnswered(batch, ops);
145
332
  return landed;
146
333
  };
334
+ /*
335
+ * THE SERVER'S WHOLE STATE, ADOPTED (FR-53): fetched, taken as this
336
+ * store's graph and log by `store.adopt`, and this client's unanswered
337
+ * batches applied again on top. A batch the state already holds (a live
338
+ * client's, landed before its ack came) is answered, not applied twice.
339
+ * What arrived while the state was on its way lands after it; whatever
340
+ * the state already holds is skipped. A state that cannot be fetched
341
+ * leaves the client as it was, and the next answer that cannot land asks
342
+ * again.
343
+ */
344
+ const resync = () => {
345
+ if (resyncing)
346
+ return;
347
+ resyncing = track(fetchState()
348
+ .then((next) => {
349
+ // A state on another declaration is not this store's to adopt: the client opens on it instead (FR-43).
350
+ if (moved(next)) {
351
+ meanwhile = [];
352
+ return;
353
+ }
354
+ const held = new Set(next.log.map((op) => op.batch));
355
+ const answered = pending.filter((batch) => held.has(batch));
356
+ for (const batch of answered)
357
+ settle(batch);
358
+ const adopted = store.adopt({
359
+ snapshot: next.snapshot,
360
+ log: next.log,
361
+ ...(next.horizon !== undefined ? { horizon: next.horizon } : {}),
362
+ pending: [...pending],
363
+ drop: [...provisional].filter((batch) => !pending.includes(batch)),
364
+ });
365
+ // The only provisional ops in the log now are the ones applied again.
366
+ provisional.clear();
367
+ for (const op of adopted.pending)
368
+ provisional.add(op.batch);
369
+ seen = next.log.at(-1)?.seq ?? (next.horizon ?? 0) - 1;
370
+ revisions = FieldRevisions.of(next.log);
371
+ tally.resyncs++;
372
+ for (const batch of answered)
373
+ tellAnswered(batch, next.log);
374
+ })
375
+ .then(() => {
376
+ resyncing = undefined;
377
+ const later = meanwhile;
378
+ meanwhile = [];
379
+ for (const { ops, drop } of later)
380
+ land(ops, drop);
381
+ }, () => {
382
+ // Not reached, or not adopted: as it was. What waited comes again from `seen`.
383
+ resyncing = undefined;
384
+ meanwhile = [];
385
+ }));
386
+ };
387
+ /*
388
+ * EVERY ANSWER A POLL READS SAYS WHICH DECLARATION AND WHICH BUILD
389
+ * (FR-43, FR-44). One on another declaration is not landed here: the
390
+ * client opens on the new one, exactly as a socket's `declaration` makes
391
+ * it, and its calls on the way go with it.
392
+ */
393
+ const moved = (answer) => {
394
+ if (typeof answer.build === "string")
395
+ noticeBuild(answer.build);
396
+ if (typeof answer.version !== "number" || answer.version === state.version)
397
+ return false;
398
+ void declarationChanged(answer.version);
399
+ return true;
400
+ };
147
401
  const since = async (seq) => {
148
- const response = await call(`${options.url}/graview/since?seq=${seq}`, { headers });
149
- return (await response.json()).ops ?? [];
402
+ const response = await reach(`${options.url}/graview/since?seq=${seq}`, { headers });
403
+ const answer = (await response.json());
404
+ return moved(answer) ? [] : (answer.ops ?? []);
150
405
  };
406
+ /** Asks for what is new, and waits for a resync the answer started, so the store is the server's when it returns. */
151
407
  const pull = async () => {
152
- if (mine && !socketReady()) {
153
- const response = await call(`${options.url}/graview/here`, {
408
+ const landed = await pulled();
409
+ if (resyncing)
410
+ await resyncing;
411
+ return landed;
412
+ };
413
+ const pulled = async () => {
414
+ // Presence rides the poll only while somebody is looking (FR-49).
415
+ if (mine && !socketReady() && visible()) {
416
+ const response = await reach(`${options.url}/graview/here`, {
154
417
  method: "POST",
155
418
  headers,
156
419
  body: JSON.stringify({ presence: mine, seq: seen }),
157
420
  });
158
- const { who, ops } = (await response.json());
159
- heard(who ?? []);
160
- return land(ops ?? []);
421
+ const answer = (await response.json());
422
+ if (moved(answer))
423
+ return [];
424
+ if (typeof answer.participant === "string")
425
+ self = answer.participant;
426
+ heard(answer.who ?? []);
427
+ return land(answer.ops ?? []);
161
428
  }
162
429
  return land(await since(seen));
163
430
  };
@@ -180,19 +447,89 @@ export async function openRemote(options) {
180
447
  * dropped, in one rebase. `send` never applies first, so its answer
181
448
  * lands under whatever is pending.
182
449
  */
183
- const post = async (body, mine) => {
184
- const response = await call(`${options.url}/graview/ops`, {
185
- method: "POST",
186
- headers,
187
- // A person at an interface, unless the caller said otherwise (FR-06).
188
- body: JSON.stringify({ via: options.via ?? "web", ...body }),
189
- });
190
- const answer = (await response.json());
450
+ /*
451
+ * ONE POST AT A TIME, IN THE ORDER THE CHANGES WERE MADE. The server
452
+ * judges them in the order they reach it, and a post that has to wait —
453
+ * the host is busy (FR-45), or the server cannot be reached (FR-49) —
454
+ * must not be overtaken by one made after it. So a post waits in its
455
+ * turn and goes again from there, and the posts behind it wait for it.
456
+ */
457
+ let lane = Promise.resolve();
458
+ /** How many times in a row the host said it takes no changes for a while: the backoff's attempt. */
459
+ let unavailableTries = 0;
460
+ const post = (body, mine) => {
461
+ const turn = lane.then(() => posted(body, mine));
462
+ lane = turn.catch(() => { });
463
+ return turn;
464
+ };
465
+ /** Resolves once the server is reached again (FR-49); rejects if the client closes first. */
466
+ const backOnline = () => new Promise((again, give) => held.push({ again, give }));
467
+ const posted = async (body, mine) => {
468
+ let response;
469
+ let answer;
470
+ for (;;) {
471
+ try {
472
+ response = await reach(`${options.url}/graview/ops`, {
473
+ method: "POST",
474
+ headers,
475
+ body: JSON.stringify(body),
476
+ });
477
+ }
478
+ catch (error) {
479
+ /*
480
+ * NOT REFUSED, NOT REACHED (FR-49). A call the server never heard is
481
+ * not taken back as if it had been refused: it stays shown, counts as
482
+ * pending, and goes again — down the socket or over HTTP, whichever is
483
+ * up — the moment the server is reached again. Posts batch-named, so
484
+ * one the server did hear is answered with the ops it made.
485
+ */
486
+ if (!(error instanceof Unreached) || closed)
487
+ throw error;
488
+ await backOnline();
489
+ if (socketReady())
490
+ return viaSocket(body, mine);
491
+ continue;
492
+ }
493
+ answer = (await response.json().catch(() => ({})));
494
+ /*
495
+ * ONE WAY TO WAIT, IN THE POST LANE. Not for a while (FR-46): a 503
496
+ * whose reason is `unavailable` — the host takes no changes now and
497
+ * cannot say how long — waits a backoff, as a reconnect would. Busy
498
+ * (FR-45): a 429 waits what it asks, `Retry-After` read in seconds and
499
+ * a JSON `retryAfter` in milliseconds (`retryAfterMs`). Either way the
500
+ * change stays shown and pending, refused by nobody, and goes again.
501
+ */
502
+ let wait;
503
+ if (response.status === 503 && answer.reason === "unavailable" && !closed)
504
+ wait = backoffFor(options.backoff, unavailableTries++);
505
+ else {
506
+ unavailableTries = 0;
507
+ if (response.status !== 429 || closed)
508
+ break;
509
+ wait = retryAfterMs(response.headers.get("retry-after"), answer.retryAfter);
510
+ }
511
+ await new Promise((later) => setTimeout(later, wait));
512
+ if (socketReady())
513
+ return viaSocket(body, mine);
514
+ }
515
+ /*
516
+ * Answered on another declaration, or after this store was let go: the
517
+ * call goes with the rest to the store on the new one, under its batch,
518
+ * where the server answers it once (FR-43).
519
+ */
520
+ if (retiring || moved(answer))
521
+ throw new Superseded("The app was changed.");
191
522
  if (!response.ok) {
192
523
  // The policy's own sentence, carried across the wire unchanged: a
193
524
  // refusal a person can read is the whole point of having one.
194
525
  const sentence = answer.error ?? `The server refused (${response.status})`;
195
- throw answer.conflict ? new StaleWrite(sentence, answer.conflicts ?? []) : new Error(sentence);
526
+ if (answer.conflict)
527
+ throw new StaleWrite(sentence, answer.conflicts ?? []);
528
+ throw new RemoteRefusedError({
529
+ reason: answer.reason ?? REASON_BY_STATUS[response.status] ?? "invalid",
530
+ sentence,
531
+ ...(answer.wouldNeed?.length ? { wouldNeed: answer.wouldNeed } : {}),
532
+ });
196
533
  }
197
534
  let ops = answer.ops ?? [];
198
535
  /*
@@ -241,23 +578,59 @@ export async function openRemote(options) {
241
578
  }
242
579
  };
243
580
  const sayWhere = (force = false) => {
244
- if (!mine || !socketReady())
581
+ if (!mine || !socketReady() || !visible())
245
582
  return;
246
- if (!force && said && samePresence(mine, said) && Date.now() - saidAt < PRESENCE_TTL_MS / 2)
583
+ // Unchanged: said again only on a heartbeat the host opted into. The server holds it while the socket is open.
584
+ if (!force && said && samePresence(mine, said) && (presenceEveryMs === undefined || Date.now() - saidAt < presenceEveryMs))
247
585
  return;
248
586
  if (say({ t: "here", presence: mine })) {
249
587
  said = mine;
250
588
  saidAt = Date.now();
251
589
  }
252
590
  };
591
+ /*
592
+ * CALLS THE HOST ASKED TO WAIT (FR-45), by cid. They stay shown and
593
+ * pending, and go again together once the wait is over, in the order
594
+ * they were made; a call made meanwhile joins them rather than going
595
+ * ahead of them.
596
+ */
597
+ const busy = new Set();
598
+ let busyTimer;
599
+ const sendBusy = () => {
600
+ busyTimer = undefined;
601
+ const again = [...waiting.entries()].filter(([cid]) => busy.has(cid));
602
+ busy.clear();
603
+ for (const [, waiter] of again)
604
+ say(waiter.message);
605
+ };
606
+ const hold = (cid, retryAfter) => {
607
+ if (!waiting.has(cid))
608
+ return;
609
+ busy.add(cid);
610
+ if (busyTimer)
611
+ clearTimeout(busyTimer);
612
+ busyTimer = setTimeout(sendBusy, Math.max(0, retryAfter));
613
+ };
253
614
  /** A call down the socket; its answer lands when it comes, in the order the server said it. */
254
615
  const viaSocket = (body, mine) => new Promise((resolve, reject) => {
255
616
  const cid = mine ?? `send-${++counter}`;
256
- const via = options.via ?? "web";
257
617
  const message = body.undo
258
- ? { t: "undo", cid, batches: body.undo, via, ...(body.intent ? { intent: body.intent } : {}), ...(body.batch ? { batch: body.batch } : {}) }
259
- : { t: "call", cid, calls: body.calls ?? [], via, ...(body.intent ? { intent: body.intent } : {}), ...(body.batch ? { batch: body.batch } : {}), ...(body.base?.length ? { base: body.base } : {}) };
618
+ ? { t: "undo", cid, batches: body.undo, ...(body.intent ? { intent: body.intent } : {}), ...(body.batch ? { batch: body.batch } : {}), ...(body.via ? { via: body.via } : {}) }
619
+ : {
620
+ t: "call",
621
+ cid,
622
+ calls: body.calls ?? [],
623
+ ...(body.intent ? { intent: body.intent } : {}),
624
+ ...(body.batch ? { batch: body.batch } : {}),
625
+ ...(body.base?.length ? { base: body.base } : {}),
626
+ ...(body.via ? { via: body.via } : {}),
627
+ };
260
628
  waiting.set(cid, { message, ...(mine !== undefined ? { mine } : {}), resolve, reject });
629
+ // Behind calls the host asked to wait: it goes with them.
630
+ if (busy.size > 0) {
631
+ busy.add(cid);
632
+ return;
633
+ }
261
634
  // Not open: it goes when the socket is back, after the welcome has caught this client up.
262
635
  say(message);
263
636
  });
@@ -266,13 +639,27 @@ export async function openRemote(options) {
266
639
  const hear = (message) => {
267
640
  switch (message.t) {
268
641
  case "welcome": {
642
+ noticeBuild(message.build);
643
+ // Back on a server whose declaration moved while this socket was away (FR-43): its ops are not this store's to fold.
644
+ if (typeof message.version === "number" && message.version !== state.version) {
645
+ void declarationChanged(message.version);
646
+ return;
647
+ }
269
648
  welcomed = true;
270
649
  attempts = 0;
650
+ if (typeof message.participant === "string")
651
+ self = message.participant;
271
652
  land(message.ops ?? []);
272
653
  // Whatever was sent and never answered goes again: the server answers a batch it already has with its ops.
654
+ busy.clear();
655
+ if (busyTimer)
656
+ clearTimeout(busyTimer);
657
+ busyTimer = undefined;
273
658
  for (const waiter of waiting.values())
274
659
  say(waiter.message);
275
660
  sayWhere(true);
661
+ // And what could not reach the server at all goes after it.
662
+ become("online");
276
663
  opened();
277
664
  return;
278
665
  }
@@ -286,6 +673,7 @@ export async function openRemote(options) {
286
673
  return;
287
674
  }
288
675
  waiting.delete(message.cid);
676
+ unavailableTries = 0;
289
677
  if (waiter.mine !== undefined) {
290
678
  batches.set(waiter.mine, message.batch);
291
679
  settle(waiter.mine);
@@ -299,17 +687,181 @@ export async function openRemote(options) {
299
687
  const waiter = waiting.get(message.cid);
300
688
  if (!waiter)
301
689
  return;
690
+ // Not for a while, and not final (FR-46): kept, and sent again after a backoff, with every call made behind it.
691
+ if (message.t === "refused" && message.reason === "unavailable") {
692
+ hold(message.cid, backoffFor(options.backoff, unavailableTries++));
693
+ return;
694
+ }
302
695
  waiting.delete(message.cid);
303
- waiter.reject(message.t === "conflict" ? new StaleWrite(message.sentence, message.conflicts ?? []) : new Error(message.sentence));
696
+ waiter.reject(message.t === "conflict"
697
+ ? new StaleWrite(message.sentence, message.conflicts ?? [])
698
+ : new RemoteRefusedError({
699
+ // A server before FR-46 says no reason.
700
+ reason: message.reason ?? "invalid",
701
+ sentence: message.sentence,
702
+ ...(message.wouldNeed?.length ? { wouldNeed: [...message.wouldNeed] } : {}),
703
+ }));
304
704
  return;
305
705
  }
706
+ case "busy":
707
+ // Not now, and not refused (FR-45): kept, and sent again after the wait.
708
+ if (typeof message.cid === "string")
709
+ hold(message.cid, typeof message.retryAfter === "number" ? message.retryAfter : 1000);
710
+ return;
306
711
  case "presence":
307
712
  heard(message.who ?? []);
308
713
  return;
714
+ case "declaration":
715
+ if (typeof message.version === "number" && message.version !== state.version)
716
+ void declarationChanged(message.version);
717
+ return;
718
+ case "reload":
719
+ reloadOntoNewer(typeof message.reason === "string" ? message.reason : "This app was updated.");
720
+ return;
721
+ case "error":
722
+ // The host lost who this socket is: a new socket's upgrade tells it again, and what was not answered is sent again there.
723
+ if (message.reopen === true && socket) {
724
+ const was = socket;
725
+ dropped(was);
726
+ try {
727
+ was.close(1000, "Opening again.");
728
+ }
729
+ catch {
730
+ // Already closing.
731
+ }
732
+ }
733
+ return;
309
734
  default:
310
735
  return;
311
736
  }
312
737
  };
738
+ /* ── SKEW AND CHANGE (FR-43, FR-44) ─────────────────────────────────── */
739
+ /** Set once this store has been let go of, for a new declaration or a reload: it acts on nothing more. */
740
+ let retiring = false;
741
+ const declarationListeners = wiring.declarations;
742
+ const buildListeners = wiring.builds;
743
+ const noticeBuild = (build) => {
744
+ if (retiring || wiring.otherBuild !== undefined || !options.build || typeof build !== "string" || build.length === 0 || build === options.build)
745
+ return;
746
+ wiring.otherBuild = build;
747
+ for (const listener of [...buildListeners])
748
+ listener(build);
749
+ };
750
+ /** Every call this client applied that the server has not answered, oldest first; and how many undos are. */
751
+ const unanswered = () => {
752
+ const carried = [];
753
+ let undos = 0;
754
+ for (const batch of pending) {
755
+ const made = asked.get(batch);
756
+ if (made)
757
+ carried.push({ calls: made.calls, ...(made.intent ? { intent: made.intent } : {}), ...(made.via ? { via: made.via } : {}), batch });
758
+ else
759
+ undos++;
760
+ }
761
+ return { carried, undos };
762
+ };
763
+ const undosSaid = (undos, why) => `${why} while ${undos === 1 ? "an undo of yours was" : "undos of yours were"} on the way; ${undos === 1 ? "it was" : "they were"} not made.`;
764
+ /** Lets this store go: what it waits for is let go too, never said to be refused, and its socket closes without a goodbye. */
765
+ const retire = (why) => {
766
+ retiring = true;
767
+ // Where this page stands is the next store's to say now: closing this one later must not say it left.
768
+ mine = null;
769
+ const superseded = new Superseded(why);
770
+ for (const waiter of waiting.values())
771
+ waiter.reject(superseded);
772
+ waiting.clear();
773
+ if (timer)
774
+ clearInterval(timer);
775
+ closed = true;
776
+ if (retry)
777
+ clearTimeout(retry);
778
+ if (busyTimer)
779
+ clearTimeout(busyTimer);
780
+ if (lapse)
781
+ clearTimeout(lapse);
782
+ // A post waiting for the server to be reached again goes with the rest instead.
783
+ for (const waiting of held.splice(0))
784
+ waiting.give(superseded);
785
+ const was = socket;
786
+ socket = undefined;
787
+ welcomed = false;
788
+ try {
789
+ was?.close(1000, why);
790
+ }
791
+ catch {
792
+ // Already gone.
793
+ }
794
+ opened();
795
+ };
796
+ /*
797
+ * THE DECLARATION CHANGED (FR-43). The host's `resolveApp` names the app
798
+ * at the server's version; a remote store is opened on it — the
799
+ * server's migrated state — and handed to `onDeclaration`, with every
800
+ * call this one had on the way offered again there under the batch it
801
+ * was sent in, so one the server already made is not made twice.
802
+ */
803
+ async function declarationChanged(version) {
804
+ if (retiring)
805
+ return;
806
+ if (!options.resolveApp) {
807
+ reloadOntoNewer(`This app was changed on its server (version ${version}); reload the page to carry on.`);
808
+ return;
809
+ }
810
+ const { carried, undos } = unanswered();
811
+ const resolveApp = options.resolveApp;
812
+ const standing = mine;
813
+ retire("The app was changed.");
814
+ try {
815
+ const resolved = await resolveApp(version);
816
+ // The host's wiring goes with it: its listeners, the counters, the build it was told of.
817
+ const next = await opening({ ...options, app: resolved }, carried, "The app was changed while your changes were on the way.", wiring);
818
+ if (standing)
819
+ next.remote.presence.here(standing);
820
+ for (const listener of [...declarationListeners])
821
+ listener(next.remote, version);
822
+ const said = [...(undos > 0 ? [refused(undosSaid(undos, "The app was changed"))] : []), ...next.unheard()];
823
+ for (const refusal of said)
824
+ for (const told of refusals)
825
+ told(refusal.sentence, refusal);
826
+ }
827
+ catch (error) {
828
+ const sentence = `The app was changed, but the new version could not be opened: ${error instanceof Error ? error.message : String(error)}`;
829
+ for (const told of refusals)
830
+ told(sentence, refused(sentence));
831
+ }
832
+ }
833
+ /*
834
+ * THE SERVER NO LONGER SERVES THIS PAGE'S PROTOCOL (FR-44). Every call
835
+ * not yet answered is kept in `carry`, the page reloads, and the next
836
+ * `openRemote` with the same key offers them again. Without `carry`
837
+ * they are refused in words first, so nobody believes they were made.
838
+ */
839
+ function reloadOntoNewer(reason) {
840
+ if (retiring)
841
+ return;
842
+ const { carried, undos } = unanswered();
843
+ retire(reason);
844
+ let kept = false;
845
+ if (options.carry && carried.length > 0) {
846
+ try {
847
+ options.carry.storage.setItem(options.carry.key, JSON.stringify(carried));
848
+ kept = true;
849
+ }
850
+ catch {
851
+ // Storage full or refused: the reload still happens, and the calls are said lost below.
852
+ }
853
+ }
854
+ const said = [];
855
+ if (!kept && carried.length > 0) {
856
+ said.push(`${reason} ${carried.length === 1 ? "A change of yours was" : `${carried.length} changes of yours were`} not sent; make ${carried.length === 1 ? "it" : "them"} again after the page reloads.`);
857
+ }
858
+ if (undos > 0)
859
+ said.push(undosSaid(undos, "This app was updated"));
860
+ for (const sentence of said)
861
+ for (const told of refusals)
862
+ told(sentence, refused(sentence));
863
+ (options.reloadPage ?? pageReload)();
864
+ }
313
865
  const connect = () => {
314
866
  if (closed || !live)
315
867
  return;
@@ -317,7 +869,7 @@ export async function openRemote(options) {
317
869
  const { "content-type": _json, ...carried } = headers;
318
870
  let made;
319
871
  try {
320
- made = (options.socket ?? platformSocket)(url, carried);
872
+ made = options.socket ? options.socket(url, carried, [LIVE_SUBPROTOCOL]) : platformSocket(url, carried);
321
873
  }
322
874
  catch {
323
875
  return reconnect();
@@ -328,7 +880,8 @@ export async function openRemote(options) {
328
880
  if (socket !== made)
329
881
  return;
330
882
  // From the last op this client has: the welcome brings exactly the ones after it.
331
- made.send(JSON.stringify({ t: "hello", seq: seen, protocol: WIRE_PROTOCOL }));
883
+ // Which codec, which protocol and which build this page speaks (FR-44).
884
+ made.send(JSON.stringify({ t: "hello", seq: seen, protocol: WIRE_PROTOCOL, wire: LIVE_WIRE, ...(options.build ? { build: options.build.slice(0, 64) } : {}), ...(options.hostProtocol !== undefined ? { hostProtocol: options.hostProtocol } : {}) }));
332
885
  };
333
886
  made.onmessage = (event) => {
334
887
  if (socket !== made)
@@ -342,22 +895,55 @@ export async function openRemote(options) {
342
895
  }
343
896
  hear(message);
344
897
  };
345
- made.onclose = () => {
346
- if (socket !== made)
347
- return;
348
- socket = undefined;
349
- welcomed = false;
350
- said = null;
351
- reconnect();
352
- };
898
+ made.onclose = () => dropped(made);
353
899
  made.onerror = () => {
354
900
  // The close follows; that is where reconnecting is decided.
355
901
  };
356
902
  };
903
+ /*
904
+ * WHAT A DROPPED SOCKET WAS TOLD STANDS NO LONGER ON THE SERVER'S WORD. A
905
+ * presence held by somebody's socket stands while the server lists it,
906
+ * and this client hears the server no longer. Unless a list comes within
907
+ * `REMOTE_PRESENCE_TTL_MS` — a welcome after a reconnect, a poll — the
908
+ * held ones are let go, as a word that old would be.
909
+ */
910
+ let lapse;
911
+ const lapseHeld = () => {
912
+ heardWho = false;
913
+ if (lapse)
914
+ clearTimeout(lapse);
915
+ lapse = setTimeout(() => {
916
+ lapse = undefined;
917
+ if (heardWho || closed)
918
+ return;
919
+ const kept = new Map([...known].filter(([, presence]) => presence.held !== "socket"));
920
+ if (kept.size === known.size)
921
+ return;
922
+ known = kept;
923
+ for (const listener of whoListeners)
924
+ listener([...known.values()]);
925
+ }, REMOTE_PRESENCE_TTL_MS);
926
+ lapse.unref?.();
927
+ };
928
+ /** A socket gone — closed, or one the host no longer knows: forgotten, and another opened after a backoff. */
929
+ function dropped(made) {
930
+ if (socket !== made)
931
+ return;
932
+ const wasUp = welcomed;
933
+ socket = undefined;
934
+ welcomed = false;
935
+ said = null;
936
+ // A socket that never opened says nothing a poll does not; one that was up and dropped is the server gone.
937
+ if (wasUp) {
938
+ become("offline");
939
+ lapseHeld();
940
+ }
941
+ reconnect();
942
+ }
357
943
  const reconnect = () => {
358
944
  if (closed)
359
945
  return;
360
- const wait = Math.min(10_000, 250 * 2 ** attempts) * (0.75 + Math.random() * 0.5);
946
+ const wait = backoffFor(options.backoff, attempts);
361
947
  attempts++;
362
948
  retry = setTimeout(connect, wait);
363
949
  };
@@ -377,8 +963,12 @@ export async function openRemote(options) {
377
963
  */
378
964
  const appliedAll = store.applyAll.bind(store);
379
965
  const undone = store.undo.bind(store);
380
- const refusals = new Set();
381
- const conflictListeners = new Set();
966
+ const refusals = wiring.refusals;
967
+ /** What became of carried calls before anybody listened: told to the first listener (FR-43, FR-44). */
968
+ let unheard = [];
969
+ /** A change of this client's that did not survive a new declaration or a reload: `invalid`, it no longer fits (FR-46). */
970
+ const refused = (sentence) => ({ reason: "invalid", sentence });
971
+ const conflictListeners = wiring.conflicts;
382
972
  /** Set while `useMine` sends a change again: it goes without the revisions it was refused for. */
383
973
  let overriding = false;
384
974
  /*
@@ -389,7 +979,11 @@ export async function openRemote(options) {
389
979
  * as it never happened there.
390
980
  */
391
981
  const takeBack = async (batch, error) => {
392
- const reason = error instanceof Error ? error.message : String(error);
982
+ // Let go of for a new declaration or a reload: carried, not refused (FR-43, FR-44).
983
+ if (error instanceof Superseded || retiring)
984
+ return;
985
+ const refusal = error instanceof RemoteRefusedError ? error.refusal : refusalOf(error);
986
+ const reason = refusal.sentence;
393
987
  settle(batch);
394
988
  try {
395
989
  land([], [batch]);
@@ -400,6 +994,8 @@ export async function openRemote(options) {
400
994
  }
401
995
  const made = asked.get(batch);
402
996
  asked.delete(batch);
997
+ if (error instanceof StaleWrite)
998
+ tally.conflicts++;
403
999
  /*
404
1000
  * A stale write means this client is behind: theirs is on the server
405
1001
  * and not yet here. A socket has already pushed it; a poller asks, so
@@ -421,7 +1017,7 @@ export async function openRemote(options) {
421
1017
  chosen = true;
422
1018
  overriding = true;
423
1019
  try {
424
- store.applyAll(made.calls, made.intent ? { intent: made.intent } : {});
1020
+ store.applyAll(made.calls, { ...(made.intent ? { intent: made.intent } : {}), ...(made.via ? { via: made.via } : {}) });
425
1021
  }
426
1022
  finally {
427
1023
  overriding = false;
@@ -433,7 +1029,7 @@ export async function openRemote(options) {
433
1029
  return;
434
1030
  }
435
1031
  for (const told of refusals)
436
- told(reason);
1032
+ told(reason, refusal);
437
1033
  };
438
1034
  /*
439
1035
  * EVERY WAY THE GRAPH CHANGES GOES DOWN THE WIRE. `apply` is one call;
@@ -465,14 +1061,15 @@ export async function openRemote(options) {
465
1061
  });
466
1062
  pending.push(result.batch);
467
1063
  provisional.add(result.batch);
468
- asked.set(result.batch, { calls, ...(applyOptions?.intent ? { intent: applyOptions.intent } : {}) });
1064
+ asked.set(result.batch, { calls, ...(applyOptions?.intent ? { intent: applyOptions.intent } : {}), ...(applyOptions?.via ? { via: applyOptions.via } : {}) });
469
1065
  // The revision of each field this changes, as this browser saw it — unless the person chose theirs over it.
470
1066
  const base = overriding ? [] : revisions.baseFor(result.ops, earlier);
471
1067
  answers.set(result.batch, track(transmit({
472
1068
  calls,
473
1069
  ...(applyOptions?.intent ? { intent: applyOptions.intent } : {}),
474
- ...(live ? { batch: result.batch } : {}),
1070
+ batch: result.batch,
475
1071
  ...(base.length > 0 ? { base } : {}),
1072
+ ...(applyOptions?.via ? { via: applyOptions.via } : {}),
476
1073
  }, result.batch).catch((error) => takeBack(result.batch, error))));
477
1074
  return result;
478
1075
  });
@@ -500,12 +1097,23 @@ export async function openRemote(options) {
500
1097
  .then(() => transmit({
501
1098
  undo: ids.map((id) => batches.get(id) ?? id),
502
1099
  ...(undoOptions?.intent ? { intent: undoOptions.intent } : {}),
503
- ...(live ? { batch: result.batch } : {}),
1100
+ batch: result.batch,
1101
+ ...(undoOptions?.via ? { via: undoOptions.via } : {}),
504
1102
  }, result.batch))
505
1103
  .catch((error) => takeBack(result.batch, error))));
506
1104
  return result;
507
1105
  });
508
- const send = async (calls, sending = {}) => (await track(transmit({ calls, ...sending }))).ops;
1106
+ const send = async (calls, sending = {}) => {
1107
+ sendsOut++;
1108
+ try {
1109
+ return (await track(transmit({ calls, ...sending }))).ops;
1110
+ }
1111
+ finally {
1112
+ sendsOut--;
1113
+ }
1114
+ };
1115
+ /** `send` calls not yet answered: they apply nothing here first, so `pending` does not hold them. */
1116
+ let sendsOut = 0;
509
1117
  const presence = {
510
1118
  here(next) {
511
1119
  mine = next;
@@ -513,6 +1121,9 @@ export async function openRemote(options) {
513
1121
  },
514
1122
  onWho(listener) {
515
1123
  whoListeners.add(listener);
1124
+ // Told at once who is here already: a host that subscribes after the welcome is not shown an empty room.
1125
+ if (known.size > 0)
1126
+ listener([...known.values()]);
516
1127
  return () => {
517
1128
  whoListeners.delete(listener);
518
1129
  };
@@ -520,7 +1131,7 @@ export async function openRemote(options) {
520
1131
  leave() {
521
1132
  if (!mine)
522
1133
  return;
523
- const body = JSON.stringify({ participant: mine.participant });
1134
+ const body = JSON.stringify({ participant: self ?? mine.participant });
524
1135
  mine = null;
525
1136
  if (say({ t: "bye" }))
526
1137
  return;
@@ -551,7 +1162,30 @@ export async function openRemote(options) {
551
1162
  await Promise.race([openedLive, new Promise((done) => (waited = setTimeout(done, options.openTimeoutMs ?? 3000)))]);
552
1163
  clearTimeout(waited);
553
1164
  }
554
- return {
1165
+ /*
1166
+ * CALLS CARRIED HERE — from the store this one replaces, or across a
1167
+ * reload — offered again now it is open, each under the batch it was
1168
+ * sent in. One the server's log already holds landed before the change
1169
+ * and is not made twice; one that no longer fits is named, in words.
1170
+ */
1171
+ if (offered.length > 0 && !retiring) {
1172
+ const lost = [];
1173
+ const landed = new Set(store.log.all().map((op) => op.batch));
1174
+ for (const one of offered) {
1175
+ if (one.batch !== undefined && landed.has(one.batch))
1176
+ continue;
1177
+ try {
1178
+ store.applyAll(one.calls, { ...(one.intent ? { intent: one.intent } : {}), ...(one.batch ? { batch: one.batch } : {}), ...(one.via ? { via: one.via } : {}) });
1179
+ }
1180
+ catch (error) {
1181
+ lost.push(named(one, error));
1182
+ }
1183
+ }
1184
+ if (lost.length > 0) {
1185
+ unheard.push(refused(`${lostSaid} ${lost.length === 1 ? "One no longer fits and was not made" : `${lost.length} no longer fit and were not made`}: ${lost.join("; ")}.`));
1186
+ }
1187
+ }
1188
+ const remote = {
555
1189
  store,
556
1190
  version: state.version,
557
1191
  migrated: state.migrated ?? [],
@@ -559,15 +1193,38 @@ export async function openRemote(options) {
559
1193
  pull,
560
1194
  onRefusal(listener) {
561
1195
  refusals.add(listener);
1196
+ const told = unheard;
1197
+ unheard = [];
1198
+ for (const refusal of told)
1199
+ listener(refusal.sentence, refusal);
562
1200
  return () => refusals.delete(listener);
563
1201
  },
1202
+ onDeclaration(listener) {
1203
+ declarationListeners.add(listener);
1204
+ return () => declarationListeners.delete(listener);
1205
+ },
1206
+ onBuild(listener) {
1207
+ buildListeners.add(listener);
1208
+ if (wiring.otherBuild !== undefined)
1209
+ listener(wiring.otherBuild);
1210
+ return () => buildListeners.delete(listener);
1211
+ },
564
1212
  onConflict(listener) {
565
1213
  conflictListeners.add(listener);
566
1214
  return () => conflictListeners.delete(listener);
567
1215
  },
568
1216
  revision: (node, field) => revisions.of(node, field),
569
1217
  seq: () => seen,
1218
+ participant: () => self,
570
1219
  transport: () => (socketReady() ? "socket" : "poll"),
1220
+ status: () => status,
1221
+ onStatus(listener) {
1222
+ statusListeners.add(listener);
1223
+ return () => statusListeners.delete(listener);
1224
+ },
1225
+ counters: () => ({ ...tally }),
1226
+ who: () => [...known.values()],
1227
+ pending: () => pending.length + sendsOut,
571
1228
  async settled() {
572
1229
  // Whatever is in flight now — and whatever a settling handler put in flight after it.
573
1230
  while (inFlight.size > 0)
@@ -581,6 +1238,12 @@ export async function openRemote(options) {
581
1238
  closed = true;
582
1239
  if (retry)
583
1240
  clearTimeout(retry);
1241
+ if (busyTimer)
1242
+ clearTimeout(busyTimer);
1243
+ if (lapse)
1244
+ clearTimeout(lapse);
1245
+ for (const waiting of held.splice(0))
1246
+ waiting.give(new Error("The client closed before the server could be reached."));
584
1247
  const was = socket;
585
1248
  socket = undefined;
586
1249
  welcomed = false;
@@ -592,25 +1255,79 @@ export async function openRemote(options) {
592
1255
  }
593
1256
  },
594
1257
  };
1258
+ return {
1259
+ remote,
1260
+ unheard() {
1261
+ const told = unheard;
1262
+ unheard = [];
1263
+ return told;
1264
+ },
1265
+ };
595
1266
  /** The platform's WebSocket, with the headers where the runtime can send them. */
596
1267
  function platformSocket(url, carried) {
597
1268
  const Socket = globalThis.WebSocket;
598
1269
  if (!Socket)
599
1270
  throw new Error("This runtime has no WebSocket; the client polls instead.");
600
1271
  const page = typeof globalThis.document !== "undefined";
1272
+ const protocols = options.subprotocol ? [LIVE_SUBPROTOCOL] : [];
601
1273
  if (!page) {
602
1274
  try {
603
- return new Socket(url, { headers: carried });
1275
+ return new Socket(url, { headers: carried, ...(protocols.length > 0 ? { protocols } : {}) });
604
1276
  }
605
1277
  catch {
606
1278
  // A runtime whose WebSocket takes protocols only: the seat rides in the query, as a page's does.
607
1279
  }
608
1280
  }
609
1281
  const withSeat = new URL(url);
610
- for (const [name, value] of Object.entries(seatHeaders(options.principal)))
1282
+ for (const [name, value] of Object.entries(seat))
611
1283
  withSeat.searchParams.set(name, value);
612
- return new Socket(withSeat.toString());
1284
+ return protocols.length > 0 ? new Socket(withSeat.toString(), protocols) : new Socket(withSeat.toString());
1285
+ }
1286
+ }
1287
+ /**
1288
+ * HOW LONG A 429 ASKS TO WAIT, IN MILLISECONDS (FR-45). The `Retry-After`
1289
+ * header is read as HTTP says — delta SECONDS, or an HTTP date — and the
1290
+ * JSON `retryAfter` as ship documents it, MILLISECONDS, the finer of the
1291
+ * two. A JSON wait under 50 beside a header that says the same number of
1292
+ * seconds is a host that said seconds in the body too (`retryAfter: 2`,
1293
+ * `Retry-After: 2` — two "milliseconds" is a retry storm, not a wait): the
1294
+ * header wins. Ship's own handler says a short wait as, say, 30 in the body
1295
+ * and 1 in the header, which is read as the 30 ms it means. Neither said:
1296
+ * a second.
1297
+ */
1298
+ function retryAfterMs(header, json, now = Date.now()) {
1299
+ let fromHeader;
1300
+ const said = header?.trim();
1301
+ if (said) {
1302
+ if (/^\d+(\.\d+)?$/.test(said))
1303
+ fromHeader = Number(said) * 1000;
1304
+ else {
1305
+ const date = Date.parse(said);
1306
+ if (Number.isFinite(date))
1307
+ fromHeader = Math.max(0, date - now);
1308
+ }
613
1309
  }
1310
+ const fromJson = typeof json === "number" && Number.isFinite(json) && json >= 0 ? json : undefined;
1311
+ const secondsInTheBody = fromJson !== undefined && fromJson < 50 && fromHeader !== undefined && Math.abs(fromJson * 1000 - fromHeader) < 1000;
1312
+ if (fromJson !== undefined && !secondsInTheBody)
1313
+ return fromJson;
1314
+ return fromHeader ?? 1000;
1315
+ }
1316
+ /** The page's own reload, where there is a page. */
1317
+ function pageReload() {
1318
+ globalThis.location?.reload?.();
1319
+ }
1320
+ /** Whether a page is being looked at; a runtime with no document always is. */
1321
+ function pageVisible() {
1322
+ const page = globalThis.document;
1323
+ return page?.visibilityState !== "hidden";
1324
+ }
1325
+ /** How long before reconnect attempt `attempt` (FR-49): the host's own, or jittered exponential. */
1326
+ function backoffFor(backoff, attempt) {
1327
+ if (typeof backoff === "function")
1328
+ return Math.max(0, backoff(attempt));
1329
+ const { min = 250, max = 10_000, factor = 2 } = backoff ?? {};
1330
+ return Math.min(max, min * factor ** attempt) * (0.75 + Math.random() * 0.5);
614
1331
  }
615
1332
  /**
616
1333
  * A principal as the headers a TRUSTED server reads (`trustSeatHeaders`):