@mmstack/mesh 22.14.0 → 22.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mmstack/mesh",
3
- "version": "22.14.0",
3
+ "version": "22.15.0",
4
4
  "keywords": [
5
5
  "angular",
6
6
  "signals",
@@ -20,8 +20,8 @@
20
20
  "homepage": "https://github.com/mihajm/mmstack/blob/master/packages/mesh/client",
21
21
  "peerDependencies": {
22
22
  "@angular/core": ">=22 <23",
23
- "@mmstack/primitives": ">=22.24 <23",
24
- "@mmstack/mesh-protocol": ">=0.14 <1"
23
+ "@mmstack/primitives": ">=22.25 <23",
24
+ "@mmstack/mesh-protocol": ">=0.15 <1"
25
25
  },
26
26
  "sideEffects": false,
27
27
  "module": "fesm2022/mmstack-mesh.mjs",
@@ -1,6 +1,130 @@
1
- import { ClientMsg, ClientSignalMsg, IceServer, OpPolicy, PolicyViolation, PresenceState, PrincipalCtx, Relay, ServerDirectMsg, ServerMsg } from "@mmstack/mesh-protocol";
2
- import { AsyncStore, DiffOpsOptions, ForkStoreOptions, MergePolicyEntry, OpEnvelope, OpSync, StoreOp, SyncedFork, WritableSignalStore, toStoreOptions } from "@mmstack/primitives/core";
1
+ import { ClientMsg, ClientSignalMsg, CoverContext, Dot, GenerationReason, Hlc, IceServer, Key, OpEnvelope, OpPolicy, PolicyViolation, PresenceState, PrincipalCtx, Ranges, Receipts, RegisterStore, Relay, ServerDirectMsg, ServerMsg, StoreOp, TailPolicy, VersionRange } from "@mmstack/mesh-protocol";
2
+ import { AsyncStore, DiffOpsOptions, ForkStoreOptions, MergePolicyEntry, OpEnvelope as OpEnvelope$1, OpSync, StoreOp as StoreOp$1, SyncedFork, WritableSignalStore, toStoreOptions } from "@mmstack/primitives/core";
3
3
  import { Injector, Signal, WritableSignal } from "@angular/core";
4
+ /**
5
+ * The client half of a room generation: the record fields a snapshot welcome carries, the admission
6
+ * evidence the client keeps for its pre-check, and the pure decisions the session takes on them
7
+ * (which welcome to install, what a new generation does with the pending tail, whether a replayed
8
+ * envelope may be sent, when a member is ready for a consensus cut). Nothing here touches a socket,
9
+ * a store or a timer, so a harness can drive the same decisions the session does.
10
+ */
11
+ /** The immutable fields of the installed generation, as the client keeps them in its record. */
12
+ type InstalledGeneration = {
13
+ readonly instance: string;
14
+ readonly index: number;
15
+ readonly reason: GenerationReason;
16
+ readonly policy: TailPolicy;
17
+ readonly extent: Readonly<Record<string, Readonly<Record<string, Hlc>>>>;
18
+ readonly preCutMax: Readonly<Record<string, Hlc>>;
19
+ /** The seq of the snapshot welcome that installed it (or a later one of the same generation). */
20
+ readonly seq: number;
21
+ };
22
+ /**
23
+ * The admission evidence of the installed generation as this client knows it: the welcome's ranges,
24
+ * settled vector and first stamps, then every envelope the client ingests (its own included).
25
+ * A lead or lag against the relay's view only ever yields a refusal the client lands as a conflict.
26
+ */
27
+ type ClientAdmission = {
28
+ readonly ranges: Map<string, Ranges>;
29
+ readonly settled: Map<string, Hlc>;
30
+ readonly firstStamps: Map<string, Hlc>;
31
+ };
32
+ /** The serializable form of {@link ClientAdmission}. */
33
+ type ClientAdmissionRecord = {
34
+ readonly ranges: Readonly<Record<string, readonly VersionRange[]>>;
35
+ readonly settled: Readonly<Record<string, Hlc>>;
36
+ readonly firstStamps: Readonly<Record<string, Hlc>>;
37
+ };
38
+ declare const emptyAdmission: () => ClientAdmission;
39
+ /** The admission evidence a snapshot welcome carries, as of its seq. */
40
+ declare const admissionOf: (src: ClientAdmissionRecord) => ClientAdmission;
41
+ declare const admissionRecord: (a: ClientAdmission) => ClientAdmissionRecord;
42
+ /**
43
+ * One envelope reaches this client's view (its own emission, a relay delivery, a replayed or
44
+ * re-applied own write). A version it already holds is a duplicate, and one below its origin's
45
+ * maximum was skipped by the relay: both are refused (`false`), nothing is recorded. Otherwise the
46
+ * version joins the evidence exactly as the relay records it.
47
+ */
48
+ declare function admitLocal(a: ClientAdmission, env: {
49
+ readonly origin: string;
50
+ readonly version: number;
51
+ readonly hlc: Hlc;
52
+ }): boolean;
53
+ /** The context `admits` reads: the installed record's extent and preCutMax, the client's evidence. */
54
+ declare const coverContext: (gen: Pick<InstalledGeneration, "extent" | "preCutMax">, a: ClientAdmission) => CoverContext;
55
+ /**
56
+ * The replay pre-check: every cite of `env` (its own dot excepted) the installed state does not
57
+ * cover, by the same `admits` the relay runs, over the client's register store. An envelope with
58
+ * an uncovered cite is never sent; it is a conflict.
59
+ */
60
+ declare function uncoveredCites(store: RegisterStore, ctx: CoverContext, env: OpEnvelope): {
61
+ readonly path: readonly Key[];
62
+ readonly dot: Dot;
63
+ }[];
64
+ /** What the client knows of its installed generation when a snapshot welcome arrives. */
65
+ type WelcomeFence = {
66
+ readonly index: number;
67
+ readonly instance: string | undefined;
68
+ /** The seq of the installed snapshot. */
69
+ readonly seq: number;
70
+ /** The highest seq of a relay-delivered envelope of this generation, deduplicated or not. */
71
+ readonly maxSeq: number;
72
+ };
73
+ /**
74
+ * Which snapshot welcome installs. A newer generation (higher index) always does. One of the
75
+ * installed generation does when it is not older than the installed snapshot (`stale` otherwise)
76
+ * and not older than relay traffic already delivered (`older-than-traffic`): installing it would
77
+ * replace that traffic with an earlier state. Anything else is stale.
78
+ */
79
+ declare function welcomeVerdict(installed: WelcomeFence, msg: {
80
+ readonly index: number;
81
+ readonly instance: string;
82
+ readonly seq: number;
83
+ }): 'newer' | 'same' | 'stale' | 'older-than-traffic';
84
+ /** A pending envelope of an earlier generation, as the tail policy reads it. */
85
+ type Pending = {
86
+ readonly env: Pick<OpEnvelope, 'origin' | 'instance' | 'version'>;
87
+ };
88
+ /**
89
+ * A new generation's first step with the pending tail: in version order, an envelope whose version
90
+ * the receipts of its origin hold — in ANY generation — was admitted and is never resent; the rest
91
+ * is kept for the tail policy. Membership is instance-agnostic: a replayed envelope carries the
92
+ * current instance, so the relay receipts it there while the tail entry still names the generation
93
+ * it was authored in, and a crash between the wire and the record would otherwise replay it again
94
+ * after the next cut. An origin's versions never repeat (the counter runs through replay; a restart
95
+ * that loses it mints a new origin), so the version alone identifies the write.
96
+ */
97
+ declare function trimByReceipts<T extends Pending>(pending: readonly T[], receipts: Receipts): {
98
+ readonly trimmed: T[];
99
+ readonly keep: T[];
100
+ };
101
+ /** A refusal was classified: a snapshot at or past its seq is owed. */
102
+ declare const owedAfterRefusal: (owed: number | undefined, seq: number) => number;
103
+ /** A snapshot installed at `seq`: the owed rehydration completes when it reaches the refusal. */
104
+ declare const owedAfterInstall: (owed: number | undefined, seq: number) => number | undefined;
105
+ /**
106
+ * A member's readiness for a consensus cut: it pressed Compact, it is connected, and nothing it
107
+ * wrote is outstanding (its outbox empty, no replay running). A conflict is never outstanding: it
108
+ * is out of the outbox the moment it is classified.
109
+ */
110
+ declare const readyValue: (s: {
111
+ readonly pressed: boolean;
112
+ readonly connected: boolean;
113
+ readonly replaying: boolean;
114
+ readonly outstanding: number;
115
+ }) => boolean;
116
+ /**
117
+ * The authored intent of an envelope: its raw op list and one bump flag, what a re-author rebuilds
118
+ * from. The raws are the stamped ops without their expansion clears (a diffed write never emits a
119
+ * `clear` of its own, so every `clear` is one) and without cites and epoch. The envelope bumped when
120
+ * an op's epoch rises above the register baseline at its path as the client held it before the
121
+ * envelope (the relay's own test for a bump).
122
+ */
123
+ type Intent = {
124
+ readonly raws: readonly StoreOp[];
125
+ readonly bump: boolean;
126
+ };
127
+ declare function intentOf(env: OpEnvelope, baseline: (path: readonly Key[]) => number): Intent;
4
128
  /**
5
129
  * One live connection to a relay. `meshSync` calls the factory per (re)connect; a transport
6
130
  * represents a single connection and never reconnects itself.
@@ -21,8 +145,65 @@ export declare function webSocketTransport(url: string, protocols?: string | str
21
145
  /**
22
146
  * Connects directly to an in-process `createRelay` — no network. The backbone of full-loop
23
147
  * tests, and handy for single-process demos or an SSR-side room.
148
+ *
149
+ * Messages cross as JSON in both directions, as they would over a socket, so a direct peer holds
150
+ * exactly what a socket peer would. Handed over by reference, an `undefined` an emitter wrote
151
+ * would reach relay memory where a socket peer's would have been dropped.
24
152
  */
25
153
  export declare function directTransport(relay: Relay, ctx: PrincipalCtx): MeshTransportFactory;
154
+ /**
155
+ * Why a write is a conflict: its replay into a new generation cites something the generation does
156
+ * not hold (`'uncovered'`, never sent), or the relay refused it — a cite it does not cover
157
+ * (`'citation'`) or an epoch raised without the authority to (`'epoch-bump'`).
158
+ */
159
+ type ConflictCause = 'uncovered' | 'citation' | 'epoch-bump';
160
+ /**
161
+ * A write that will never be admitted as it stands. Its local effect is retracted (a replay that
162
+ * failed its pre-check is never applied; a refused write is dropped by the snapshot that follows).
163
+ * The two verbs are the whole surface: `discard()` lets it go, `reauthor()` writes its raw ops again
164
+ * as a new write citing the current state. Neither can submit the original envelope.
165
+ */
166
+ type MeshConflict = {
167
+ /** The envelope as it was authored (its values, cites and epoch). */
168
+ readonly env: OpEnvelope$1;
169
+ readonly intent: Intent;
170
+ readonly cause: ConflictCause;
171
+ discard(): void;
172
+ /** Write the raw ops again as a new write; false when the shell cannot write (no `reauthor`). */
173
+ reauthor(): boolean;
174
+ };
175
+ /** The room's compaction state, as the relay last announced it. */
176
+ type CompactionState = {
177
+ /** Droppable tombstones counted against the budget. */
178
+ readonly count: number;
179
+ /** The hard budget, 0 when the room arms none. */
180
+ readonly budget: number;
181
+ /** Origins of the members currently declared ready for a consensus cut. */
182
+ readonly ready: readonly string[];
183
+ };
184
+ /**
185
+ * The session's durable half, persisted as one unit with the outbox: the fields of the generation
186
+ * the tail was written in and its admission evidence, the intents of the pending writes, unresolved
187
+ * conflicts and an owed snapshot. It holds NO registers and no sequence knowledge: a restart never
188
+ * trusts stale registers — it installs nothing from disk, asks for a snapshot (hello without seq)
189
+ * and resends its outbox first.
190
+ */
191
+ type SessionRecord = {
192
+ readonly generation?: Omit<InstalledGeneration, 'seq'>;
193
+ readonly admission?: ClientAdmissionRecord;
194
+ readonly intents?: readonly {
195
+ readonly origin: string;
196
+ readonly version: number;
197
+ readonly intent: Intent;
198
+ }[];
199
+ readonly conflicts?: readonly {
200
+ readonly env: OpEnvelope$1;
201
+ readonly intent: Intent;
202
+ readonly cause: ConflictCause;
203
+ }[];
204
+ /** A refusal's seq: a snapshot at or past it must install before the client trusts its view. */
205
+ readonly rehydrateOwed?: number;
206
+ };
26
207
  type MeshStatus = 'connecting' |
27
208
  /** Queued behind another tab that owns this key's durable outbox (`crossTab: 'queue'`). */
28
209
  'waiting' | 'live' | 'reconnecting' | 'ejected' | 'closed';
@@ -42,7 +223,7 @@ type RemoteBatch = {
42
223
  /** The relay's total-order stamp for this batch. */
43
224
  readonly seq: number;
44
225
  readonly writer: string;
45
- readonly ops: readonly StoreOp[];
226
+ readonly ops: readonly StoreOp$1[];
46
227
  };
47
228
  /**
48
229
  * Environment callbacks a session shell provides. All are optional except `onStatus`; the
@@ -95,14 +276,19 @@ type MeshSessionHooks = {
95
276
  onTerminal?(state: 'ejected' | 'closed', reason?: string): void;
96
277
  /**
97
278
  * The relay refused one of this session's writes: it is not in the room and never will be.
98
- * `'generation'` — written in a room generation that has since been cut (the whole tail is
99
- * refused at the welcome that names the new one, or one envelope by the relay's reply);
100
- * `'schema'` — a data shape older than the room's; `'order'` — a version below this origin's
101
- * admitted maximum that was never admitted (a second tab on one origin). The session drops
102
- * the write locally and hydrates from a fresh snapshot; the envelope carries the values, so
103
- * the application can offer to write them again. Any `whenAcked` waiter rejects.
104
- */
105
- onRefused?(env: OpEnvelope, reason: 'generation' | 'schema' | 'order'): void;
279
+ * `'generation'` — written in a room generation that a cut with the `discard` policy closed (a
280
+ * migration or a rollback: the reset is the intent), or in a room recreated without its
281
+ * generation record; `'schema'` — a data shape older than the room's; `'order'` — a version
282
+ * below this origin's admitted maximum that was never admitted (a second tab on one origin). The
283
+ * session drops the write locally and hydrates from a fresh snapshot; the envelope carries the
284
+ * values, so the application can offer to write them again. Any `whenAcked` waiter rejects.
285
+ * A write a compaction cut replays is never refused here: it is resent, or it is a conflict.
286
+ */
287
+ onRefused?(env: OpEnvelope$1, reason: 'generation' | 'schema' | 'order'): void;
288
+ /** The unresolved conflicts changed (a write classified, discarded or re-authored). */
289
+ onConflicts?(conflicts: readonly MeshConflict[]): void;
290
+ /** The relay announced the room's compaction state (count, budget, ready members). */
291
+ onCompaction?(state: CompactionState): void;
106
292
  };
