foldkit-sync 0.8.0 → 0.10.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/dist/index.d.mts CHANGED
@@ -1,627 +1,11 @@
1
- import { Config, Context, Duration, Effect, Exit, Layer, Metric, PubSub, Schema as Schema$1, Scope, Stream } from "effect";
2
- import { AppScope, Contract, MergeConstructors, MergeFields, MessageSet, RunnableApplication, Surface, Wiring, WritableProjection } from "foldkit-surface";
1
+ import { $ as InvalidOutboxError, A as ExchangeReply, B as nativeSocket, C as ReplicaStatus, D as defineSync, E as TransportClient, F as TransportError, G as OutboxEntry, H as serveSocket, I as TransportShape, J as CheckpointRegressionError, K as Storage, L as layerFromPromise, M as SocketLike, N as SocketOptions, O as syncMetrics, P as Transport, Q as InvalidExchangeError, R as layerLoopback, S as ReplicaState, T as SyncDefinition, U as toPromise, V as portSocket, W as workerSocket, X as ForeignAcknowledgementError, Y as CommittedOrderError, Z as ForeignRejectionError, _ as JournalContract, _t as sequence, a as DefinedSync, at as UnsupportedClockVersionError, b as Replica, c as MsgOf, ct as DocumentId, d as SyncFragment, dt as ReplicaId, et as InvalidReplicaHistoryError, f as forApplication, ft as Sequence, g as Exchange, gt as replicaId, h as CommittedOperation, ht as opId, i as AuthorizeRequest, it as StorageError, j as NotifyFrame, k as ExchangeFrame, l as PolicyJournalContract, lt as LocalSequence, m as CommitStamp, mt as localSequence, n as AuthorizeDecision, nt as ReplicaClosedError, o as FragmentMessages, ot as UnsupportedReplicaVersionError, p as Checkpoint, pt as documentId, q as indexedDb, r as AuthorizePolicy, rt as ReplicaError, s as MakeOptions, st as WrongReplicaStorageError, t as ApplicationSync, tt as ReplayError, u as StampPolicy, ut as OpId, v as Operation, w as Sync$1, x as ReplicaSnapshot, y as Rejection, z as layerSocket } from "./make-h5yD8STj.mjs";
2
+ import { Duration, Effect, Exit, Layer, PubSub, Schema as Schema$1, Scope, Stream } from "effect";
3
+ import { RunnableApplication } from "foldkit-surface";
3
4
  import { UrlRequest } from "foldkit/navigation";
4
5
  import { Subscriptions } from "foldkit/subscription";
5
6
  import * as Url from "foldkit/url";
6
7
  import { Document, HtmlBuilder } from "foldkit/html";
7
8
  import * as Update from "foldkit/update";
