foldkit-sync 0.9.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,169 +1,11 @@
1
- import { $ as Sequence, A as serveSocket, B as InvalidOutboxError, C as TransportError, D as layerSocket, E as layerLoopback, F as CheckpointRegressionError, G as StorageError, H as ReplayError, I as CommittedOrderError, J as WrongReplicaStorageError, K as UnsupportedClockVersionError, L as ForeignAcknowledgementError, M as OutboxEntry, N as Storage, O as nativeSocket, P as indexedDb, Q as ReplicaId, R as ForeignRejectionError, S as Transport, T as layerFromPromise, U as ReplicaClosedError, V as InvalidReplicaHistoryError, W as ReplicaError, X as LocalSequence, Y as DocumentId, Z as OpId, _ as ExchangeFrame, a as JournalContract, b as SocketLike, c as Replica, d as ReplicaStatus, et as documentId, f as Sync$1, g as syncMetrics, h as defineSync, i as Exchange, it as sequence, j as toPromise, k as portSocket, l as ReplicaSnapshot, m as TransportClient, n as CommitStamp, nt as opId, o as Operation, p as SyncDefinition, q as UnsupportedReplicaVersionError, r as CommittedOperation, rt as replicaId, s as Rejection, t as Checkpoint, tt as localSequence, u as ReplicaState, v as ExchangeReply, w as TransportShape, x as SocketOptions, y as NotifyFrame, z as InvalidExchangeError } from "./sync-CP5UGs4r.mjs";
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
2
  import { Duration, Effect, Exit, Layer, PubSub, Schema as Schema$1, Scope, Stream } from "effect";
3
- import { AppScope, Contract, MergeConstructors, MergeFields, MessageSet, RunnableApplication, Surface, Wiring, WritableProjection } from "foldkit-surface";
3
+ import { RunnableApplication } from "foldkit-surface";
4
4
  import { UrlRequest } from "foldkit/navigation";
5
5
  import { Subscriptions } from "foldkit/subscription";
6
6
  import * as Url from "foldkit/url";
7
7
  import { Document, HtmlBuilder } from "foldkit/html";
8
8
  import * as Update from "foldkit/update";