107
293
  type MeshSessionOptions<T extends object> = {
108
294
  readonly room: string;
@@ -117,6 +303,16 @@ type MeshSessionOptions<T extends object> = {
117
303
  readonly schemaVersion?: number;
118
304
  /** The room generation a restored outbox was written in; the first welcome decides whether it still holds. */
119
305
  readonly instance?: string;
306
+ /**
307
+ * The restored durable record (see {@link SessionRecord}), applied at `connect()` on top of the
308
+ * restored outbox: the registers are hydrated with the pending writes re-applied over them.
309
+ */
310
+ readonly record?: SessionRecord;
311
+ /**
312
+ * Write a conflict's raw ops again (a new write citing the current state), on the shell's store;
313
+ * with `bump`, as an authority override. Without it a conflict can only be discarded.
314
+ */
315
+ readonly reauthor?: (intent: Intent) => void;
120
316
  readonly reconnect?: {
121
317
  readonly maxDelayMs?: number;
122
318
  };
@@ -154,7 +350,7 @@ type MeshSession = {
154
350
  */
155
351
  whenAcked(): Promise<void>;
156
352
  /** The unacknowledged local tail (the durable-outbox payload). */
157
- unackedEnvs(): readonly OpEnvelope[];
353
+ unackedEnvs(): readonly OpEnvelope$1[];
158
354
  /** The room generation this session is in, once a welcome (or a restored outbox) named one. */
159
355
  instance(): string | undefined;
160
356
  peers(): ReadonlyMap<string, PresenceState>;
@@ -163,6 +359,16 @@ type MeshSession = {
163
359
  sendSignal(msg: ClientSignalMsg): void;
164
360
  /** Send a `direct` frame to one member over the current connection; lost when there is none. */
165
361
  sendDirect(to: string, data: unknown): void;
362
+ /** Writes that will never be admitted as they stand, each with its two verbs. */
363
+ conflicts(): readonly MeshConflict[];
364
+ /**
365
+ * The member pressed (or released) Compact. While pressed, the session declares itself ready for
366
+ * a consensus cut whenever nothing it wrote is outstanding, and re-declares on every change; a
367
+ * reconnect and a new generation release the press. Safety never depends on it.
368
+ */
369
+ declareReady(pressed: boolean): void;
370
+ /** The durable record to persist with the outbox (see {@link SessionRecord}). */
371
+ record(): SessionRecord;
166
372
  close(): void;
167
373
  };
168
374
  declare function meshSession<T extends object>(opt: MeshSessionOptions<T>): MeshSession;
@@ -409,7 +615,7 @@ type MeshSyncOptions = {
409
615
  /** The connection dropped and a reconnect is scheduled; `code` is the close code (1009 = message too big, 1006 = dropped). */
410
616
  readonly onDisconnect?: (code: number, reason: string) => void;
411
617
  /** A write the relay refused (see `MeshSessionHooks.onRefused`); the envelope carries its values. */
412
- readonly onRefused?: (env: OpEnvelope, reason: 'generation' | 'schema' | 'order') => void;
618
+ readonly onRefused?: (env: OpEnvelope$1, reason: 'generation' | 'schema' | 'order') => void;
413
619
  /**
414
620
  * Hold the connection until the local base is assembled. `meshSync` awaits this before it connects
415
621
  * (and before it restores an `outbox`), so a store hydrated from another source first (a worker
@@ -508,6 +714,20 @@ type MeshSyncRef<T extends object = Record<string, unknown>> = {
508
714
  fork(opt?: ForkStoreOptions<T & Record<string, any>>): SyncedFork<T & Record<string, any>>;
509
715
  /** Authority surface over the CURRENT op-sync (it is rebuilt on restore); see {@link SeatSync}. */
510
716
  readonly sync: SeatSync<T>;
717
+ /**
718
+ * Writes that will never be admitted as they stand: a write a compaction cut could not replay
719
+ * (it cites something the cut folded away) or one the relay refused. Each offers `discard()` or
720
+ * `reauthor()` (write its values again, citing the current state). Persisted with the outbox.
721
+ */
722
+ readonly conflicts: Signal<readonly MeshConflict[]>;
723
+ /** The room's compaction state as the relay last announced it; undefined before any notice. */
724
+ readonly compaction: Signal<CompactionState | undefined>;
725
+ /**
726
+ * The member pressed (`true`) or released Compact: the client declares itself ready for a
727
+ * consensus cut whenever nothing it wrote is outstanding, re-declaring on every change. A
728
+ * reconnect or a new generation releases it.
729
+ */
730
+ declareReady(pressed: boolean): void;
511
731
  close(): void;
512
732
  };
513
733
  /**
@@ -524,7 +744,7 @@ type SeatChange = {
524
744
  /** The relay's total-order stamp. Strictly increasing across `change` events between resyncs. */
525
745
  readonly seq: number;
526
746
  readonly writer: string;
527
- readonly ops: readonly StoreOp[];
747
+ readonly ops: readonly StoreOp$1[];
528
748
  };
529
749
  /**
530
750
  * Seq continuity broke: the seat re-established state from a room snapshot (a reconnect past
@@ -579,7 +799,7 @@ type AgentSeatOptions = {
579
799
  readonly context?: toStoreOptions;
580
800
  readonly onEject?: (reason: string) => void;
581
801
  /** A write the relay refused; it is not in the room, and the doc was rehydrated. The envelope carries its values. */
582
- readonly onRefused?: (env: OpEnvelope, reason: 'generation' | 'schema' | 'order') => void;
802
+ readonly onRefused?: (env: OpEnvelope$1, reason: 'generation' | 'schema' | 'order') => void;
583
803
  };
584
804
  type AgentSeat<T extends object> = {
585
805
  /** The live converging replica. Reads exactly like a local signal store. */
@@ -595,6 +815,11 @@ type AgentSeat<T extends object> = {
595
815
  stableSnapshot(): StableSnapshot<T> | null;
596
816
  /** Run local writes and emit them to the room as one envelope, like any peer's edit. */
597
817
  write(fn: () => void): void;
818
+ /**
819
+ * The seat's writes that will never be admitted as they stand (a replay a compaction cut could not
820
+ * carry, or a relay refusal), each with `discard()` and `reauthor()`.
821
+ */
822
+ conflicts(): readonly MeshConflict[];
598
823
  /** Path-addressed write (`'a.b.c'` or segments), emitted immediately. */
599
824
  setAtPath(path: string | readonly (string | number)[], value: unknown): void;
600
825
  /**
@@ -664,7 +889,7 @@ export declare function setAtPath(node: unknown, path: string | readonly PathSeg
664
889
  * activity feeds and model context. Values render as truncated JSON. Pair with a seat's
665
890
  * `changes` stream: narrating each batch's ops yields an append-only account of the room.
666
891
  */
667
- export declare function describeOp(op: StoreOp, writer: string): string;
892
+ export declare function describeOp(op: StoreOp$1, writer: string): string;
668
893
  type WebRtcMeshOptions = {
669
894
  readonly room: string;
670
895
  readonly writer: string;