8
- //#region src/ids.d.ts
9
- /** Identifies the replicated document a replica or operation belongs to. */
10
- export declare const DocumentId: Schema$1.brand<Schema$1.NonEmptyString, "@foldkit-sync/DocumentId">;
11
- export type DocumentId = typeof DocumentId.Type;
12
- /** Identifies one replica (writer identity) within a document. */
13
- export declare const ReplicaId: Schema$1.brand<Schema$1.NonEmptyString, "@foldkit-sync/ReplicaId">;
14
- export type ReplicaId = typeof ReplicaId.Type;
15
- /** The stable identity of one operation within a document. */
16
- export declare const OpId: Schema$1.brand<Schema$1.NonEmptyString, "@foldkit-sync/OpId">;
17
- export type OpId = typeof OpId.Type;
18
- /**
19
- * A position in the committed document order. `0` is the start; a committed
20
- * operation's `serverSequence` and a replica's `cursor` are the same family.
21
- */
22
- export declare const Sequence: Schema$1.brand<Schema$1.Number, "@foldkit-sync/Sequence">;
23
- export type Sequence = typeof Sequence.Type;
24
- /** A replica's own operation counter within a document; 1-based. */
25
- export declare const LocalSequence: Schema$1.brand<Schema$1.Number, "@foldkit-sync/LocalSequence">;
26
- export type LocalSequence = typeof LocalSequence.Type;
27
- /**
28
- * Decode-and-brand helpers. A branded schema constructs the same value with
29
- * `DocumentId.make('todos')`, which is the spelling to lead with; these stay
30
- * for callers that already have them.
31
- */
32
- export declare const documentId: (value: string) => DocumentId;
33
- export declare const replicaId: (value: string) => ReplicaId;
34
- export declare const opId: (value: string) => OpId;
35
- export declare const sequence: (value: number) => Sequence;
36
- export declare const localSequence: (value: number) => LocalSequence;
37
- //#endregion
38
- //#region src/errors.d.ts
39
- declare const StorageError_base: Schema$1.Class<StorageError, Schema$1.TaggedStruct<"StorageError", {
40
- readonly message: Schema$1.String;
41
- readonly cause: Schema$1.optional<Schema$1.Unknown>;
42
- }>, import("effect/Cause").YieldableError>;
43
- /** The persisted storage could not be read or written. */
44
- export declare class StorageError extends StorageError_base {}
45
- declare const UnsupportedClockVersionError_base: Schema$1.Class<UnsupportedClockVersionError, Schema$1.TaggedStruct<"UnsupportedClockVersionError", {
46
- readonly schemaVersion: Schema$1.NullOr<Schema$1.Number>;
47
- readonly message: Schema$1.String;
48
- }>, import("effect/Cause").YieldableError>;
49
- /** The stored clock state targets a schema version this build does not support. */
50
- export declare class UnsupportedClockVersionError extends UnsupportedClockVersionError_base {}
51
- declare const WrongReplicaStorageError_base: Schema$1.Class<WrongReplicaStorageError, Schema$1.TaggedStruct<"WrongReplicaStorageError", {
52
- readonly documentId: Schema$1.String;
53
- readonly replicaId: Schema$1.String;
54
- readonly message: Schema$1.String;
55
- }>, import("effect/Cause").YieldableError>;
56
- /** The storage holds a different replica's state. */
57
- export declare class WrongReplicaStorageError extends WrongReplicaStorageError_base {}
58
- declare const InvalidReplicaHistoryError_base: Schema$1.Class<InvalidReplicaHistoryError, Schema$1.TaggedStruct<"InvalidReplicaHistoryError", {
59
- readonly message: Schema$1.String;
60
- readonly cause: Schema$1.optional<Schema$1.Unknown>;
61
- }>, import("effect/Cause").YieldableError>;
62
- /** The persisted replica history is internally inconsistent. */
63
- export declare class InvalidReplicaHistoryError extends InvalidReplicaHistoryError_base {}
64
- declare const InvalidExchangeError_base: Schema$1.Class<InvalidExchangeError, Schema$1.TaggedStruct<"InvalidExchangeError", {
65
- readonly message: Schema$1.String;
66
- readonly cause: Schema$1.optional<Schema$1.Unknown>;
67
- }>, import("effect/Cause").YieldableError>;
68
- /** The server's exchange response did not match the protocol schema. */
69
- export declare class InvalidExchangeError extends InvalidExchangeError_base {}
70
- declare const InvalidOutboxError_base: Schema$1.Class<InvalidOutboxError, Schema$1.TaggedStruct<"InvalidOutboxError", {
71
- readonly message: Schema$1.String;
72
- }>, import("effect/Cause").YieldableError>;
73
- /** A persisted pending operation could not have been produced by this replica. */
74
- export declare class InvalidOutboxError extends InvalidOutboxError_base {}
75
- declare const CheckpointRegressionError_base: Schema$1.Class<CheckpointRegressionError, Schema$1.TaggedStruct<"CheckpointRegressionError", {
76
- readonly cursor: Schema$1.Number;
77
- readonly checkpointCursor: Schema$1.Number;
78
- readonly message: Schema$1.String;
79
- }>, import("effect/Cause").YieldableError>;
80
- /** The server sent a checkpoint older than the replica's cursor. */
81
- export declare class CheckpointRegressionError extends CheckpointRegressionError_base {}
82
- declare const CommittedOrderError_base: Schema$1.Class<CommittedOrderError, Schema$1.TaggedStruct<"CommittedOrderError", {
83
- readonly expected: Schema$1.Number;
84
- readonly actual: Schema$1.Number;
85
- readonly message: Schema$1.String;
86
- }>, import("effect/Cause").YieldableError>;
87
- /** Committed operations were not contiguous from the replica's cursor. */
88
- export declare class CommittedOrderError extends CommittedOrderError_base {}
89
- declare const ForeignRejectionError_base: Schema$1.Class<ForeignRejectionError, Schema$1.TaggedStruct<"ForeignRejectionError", {
90
- readonly opId: Schema$1.String;
91
- readonly message: Schema$1.String;
92
- }>, import("effect/Cause").YieldableError>;
93
- /** The server rejected an operation the replica never sent. */
94
- export declare class ForeignRejectionError extends ForeignRejectionError_base {}
95
- declare const ForeignAcknowledgementError_base: Schema$1.Class<ForeignAcknowledgementError, Schema$1.TaggedStruct<"ForeignAcknowledgementError", {
96
- readonly opId: Schema$1.String;
97
- readonly message: Schema$1.String;
98
- }>, import("effect/Cause").YieldableError>;
99
- /**
100
- * The server answered an operation this request never sent, or both
101
- * acknowledged and rejected it. Acting on either would let a faulty or hostile
102
- * server delete local work.
103
- */
104
- export declare class ForeignAcknowledgementError extends ForeignAcknowledgementError_base {}
105
- declare const ReplicaClosedError_base: Schema$1.Class<ReplicaClosedError, Schema$1.TaggedStruct<"ReplicaClosedError", {
106
- readonly message: Schema$1.String;
107
- }>, import("effect/Cause").YieldableError>;
108
- /** The replica was closed while work was still being submitted. */
109
- export declare class ReplicaClosedError extends ReplicaClosedError_base {}
110
- declare const UnsupportedReplicaVersionError_base: Schema$1.Class<UnsupportedReplicaVersionError, Schema$1.TaggedStruct<"UnsupportedReplicaVersionError", {
111
- readonly protocolVersion: Schema$1.NullOr<Schema$1.Number>;
112
- readonly schemaVersion: Schema$1.NullOr<Schema$1.Number>;
113
- readonly message: Schema$1.String;
114
- }>, import("effect/Cause").YieldableError>;
115
- /** The stored replica state targets a protocol or schema version this build does not support. */
116
- export declare class UnsupportedReplicaVersionError extends UnsupportedReplicaVersionError_base {}
117
- declare const ReplayError_base: Schema$1.Class<ReplayError, Schema$1.TaggedStruct<"ReplayError", {
118
- readonly message: Schema$1.String;
119
- readonly cause: Schema$1.optional<Schema$1.Unknown>;
120
- }>, import("effect/Cause").YieldableError>;
121
- /**
122
- * `replay` threw for a submitted Message, so it could never be applied here or
123
- * on any other replica; nothing was written.
124
- */
125
- export declare class ReplayError extends ReplayError_base {}
126
- type ReplicaError = StorageError | ReplayError | WrongReplicaStorageError | InvalidReplicaHistoryError | InvalidExchangeError | UnsupportedReplicaVersionError | InvalidOutboxError | CheckpointRegressionError | CommittedOrderError | ForeignRejectionError | ForeignAcknowledgementError | ReplicaClosedError;
127
- //#endregion
128
- //#region src/indexedDb.d.ts
129
- /** One submitted operation, as `Storage.append` records it. */
130
- interface OutboxEntry {
131
- /** The replica's revision once this operation is in its outbox. */
132
- readonly revision: number;
133
- readonly nextLocalSequence: number;
134
- /**
135
- * The operation's local sequence. An entry with the sequence of one already in the
136
- * outbox replaces it: a coalesced submit rewrites the last operation.
137
- */
138
- readonly localSequence: number;
139
- /** The operation, encoded. */
140
- readonly operation: unknown;
141
- }
142
- /** Persists a replica's state with compare-and-swap on its revision. */
143
- interface Storage {
144
- /**
145
- * The saved state, with every operation appended since in its `pending` (replacing the
146
- * one of the same local sequence), and the last one's `revision` and `nextLocalSequence`.
147
- */
148
- load: () => Effect.Effect<unknown, StorageError>;
149
- /** Replaces the whole state, and with it every appended operation. */
150
- save: (state: unknown, expectedRevision: number | null) => Effect.Effect<void, StorageError>;
151
- /**
152
- * Optional. Records one submitted operation without rewriting the rest of the state, so
153
- * a submit costs the operation's size rather than the document's. Without it, a submit
154
- * saves the whole state.
155
- */
156
- append?: (entry: OutboxEntry, expectedRevision: number) => Effect.Effect<void, StorageError>;
157
- /** Idempotent; the caller closes the connection explicitly. */
158
- close: Effect.Effect<void>;
159
- }
160
- /** One database per document/replica; CAS prevents two tabs from sharing a writer identity. */
161
- export declare const indexedDb: (name: string | Config.Config<string>, factory?: IDBFactory | undefined) => Effect.Effect<Required<Storage>, StorageError, import("effect/Scope").Scope>;
162
- //#endregion
163
- //#region src/transport.d.ts
164
- declare const TransportError_base: Schema$1.Class<TransportError, Schema$1.TaggedStruct<"SyncTransportError", {
165
- readonly message: Schema$1.String;
166
- }>, import("effect/Cause").YieldableError>;
167
- /** The wire failure of a transport. A refusal is a result, not an error. */
168
- export declare class TransportError extends TransportError_base {}
169
- /** One request/response frame, as it crosses a wire. */
170
- interface ExchangeFrame {
171
- readonly id: string;
172
- readonly cursor: number;
173
- readonly pending: ReadonlyArray<Operation>;
174
- readonly epoch?: string | undefined;
175
- }
176
- interface ExchangeReply {
177
- readonly id: string;
178
- readonly result?: unknown;
179
- readonly error?: string;
180
- }
181
- /**
182
- * Sent by a server, unasked, when the document may have changed. It carries no
183
- * data: the replica exchanges from its own cursor, so a notice that is lost,
184
- * late, or one of many is harmless.
185
- */
186
- interface NotifyFrame {
187
- readonly notify: true;
188
- }
189
- interface TransportShape {
190
- /** `epoch` is the server history the replica's cursor points into, when it knows one. */
191
- readonly exchange: (cursor: number, pending: ReadonlyArray<Operation>, epoch?: string | undefined) => Effect.Effect<unknown, TransportError>;
192
- /**
193
- * Emits when the server may have something new, for a transport that can hear
194
- * it: `Replica.start` exchanges on each. A wake-up, not data.
195
- */
196
- readonly changes?: Stream.Stream<void> | undefined;
197
- /**
198
- * The connection itself, for another protocol to share, such as presence: a send goes to
199
- * the socket open now and is dropped while none is, and messages from every socket the
200
- * transport opens arrive here. It is the transport's to close.
201
- */
202
- readonly socket?: SocketLike | undefined;
203
- }
204
- declare const Transport_base: Context.ServiceClass<Transport, "foldkit-sync/Transport", TransportShape>;
205
- /**
206
- * The seam the replica syncs through.
207
- *
208
- * A service, not a concrete client, so an application substitutes an in-process
209
- * transport, a socket, or a test double without the replica knowing. A refusal
210
- * arrives in the exchange result; only a wire failure is a `TransportError`.
211
- */
212
- export declare class Transport extends Transport_base {}
213
- /** A transport backed by an in-process handler, for tests and single-process demos. */
214
- export declare const layerLoopback: (handler: (cursor: number, pending: ReadonlyArray<Operation>, epoch?: string | undefined) => unknown | Promise<unknown>) => Layer.Layer<Transport>;
215
- /** Wraps the promise-based client the replica already speaks. */
216
- export declare const layerFromPromise: (transport: TransportClient) => Layer.Layer<Transport>;
217
- /** Bridges the service back to the promise client the replica consumes. */
218
- export declare const toPromise: (transport: TransportShape) => TransportClient;
219
- /**
220
- * Serves one accepted socket, answering each exchange frame.
221
- *
222
- * The counterpart to `layerSocket`: the handler returns the exchange result, or
223
- * throws and the failure is written back as an error frame. With `changes`, a
224
- * subscription to the document's commits, the socket is also sent a
225
- * `NotifyFrame` after each, so a client hears of others' edits without polling.
226
- * Returns a function that stops serving.
227
- */
228
- export declare const serveSocket: (socket: SocketLike, options: {
229
- readonly exchange: (cursor: number, pending: ReadonlyArray<Operation>, epoch?: string | undefined) => unknown | Promise<unknown>;
230
- /** Subscribes to the document's commits; returns the unsubscribe. */
231
- readonly changes?: ((listener: () => void) => () => void) | undefined;
232
- }) => (() => void);
233
- /** The minimal socket the layer needs; the global `WebSocket` satisfies it. */
234
- interface SocketLike {
235
- send(data: string): void;
236
- close(): void;
237
- onMessage(listener: (data: string) => void): () => void;
238
- onClose(listener: () => void): () => void;
239
- /**
240
- * Optional. When provided, exchanges wait for it before sending, so a
241
- * transport can connect asynchronously. Absent means already connected.
242
- */
243
- onOpen?(listener: () => void): () => void;
244
- }
245
- interface SocketOptions {
246
- readonly url: string;
247
- /** Injectable for tests; defaults to the platform `WebSocket`. */
248
- readonly makeSocket?: ((url: string) => SocketLike) | undefined;
249
- /**
250
- * Consecutive failed connections after which queued work fails and new
251
- * exchanges fail fast until a connection is healthy again. Reconnecting goes
252
- * on regardless. Default 5.
253
- */
254
- readonly maxRetries?: number | undefined;
255
- /** Base delay of the exponential reconnect backoff. Default `50 millis`. */
256
- readonly retryBase?: Duration.Input | undefined;
257
- /** Longest wait between reconnect attempts. Default `5 seconds`. */
258
- readonly maxRetryDelay?: Duration.Input | undefined;
259
- /** Exchanges queued or in flight before new ones fail. Default 64. */
260
- readonly maxQueue?: number | undefined;
261
- }
262
- /** The default socket factory: the platform `WebSocket`, as a `SocketLike`. */
263
- export declare const nativeSocket: (url: string) => SocketLike;
264
- /**
265
- * A WebSocket client transport.
266
- *
267
- * One connection is live at a time. While it is connecting, exchanges queue; if
268
- * it closes, the transport reconnects on an exponential, jittered backoff and
269
- * re-sends every queued and in-flight frame with its original id, so a lost
270
- * reply is answered rather than dropped and a late reply cannot resolve a newer
271
- * frame. It never stops reconnecting: after `maxRetries` consecutive failures
272
- * queued work fails with a `TransportError`, and exchanges fail fast while no
273
- * socket is up, until a socket opens. The count resets only when a connection
274
- * proves healthy, by answering a frame or by staying open for `maxRetryDelay`:
275
- * a server that accepts a socket and drops it at once is backed off like one
276
- * that refuses it. A queue over `maxQueue` fails new
277
- * exchanges with backpressure. The socket is released when the layer's scope
278
- * ends.
279
- */
280
- export declare const layerSocket: (options: SocketOptions) => Layer.Layer<Transport, TransportError>;
281
- //#endregion
282
- //#region src/sync.d.ts
283
- /** Wire and persisted-format versions. A bump must handle the older value explicitly. */
284
- declare const PROTOCOL_VERSION = 1;
285
- declare const SCHEMA_VERSION = 1;
286
- /** A client-authored operation envelope. `message` is the application's encoded Message. */
287
- declare const OperationSchema: Schema$1.Struct<{
288
- readonly protocolVersion: Schema$1.Literal<1>;
289
- readonly schemaVersion: Schema$1.Literal<1>;
290
- readonly documentId: Schema$1.brand<Schema$1.NonEmptyString, "@foldkit-sync/DocumentId">;
291
- readonly replicaId: Schema$1.brand<Schema$1.NonEmptyString, "@foldkit-sync/ReplicaId">;
292
- readonly localSequence: Schema$1.brand<Schema$1.Number, "@foldkit-sync/LocalSequence">;
293
- readonly opId: Schema$1.brand<Schema$1.NonEmptyString, "@foldkit-sync/OpId">;
294
- readonly baseCursor: Schema$1.brand<Schema$1.Number, "@foldkit-sync/Sequence">;
295
- readonly message: Schema$1.Unknown;
296
- }>;
297
- type Operation = typeof OperationSchema.Type;
298
- /** An operation the server committed, with its authoritative order and actor. */
299
- declare const CommittedSchema: Schema$1.Struct<{
300
- readonly serverSequence: Schema$1.brand<Schema$1.Number, "@foldkit-sync/Sequence">;
301
- readonly actorId: Schema$1.NonEmptyString;
302
- readonly protocolVersion: Schema$1.Literal<1>;
303
- readonly schemaVersion: Schema$1.Literal<1>;
304
- readonly documentId: Schema$1.brand<Schema$1.NonEmptyString, "@foldkit-sync/DocumentId">;
305
- readonly replicaId: Schema$1.brand<Schema$1.NonEmptyString, "@foldkit-sync/ReplicaId">;
306
- readonly localSequence: Schema$1.brand<Schema$1.Number, "@foldkit-sync/LocalSequence">;
307
- readonly opId: Schema$1.brand<Schema$1.NonEmptyString, "@foldkit-sync/OpId">;
308
- readonly baseCursor: Schema$1.brand<Schema$1.Number, "@foldkit-sync/Sequence">;
309
- readonly message: Schema$1.Unknown;
310
- }>;
311
- /** Named to avoid colliding with `foldkit-durable`'s `Committed`. */
312
- type CommittedOperation = typeof CommittedSchema.Type;
313
- /** Counters and a histogram an application can scrape. */
314
- export declare const syncMetrics: {
315
- exchanges: Metric.Counter<number>;
316
- applied: Metric.Counter<number>;
317
- checkpoints: Metric.Counter<number>;
318
- exchangePending: Metric.Histogram<number>;
319
- };
320
- interface Checkpoint<Shared> {
321
- readonly cursor: Sequence;
322
- readonly model: Shared;
323
- }
324
- interface Exchange<Shared> {
325
- /** Server-committed operations as they arrived; validated against `CommittedOperation` on adoption. */
326
- readonly operations: ReadonlyArray<unknown>;
327
- readonly rejected: ReadonlyArray<OpId>;
328
- /** Sends from the request that are durably committed, so the replica can drop them. */
329
- readonly acknowledged?: ReadonlyArray<OpId> | undefined;
330
- /** The snapshot a replica predating compaction adopts in place of the log. */
331
- readonly checkpoint?: Checkpoint<Shared> | undefined;
332
- /** The server sent only part of what is after the cursor; the replica asks again. */
333
- readonly more?: boolean | undefined;
334
- /**
335
- * The identity of the server's history. The replica sends back the one it last saw; a
336
- * server that finds another answers from the start of its own history, and the replica,
337
- * seeing a new epoch, rebuilds its committed state from that answer and keeps its outbox.
338
- */
339
- readonly epoch?: string | undefined;
340
- }
341
- interface ReplicaState<Shared> {
342
- readonly protocolVersion: typeof PROTOCOL_VERSION;
343
- readonly schemaVersion: typeof SCHEMA_VERSION;
344
- readonly documentId: DocumentId;
345
- readonly replicaId: ReplicaId;
346
- readonly revision: number;
347
- readonly nextLocalSequence: LocalSequence;
348
- readonly cursor: Sequence;
349
- readonly committed: Shared;
350
- readonly committedIds: ReadonlyArray<string>;
351
- readonly pending: ReadonlyArray<Operation>;
352
- /** The server history `cursor` points into, once an exchange has named one. */
353
- readonly epoch?: string;
354
- }
355
- /**
356
- * What the promise-based edge adapter consumes; the Effect `Transport` service
357
- * is the primary seam.
358
- */
359
- interface TransportClient {
360
- /** `epoch` is the server history the replica's cursor points into, when it knows one. */
361
- exchange(cursor: Sequence, pending: ReadonlyArray<Operation>, epoch?: string | undefined): Promise<unknown>;
362
- }
363
- /** A redacted view of a replica's state, for a UI to explain and recover. */
364
- interface ReplicaStatus {
365
- readonly pending: number;
366
- readonly cursor: Sequence;
367
- /** The last exchange failure, cleared by a successful exchange. */
368
- readonly lastError: string | undefined;
369
- /** Operations the server refused, most recent first. */
370
- readonly rejected: ReadonlyArray<OpId>;
371
- }
372
- /**
373
- * A consistent status and optimistic-shared pair, read from one replica state.
374
- * `Replica.changes` emits it so a UI can hold a single subscription.
375
- */
376
- interface ReplicaSnapshot<Shared> {
377
- readonly status: ReplicaStatus;
378
- readonly shared: Shared;
379
- /** The server-confirmed state the optimistic `shared` is built on. */
380
- readonly committed: Shared;
381
- /**
382
- * The local sequence the next submitted operation takes. Only a successful
383
- * submit moves it, so a caller that submits one Message at a time can tell
384
- * from one snapshot whether `shared` already holds it.
385
- */
386
- readonly nextLocalSequence: LocalSequence;
387
- }
388
- interface Replica<Message, Shared> {
389
- /** The optimistic projection: committed state with pending operations replayed. */
390
- readonly shared: Effect.Effect<Shared>;
391
- /**
392
- * The server-confirmed state through `cursor`, with no pending operation
393
- * applied. A pending edit reaches it only once the server commits it, and a
394
- * rejected one never does.
395
- */
396
- readonly committed: Effect.Effect<Shared>;
397
- readonly pending: Effect.Effect<ReadonlyArray<Operation>>;
398
- readonly cursor: Effect.Effect<Sequence>;
399
- /**
400
- * Waiting/recovery information without exposing Messages or the Model. It is a
401
- * snapshot; `statusChanges` re-emits it after every submit and exchange.
402
- */
403
- readonly status: Effect.Effect<ReplicaStatus>;
404
- /** The status, re-emitted after every submit and exchange. */
405
- readonly statusChanges: Stream.Stream<ReplicaStatus>;
406
- /**
407
- * The status and the optimistic shared value together, re-emitted after every
408
- * submit and exchange, so a UI can subscribe once instead of to both.
409
- */
410
- readonly changes: Stream.Stream<ReplicaSnapshot<Shared>>;
411
- /** The status, `shared`, `committed` and next local sequence, read from one replica state. */
412
- readonly snapshot: Effect.Effect<ReplicaSnapshot<Shared>>;
413
- readonly submit: (message: Message) => Effect.Effect<void, ReplicaError>;
414
- /** Reconciles against the server. The `Transport` service must be provided. */
415
- readonly synchronize: Effect.Effect<void, ReplicaError | TransportError, Transport>;
416
- /**
417
- * The exchange loop: exchanges once, then after every `submit` and every
418
- * notice on the transport's `changes`, until the replica closes or the fiber
419
- * is interrupted. A failed exchange is recorded
420
- * in `status.lastError` and retried on a backoff (from 0.5 s, doubling up to
421
- * 30 s), or at once on the next `submit`, so the fiber never fails. Fork it
422
- * with `Effect.forkScoped` and provide `Transport`.
423
- */
424
- readonly start: Effect.Effect<void, never, Transport>;
425
- readonly close: Effect.Effect<void>;
426
- }
427
- interface SyncDefinition<Message, Shared, MessageEncoded, SharedEncoded> {
428
- readonly documentId: DocumentId;
429
- readonly message: Schema$1.Codec<Message, MessageEncoded, never, never>;
430
- readonly shared: Schema$1.Codec<Shared, SharedEncoded, never, never>;
431
- readonly empty: Shared;
432
- readonly durable: (message: Message) => boolean;
433
- readonly replay: (shared: Shared, message: Message) => Shared;
434
- /**
435
- * Optional. Merges a durable Message into the one submitted before it, while that one
436
- * has not been sent: one operation instead of two, for a burst of typing. Replaying the
437
- * result must equal replaying `last` then `next`. Undefined keeps them apart.
438
- */
439
- readonly coalesce?: ((last: Message, next: Message) => Message | undefined) | undefined;
440
- }
441
- interface Sync$1<Message, Shared> {
442
- readonly documentId: DocumentId;
443
- /** Whether a Message is one the replica records and replays. */
444
- readonly durable: (message: Message) => boolean;
445
- /**
446
- * Low-level wire codecs for adapters and the transport. Most applications use
447
- * `journalContract` and `openReplica`; these are exposed for a custom
448
- * transport or a server that must speak the operation envelope directly.
449
- */
450
- readonly codec: {
451
- readonly normalizeOperation: (input: unknown) => Operation;
452
- readonly operationFrom: (input: unknown, documentId: DocumentId) => Operation;
453
- readonly committedFrom: (input: unknown, documentId: DocumentId) => CommittedOperation;
454
- readonly decodeExchange: (input: unknown) => Exchange<Shared>;
455
- };
456
- /** The codecs and pure reducer `foldkit-durable`'s `makeJournal` consumes. */
457
- readonly journalContract: () => JournalContract<Operation, Shared>;
458
- readonly openReplica: (replicaId: ReplicaId, storage: Storage) => Effect.Effect<Replica<Message, Shared>, ReplicaError>;
459
- }
460
- /** Structural match for `foldkit-durable`'s journal options; Sync stays independent. */
461
- interface JournalContract<Operation, Shared> {
462
- /** The replica each operation came from, which Durable binds to its first committer. */
463
- readonly replicaId: (operation: Operation) => string;
464
- /** Sync's operation id includes the replica, even after Durable compacts its payload. */
465
- readonly legacyReplicaId: (opId: string) => string;
466
- readonly operation: {
467
- /** Operations are stored in their encoded form, so this is the identity. */
468
- readonly encode: (operation: Operation) => Operation;
469
- readonly decode: (input: unknown) => Operation;
470
- };
471
- readonly snapshot: {
472
- readonly encode: (snapshot: Shared) => unknown;
473
- readonly decode: (input: unknown) => Shared;
474
- };
475
- readonly empty: () => Shared;
476
- readonly reduce: (snapshot: Shared, operation: Operation) => Shared;
477
- }
478
- /**
479
- * Binds the replicated-state protocol to one application contract.
480
- *
481
- * The returned codecs decide what is a valid operation and what the shared
482
- * projection means; the replica owns the local outbox, optimistic projection,
483
- * and reconciliation as Effects, and never runs a second reducer.
484
- */
485
- export declare const defineSync: <Message, Shared, MessageEncoded, SharedEncoded>(definition: SyncDefinition<Message, Shared, MessageEncoded, SharedEncoded>) => Sync$1<Message, Shared>;
486
- //#endregion
487
- //#region src/make.d.ts
488
- type MessageConstructor<Message> = (...args: never[]) => Message;
489
- /** The Message union a tuple of constructors produces. */
490
- type MsgOf<Ms extends readonly unknown[]> = Ms[number] extends ((...args: never[]) => infer M) ? M : never;
491
- type AppMessage<AppModel, F extends Schema$1.Struct.Fields, Cases extends Record<string, Schema$1.Struct.Fields>> = Schema$1.Schema.Type<AppScope<AppModel, F, Cases>['Message']>;
492
- /** The `_tag` literal of the Message a constructor produces. */
493
- type TagOf<C> = C extends ((...args: never[]) => infer M) ? M extends {
494
- readonly _tag: infer T extends string;
495
- } ? T : never : never;
496
- /**
497
- * A journal contract that also carries the declared authorization policy, in
498
- * the shape `makeJournal` takes, so `makeJournal({ ...contract })` applies it.
499
- */
500
- interface PolicyJournalContract<Operation, Shared, Principal> extends JournalContract<Operation, Shared> {
501
- readonly authorize?: (request: {
502
- readonly principal: Principal;
503
- readonly operation: Operation;
504
- readonly snapshot: Shared;
505
- }) => boolean;
506
- }
507
- /** What a per-variant `authorize` rule sees before the journal commits. */
508
- interface AuthorizeRequest<Principal, Message, Shared> {
509
- readonly principal: Principal;
510
- readonly message: Message;
511
- readonly shared: Shared;
512
- }
513
- /**
514
- * Per-variant policy, keyed by durable tag: `message` is that variant exactly,
515
- * `shared` the authoritative snapshot. A variant without a rule is allowed; the
516
- * server may still refuse on its own grounds.
517
- */
518
- type AuthorizePolicy<Principal, Fields extends Schema$1.Struct.Fields, Ms extends readonly unknown[]> = { readonly [K in TagOf<Ms[number]>]?: (request: AuthorizeRequest<Principal, Extract<MsgOf<Ms>, {
519
- readonly _tag: K;
520
- }>, Schema$1.Struct.Type<Fields>>) => boolean; };
521
- interface BaseOptions<Principal, Fields extends Schema$1.Struct.Fields, Ms extends readonly unknown[]> {
522
- readonly documentId: DocumentId;
523
- /** Name for the generated `surface`; defaults to the document id. */
524
- readonly name?: string;
525
- /**
526
- * Replaces the replay derived from the application's `update`. It is a pure
527
- * reducer over the shared subset; only durable Messages reach it, and it runs
528
- * during admission, replay, and optimistic projection. It is not guarded: the
529
- * author owns its agreement with `update`.
530
- */
531
- readonly replay?: (shared: Schema$1.Struct.Type<NoInfer<Fields>>, message: MsgOf<NoInfer<Ms>>) => Schema$1.Struct.Type<NoInfer<Fields>>;
532
- /** Authorization the server journal applies before committing; see `AuthorizePolicy`. */
533
- readonly authorize?: AuthorizePolicy<Principal, NoInfer<Fields>, NoInfer<Ms>>;
534
- /**
535
- * Merges a durable Message into the one submitted before it while that one is unsent,
536
- * so a burst of edits is one operation. Replaying the result must equal replaying
537
- * `last` then `next`; undefined keeps them apart.
538
- */
539
- readonly coalesce?: (last: MsgOf<NoInfer<Ms>>, next: MsgOf<NoInfer<Ms>>) => MsgOf<NoInfer<Ms>> | undefined;
540
- }
541
- interface MakeOptions<AppModel, Fields extends Schema$1.Struct.Fields, Subset, Ms extends readonly MessageConstructor<any>[], Principal = unknown> extends BaseOptions<Principal, Fields, Ms> {
542
- /** The writable projection of the shared fields. */
543
- readonly shared: WritableProjection<AppModel, Fields>;
544
- /** The Message subset the replica durably records and replays. */
545
- readonly durable: MessageSet<AppModel, any, Subset, Ms>;
546
- }
547
- /**
548
- * One feature's contribution to a document: the fields it shares and the
549
- * Messages it records. `compose` merges fragments into one, to spread into
550
- * `make`; a field declared twice with a different codec or a tag declared twice
551
- * is rejected there.
552
- */
553
- interface SyncFragment<AppModel, Fields extends Schema$1.Struct.Fields, Subset, Ms extends readonly MessageConstructor<any>[]> {
554
- readonly shared: WritableProjection<AppModel, Fields>;
555
- readonly durable: MessageSet<AppModel, any, Subset, Ms>;
556
- }
557
- type SharedOf<Fs extends readonly SyncFragment<any, any, any, any>[]> = { readonly [K in keyof Fs]: Fs[K]['shared']; };
558
- type DurableOf<Fs extends readonly SyncFragment<any, any, any, any>[]> = { readonly [K in keyof Fs]: Fs[K]['durable']; };
559
- /** The merged shared fields of several fragments. */
560
- type FragmentFields<Fs extends readonly SyncFragment<any, any, any, any>[]> = MergeFields<SharedOf<Fs>>;
561
- /** The concatenated durable constructors of several fragments. */
562
- type FragmentConstructors<Fs extends readonly SyncFragment<any, any, any, any>[]> = MergeConstructors<DurableOf<Fs>>;
563
- /** The union of Messages several fragments record. */
564
- type FragmentMessages<Fs extends readonly SyncFragment<any, any, any, any>[]> = Fs[number] extends SyncFragment<any, any, infer V, any> ? V : never;
565
- /**
566
- * The value `make` returns: the low-level `Sync` protocol plus the writable
567
- * projection, the declared Messages, and a read-only Surface over the
568
- * projection. Exported so a consumer can name the type.
569
- */
570
- interface DefinedSync<AppModel, Fields extends Schema$1.Struct.Fields, Message, Ms extends readonly unknown[], Principal = unknown,
571
- /** `true` when `make` was given `authorize`, so the contract's `authorize` is present. */
572
- Authorized extends boolean = false> extends Sync$1<Message, Schema$1.Struct.Type<Fields>> {
573
- readonly surface: Surface<AppModel, Schema$1.Struct.Type<Fields>, MsgOf<Ms>, void>;
574
- readonly projection: WritableProjection<AppModel, Fields>;
575
- /** The reducer the replica replays durable Messages with: derived from `update`, or `make`'s `replay`. */
576
- readonly replay: (shared: Schema$1.Struct.Type<Fields>, message: Message) => Schema$1.Struct.Type<Fields>;
577
- readonly messages: Ms;
578
- /** For `Module`: this contract owns the shared projection's paths and records the durable tags. */
579
- readonly contract: Contract;
580
- /**
581
- * How this contract joins an assembly: contract-only, so the Module sees it.
582
- * It routes nothing, runs nothing, and subscribes to nothing; Sync owns the
583
- * runtime through `mount` rather than joining it.
584
- */
585
- readonly wiring: () => Wiring<AppModel, never>;
586
- /** The durable journal's codecs, reducer, and, when declared, authorization. */
587
- readonly journalContract: () => Authorized extends true ? PolicyJournalContract<Operation, Schema$1.Struct.Type<Fields>, Principal> & Required<Pick<PolicyJournalContract<Operation, Schema$1.Struct.Type<Fields>, Principal>, 'authorize'>> : PolicyJournalContract<Operation, Schema$1.Struct.Type<Fields>, Principal>;
588
- }
589
- /** The sync constructors specialized to one application. */
590
- interface ApplicationSync<AppModel, F extends Schema$1.Struct.Fields, Cases extends Record<string, Schema$1.Struct.Fields>, Principal = unknown> {
591
- /**
592
- * Fixes the `Principal` that `authorize` rules see. A `Principal` cannot be a
593
- * positional type argument beside an inferred Model, so it is supplied here:
594
- * `Sync.forApplication(App).withPrincipal<User>()`. Type-only.
595
- */
596
- readonly withPrincipal: <P>() => ApplicationSync<AppModel, F, Cases, P>;
597
- /** One feature's shared fields and durable Messages, for `compose`. */
598
- readonly fragment: <Fields extends Schema$1.Struct.Fields, Subset, Ms extends readonly MessageConstructor<AppMessage<AppModel, F, Cases>>[]>(config: {
599
- readonly shared: WritableProjection<AppModel, Fields>;
600
- readonly durable: MessageSet<AppModel, any, Subset, Ms>;
601
- }) => SyncFragment<AppModel, Fields, Subset, Ms>;
602
- /**
603
- * Merges fragments into one: `make({ documentId, ...compose(Todos, Members) })`.
604
- * A field declared twice with a different codec, a tag declared twice, or a
605
- * fragment from another application throws.
606
- */
607
- readonly compose: <const Fs extends readonly SyncFragment<AppModel, any, any, any>[]>(...fragments: Fs) => SyncFragment<AppModel, FragmentFields<Fs>, FragmentMessages<Fs>, FragmentConstructors<Fs>>;
608
- readonly make: {
609
- <Fields extends Schema$1.Struct.Fields, Subset, Ms extends readonly MessageConstructor<AppMessage<AppModel, F, Cases>>[]>(options: MakeOptions<AppModel, Fields, Subset, Ms, Principal> & {
610
- readonly authorize: AuthorizePolicy<Principal, NoInfer<Fields>, NoInfer<Ms>>;
611
- }): DefinedSync<AppModel, Fields, AppMessage<AppModel, F, Cases>, Ms, Principal, true>;
612
- <Fields extends Schema$1.Struct.Fields, Subset, Ms extends readonly MessageConstructor<AppMessage<AppModel, F, Cases>>[]>(options: MakeOptions<AppModel, Fields, Subset, Ms, Principal>): DefinedSync<AppModel, Fields, AppMessage<AppModel, F, Cases>, Ms, Principal>;
613
- };
614
- }
615
- /**
616
- * Specializes the sync constructors to a `Surface.application`, so
617
- * `Sync.forApplication(App).make({ documentId, shared, durable })` derives the
618
- * shared codec, the initial snapshot, the durable predicate, and replay from
619
- * the application, and refuses a subset that belongs to another application.
620
- * `defineSync` remains the protocol primitive when there is no application to
621
- * derive from.
622
- */
623
- export declare const forApplication: <AppModel, F extends Schema$1.Struct.Fields, Cases extends Record<string, Schema$1.Struct.Fields>>(app: RunnableApplication<AppModel, F, Cases, any>) => ApplicationSync<AppModel, F, Cases>;
624
- //#endregion
625
9
  //#region src/mount.d.ts