9
- //#region src/make.d.ts
10
- type MessageConstructor<Message> = (...args: never[]) => Message;
11
- /** The Message union a tuple of constructors produces. */
12
- type MsgOf<Ms extends readonly unknown[]> = Ms[number] extends ((...args: never[]) => infer M) ? M : never;
13
- 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']>;
14
- /** The `_tag` literal of the Message a constructor produces. */
15
- type TagOf<C> = C extends ((...args: never[]) => infer M) ? M extends {
16
- readonly _tag: infer T extends string;
17
- } ? T : never : never;
18
- /**
19
- * A journal contract that also carries the declared authorization policy, in
20
- * the shape `makeJournal` takes, so `makeJournal({ ...contract })` applies it.
21
- */
22
- interface PolicyJournalContract<Operation, Shared, Principal> extends JournalContract<Operation, Shared> {
23
- readonly authorize?: (request: {
24
- readonly principal: Principal;
25
- readonly operation: Operation;
26
- readonly snapshot: Shared;
27
- }) => AuthorizeDecision;
28
- }
29
- /**
30
- * What a rule decides: allowed, refused, or refused with a reason the server
31
- * sends to the person whose edit it was. The shape of Durable's own decision.
32
- */
33
- type AuthorizeDecision = boolean | {
34
- readonly allowed: false;
35
- readonly reason: string;
36
- };
37
- /** What a per-variant `authorize` rule sees before the journal commits. */
38
- interface AuthorizeRequest<Principal, Message, Shared> {
39
- readonly principal: Principal;
40
- readonly message: Message;
41
- readonly shared: Shared;
42
- }
43
- /**
44
- * Per-variant policy, keyed by durable tag: `message` is that variant exactly,
45
- * `shared` the authoritative snapshot. A variant without a rule is allowed; the
46
- * server may still refuse on its own grounds.
47
- */
48
- 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>, {
49
- readonly _tag: K;
50
- }>, Schema$1.Struct.Type<Fields>>) => AuthorizeDecision; };
51
- /**
52
- * Per-variant commit stamps, keyed by durable tag: each writes what the server's commit
53
- * decided (its sequence, its actor) into that variant, and returns the same variant. A
54
- * variant without one is committed as sent.
55
- */
56
- type StampPolicy<Ms extends readonly unknown[]> = { readonly [K in TagOf<Ms[number]>]?: (message: Extract<MsgOf<Ms>, {
57
- readonly _tag: K;
58
- }>, commit: CommitStamp) => Extract<MsgOf<Ms>, {
59
- readonly _tag: K;
60
- }>; };
61
- interface BaseOptions<Principal, Fields extends Schema$1.Struct.Fields, Ms extends readonly unknown[]> {
62
- readonly documentId: DocumentId;
63
- /** Name for the generated `surface`; defaults to the document id. */
64
- readonly name?: string;
65
- /**
66
- * Replaces the replay derived from the application's `update`. It is a pure
67
- * reducer over the shared subset; only durable Messages reach it, and it runs
68
- * during admission, replay, and optimistic projection. It is not guarded: the
69
- * author owns its agreement with `update`.
70
- */
71
- readonly replay?: (shared: Schema$1.Struct.Type<NoInfer<Fields>>, message: MsgOf<NoInfer<Ms>>) => Schema$1.Struct.Type<NoInfer<Fields>>;
72
- /** Authorization the server journal applies before committing; see `AuthorizePolicy`. */
73
- readonly authorize?: AuthorizePolicy<Principal, NoInfer<Fields>, NoInfer<Ms>>;
74
- /** What the server's commit writes into a durable Message; see `StampPolicy`. */
75
- readonly stamp?: StampPolicy<NoInfer<Ms>>;
76
- /**
77
- * Merges a durable Message into the one submitted before it while that one is unsent,
78
- * so a burst of edits is one operation. Replaying the result must equal replaying
79
- * `last` then `next`; undefined keeps them apart.
80
- */
81
- readonly coalesce?: (last: MsgOf<NoInfer<Ms>>, next: MsgOf<NoInfer<Ms>>) => MsgOf<NoInfer<Ms>> | undefined;
82
- }
83
- interface MakeOptions<AppModel, Fields extends Schema$1.Struct.Fields, Subset, Ms extends readonly MessageConstructor<any>[], Principal = unknown> extends BaseOptions<Principal, Fields, Ms> {
84
- /** The writable projection of the shared fields. */
85
- readonly shared: WritableProjection<AppModel, Fields>;
86
- /** The Message subset the replica durably records and replays. */
87
- readonly durable: MessageSet<AppModel, any, Subset, Ms>;
88
- }
89
- /**
90
- * One feature's contribution to a document: the fields it shares and the
91
- * Messages it records. `compose` merges fragments into one, to spread into
92
- * `make`; a field declared twice with a different codec or a tag declared twice
93
- * is rejected there.
94
- */
95
- interface SyncFragment<AppModel, Fields extends Schema$1.Struct.Fields, Subset, Ms extends readonly MessageConstructor<any>[]> {
96
- readonly shared: WritableProjection<AppModel, Fields>;
97
- readonly durable: MessageSet<AppModel, any, Subset, Ms>;
98
- }
99
- type SharedOf<Fs extends readonly SyncFragment<any, any, any, any>[]> = { readonly [K in keyof Fs]: Fs[K]['shared']; };
100
- type DurableOf<Fs extends readonly SyncFragment<any, any, any, any>[]> = { readonly [K in keyof Fs]: Fs[K]['durable']; };
101
- /** The merged shared fields of several fragments. */
102
- type FragmentFields<Fs extends readonly SyncFragment<any, any, any, any>[]> = MergeFields<SharedOf<Fs>>;
103
- /** The concatenated durable constructors of several fragments. */
104
- type FragmentConstructors<Fs extends readonly SyncFragment<any, any, any, any>[]> = MergeConstructors<DurableOf<Fs>>;
105
- /** The union of Messages several fragments record. */
106
- type FragmentMessages<Fs extends readonly SyncFragment<any, any, any, any>[]> = Fs[number] extends SyncFragment<any, any, infer V, any> ? V : never;
107
- /**
108
- * The value `make` returns: the low-level `Sync` protocol plus the writable
109
- * projection, the declared Messages, and a read-only Surface over the
110
- * projection. Exported so a consumer can name the type.
111
- */
112
- interface DefinedSync<AppModel, Fields extends Schema$1.Struct.Fields, Message, Ms extends readonly unknown[], Principal = unknown,
113
- /** `true` when `make` was given `authorize`, so the contract's `authorize` is present. */
114
- Authorized extends boolean = false> extends Sync$1<Message, Schema$1.Struct.Type<Fields>> {
115
- readonly surface: Surface<AppModel, Schema$1.Struct.Type<Fields>, MsgOf<Ms>, void>;
116
- readonly projection: WritableProjection<AppModel, Fields>;
117
- /** The reducer the replica replays durable Messages with: derived from `update`, or `make`'s `replay`. */
118
- readonly replay: (shared: Schema$1.Struct.Type<Fields>, message: Message) => Schema$1.Struct.Type<Fields>;
119
- readonly messages: Ms;
120
- /** For `Module`: this contract owns the shared projection's paths and records the durable tags. */
121
- readonly contract: Contract;
122
- /**
123
- * How this contract joins an assembly: contract-only, so the Module sees it.
124
- * It routes nothing, runs nothing, and subscribes to nothing; Sync owns the
125
- * runtime through `mount` rather than joining it.
126
- */
127
- readonly wiring: () => Wiring<AppModel, never>;
128
- /** The durable journal's codecs, reducer, and, when declared, authorization. */
129
- 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>;
130
- }
131
- /** The sync constructors specialized to one application. */
132
- interface ApplicationSync<AppModel, F extends Schema$1.Struct.Fields, Cases extends Record<string, Schema$1.Struct.Fields>, Principal = unknown> {
133
- /**
134
- * Fixes the `Principal` that `authorize` rules see. A `Principal` cannot be a
135
- * positional type argument beside an inferred Model, so it is supplied here:
136
- * `Sync.forApplication(App).withPrincipal<User>()`. Type-only.
137
- */
138
- readonly withPrincipal: <P>() => ApplicationSync<AppModel, F, Cases, P>;
139
- /** One feature's shared fields and durable Messages, for `compose`. */
140
- readonly fragment: <Fields extends Schema$1.Struct.Fields, Subset, Ms extends readonly MessageConstructor<AppMessage<AppModel, F, Cases>>[]>(config: {
141
- readonly shared: WritableProjection<AppModel, Fields>;
142
- readonly durable: MessageSet<AppModel, any, Subset, Ms>;
143
- }) => SyncFragment<AppModel, Fields, Subset, Ms>;
144
- /**
145
- * Merges fragments into one: `make({ documentId, ...compose(Todos, Members) })`.
146
- * A field declared twice with a different codec, a tag declared twice, or a
147
- * fragment from another application throws.
148
- */
149
- readonly compose: <const Fs extends readonly SyncFragment<AppModel, any, any, any>[]>(...fragments: Fs) => SyncFragment<AppModel, FragmentFields<Fs>, FragmentMessages<Fs>, FragmentConstructors<Fs>>;
150
- readonly make: {
151
- <Fields extends Schema$1.Struct.Fields, Subset, Ms extends readonly MessageConstructor<AppMessage<AppModel, F, Cases>>[]>(options: MakeOptions<AppModel, Fields, Subset, Ms, Principal> & {
152
- readonly authorize: AuthorizePolicy<Principal, NoInfer<Fields>, NoInfer<Ms>>;
153
- }): DefinedSync<AppModel, Fields, AppMessage<AppModel, F, Cases>, Ms, Principal, true>;
154
- <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>;
155
- };
156
- }
157
- /**
158
- * Specializes the sync constructors to a `Surface.application`, so
159
- * `Sync.forApplication(App).make({ documentId, shared, durable })` derives the
160
- * shared codec, the initial snapshot, the durable predicate, and replay from
161
- * the application, and refuses a subset that belongs to another application.
162
- * `defineSync` remains the protocol primitive when there is no application to
163
- * derive from.
164
- */
165
- 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>;
166
- //#endregion
167
9
  //#region src/mount.d.ts