626
10
  /**
627
11
  * A Command that dispatches `message` as the next transition, which under `Sync.mount`
@@ -674,7 +58,23 @@ interface MountOptions<Model, Message, Shared, Resources> {
674
58
  * return Commands (a DOM the change has to reach). Omitted, the Model is `next`. It is
675
59
  * not called for a status that changes nothing the Model shows, such as the first.
676
60
  */
677
- readonly onReinstall?: ((next: Model, previous: Model) => Update.Return<Model, Message, Resources>) | undefined;
61
+ readonly onReinstall?: ((next: Model, previous: Model, change: Reinstall) => Update.Return<Model, Message, Resources>) | undefined;
62
+ /**
63
+ * Runs on the Model after every update of the mounted application, a durable
64
+ * Message's and a reinstall's included, and never in replay: for local state
65
+ * derived from the shared slice, which a durable transition may not write
66
+ * (the overlays `foldkit-sync/remote` keeps in Remote). With nothing to
67
+ * change it returns the Model it was given.
68
+ */
69
+ readonly afterUpdate?: ((model: Model) => Update.Return<Model, Message, Resources>) | undefined;
70
+ }
71
+ /**
72
+ * What a reinstall came from. `reset` is a server reset: the replica's
73
+ * committed history is a new one, so anything an application derived from
74
+ * the old one (reads cached by commit sequence, say) is to be read again.
75
+ */
76
+ interface Reinstall {
77
+ readonly reset: boolean;
678
78
  }
679
79
  /**
680
80
  * The shared slice as the server has confirmed it, outside the Model. It is a
@@ -704,6 +104,15 @@ interface Mounted<Model, Message, Shared = unknown> {
704
104
  * report an optimistic edit as done: `Agent.when({ source: mounted.committed, … })`.
705
105
  */
706
106
  readonly committed: CommittedView<Shared>;
107
+ /**
108
+ * Resolves once the Model has caught up with the replica: no persist in
109
+ * flight or unanswered, every replica status the mount was told of seen,
110
+ * and every reinstall it asked for applied. It observes and never does the
111
+ * work. Frames are not its to wait for (`Frames.track` in
112
+ * `foldkit-mixins/testing` is), nor I/O a Command started. Rejects after
113
+ * `dispose`.
114
+ */
115
+ readonly settled: () => Promise<void>;
707
116
  /** Waits for in-flight persists, then disposes the runtime. The replica stays open. */
708
117
  readonly dispose: () => Promise<void>;
709
118
  }
@@ -814,9 +223,16 @@ export declare const createPresenceHub: <Update>() => PresenceHub<Update>;
814
223
  * id: the server owns peer identity, so a client cannot assert another's.
815
224
  */
816
225
  export declare const socketPresenceChannel: <Update>(socket: SocketLike) => Effect.Effect<PresenceChannel<Update>, never, Scope.Scope>;