168
10
  /**
169
11
  * A Command that dispatches `message` as the next transition, which under `Sync.mount`
@@ -217,6 +59,14 @@ interface MountOptions<Model, Message, Shared, Resources> {
217
59
  * not called for a status that changes nothing the Model shows, such as the first.
218
60
  */
219
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;
220
70
  }
221
71
  /**
222
72
  * What a reinstall came from. `reset` is a server reset: the replica's
@@ -376,9 +226,13 @@ export declare const socketPresenceChannel: <Update>(socket: SocketLike) => Effe
376
226
  /**
377
227
  * Serves presence frames on an accepted socket, stamping the connection's
378
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.
379
232
  */
380
233
  export declare const servePresence: <Update>(socket: SocketLike, hub: PresenceHub<Update>, options: {
381
234
  readonly peerId: string;
235
+ readonly opens?: Effect.Effect<boolean, unknown> | undefined;
382
236
  }) => (() => void);
383
237
  //#endregion
384
238
  //#region src/lww.d.ts
@@ -499,6 +353,8 @@ export declare const Sync: {
499
353
  readonly exchange: (cursor: number, pending: ReadonlyArray<Operation>, epoch?: string | undefined) => unknown | Promise<unknown>;
500
354
  readonly changes?: ((listener: () => void) => () => void) | undefined;
501
355
  }) => (() => void);