817
- /** Serves presence frames on an accepted socket, stamping the connection's identity. */
226
+ /**
227
+ * Serves presence frames on an accepted socket, stamping the connection's
228
+ * identity, until the socket closes or the returned function is called.
229
+ * With `opens`, the connection joins only once it answers that it may open
230
+ * the document the presence accompanies: until then, and for good when it
231
+ * is refused or fails, nothing reaches it and nothing it sends is relayed.
232
+ */
818
233
  export declare const servePresence: <Update>(socket: SocketLike, hub: PresenceHub<Update>, options: {
819
234
  readonly peerId: string;
235
+ readonly opens?: Effect.Effect<boolean, unknown> | undefined;
820
236
  }) => (() => void);
821
237
  //#endregion
822
238
  //#region src/lww.d.ts
@@ -937,8 +353,14 @@ export declare const Sync: {
937
353
  readonly exchange: (cursor: number, pending: ReadonlyArray<Operation>, epoch?: string | undefined) => unknown | Promise<unknown>;
938
354
  readonly changes?: ((listener: () => void) => () => void) | undefined;
939
355
  }) => (() => void);
356
+ /** The accepted end of a Cloudflare `WebSocketPair`, for `serve`. */
357
+ workerSocket: (socket: WebSocket) => SocketLike;
940
358
  /** The default socket factory: the platform `WebSocket`. */
941
359
  nativeSocket: (url: string) => SocketLike;
360
+ /** A socket over a `MessagePort`, closed by `close()` or an abort signal. */
361
+ portSocket: (port: MessagePort, options?: {
362
+ readonly signal?: AbortSignal | undefined;
363
+ }) => SocketLike;
942
364
  };
943
365
  /** An ephemeral, TTL'd peer registry, deliberately outside the durable log. */
944
366
  presence: {
@@ -964,6 +386,7 @@ export declare const Sync: {
964
386
  /** Serves presence frames on an accepted socket, stamping the connection's identity. */
965
387
  serve: <Update>(socket: SocketLike, hub: PresenceHub<Update>, options: {
966
388
  readonly peerId: string;
389
+ readonly opens?: import("effect/Effect").Effect<boolean, unknown> | undefined;
967
390
  }) => (() => void);
968
391
  socketChannel: <Update>(socket: SocketLike) => import("effect/Effect").Effect<PresenceChannel<Update>, never, import("effect/Scope").Scope>;
969
392
  loopbackChannel: <Update>() => import("effect/Effect").Effect<{
@@ -1016,5 +439,5 @@ export declare const Sync: {
1016
439
  };
1017
440
  };
1018
441
  //#endregion
1019
- export type { ApplicationSync, AuthorizePolicy, AuthorizeRequest, Checkpoint, CommittedOperation, CommittedView, DefinedSync, Exchange, ExchangeFrame, ExchangeReply, FragmentMessages, JournalContract, LwwClock, LwwClockState, MakeOptions, MountOptions, MountUrl, Mounted, MsgOf, NotifyFrame, Operation, OutboxEntry, PolicyJournalContract, Presence, PresenceChannel, PresenceHub, PresenceOptions, PresencePeer, PresenceUpdate, Replica, ReplicaError, ReplicaSnapshot, ReplicaState, ReplicaStatus, SocketLike, SocketOptions, Storage, SyncDefinition, SyncFragment, TransportClient, TransportShape };
442
+ export { type ApplicationSync, type AuthorizeDecision, type AuthorizePolicy, type AuthorizeRequest, type Checkpoint, CheckpointRegressionError, type CommitStamp, type CommittedOperation, CommittedOrderError, type CommittedView, type DefinedSync, DocumentId, type Exchange, type ExchangeFrame, type ExchangeReply, ForeignAcknowledgementError, ForeignRejectionError, type FragmentMessages, InvalidExchangeError, InvalidOutboxError, InvalidReplicaHistoryError, type JournalContract, LocalSequence, type LwwClock, type LwwClockState, type MakeOptions, type MountOptions, type MountUrl, type Mounted, type MsgOf, type NotifyFrame, OpId, type Operation, type OutboxEntry, type PolicyJournalContract, type Presence, type PresenceChannel, type PresenceHub, type PresenceOptions, type PresencePeer, type PresenceUpdate, type Reinstall, type Rejection, ReplayError, type Replica, ReplicaClosedError, type ReplicaError, ReplicaId, type ReplicaSnapshot, type ReplicaState, type ReplicaStatus, Sequence, type SocketLike, type SocketOptions, type StampPolicy, type Storage, StorageError, type SyncDefinition, type SyncFragment, Transport, type TransportClient, TransportError, type TransportShape, UnsupportedClockVersionError, UnsupportedReplicaVersionError, WrongReplicaStorageError, defineSync, documentId, forApplication, indexedDb, layerFromPromise, layerLoopback, layerSocket, localSequence, nativeSocket, opId, portSocket, replicaId, sequence, serveSocket, syncMetrics, toPromise, workerSocket };
1020
443
  //# sourceMappingURL=index.d.mts.map