356
+ /** The accepted end of a Cloudflare `WebSocketPair`, for `serve`. */
357
+ workerSocket: (socket: WebSocket) => SocketLike;
502
358
  /** The default socket factory: the platform `WebSocket`. */
503
359
  nativeSocket: (url: string) => SocketLike;
504
360
  /** A socket over a `MessagePort`, closed by `close()` or an abort signal. */
@@ -530,6 +386,7 @@ export declare const Sync: {
530
386
  /** Serves presence frames on an accepted socket, stamping the connection's identity. */
531
387
  serve: <Update>(socket: SocketLike, hub: PresenceHub<Update>, options: {
532
388
  readonly peerId: string;
389
+ readonly opens?: import("effect/Effect").Effect<boolean, unknown> | undefined;
533
390
  }) => (() => void);
534
391
  socketChannel: <Update>(socket: SocketLike) => import("effect/Effect").Effect<PresenceChannel<Update>, never, import("effect/Scope").Scope>;
535
392
  loopbackChannel: <Update>() => import("effect/Effect").Effect<{
@@ -582,5 +439,5 @@ export declare const Sync: {
582
439
  };
583
440
  };
584
441
  //#endregion
585
- 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, indexedDb, layerFromPromise, layerLoopback, layerSocket, localSequence, nativeSocket, opId, portSocket, replicaId, sequence, serveSocket, syncMetrics, toPromise };
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 };
586
443
  //# sourceMappingURL=index.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","names":[],"sources":["../src/make.ts","../src/mount.ts","../src/presence.ts","../src/lww.ts","../src/index.ts"],"mappings":";;;;;;;;;KA4BK,mBAAmB,eAAe,kBAAkB;;KAG7C,MAAM,iCAAiC,wBAAuB,wBAAwB,KAC9F;KAGC,WACH,UACA,UAAU,SAAO,OAAO,QACxB,cAAc,eAAe,SAAO,O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back, l as toPromise, m as Sequence, n as TransportError, o as nativeSocket, p as ReplicaId, r as layerFromPromise, s as portSocket, t as Transport, u as DocumentId, v as replicaId, y as sequence } from "./transport-hlEQpHIv.mjs";
1
+ import { _ as localSequence, a as layerSocket, b as sequence, c as serveSocket, d as DocumentId, f as LocalSequence, g as documentId, h as Sequence, i as layerLoopback, l as toPromise, m as ReplicaId, n as TransportError, o as nativeSocket, p as OpId, r as layerFromPromise, s as portSocket, t as Transport, u as workerSocket, v as opId, y as replicaId } from "./transport-DiKXy5zx.mjs";
2
2
  import { Clock, Duration, Effect, Equal, Exit, Fiber, Metric, Option, Predicate, PubSub, Queue, Ref, Schema, Stream, SynchronizedRef } from "effect";
3
3
  import { MessageSet, Projection, Surface } from "foldkit-surface";
4
4
  import { absurd } from "effect/Function";
@@ -1097,8 +1097,13 @@ const mount = (app, sync, options) => {
1097
1097
  }
1098
1098
  };
1099
1099
  const update = (model, message) => {
1100
- if (isPrivate(message)) return updatePrivate(model, message);
1101
- return transition(model, message);
1100
+ const result = isPrivate(message) ? updatePrivate(model, message) : transition(model, message);
1101
+ if (options.afterUpdate === void 0) return result;
1102
+ const after = applyFacts(options.afterUpdate(result.model));
1103
+ return after.model === result.model && (after.commands ?? []).length === 0 ? result : {
1104
+ model: after.model,
1105
+ commands: [...result.commands ?? [], ...after.commands ?? []]
1106
+ };
1102
1107
  };
1103
1108
  const reinstalled = (next, previous, change) => options.onReinstall === void 0 ? { model: next } : applyFacts(options.onReinstall(next, previous, change));
1104
1109
  /** The application's transition for one of its Messages, with the persist a durable one needs. */
@@ -1494,21 +1499,41 @@ const socketPresenceChannel = (socket) => Effect.gen(function* () {
1494
1499
  /**
1495
1500
  * Serves presence frames on an accepted socket, stamping the connection's
1496
1501
  * identity, until the socket closes or the returned function is called.
1502
+ * With `opens`, the connection joins only once it answers that it may open
1503
+ * the document the presence accompanies: until then, and for good when it
1504
+ * is refused or fails, nothing reaches it and nothing it sends is relayed.
1497
1505
  */
1498
1506
  const servePresence = (socket, hub, options) => {
1499
1507
  const send = (update) => socket.send(JSON.stringify({ [frameType]: {
1500
1508
  id: update.id,
1501
1509
  value: update.value
1502
1510
  } }));
1503
- const leave = hub.join(send);
1504
- const off = socket.onMessage((data) => {
1505
- const frame = decodePresence(data);
1506
- if (frame !== void 0) hub.publish({
1507
- id: options.peerId,
1508
- value: frame.value
1511
+ let stopped = false;
1512
+ let leave = () => {};
1513
+ let off = () => {};
1514
+ const join = () => {
1515
+ leave = hub.join(send);
1516
+ off = socket.onMessage((data) => {
1517
+ const frame = decodePresence(data);
1518
+ if (frame === void 0) return;
1519
+ const publish = () => hub.publish({
1520
+ id: options.peerId,
1521
+ value: frame.value
1522
+ });
1523
+ if (options.opens === void 0) return publish();
1524
+ Effect.runPromise(options.opens).then((open) => {
1525
+ if (stopped) return;
1526
+ if (open) publish();
1527
+ else stop();
1528
+ }, () => stop());
1509
1529
  });
1510
- });
1530
+ };
1531
+ if (options.opens === void 0) join();
1532
+ else Effect.runPromise(options.opens).then((open) => {
1533
+ if (open && !stopped) join();
1534
+ }, () => {});
1511
1535
  const stop = () => {
1536
+ stopped = true;
1512
1537
  off();
1513
1538
  leave();
1514
1539
  };
@@ -1558,6 +1583,8 @@ const Sync = {
1558
1583
  toPromise,
1559
1584
  /** The server side of one accepted socket connection. */
1560
1585
  serve: serveSocket,
1586
+ /** The accepted end of a Cloudflare `WebSocketPair`, for `serve`. */
1587
+ workerSocket,
1561
1588
  /** The default socket factory: the platform `WebSocket`. */
1562
1589
  nativeSocket,
1563
1590
  /** A socket over a `MessagePort`, closed by `close()` or an abort signal. */
@@ -1581,6 +1608,6 @@ const Sync = {
1581
1608
  }
1582
1609
  };
1583
1610
  //#endregion
1584
- export { CheckpointRegressionError, CommittedOrderError, DocumentId, ForeignAcknowledgementError, ForeignRejectionError, InvalidExchangeError, InvalidOutboxError, InvalidReplicaHistoryError, LocalSequence, OpId, ReplayError, ReplicaClosedError, ReplicaId, Sequence, StorageError, Sync, Transport, TransportError, UnsupportedClockVersionError, UnsupportedReplicaVersionError, WrongReplicaStorageError, createPresence, createPresenceHub, defineSync, documentId, fact, forApplication, indexedDb, layerFromPromise, layerLoopback, layerSocket, localSequence, loopbackPresenceChannel, lwwRegister, mount, nativeSocket, opId, openLwwClock, portSocket, replicaId, sequence, servePresence, serveSocket, socketPresenceChannel, syncMetrics, toPromise };
1611
+ export { CheckpointRegressionError, CommittedOrderError, DocumentId, ForeignAcknowledgementError, ForeignRejectionError, InvalidExchangeError, InvalidOutboxError, InvalidReplicaHistoryError, LocalSequence, OpId, ReplayError, ReplicaClosedError, ReplicaId, Sequence, StorageError, Sync, Transport, TransportError, UnsupportedClockVersionError, UnsupportedReplicaVersionError, WrongReplicaStorageError, createPresence, createPresenceHub, defineSync, documentId, fact, forApplication, indexedDb, layerFromPromise, layerLoopback, layerSocket, localSequence, loopbackPresenceChannel, lwwRegister, mount, nativeSocket, opId, openLwwClock, portSocket, replicaId, sequence, servePresence, serveSocket, socketPresenceChannel, syncMetrics, toPromise, workerSocket };
1585
1612
 
1586
1613
  //# sourceMappingURL=index.mjs.map