foldkit-sync 0.12.3 → 0.13.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.
Files changed (82) hide show
  1. package/README.md +76 -24
  2. package/dist/diagnostics.d.ts +71 -0
  3. package/dist/diagnostics.d.ts.map +1 -0
  4. package/dist/diagnostics.js +67 -0
  5. package/dist/diagnostics.js.map +1 -0
  6. package/dist/{do.d.mts → do.d.ts} +12 -2
  7. package/dist/do.d.ts.map +1 -0
  8. package/dist/{do.mjs → do.js} +15 -9
  9. package/dist/do.js.map +1 -0
  10. package/dist/{entity.d.mts → entity.d.ts} +1 -1
  11. package/dist/entity.d.ts.map +1 -0
  12. package/dist/{entity.mjs → entity.js} +1 -1
  13. package/dist/entity.js.map +1 -0
  14. package/dist/errors.d.ts +91 -0
  15. package/dist/errors.d.ts.map +1 -0
  16. package/dist/errors.js +75 -0
  17. package/dist/errors.js.map +1 -0
  18. package/dist/ids.d.ts +30 -0
  19. package/dist/ids.d.ts.map +1 -0
  20. package/dist/ids.js +28 -0
  21. package/dist/ids.js.map +1 -0
  22. package/dist/index.d.ts +106 -0
  23. package/dist/index.d.ts.map +1 -0
  24. package/dist/index.js +77 -0
  25. package/dist/index.js.map +1 -0
  26. package/dist/indexedDb.d.ts +62 -0
  27. package/dist/indexedDb.d.ts.map +1 -0
  28. package/dist/indexedDb.js +128 -0
  29. package/dist/indexedDb.js.map +1 -0
  30. package/dist/{journal.d.mts → journal.d.ts} +29 -5
  31. package/dist/journal.d.ts.map +1 -0
  32. package/dist/{journal-D5h-jqXE.mjs → journal.js} +43 -32
  33. package/dist/journal.js.map +1 -0
  34. package/dist/lww.d.ts +76 -0
  35. package/dist/lww.d.ts.map +1 -0
  36. package/dist/lww.js +121 -0
  37. package/dist/lww.js.map +1 -0
  38. package/dist/make.d.ts +162 -0
  39. package/dist/make.d.ts.map +1 -0
  40. package/dist/make.js +153 -0
  41. package/dist/make.js.map +1 -0
  42. package/dist/mount.d.ts +138 -0
  43. package/dist/mount.d.ts.map +1 -0
  44. package/dist/mount.js +344 -0
  45. package/dist/mount.js.map +1 -0
  46. package/dist/presence.d.ts +116 -0
  47. package/dist/presence.d.ts.map +1 -0
  48. package/dist/presence.js +277 -0
  49. package/dist/presence.js.map +1 -0
  50. package/dist/{remote.d.mts → remote.d.ts} +2 -2
  51. package/dist/remote.d.ts.map +1 -0
  52. package/dist/{remote.mjs → remote.js} +1 -1
  53. package/dist/remote.js.map +1 -0
  54. package/dist/revalidate.d.ts +6 -0
  55. package/dist/revalidate.d.ts.map +1 -0
  56. package/dist/revalidate.js +10 -0
  57. package/dist/revalidate.js.map +1 -0
  58. package/dist/sync.d.ts +276 -0
  59. package/dist/sync.d.ts.map +1 -0
  60. package/dist/sync.js +512 -0
  61. package/dist/sync.js.map +1 -0
  62. package/dist/transport.d.ts +151 -0
  63. package/dist/transport.d.ts.map +1 -0
  64. package/dist/{transport-BZ6utYmB.mjs → transport.js} +20 -30
  65. package/dist/transport.js.map +1 -0
  66. package/package.json +24 -24
  67. package/dist/do.d.mts.map +0 -1
  68. package/dist/do.mjs.map +0 -1
  69. package/dist/entity.d.mts.map +0 -1
  70. package/dist/entity.mjs.map +0 -1
  71. package/dist/index.d.mts +0 -397
  72. package/dist/index.d.mts.map +0 -1
  73. package/dist/index.mjs +0 -1613
  74. package/dist/index.mjs.map +0 -1
  75. package/dist/journal-D5h-jqXE.mjs.map +0 -1
  76. package/dist/journal.d.mts.map +0 -1
  77. package/dist/journal.mjs +0 -1
  78. package/dist/make-DJ0Q1SSc.d.mts +0 -702
  79. package/dist/make-DJ0Q1SSc.d.mts.map +0 -1
  80. package/dist/remote.d.mts.map +0 -1
  81. package/dist/remote.mjs.map +0 -1
  82. package/dist/transport-BZ6utYmB.mjs.map +0 -1
@@ -0,0 +1,151 @@
1
+ import { Context, Duration, Effect, Layer, Schema, Stream } from "effect";
2
+ import { Operation, TransportClient } from "./sync.js";
3
+ declare const TransportError_base: Schema.Class<TransportError, Schema.TaggedStruct<"SyncTransportError", {
4
+ readonly message: Schema.String;
5
+ }>, import("effect/Cause").YieldableError>;
6
+ /** The wire failure of a transport. A refusal is a result, not an error. */
7
+ export declare class TransportError extends TransportError_base {}
8
+ /** One request/response frame, as it crosses a wire. */
9
+ export interface ExchangeFrame {
10
+ readonly id: string;
11
+ readonly cursor: number;
12
+ readonly pending: ReadonlyArray<Operation>;
13
+ readonly epoch?: string | undefined;
14
+ }
15
+ export interface ExchangeReply {
16
+ readonly id: string;
17
+ readonly result?: unknown;
18
+ readonly error?: string;
19
+ }
20
+ /**
21
+ * Sent by a server, unasked, when the document may have changed. It carries no
22
+ * data: the replica exchanges from its own cursor, so a notice that is lost,
23
+ * late, or one of many is harmless.
24
+ */
25
+ export interface NotifyFrame {
26
+ readonly notify: true;
27
+ }
28
+ export interface TransportShape {
29
+ /** `epoch` is the server history the replica's cursor points into, when it knows one. */
30
+ readonly exchange: (cursor: number, pending: ReadonlyArray<Operation>, epoch?: string | undefined) => Effect.Effect<unknown, TransportError>;
31
+ /**
32
+ * Emits when the server may have something new, for a transport that can hear
33
+ * it: `Replica.start` exchanges on each. A wake-up, not data.
34
+ */
35
+ readonly changes?: Stream.Stream<void> | undefined;
36
+ }
37
+ declare const Transport_base: Context.ServiceClass<Transport, "foldkit-sync/Transport", TransportShape>;
38
+ /**
39
+ * The seam the replica syncs through.
40
+ *
41
+ * A service, not a concrete client, so an application substitutes an in-process
42
+ * transport, a socket, or a test double without the replica knowing. A refusal
43
+ * arrives in the exchange result; only a wire failure is a `TransportError`.
44
+ */
45
+ export declare class Transport extends Transport_base {}
46
+ declare const TransportSocket_base: Context.ServiceClass<TransportSocket, "foldkit-sync/TransportSocket", SocketLike>;
47
+ /**
48
+ * The connection `layerSocket` keeps, for another protocol to share, such as
49
+ * presence: a send goes to the socket open now and is dropped while none is,
50
+ * and messages from every socket the transport opens arrive here. It is the
51
+ * transport's to close. Only a socket transport provides it, so a layer that
52
+ * has one says so in its type.
53
+ */
54
+ export declare class TransportSocket extends TransportSocket_base {}
55
+ /** A transport backed by an in-process handler, for tests and single-process demos. */
56
+ export declare const layerLoopback: (handler: (cursor: number, pending: ReadonlyArray<Operation>, epoch?: string | undefined) => unknown | Promise<unknown>) => Layer.Layer<Transport>;
57
+ /** Wraps the promise-based client the replica already speaks. */
58
+ export declare const layerFromPromise: (transport: TransportClient) => Layer.Layer<Transport>;
59
+ /** Bridges the service back to the promise client the replica consumes. */
60
+ export declare const toPromise: (transport: TransportShape) => TransportClient;
61
+ /**
62
+ * Serves one accepted socket, answering each exchange frame.
63
+ *
64
+ * The counterpart to `layerSocket`: the handler returns the exchange result, or
65
+ * throws and the failure is written back as an error frame. With `changes`, a
66
+ * subscription to the document's commits, the socket is also sent a
67
+ * `NotifyFrame` after each, so a client hears of others' edits without polling.
68
+ * Returns a function that stops serving.
69
+ */
70
+ export declare const serveSocket: (socket: SocketLike, options: {
71
+ readonly exchange: (cursor: number, pending: ReadonlyArray<Operation>, epoch?: string | undefined) => unknown | Promise<unknown>;
72
+ /** Subscribes to the document's commits; returns the unsubscribe. */
73
+ readonly changes?: ((listener: () => void) => () => void) | undefined;
74
+ }) => (() => void);
75
+ /** The minimal socket the layer needs; the global `WebSocket` satisfies it. */
76
+ export interface SocketLike {
77
+ send(data: string): void;
78
+ close(): void;
79
+ onMessage(listener: (data: string) => void): () => void;
80
+ onClose(listener: () => void): () => void;
81
+ /**
82
+ * Optional. When provided, exchanges wait for it before sending, so a
83
+ * transport can connect asynchronously. Absent means already connected.
84
+ */
85
+ onOpen?(listener: () => void): () => void;
86
+ }
87
+ /**
88
+ * Where `layerSocket` connects: a `url` for the platform `WebSocket`, or a
89
+ * `makeSocket` that opens any other `SocketLike` (a port, a test socket), called
90
+ * again on every reconnect.
91
+ */
92
+ export type SocketOptions = SocketTuning & ({
93
+ readonly url: string;
94
+ readonly makeSocket?: undefined;
95
+ } | {
96
+ readonly makeSocket: () => SocketLike;
97
+ readonly url?: undefined;
98
+ });
99
+ interface SocketTuning {
100
+ /**
101
+ * Consecutive failed connections after which queued work fails and new
102
+ * exchanges fail fast until a connection is healthy again. Reconnecting goes
103
+ * on regardless. Default 5.
104
+ */
105
+ readonly maxRetries?: number | undefined;
106
+ /** Base delay of the exponential reconnect backoff. Default `50 millis`. */
107
+ readonly retryBase?: Duration.Input | undefined;
108
+ /** Longest wait between reconnect attempts. Default `5 seconds`. */
109
+ readonly maxRetryDelay?: Duration.Input | undefined;
110
+ /** Exchanges queued or in flight before new ones fail. Default 64. */
111
+ readonly maxQueue?: number | undefined;
112
+ }
113
+ /** The default socket factory: the platform `WebSocket`, as a `SocketLike`. */
114
+ export declare const nativeSocket: (url: string) => SocketLike;
115
+ /**
116
+ * A socket over a `MessagePort`, for either end: its frames are the port's
117
+ * string messages, and anything else on the port is ignored. A port tells
118
+ * neither end when the other goes, so `onClose` fires once, on `close()` or
119
+ * when `signal` aborts; a host that serves a pane aborts it when the pane is
120
+ * gone, which stops `serveSocket` and anything else listening.
121
+ */
122
+ export declare const portSocket: (port: MessagePort, options?: {
123
+ readonly signal?: AbortSignal | undefined;
124
+ }) => SocketLike;
125
+ /**
126
+ * A socket over an existing `WebSocket`: the accepted end of a Cloudflare
127
+ * `WebSocketPair`, or any other socket the platform hands over. Unlike
128
+ * `nativeSocket` it opens nothing — accept the pair first — and unlike
129
+ * `portSocket` there is no signal: the socket closing, erroring, or being
130
+ * closed fires `onClose` once, which is how a host stops serving it.
131
+ */
132
+ export declare const workerSocket: (socket: WebSocket) => SocketLike;
133
+ /**
134
+ * A WebSocket client transport.
135
+ *
136
+ * One connection is live at a time. While it is connecting, exchanges queue; if
137
+ * it closes, the transport reconnects on an exponential, jittered backoff and
138
+ * re-sends every queued and in-flight frame with its original id, so a lost
139
+ * reply is answered rather than dropped and a late reply cannot resolve a newer
140
+ * frame. It never stops reconnecting: after `maxRetries` consecutive failures
141
+ * queued work fails with a `TransportError`, and exchanges fail fast while no
142
+ * socket is up, until a socket opens. The count resets only when a connection
143
+ * proves healthy, by answering a frame or by staying open for `maxRetryDelay`:
144
+ * a server that accepts a socket and drops it at once is backed off like one
145
+ * that refuses it. A queue over `maxQueue` fails new
146
+ * exchanges with backpressure. The socket is released when the layer's scope
147
+ * ends.
148
+ */
149
+ export declare const layerSocket: (options: SocketOptions) => Layer.Layer<Transport | TransportSocket, TransportError>;
150
+ export {};
151
+ //# sourceMappingURL=transport.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"transport.d.ts","names":[],"sources":["../src/transport.ts"],"mappings":";;;;;;qBAOa,uBAAuB;;iBAKnB;WACN;WACA;WACA,SAAS,cAAc;WACvB;;iBAGM;WACN;WACA;WACA;;;;;;;iBAQM;WACN;;iBAGM;;WAEN,WACP,gBACA,SAAS,cAAc,YACvB,+BACG,OAAO,gBAAgB;;;;;WAKnB,UAAU,OAAO;;;;;;;;;;qBAUf,kBAAkB;;;;;;;;;qBAWlB,wBAAwB;;qBAQxB,gBAAa,UAEtB,gBACA,SAAS,cAAc,YACvB,yCACa,qBACd,MAAM,MAAM;;qBAUF,mBAAgB,WAAe,oBAAkB,MAAM,MAAM;;qBAU7D,YAAS,WAAe,mBAAiB;;;;;;;;;;qBAczC,cAAW,QACd,YAAU;WAEP,WACP,gBACA,SAAS,cAAc,YACvB,yCACa;;WAEN,YAAY;;;iBAgER;EACf,KAAK;EACL;EACA,UAAU,WAAW;EACrB,QAAQ;;;;;EAKR,QAAQ;;;;;;;YAQE,gBAAgB;WAEX;WAAsB;;WACtB,kBAAkB;WAAqB;;UAG9C;;;;;;WAMC;;WAEA,YAAY,SAAS;;WAErB,gBAAgB,SAAS;;WAEzB;;;qBAIE,eAAY,gBAAkB;;;;;;;;qBAiC9B,aAAU,MACf,aAAW;WACG,SAAS;MAC5B;;;;;;;;qBAwCU,eAAY,QAAY,cAAY;;;;;;;;;;;;;;;;;qBAuEpC,cAAW,SACb,kBACR,MAAM,MAAM,YAAY,iBAAiB"}
@@ -1,28 +1,7 @@
1
1
  import { Clock, Context, Duration, Effect, Layer, PubSub, Schema, Stream } from "effect";
2
- // src/ids.ts
3
- /** Identifies the replicated document a replica or operation belongs to. */
4
- const DocumentId = Schema.NonEmptyString.pipe(Schema.brand("@foldkit-sync/DocumentId"));
5
- /** Identifies one replica (writer identity) within a document. */
6
- const ReplicaId = Schema.NonEmptyString.pipe(Schema.brand("@foldkit-sync/ReplicaId"));
7
- /** The stable identity of one operation within a document. */
8
- const OpId = Schema.NonEmptyString.pipe(Schema.brand("@foldkit-sync/OpId"));
9
- /**
10
- * A position in the committed document order. `0` is the start; a committed
11
- * operation's `serverSequence` and a replica's `cursor` are the same family.
12
- */
13
- const Sequence = Schema.Number.check(Schema.isInt(), Schema.isGreaterThanOrEqualTo(0), Schema.isLessThanOrEqualTo(Number.MAX_SAFE_INTEGER)).pipe(Schema.brand("@foldkit-sync/Sequence"));
14
- /** A replica's own operation counter within a document; 1-based. */
15
- const LocalSequence = Schema.Number.check(Schema.isInt(), Schema.isGreaterThanOrEqualTo(1), Schema.isLessThanOrEqualTo(Number.MAX_SAFE_INTEGER)).pipe(Schema.brand("@foldkit-sync/LocalSequence"));
16
- /**
17
- * Decode-and-brand helpers. A branded schema constructs the same value with
18
- * `DocumentId.make('todos')`, which is the spelling to lead with; these stay
19
- * for callers that already have them.
20
- */
21
- const documentId = (value) => Schema.decodeUnknownSync(DocumentId)(value);
22
- const replicaId = (value) => Schema.decodeUnknownSync(ReplicaId)(value);
23
- const opId = (value) => Schema.decodeUnknownSync(OpId)(value);
24
- const sequence = (value) => Schema.decodeUnknownSync(Sequence)(value);
25
- const localSequence = (value) => Schema.decodeUnknownSync(LocalSequence)(value);
2
+ import { Diagnostics } from "foldkit-surface";
3
+ import { listenerFailed } from "./diagnostics.js";
4
+ import { sequence } from "./ids.js";
26
5
  // src/transport.ts
27
6
  /** The wire failure of a transport. A refusal is a result, not an error. */
28
7
  var TransportError = class extends Schema.TaggedError()("SyncTransportError", { message: Schema.String }) {};
@@ -34,6 +13,14 @@ var TransportError = class extends Schema.TaggedError()("SyncTransportError", {
34
13
  * arrives in the exchange result; only a wire failure is a `TransportError`.
35
14
  */
36
15
  var Transport = class extends Context.Service()("foldkit-sync/Transport") {};
16
+ /**
17
+ * The connection `layerSocket` keeps, for another protocol to share, such as
18
+ * presence: a send goes to the socket open now and is dropped while none is,
19
+ * and messages from every socket the transport opens arrive here. It is the
20
+ * transport's to close. Only a socket transport provides it, so a layer that
21
+ * has one says so in its type.
22
+ */
23
+ var TransportSocket = class extends Context.Service()("foldkit-sync/TransportSocket") {};
37
24
  const failure = (error) => new TransportError({ message: error instanceof Error ? error.message : String(error) });
38
25
  /** A transport backed by an in-process handler, for tests and single-process demos. */
39
26
  const layerLoopback = (handler) => Layer.succeed(Transport, { exchange: (cursor, pending, epoch) => Effect.tryPromise({
@@ -250,13 +237,14 @@ const connector = (options) => {
250
237
  * exchanges with backpressure. The socket is released when the layer's scope
251
238
  * ends.
252
239
  */
253
- const layerSocket = (options) => Layer.effect(Transport, Effect.fn("Transport.layerSocket")(function* () {
240
+ const layerSocket = (options) => Layer.effectContext(Effect.fn("Transport.layerSocket")(function* () {
254
241
  const makeSocket = connector(options);
255
242
  const maxQueue = options.maxQueue ?? 64;
256
243
  const maxRetries = options.maxRetries ?? 5;
257
244
  const retryBase = Duration.toMillis(Duration.fromInputUnsafe(options.retryBase ?? "50 millis"));
258
245
  const maxRetryDelay = Duration.toMillis(Duration.fromInputUnsafe(options.maxRetryDelay ?? "5 seconds"));
259
246
  const clock = yield* Clock.Clock;
247
+ const reporter = yield* Effect.service(Diagnostics.Reporter);
260
248
  const notices = yield* PubSub.sliding(1);
261
249
  const listeners = /* @__PURE__ */ new Set();
262
250
  const shared = {
@@ -320,7 +308,9 @@ const layerSocket = (options) => Layer.effect(Transport, Effect.fn("Transport.la
320
308
  const offMessage = next.onMessage((data) => {
321
309
  for (const listener of [...listeners]) try {
322
310
  listener(data);
323
- } catch {}
311
+ } catch (thrown) {
312
+ Effect.runFork(Diagnostics.report(listenerFailed("Socket", thrown)).pipe(Effect.provideService(Diagnostics.Reporter, reporter)));
313
+ }
324
314
  let reply;
325
315
  try {
326
316
  reply = JSON.parse(data);
@@ -372,9 +362,8 @@ const layerSocket = (options) => Layer.effect(Transport, Effect.fn("Transport.la
372
362
  socket = void 0;
373
363
  failAll("transport closed");
374
364
  }));
375
- return Transport.of({
365
+ const transport = Transport.of({
376
366
  changes: Stream.fromPubSub(notices),
377
- socket: shared,
378
367
  exchange: (cursor, pending, epoch) => Effect.callback((resume) => {
379
368
  if (disposed) {
380
369
  resume(Effect.fail(new TransportError({ message: "transport closed" })));
@@ -404,7 +393,8 @@ const layerSocket = (options) => Layer.effect(Transport, Effect.fn("Transport.la
404
393
  });
405
394
  })
406
395
  });
396
+ return Context.make(Transport, transport).pipe(Context.add(TransportSocket, shared));
407
397
  })());
408
- export { localSequence as _, layerSocket as a, sequence as b, serveSocket as c, DocumentId as d, LocalSequence as f, documentId as g, Sequence as h, layerLoopback as i, toPromise as l, ReplicaId as m, TransportError as n, nativeSocket as o, OpId as p, layerFromPromise as r, portSocket as s, Transport as t, workerSocket as u, opId as v, replicaId as y };
398
+ export { Transport, TransportError, TransportSocket, layerFromPromise, layerLoopback, layerSocket, nativeSocket, portSocket, serveSocket, toPromise, workerSocket };
409
399
 
410
- //# sourceMappingURL=transport-BZ6utYmB.mjs.map
400
+ //# sourceMappingURL=transport.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"transport.js","names":[],"sources":["../src/transport.ts"],"sourcesContent":["import { Clock, Context, Duration, Effect, Layer, PubSub, Schema, Stream } from 'effect'\nimport { sequence } from './ids.js'\nimport type { Operation, TransportClient } from './sync.js'\nimport { Diagnostics } from 'foldkit-surface'\nimport { listenerFailed } from './diagnostics.js'\n\n/** The wire failure of a transport. A refusal is a result, not an error. */\nexport class TransportError extends Schema.TaggedError<TransportError>()('SyncTransportError', {\n message: Schema.String,\n}) {}\n\n/** One request/response frame, as it crosses a wire. */\nexport interface ExchangeFrame {\n readonly id: string\n readonly cursor: number\n readonly pending: ReadonlyArray<Operation>\n readonly epoch?: string | undefined\n}\n\nexport interface ExchangeReply {\n readonly id: string\n readonly result?: unknown\n readonly error?: string\n}\n\n/**\n * Sent by a server, unasked, when the document may have changed. It carries no\n * data: the replica exchanges from its own cursor, so a notice that is lost,\n * late, or one of many is harmless.\n */\nexport interface NotifyFrame {\n readonly notify: true\n}\n\nexport interface TransportShape {\n /** `epoch` is the server history the replica's cursor points into, when it knows one. */\n readonly exchange: (\n cursor: number,\n pending: ReadonlyArray<Operation>,\n epoch?: string | undefined,\n ) => Effect.Effect<unknown, TransportError>\n /**\n * Emits when the server may have something new, for a transport that can hear\n * it: `Replica.start` exchanges on each. A wake-up, not data.\n */\n readonly changes?: Stream.Stream<void> | undefined\n}\n\n/**\n * The seam the replica syncs through.\n *\n * A service, not a concrete client, so an application substitutes an in-process\n * transport, a socket, or a test double without the replica knowing. A refusal\n * arrives in the exchange result; only a wire failure is a `TransportError`.\n */\nexport class Transport extends Context.Service<Transport, TransportShape>()(\n 'foldkit-sync/Transport',\n) {}\n\n/**\n * The connection `layerSocket` keeps, for another protocol to share, such as\n * presence: a send goes to the socket open now and is dropped while none is,\n * and messages from every socket the transport opens arrive here. It is the\n * transport's to close. Only a socket transport provides it, so a layer that\n * has one says so in its type.\n */\nexport class TransportSocket extends Context.Service<TransportSocket, SocketLike>()(\n 'foldkit-sync/TransportSocket',\n) {}\n\nconst failure = (error: unknown): TransportError =>\n new TransportError({ message: error instanceof Error ? error.message : String(error) })\n\n/** A transport backed by an in-process handler, for tests and single-process demos. */\nexport const layerLoopback = (\n handler: (\n cursor: number,\n pending: ReadonlyArray<Operation>,\n epoch?: string | undefined,\n ) => unknown | Promise<unknown>,\n): Layer.Layer<Transport> =>\n Layer.succeed(Transport, {\n exchange: (cursor, pending, epoch) =>\n Effect.tryPromise({\n try: () => Promise.resolve(handler(cursor, pending, epoch)),\n catch: failure,\n }),\n })\n\n/** Wraps the promise-based client the replica already speaks. */\nexport const layerFromPromise = (transport: TransportClient): Layer.Layer<Transport> =>\n Layer.succeed(Transport, {\n exchange: (cursor, pending, epoch) =>\n Effect.tryPromise({\n try: () => transport.exchange(sequence(cursor), pending, epoch),\n catch: failure,\n }),\n })\n\n/** Bridges the service back to the promise client the replica consumes. */\nexport const toPromise = (transport: TransportShape): TransportClient => ({\n exchange: (cursor, pending, epoch) =>\n Effect.runPromise(transport.exchange(cursor, pending, epoch)),\n})\n\n/**\n * Serves one accepted socket, answering each exchange frame.\n *\n * The counterpart to `layerSocket`: the handler returns the exchange result, or\n * throws and the failure is written back as an error frame. With `changes`, a\n * subscription to the document's commits, the socket is also sent a\n * `NotifyFrame` after each, so a client hears of others' edits without polling.\n * Returns a function that stops serving.\n */\nexport const serveSocket = (\n socket: SocketLike,\n options: {\n readonly exchange: (\n cursor: number,\n pending: ReadonlyArray<Operation>,\n epoch?: string | undefined,\n ) => unknown | Promise<unknown>\n /** Subscribes to the document's commits; returns the unsubscribe. */\n readonly changes?: ((listener: () => void) => () => void) | undefined\n },\n): (() => void) => {\n const send = (reply: ExchangeReply | NotifyFrame): void => {\n try {\n socket.send(JSON.stringify(reply))\n } catch {\n // The socket may have closed while the handler was running.\n }\n }\n const stopMessage = socket.onMessage(data => {\n let parsed: unknown\n try {\n parsed = JSON.parse(data)\n } catch {\n return\n }\n if (typeof parsed !== 'object' || parsed === null) return\n const { id, cursor, pending, epoch } = parsed as {\n id?: unknown\n cursor?: unknown\n pending?: unknown\n epoch?: unknown\n }\n // Without an id there is nobody to answer, so drop the frame.\n if (typeof id !== 'string') return\n if (\n typeof cursor !== 'number' ||\n !Number.isSafeInteger(cursor) ||\n cursor < 0 ||\n !Array.isArray(pending) ||\n (epoch !== undefined && typeof epoch !== 'string')\n ) {\n send({ id, error: 'Invalid exchange frame' })\n return\n }\n const frame: ExchangeFrame = {\n id,\n cursor,\n pending: pending as ReadonlyArray<Operation>,\n epoch: typeof epoch === 'string' ? epoch : undefined,\n }\n void (async () => {\n try {\n const result = await options.exchange(frame.cursor, frame.pending, frame.epoch)\n send({ id: frame.id, result })\n } catch (error) {\n send({ id: frame.id, error: error instanceof Error ? error.message : String(error) })\n }\n })()\n })\n const stopChanges = options.changes?.(() => send({ notify: true }))\n const stop = (): void => {\n stopMessage()\n stopChanges?.()\n }\n const stopClose = socket.onClose(stop)\n return () => {\n stop()\n stopClose()\n }\n}\n\n/** The minimal socket the layer needs; the global `WebSocket` satisfies it. */\nexport interface SocketLike {\n send(data: string): void\n close(): void\n onMessage(listener: (data: string) => void): () => void\n onClose(listener: () => void): () => void\n /**\n * Optional. When provided, exchanges wait for it before sending, so a\n * transport can connect asynchronously. Absent means already connected.\n */\n onOpen?(listener: () => void): () => void\n}\n\n/**\n * Where `layerSocket` connects: a `url` for the platform `WebSocket`, or a\n * `makeSocket` that opens any other `SocketLike` (a port, a test socket), called\n * again on every reconnect.\n */\nexport type SocketOptions = SocketTuning &\n (\n | { readonly url: string; readonly makeSocket?: undefined }\n | { readonly makeSocket: () => SocketLike; readonly url?: undefined }\n )\n\ninterface SocketTuning {\n /**\n * Consecutive failed connections after which queued work fails and new\n * exchanges fail fast until a connection is healthy again. Reconnecting goes\n * on regardless. Default 5.\n */\n readonly maxRetries?: number | undefined\n /** Base delay of the exponential reconnect backoff. Default `50 millis`. */\n readonly retryBase?: Duration.Input | undefined\n /** Longest wait between reconnect attempts. Default `5 seconds`. */\n readonly maxRetryDelay?: Duration.Input | undefined\n /** Exchanges queued or in flight before new ones fail. Default 64. */\n readonly maxQueue?: number | undefined\n}\n\n/** The default socket factory: the platform `WebSocket`, as a `SocketLike`. */\nexport const nativeSocket = (url: string): SocketLike => {\n const socket = new WebSocket(url)\n return {\n send: data => socket.send(data),\n close: () => socket.close(),\n onOpen: listener => {\n if (socket.readyState === WebSocket.OPEN) {\n listener()\n return () => {}\n }\n socket.addEventListener('open', listener)\n return () => socket.removeEventListener('open', listener)\n },\n onMessage: listener => {\n const handler = (event: MessageEvent): void => listener(String(event.data))\n socket.addEventListener('message', handler)\n return () => socket.removeEventListener('message', handler)\n },\n onClose: listener => {\n const handler = (): void => listener()\n socket.addEventListener('close', handler)\n return () => socket.removeEventListener('close', handler)\n },\n }\n}\n\n/**\n * A socket over a `MessagePort`, for either end: its frames are the port's\n * string messages, and anything else on the port is ignored. A port tells\n * neither end when the other goes, so `onClose` fires once, on `close()` or\n * when `signal` aborts; a host that serves a pane aborts it when the pane is\n * gone, which stops `serveSocket` and anything else listening.\n */\nexport const portSocket = (\n port: MessagePort,\n options: { readonly signal?: AbortSignal | undefined } = {},\n): SocketLike => {\n const closeListeners = new Set<() => void>()\n let closed = false\n const close = (): void => {\n closed = true\n port.close()\n for (const listener of [...closeListeners]) listener()\n closeListeners.clear()\n }\n options.signal?.addEventListener('abort', close, { once: true })\n if (options.signal?.aborted === true) close()\n port.start()\n return {\n send: data => port.postMessage(data),\n close,\n onMessage: listener => {\n const handler = (event: MessageEvent): void => {\n if (typeof event.data === 'string') listener(event.data)\n }\n port.addEventListener('message', handler)\n return () => port.removeEventListener('message', handler)\n },\n onClose: listener => {\n if (closed) {\n listener()\n return () => {}\n }\n closeListeners.add(listener)\n return () => closeListeners.delete(listener)\n },\n }\n}\n\n/**\n * A socket over an existing `WebSocket`: the accepted end of a Cloudflare\n * `WebSocketPair`, or any other socket the platform hands over. Unlike\n * `nativeSocket` it opens nothing — accept the pair first — and unlike\n * `portSocket` there is no signal: the socket closing, erroring, or being\n * closed fires `onClose` once, which is how a host stops serving it.\n */\nexport const workerSocket = (socket: WebSocket): SocketLike => {\n const messageListeners = new Set<(data: string) => void>()\n const closeListeners = new Set<() => void>()\n let closed = false\n const forget = (): void => {\n socket.removeEventListener('message', onMessageEvent)\n socket.removeEventListener('close', onClosedEvent)\n socket.removeEventListener('error', onClosedEvent)\n }\n const fireClose = (): void => {\n closed = true\n forget()\n for (const listener of [...closeListeners]) listener()\n closeListeners.clear()\n }\n const onMessageEvent = (event: MessageEvent): void => {\n for (const listener of [...messageListeners]) listener(String(event.data))\n }\n const onClosedEvent = (): void => {\n fireClose()\n }\n socket.addEventListener('message', onMessageEvent)\n socket.addEventListener('close', onClosedEvent)\n socket.addEventListener('error', onClosedEvent)\n return {\n send: data => socket.send(data),\n close: () => {\n try {\n socket.close()\n } catch {\n // Already gone: still report the close.\n }\n fireClose()\n },\n onMessage: listener => {\n messageListeners.add(listener)\n return () => messageListeners.delete(listener)\n },\n onClose: listener => {\n if (closed) {\n listener()\n return () => {}\n }\n closeListeners.add(listener)\n return () => closeListeners.delete(listener)\n },\n }\n}\n\nconst connector = (options: SocketOptions): (() => SocketLike) => {\n if (options.makeSocket !== undefined) return options.makeSocket\n const { url } = options\n return () => nativeSocket(url)\n}\n\n/**\n * A WebSocket client transport.\n *\n * One connection is live at a time. While it is connecting, exchanges queue; if\n * it closes, the transport reconnects on an exponential, jittered backoff and\n * re-sends every queued and in-flight frame with its original id, so a lost\n * reply is answered rather than dropped and a late reply cannot resolve a newer\n * frame. It never stops reconnecting: after `maxRetries` consecutive failures\n * queued work fails with a `TransportError`, and exchanges fail fast while no\n * socket is up, until a socket opens. The count resets only when a connection\n * proves healthy, by answering a frame or by staying open for `maxRetryDelay`:\n * a server that accepts a socket and drops it at once is backed off like one\n * that refuses it. A queue over `maxQueue` fails new\n * exchanges with backpressure. The socket is released when the layer's scope\n * ends.\n */\nexport const layerSocket = (\n options: SocketOptions,\n): Layer.Layer<Transport | TransportSocket, TransportError> =>\n Layer.effectContext(\n Effect.fn('Transport.layerSocket')(function* () {\n const makeSocket = connector(options)\n const maxQueue = options.maxQueue ?? 64\n const maxRetries = options.maxRetries ?? 5\n const retryBase = Duration.toMillis(\n Duration.fromInputUnsafe(options.retryBase ?? '50 millis'),\n )\n const maxRetryDelay = Duration.toMillis(\n Duration.fromInputUnsafe(options.maxRetryDelay ?? '5 seconds'),\n )\n const clock = yield* Clock.Clock\n // Listeners run in a socket's callback, outside any Effect: their\n // failures go to the reporter this layer was built with.\n const reporter = yield* Effect.service(Diagnostics.Reporter)\n\n interface Entry {\n readonly id: string\n readonly cursor: number\n readonly pending: ReadonlyArray<Operation>\n readonly epoch: string | undefined\n readonly resume: (effect: Effect.Effect<unknown, TransportError>) => void\n }\n const notices = yield* PubSub.sliding<void>(1)\n const listeners = new Set<(data: string) => void>()\n const shared: SocketLike = {\n send: data => {\n if (ready) socket?.send(data)\n },\n close: () => {},\n onMessage: listener => {\n listeners.add(listener)\n return () => listeners.delete(listener)\n },\n onClose: () => () => {},\n }\n const queued: Array<Entry> = []\n const inFlight = new Map<string, Entry>()\n let socket: SocketLike | undefined\n let ready = false\n let nextId = 0\n let disposed = false\n // Closes since a connection last proved healthy. Past `maxRetries` the\n // transport is offline: nothing waits for a socket that may be minutes away.\n let failures = 0\n const healthy = (): void => {\n failures = 0\n }\n\n const send = (entry: Entry): void => {\n inFlight.set(entry.id, entry)\n socket?.send(\n JSON.stringify({\n id: entry.id,\n cursor: entry.cursor,\n pending: entry.pending,\n ...(entry.epoch === undefined ? {} : { epoch: entry.epoch }),\n } satisfies ExchangeFrame),\n )\n }\n const flush = (): void => {\n if (socket === undefined || !ready) return\n for (const entry of queued.splice(0)) send(entry)\n }\n const requeue = (): void => {\n queued.unshift(...inFlight.values())\n inFlight.clear()\n }\n const failAll = (message: string): void => {\n const entries = [...queued.splice(0), ...inFlight.values()]\n inFlight.clear()\n for (const entry of entries) entry.resume(Effect.fail(new TransportError({ message })))\n }\n\n const connect = Effect.tryPromise({\n try: () =>\n new Promise<void>((resolve, reject) => {\n const next = makeSocket()\n socket = next\n ready = next.onOpen === undefined\n let openedAt = ready ? clock.currentTimeMillisUnsafe() : undefined\n // A socket that just (re)connected may have missed notices, so opening is one.\n const opened = (): void => {\n PubSub.publishUnsafe(notices, undefined)\n }\n const offOpen = next.onOpen?.(() => {\n ready = true\n openedAt = clock.currentTimeMillisUnsafe()\n opened()\n flush()\n })\n const offMessage = next.onMessage(data => {\n // Another protocol's listener must not cost an exchange its reply.\n for (const listener of [...listeners]) {\n try {\n listener(data)\n } catch (thrown) {\n Effect.runFork(\n Diagnostics.report(listenerFailed('Socket', thrown)).pipe(\n Effect.provideService(Diagnostics.Reporter, reporter),\n ),\n )\n }\n }\n let reply: ExchangeReply | NotifyFrame\n try {\n reply = JSON.parse(data) as ExchangeReply | NotifyFrame\n } catch {\n return\n }\n if (typeof reply !== 'object' || reply === null) return\n if ('notify' in reply) {\n if (reply.notify === true) PubSub.publishUnsafe(notices, undefined)\n return\n }\n const entry = inFlight.get(reply.id)\n if (entry === undefined) return\n healthy()\n inFlight.delete(reply.id)\n entry.resume(\n reply.error === undefined\n ? Effect.succeed(reply.result)\n : Effect.fail(new TransportError({ message: reply.error })),\n )\n })\n const offClose = next.onClose(() => {\n offOpen?.()\n offMessage()\n offClose()\n socket = undefined\n ready = false\n if (\n openedAt !== undefined &&\n clock.currentTimeMillisUnsafe() - openedAt >= maxRetryDelay\n )\n healthy()\n // Keep every unanswered frame for the next connection.\n requeue()\n reject(new Error('transport closed'))\n })\n if (ready) {\n opened()\n flush()\n }\n }),\n catch: () => new TransportError({ message: 'transport closed' }),\n })\n\n yield* Effect.forkScoped(\n Effect.gen(function* () {\n while (!disposed) {\n yield* Effect.exit(connect)\n if (disposed) return\n failures += 1\n if (failures > maxRetries) failAll('transport closed')\n const backoff = Math.min(maxRetryDelay, retryBase * 2 ** Math.min(failures - 1, 30))\n yield* Effect.sleep(backoff * (0.8 + Math.random() * 0.4))\n }\n }),\n )\n yield* Effect.addFinalizer(() =>\n Effect.sync(() => {\n disposed = true\n ready = false\n socket?.close()\n socket = undefined\n failAll('transport closed')\n }),\n )\n\n const transport = Transport.of({\n changes: Stream.fromPubSub(notices),\n exchange: (cursor, pending, epoch) =>\n Effect.callback<unknown, TransportError>(resume => {\n if (disposed) {\n resume(Effect.fail(new TransportError({ message: 'transport closed' })))\n return\n }\n if (failures > maxRetries && !ready) {\n resume(Effect.fail(new TransportError({ message: 'transport closed' })))\n return\n }\n if (queued.length + inFlight.size >= maxQueue) {\n resume(Effect.fail(new TransportError({ message: 'transport queue full' })))\n return\n }\n const entry: Entry = { id: String(nextId++), cursor, pending, epoch, resume }\n if (ready) send(entry)\n else queued.push(entry)\n // A caller interrupted before a reply must release its slot, or a\n // socket that never replies can exhaust the queue with abandoned\n // work. The frame may already be on the wire; only the local waiter\n // is forgotten, and a late reply for it is ignored.\n return Effect.sync(() => {\n const queuedIndex = queued.indexOf(entry)\n if (queuedIndex >= 0) queued.splice(queuedIndex, 1)\n if (inFlight.get(entry.id) === entry) inFlight.delete(entry.id)\n })\n }),\n })\n return Context.make(Transport, transport).pipe(Context.add(TransportSocket, shared))\n })(),\n )\n"],"mappings":";;;;;;AAOA,IAAa,iBAAb,cAAoC,OAAO,YAA4B,CAAC,CAAC,sBAAsB,EAC7F,SAAS,OAAO,OAClB,CAAC,CAAC,CAAC,CAAC;;;;;;;;AA8CJ,IAAa,YAAb,cAA+B,QAAQ,QAAmC,CAAC,CACzE,wBACF,CAAC,CAAC,CAAC;;;;;;;;AASH,IAAa,kBAAb,cAAqC,QAAQ,QAAqC,CAAC,CACjF,8BACF,CAAC,CAAC,CAAC;AAEH,MAAM,WAAW,UACf,IAAI,eAAe,EAAE,SAAS,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,EAAE,CAAC;;AAGxF,MAAa,iBACX,YAMA,MAAM,QAAQ,WAAW,EACvB,WAAW,QAAQ,SAAS,UAC1B,OAAO,WAAW;CAChB,WAAW,QAAQ,QAAQ,QAAQ,QAAQ,SAAS,KAAK,CAAC;CAC1D,OAAO;AACT,CAAC,EACL,CAAC;;AAGH,MAAa,oBAAoB,cAC/B,MAAM,QAAQ,WAAW,EACvB,WAAW,QAAQ,SAAS,UAC1B,OAAO,WAAW;CAChB,WAAW,UAAU,SAAS,SAAS,MAAM,GAAG,SAAS,KAAK;CAC9D,OAAO;AACT,CAAC,EACL,CAAC;;AAGH,MAAa,aAAa,eAAgD,EACxE,WAAW,QAAQ,SAAS,UAC1B,OAAO,WAAW,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,OAAO,SAAS,SAAS,QAAQ,UAAU;IAC7C,OAAO,OAAO,KAAK,IAAI,eAAe,EAAE,SAAS,uBAAuB,CAAC,CAAC,CAAC;IAC3E;GACF;GACA,MAAM,QAAe;IAAE,IAAI,OAAO,QAAQ;IAAG;IAAQ;IAAS;IAAO;GAAO;GAC5E,IAAI,OAAO,KAAK,KAAK;QAChB,OAAO,KAAK,KAAK;GAKtB,OAAO,OAAO,WAAW;IACvB,MAAM,cAAc,OAAO,QAAQ,KAAK;IACxC,IAAI,eAAe,GAAG,OAAO,OAAO,aAAa,CAAC;IAClD,IAAI,SAAS,IAAI,MAAM,EAAE,MAAM,OAAO,SAAS,OAAO,MAAM,EAAE;GAChE,CAAC;EACH,CAAC;CACL,CAAC;CACD,OAAO,QAAQ,KAAK,WAAW,SAAS,CAAC,CAAC,KAAK,QAAQ,IAAI,iBAAiB,MAAM,CAAC;AACrF,CAAC,CAAC,CAAC,CACL"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "foldkit-sync",
3
- "version": "0.12.3",
3
+ "version": "0.13.0",
4
4
  "description": "A local-first replica of a shared Foldkit projection: offline outbox, optimistic updates, and reconciliation.",
5
5
  "keywords": [
6
6
  "foldkit",
@@ -29,28 +29,28 @@
29
29
  "exports": {
30
30
  ".": {
31
31
  "foldkit-plus:source": "./src/index.ts",
32
- "types": "./dist/index.d.mts",
33
- "import": "./dist/index.mjs"
32
+ "types": "./dist/index.d.ts",
33
+ "import": "./dist/index.js"
34
34
  },
35
35
  "./journal": {
36
36
  "foldkit-plus:source": "./src/journal.ts",
37
- "types": "./dist/journal.d.mts",
38
- "import": "./dist/journal.mjs"
37
+ "types": "./dist/journal.d.ts",
38
+ "import": "./dist/journal.js"
39
39
  },
40
40
  "./entity": {
41
41
  "foldkit-plus:source": "./src/entity.ts",
42
- "types": "./dist/entity.d.mts",
43
- "import": "./dist/entity.mjs"
42
+ "types": "./dist/entity.d.ts",
43
+ "import": "./dist/entity.js"
44
44
  },
45
45
  "./do": {
46
46
  "foldkit-plus:source": "./src/do.ts",
47
- "types": "./dist/do.d.mts",
48
- "import": "./dist/do.mjs"
47
+ "types": "./dist/do.d.ts",
48
+ "import": "./dist/do.js"
49
49
  },
50
50
  "./remote": {
51
51
  "foldkit-plus:source": "./src/remote.ts",
52
- "types": "./dist/remote.d.mts",
53
- "import": "./dist/remote.mjs"
52
+ "types": "./dist/remote.d.ts",
53
+ "import": "./dist/remote.js"
54
54
  }
55
55
  },
56
56
  "files": [
@@ -59,13 +59,13 @@
59
59
  "LICENSE"
60
60
  ],
61
61
  "dependencies": {
62
- "foldkit-surface": "0.10.2"
62
+ "foldkit-surface": "0.11.0"
63
63
  },
64
64
  "peerDependencies": {
65
- "effect": "^4.0.0",
66
- "foldkit": "^0.169.0",
67
- "foldkit-remote": "0.20.0",
68
- "foldkit-durable": "0.9.1"
65
+ "effect": "^4.1.0",
66
+ "foldkit": "^0.170.0",
67
+ "foldkit-durable": "0.10.0",
68
+ "foldkit-remote": "0.22.0"
69
69
  },
70
70
  "peerDependenciesMeta": {
71
71
  "foldkit-durable": {
@@ -77,19 +77,19 @@
77
77
  },
78
78
  "devDependencies": {
79
79
  "@cloudflare/workers-types": "5.20261022.1",
80
- "@effect/platform-browser": "^4.0.5",
81
- "@effect/sql-d1": "^4.0.5",
82
- "effect": "^4.0.5",
80
+ "@effect/platform-browser": "^4.1.0",
81
+ "@effect/sql-d1": "^4.1.0",
82
+ "effect": "^4.1.0",
83
83
  "esbuild": "0.28.2",
84
- "foldkit": "0.169.0",
84
+ "foldkit": "0.170.0",
85
85
  "jsdom": "30.1.3",
86
86
  "miniflare": "4.20260730.0",
87
87
  "tsdown": "^0.23.1",
88
88
  "typescript": "7.0.2",
89
- "foldkit-agent": "0.8.3",
90
- "foldkit-entity": "0.12.0",
91
- "foldkit-durable": "0.9.1",
92
- "foldkit-remote": "0.20.0"
89
+ "foldkit-durable": "0.10.0",
90
+ "foldkit-agent": "0.9.0",
91
+ "foldkit-entity": "0.14.0",
92
+ "foldkit-remote": "0.22.0"
93
93
  },
94
94
  "scripts": {
95
95
  "build": "tsdown",
package/dist/do.d.mts.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"do.d.mts","names":[],"sources":["../src/do.ts"],"mappings":";;;;;iBAyCiB;WACN;;;iBAIM,mBAAmB,SAAS,QAAQ,WAAW,KAAK;;WAE1D,MAAM,KAAK,SAAS;;;;;;;;WAQpB,cACP,KAAK,qBACL,KAAK,QACF,QAAQ,QAAQ,WAAW,QAAQ,WAAW;;;;;;;;WAQ1C,mBACP,SAAS,SACT,KAAK,QACF,OAAO,OAAO,WAAW,uBAAuB;;;;;;;WAO5C,WAEH,KAAK,KACL,SAAS,QAAQ,WAAW,QAAQ,WAAW,eAC5C,OAAO;;;;;;;;;;WAWP;aAEM,OAAO,SAAS;aAChB,QAAQ,WAAW;;;WAIzB,UAAU,WAAW,cAAc,OAAO;;;;;WAK1C,UAEH,WAAW,WACX,WAAW,cACR,oBAAoB,OAAO,OAAO;;;;;;WAOlC,wBAAwB,QAAQ,WAAW,QAAQ;;;;;;;;YASlD,kBAAkB,KAAK,OAAO;WAC3B;;WACA,QAAQ,KAAK,QAAQ,MAAM,MAAM;;;;;;iBAM/B,2BAA2B;EAC1C;;;;;;;;qBAuCW,qBAAsB,SAAS,QAAQ,WAAW,KAAK,YAAU,WACjE,KAAK,qBAAqB,KAAK,gBAAc,QAChD,mBAAmB,SAAS,QAAQ,WAAW,KAAK,MAAM,kBAAkB,KAAK,aACnF,KAAK,qBAAqB,KAAK;EAAU,MAAM,SAAS,UAAU,QAAQ"}
package/dist/do.mjs.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"do.mjs","names":[],"sources":["../src/do.ts"],"sourcesContent":["/**\n * `foldkit-sync/do`: serve one document's Sync exchange from a Cloudflare\n * Durable Object, the single writer its journal wants. Each socket the\n * object accepts exchanges against the same journal through `serveJournal`;\n * the replica side already exists as `Sync.transport.socket` over the\n * object's `wss://…` URL, which hears other writers' commits as notices.\n *\n * The class takes its `DurableObject` base as a parameter, so this module\n * imports no worker runtime and loads anywhere:\n *\n * ```ts\n * import { DurableObject } from 'cloudflare:workers'\n *\n * export class SyncHost extends defineDocumentHost(DurableObject, {\n * sync: Todos,\n * openJournal: (_ctx, env) => openTodosJournal(env.DB),\n * resolvePrincipal: request =>\n * Effect.succeed({ actorId: request.headers.get('x-actor') ?? 'anon' }),\n * }) {}\n * ```\n *\n * Open the journal once per object: on the first upgrade, so probes never\n * provision storage. Route one object per document (`idFromName(sync\n * .documentId)`); its in-memory cache and change stream are then exact\n * because nothing else writes.\n */\nimport { type Duration, type Effect, type Layer, Result } from 'effect'\nimport type { RemoteUnauthenticated } from 'foldkit-remote'\nimport type { Journal } from 'foldkit-durable/core'\nimport {\n documentHost,\n type Accepted,\n type DocumentHostOptions,\n type DocumentHostOptionsLayer,\n} from './journal.js'\nimport { checkRevalidate } from './revalidate.js'\nimport type { AuthorizeDecision } from './make.js'\nimport type { Operation, Sync } from './sync.js'\nimport { workerSocket } from './transport.js'\n\n/** The sliver of a Durable Object the host uses: state for the journal to open with. */\nexport interface DocumentHostContext {\n readonly storage?: unknown\n}\n\n/** What `defineDocumentHost` needs of the application, per document. */\nexport interface DocumentHostConfig<Message, Shared, Principal, Env, RP = never> {\n /** The document's contract: its codecs and journal shape. */\n readonly sync: Sync<Message, Shared>\n /**\n * Opens the document's journal, once: on the first upgrade, not on\n * construction, so probes never provision storage. Over D1 (`d1: true`),\n * or the object's SQLite storage through `ctx`. May build with Effect and\n * unwrap; a rejection answers the upgrade with a 500, and the next upgrade\n * tries again.\n */\n readonly openJournal: (\n ctx: DocumentHostContext,\n env: Env,\n ) => Promise<Journal<Operation, Shared, Principal, Operation>>\n /**\n * Who is opening this socket, from the upgrade request. Fails with a\n * `RemoteUnauthenticated` (`foldkit-remote`; `RemoteServer.unauthenticated()`\n * makes one) to refuse it: a 401 carrying its message. A defect is a 500\n * that says nothing of it. What it needs (a session store) comes from\n * `layer`.\n */\n readonly resolvePrincipal: (\n request: Request,\n env: Env,\n ) => Effect.Effect<Principal, RemoteUnauthenticated, RP>\n /**\n * Runs after each exchange's appends and before the reply is read: apply\n * what committed to another store, through `journal.recover`. Takes the\n * environment — a D1 binding, say — and the journal, because both live\n * outside the exchange. See `serveJournal`.\n */\n readonly settle?:\n | ((\n env: Env,\n journal: Journal<Operation, Shared, Principal, Operation>,\n ) => Effect.Effect<void, unknown>)\n | undefined\n /**\n * Asks `resolvePrincipal` again, of the upgrade request, every `every`\n * while the socket is open: a refusal closes it with 4401, and a principal\n * whose `key` differs from the one it opened with (`Policy.keyOf`) closes\n * it with 1012, which the replica reconnects after, as the new principal;\n * without `key` only a refusal closes it. Without it a socket\n * serves the principal it opened with until it closes, a revoked session\n * included.\n */\n readonly revalidate?:\n | {\n readonly every: Duration.Input\n readonly key?: ((principal: Principal) => unknown) | undefined\n }\n | undefined\n /** Whether `principal` may open the document. See `journalExchange`'s `opens`. */\n readonly opens?: ((principal: Principal) => Effect.Effect<boolean>) | undefined\n /**\n * Whether an operation from `principal` may be appended, before the journal\n * sees it. See `journalExchange`'s `admit`.\n */\n readonly admit?:\n | ((\n principal: Principal,\n operation: Operation,\n ) => AuthorizeDecision | Effect.Effect<AuthorizeDecision, unknown>)\n | undefined\n /**\n * Makes the socket pair for an upgrade: the server end is accepted before\n * serving. Defaults to the `WebSocketPair` global where one exists (a\n * worker, miniflare); pass one in tests.\n */\n readonly pair?: (() => readonly [client: WebSocket, server: AcceptingWebSocket]) | undefined\n}\n\n/**\n * What the resolver needs, from the environment: required exactly when it\n * needs something. Built per upgrade and kept until the socket closes, since\n * `revalidate` asks the resolver again while it is open; an upgrade that is\n * refused closes it at once.\n */\nexport type DocumentHostLayer<Env, RP> = [RP] extends [never]\n ? { readonly layer?: undefined }\n : { readonly layer: (env: Env) => Layer.Layer<RP> }\n\n/**\n * A server `WebSocket`: accepted once it serves. The `accept` member is a\n * worker-runtime extension the DOM type does not declare.\n */\nexport interface AcceptingWebSocket extends WebSocket {\n accept(): void\n}\n\n/**\n * Closes a socket with `code`, and `reason` when the platform takes it: a\n * reason past 123 bytes, or a socket already gone, still closes or is closed.\n */\nconst closeWith = (socket: WebSocket, code: number, reason: string): void => {\n try {\n socket.close(code, reason)\n } catch {\n try {\n socket.close(code)\n } catch {\n // Already closed.\n }\n }\n}\n\nconst defaultPair = (): readonly [client: WebSocket, server: AcceptingWebSocket] => {\n const maker = (\n globalThis as {\n readonly WebSocketPair?:\n | (new () => { readonly 0: WebSocket; readonly 1: AcceptingWebSocket })\n | undefined\n }\n ).WebSocketPair\n if (maker === undefined)\n throw new Error('DocumentHost: no WebSocketPair global; pass `pair` explicitly')\n const pair = new maker()\n return [pair[0], pair[1]] as const\n}\n\n/**\n * Defines the Durable Object class serving one document's Sync exchange.\n * Non-upgrades are 404s that open nothing; a refused principal is a 401; a\n * resolver that breaks, or a journal that never opened, a 500 that says\n * nothing of it.\n */\nexport const defineDocumentHost = <Message, Shared, Principal, Env, RP = never>(\n Base: new (ctx: DocumentHostContext, env: Env) => object,\n config: DocumentHostConfig<Message, Shared, Principal, Env, RP> & DocumentHostLayer<Env, RP>,\n): new (ctx: DocumentHostContext, env: Env) => { fetch(request: Request): Promise<Response> } => {\n checkRevalidate(config.revalidate, 'defineDocumentHost')\n return class extends Base {\n private readonly host: (request: Request) => Promise<Result.Result<Accepted, Response>>\n\n constructor(ctx: DocumentHostContext, env: Env) {\n super(ctx, env)\n let ready: Promise<Journal<Operation, Shared, Principal, Operation>> | undefined\n const { layer, settle } = config\n this.host = documentHost<Message, Shared, Principal, RP>({\n sync: config.sync,\n // Opened on the first upgrade a principal passes, so probes never\n // provision storage; a failed open is tried again on the next.\n journal: () =>\n (ready ??= config.openJournal(ctx, env)).catch((error: unknown) => {\n ready = undefined\n throw error\n }),\n resolvePrincipal: request => config.resolvePrincipal(request, env),\n layer: layer === undefined ? undefined : () => layer(env),\n revalidate: config.revalidate,\n settle: settle === undefined ? undefined : journal => settle(env, journal),\n opens: config.opens,\n admit: config.admit,\n // `DocumentHostLayer` already tied `layer` to `RP` on the config; the\n // conditional cannot be resolved for an `RP` still generic here.\n } as DocumentHostOptions<Message, Shared, Principal, RP> & DocumentHostOptionsLayer<RP>)\n }\n\n async fetch(request: Request): Promise<Response> {\n if (request.headers.get('Upgrade')?.toLowerCase() !== 'websocket')\n return Response.json({ error: 'not found' }, { status: 404 })\n // Made first: a runtime without WebSocketPair is a 500 that resolves no one.\n let pair: readonly [client: WebSocket, server: AcceptingWebSocket]\n try {\n pair = (config.pair ?? defaultPair)()\n } catch (error) {\n // The replica learns nothing of it; whoever runs the host must.\n console.error('[foldkit-sync] serving an upgrade broke:', error)\n return Response.json({ error: 'Internal error' }, { status: 500 })\n }\n const [client, server] = pair\n const answered = await this.host(request)\n if (Result.isFailure(answered)) return answered.failure\n const { serve, abandon } = answered.success\n try {\n server.accept()\n serve({\n ...workerSocket(server),\n closeWith: (code, reason) => closeWith(server, code, reason),\n })\n return new Response(null, {\n status: 101,\n // The worker runtime reads the client out of the upgrade response;\n // the DOM's `ResponseInit` has no such member.\n webSocket: client,\n } as ResponseInit)\n } catch (error) {\n console.error('[foldkit-sync] serving an upgrade broke:', error)\n abandon()\n return Response.json({ error: 'Internal error' }, { status: 500 })\n }\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4IA,MAAM,aAAa,QAAmB,MAAc,WAAyB;CAC3E,IAAI;EACF,OAAO,MAAM,MAAM,MAAM;CAC3B,QAAQ;EACN,IAAI;GACF,OAAO,MAAM,IAAI;EACnB,QAAQ,CAER;CACF;AACF;AAEA,MAAM,oBAA8E;CAClF,MAAM,QACJ,WAKA;CACF,IAAI,UAAU,KAAA,GACZ,MAAM,IAAI,MAAM,+DAA+D;CACjF,MAAM,OAAO,IAAI,MAAM;CACvB,OAAO,CAAC,KAAK,IAAI,KAAK,EAAE;AAC1B;;;;;;;AAQA,MAAa,sBACX,MACA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,GAAA,cAAM,SACjB,cAAc,OAAO,GAAC,cAAK,IAChC,OAAO,gBAAc,IACrB,OAAO,OAAO,YACjB,cAAa,SAAA,GAAA;;EAOA,SAAA,OAAA,cAAa,SAAA,GAAA,cAAM,oBAAoB,cAAa,SAAA,GAAA;;EAM9C,eAAA,OAAA,cAAa,SAAA,GAAA,cAAM;;;;;;EAS7B,WAAA,UAAA,cAAa,SAAA,GAAA,cAAM,MACvB,cAAa,SAAA,GAAA,cAAM,oBAExB,cAAc,SAAQ,SAAA,GAAA;;EAiBd,UAAA,SAAA,cAAc,OAAO,GAAC,iBAC9B;aAAyB,IAAI,KAAK;aAAa,QAAM;;;;;;EAOvB,WAAA,KAAA,MAAA,GAAA,aAAA,QAAA,eAAA,OAAO,GAAC;;EAKzB,SAAA,OAAA,cAAa,SAAA,GAAA,cAAM,KAAO,KAAK,IAAE,QAAA,eAAc,OAAO,OAAM,SAAA,GAAA;EA7F3C,OAAA,MAAA,SAAA,GAAA,aAAA;;;qBAuGxB;;;YACD,eACV,UAAU,cACV,WAAW,cAAc,OAAO,OAC9B,kBAAkB,KAAK,GAAG"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"entity.mjs","names":[],"sources":["../src/entity.ts"],"sourcesContent":["/**\n * `foldkit-sync/entity`: edits to rows a server owns, kept in a replicated\n * slice that the journal owns. `foldkit-sync/remote` shows them over the rows\n * Remote reads.\n *\n * The journal orders the edits and stamps each with the sequence it\n * committed at (`at`) and who committed it from where (`by`); the table is\n * the journal's read model, each row carrying the highest sequence it has\n * applied (`revision`). An edit the table holds is absorbed: the server says\n * so (`absorbed`), every replica drops it, and the journal compacts.\n *\n * Everything here is pure: it owns no state, does no I/O, and sends nothing.\n * The application keeps the edits in its Model and calls these from\n * `update`, the stamp, and `Sync.mount`'s `onReinstall`.\n */\nimport { Equal, Option, Schema } from 'effect'\n\n/** Who committed an edit: the actor, shown in words, and the replica (a tab), which says whose it is. */\nexport const Author = Schema.Struct({ actor: Schema.String, replica: Schema.String })\nexport type Author = typeof Author.Type\n\n/** What `make` reads of an Entity: each member's schema, `id` among them. */\nexport interface EntityFields {\n readonly fields: { readonly id: { readonly schema: Schema.Top } } & {\n readonly [member: string]: { readonly schema: Schema.Top }\n }\n}\n\n/** The members an edit can change: every field but `id`. */\nexport type Member<E extends EntityFields> = Exclude<keyof E['fields'] & string, 'id'>\ntype ValueOf<E extends EntityFields, K extends Member<E>> = E['fields'][K]['schema']['Type']\ntype IdOf<E extends EntityFields> = E['fields']['id']['schema']['Type']\n\n/** One cell's new value: the member and a value of that member's type, together. */\nexport type Change<E extends EntityFields, Ms extends Member<E>> = {\n readonly [K in Ms]: { readonly id: IdOf<E>; readonly member: K; readonly value: ValueOf<E, K> }\n}[Ms]\n\n/** A cell's edit as the slice keeps it: committed `at` by `by`, or, with neither, pending. */\nexport type CellEdit<E extends EntityFields, Ms extends Member<E>> = {\n readonly [K in Ms]: {\n readonly id: IdOf<E>\n readonly member: K\n readonly value: ValueOf<E, K>\n readonly at: Option.Option<number>\n readonly by: Option.Option<Author>\n }\n}[Ms]\n\n/** A row as the table holds it: its id, the revision it has applied, and its members. */\nexport type RowOf<E extends EntityFields, Ms extends Member<E>> = {\n readonly id: IdOf<E>\n readonly revision: number\n} & { readonly [K in Ms]: ValueOf<E, K> }\n\n/** A cell this replica last wrote that a later edit replaced: its edit, and what the cell holds now. */\nexport interface Replaced<Edit> {\n readonly edit: Edit\n /** The later edit's author, when the slice still says; none once the journal absorbed it. */\n readonly by: Option.Option<Author>\n}\n\nconst make = <E extends EntityFields, const Ms extends ReadonlyArray<Member<E>>>(\n entity: E,\n options: { readonly members: Ms },\n) => {\n type M = Ms[number]\n type Edit = CellEdit<E, M>\n type Row = RowOf<E, M>\n const { members } = options\n const id = entity.fields.id.schema\n if (members.length === 0) throw new Error('EditableEntity.make: name at least one member')\n for (const member of members) {\n if ((member as string) === 'id' || !Object.hasOwn(entity.fields, member)) {\n throw new Error(`EditableEntity.make: ${member} is not a member of the entity`)\n }\n }\n const schemaOf = (member: M) => entity.fields[member]!.schema\n // One struct per member, so a value is decoded by its own member's schema:\n // the union is exactly `Change`, member and value paired.\n const Change = Schema.Union(\n members.map(member =>\n Schema.Struct({ id, member: Schema.Literal(member), value: schemaOf(member) }),\n ),\n ) as unknown as Schema.Codec<Change<E, M>, unknown>\n const Edit = Schema.Union(\n members.map(member =>\n Schema.Struct({\n id,\n member: Schema.Literal(member),\n value: schemaOf(member),\n at: Schema.OptionFromNullOr(Schema.Number),\n by: Schema.OptionFromNullOr(Author),\n }),\n ),\n ) as unknown as Schema.Codec<Edit, unknown>\n\n /** The edits by row, then member: no key is a string built from an id. */\n const indexOf = (edits: ReadonlyArray<Edit>) => {\n const index = new Map<IdOf<E>, Map<M, Edit>>()\n for (const edit of edits) {\n const row = index.get(edit.id) ?? new Map<M, Edit>()\n row.set(edit.member, edit)\n index.set(edit.id, row)\n }\n return index\n }\n const sameCell = (a: { readonly id: IdOf<E>; readonly member: M }, b: typeof a) =>\n Equal.equals(a.id, b.id) && a.member === b.member\n\n /** Whether a row read at `revision` has the edit: the table applies in the journal's order. */\n const reached = (edit: Edit, revision: number) => Option.exists(edit.at, at => at <= revision)\n\n /** Whether `replica` wrote the edit: pending here, or committed from it. */\n const mine = (edit: Edit, replica: string): boolean =>\n Option.match(edit.at, {\n onNone: () => true,\n onSome: () => Option.exists(edit.by, by => by.replica === replica),\n })\n\n return {\n /** Carried so `foldkit-sync/remote` can name the rows it overlays by the Entity's own name. */\n entity,\n members,\n /** The members, as a schema: what names a cell. */\n Member: Schema.Literals(members),\n /** One cell's change, on the wire: its member's value, by that member's schema. */\n Change,\n /** One cell's edit as the slice keeps it; `null` on the wire where it has no `at` or `by`. */\n Edit,\n /** The durable Message that edits cells: its fields, for the application's own tag. */\n edited: {\n changes: Schema.Array(Change),\n /** The journal's: absent on what a replica sends, stamped at commit. */\n at: Schema.optionalKey(Schema.Number),\n by: Schema.optionalKey(Author),\n },\n /** The server's durable Message: the table holds every edit committed through `through`. */\n absorbed: { through: Schema.Number },\n /** What the stamp writes into an edit: the sequence and the author. */\n stamped: (commit: {\n readonly sequence: number\n readonly actorId: string\n readonly replicaId: string\n }) => ({ at: commit.sequence, by: { actor: commit.actorId, replica: commit.replicaId } }),\n\n /** The edits with `changes` laid over them, each cell's latest kept. */\n merge: (\n edits: ReadonlyArray<Edit>,\n changes: ReadonlyArray<Change<E, M>>,\n at: Option.Option<number>,\n by: Option.Option<Author>,\n ): ReadonlyArray<Edit> => {\n if (changes.length === 0) return edits\n const added = changes.map(change => ({ ...change, at, by }) as Edit)\n return [...edits.filter(edit => !added.some(next => sameCell(edit, next))), ...added]\n },\n\n /** The edits less those committed through `through`; the same array when none was. */\n absorb: (edits: ReadonlyArray<Edit>, through: number): ReadonlyArray<Edit> =>\n edits.some(edit => reached(edit, through))\n ? edits.filter(edit => !reached(edit, through))\n : edits,\n\n /** Whether any edit is committed through `through`: whether an absorb would drop one. */\n holdsThrough: (edits: ReadonlyArray<Edit>, through: number): boolean =>\n edits.some(edit => reached(edit, through)),\n\n /**\n * What the slice replaced that `replica` had written: each cell whose\n * edit was its own, and now holds another replica's commit with another\n * value, though it be the same person's in another tab.\n */\n replaced: (\n previous: ReadonlyArray<Edit>,\n next: ReadonlyArray<Edit>,\n replica: string,\n ): ReadonlyArray<Replaced<Edit>> => {\n const before = indexOf(previous)\n return next.flatMap(edit => {\n const prior = before.get(edit.id)?.get(edit.member)\n if (prior === undefined || !mine(prior, replica)) return []\n return Option.match(edit.by, {\n onNone: () => [],\n onSome: by =>\n by.replica !== replica && !Equal.equals(edit.value, prior.value)\n ? [{ edit: prior, by: Option.some(by) }]\n : [],\n })\n })\n },\n\n /** The cells a set of changes names: what a refusal of them undid. */\n cellsOf: (\n changes: ReadonlyArray<Change<E, M>>,\n ): ReadonlyArray<{ readonly id: IdOf<E>; readonly member: M }> =>\n changes.map(({ id: row, member }) => ({ id: row, member })),\n\n /**\n * What a row holds in one member, as the change that would set it: the\n * value an undo puts back.\n */\n changeAt: (row: Row, member: M): Change<E, M> =>\n // The member and its value are read together, so they pair as `Change` does.\n ({ id: row.id, member, value: row[member] }) as Change<E, M>,\n\n /** The edit of one cell, if the edits hold one. */\n editOf: (edits: ReadonlyArray<Edit>, row: IdOf<E>, member: M): Option.Option<Edit> =>\n Option.fromUndefinedOr(\n edits.find(edit => Equal.equals(edit.id, row) && edit.member === member),\n ),\n\n mine,\n }\n}\n\n/** Edits to an Entity's members, kept per cell in a replicated slice and laid over its rows. */\nexport const EditableEntity = { make }\nexport type EditableEntity<\n E extends EntityFields,\n Ms extends ReadonlyArray<Member<E>>,\n> = ReturnType<typeof make<E, Ms>>\n"],"mappings":";;;;;;;;;;;;;;;;;;AAkBA,MAAa,SAAS,OAAO,OAAO;CAAE,OAAO,OAAO;CAAQ,SAAS,OAAO;AAAO,CAAC;AA4CpF,MAAM,QACJ,QACA,YACG;CAIH,MAAM,EAAE,YAAY;CACpB,MAAM,KAAK,OAAO,OAAO,GAAG;CAC5B,IAAI,QAAQ,WAAW,GAAG,MAAM,IAAI,MAAM,+CAA+C;CACzF,KAAK,MAAM,UAAU,SACnB,IAAK,WAAsB,QAAQ,CAAC,OAAO,OAAO,OAAO,QAAQ,MAAM,GACrE,MAAM,IAAI,MAAM,wBAAwB,OAAO,+BAA+B;CAGlF,MAAM,YAAY,WAAc,OAAO,OAAO,OAAO,CAAE;CAGvD,MAAM,SAAS,OAAO,MACpB,QAAQ,KAAI,WACV,OAAO,OAAO;EAAE;EAAI,QAAQ,OAAO,QAAQ,MAAM;EAAG,OAAO,SAAS,MAAM;CAAE,CAAC,CAC/E,CACF;CACA,MAAM,OAAO,OAAO,MAClB,QAAQ,KAAI,WACV,OAAO,OAAO;EACZ;EACA,QAAQ,OAAO,QAAQ,MAAM;EAC7B,OAAO,SAAS,MAAM;EACtB,IAAI,OAAO,iBAAiB,OAAO,MAAM;EACzC,IAAI,OAAO,iBAAiB,MAAM;CACpC,CAAC,CACH,CACF;;CAGA,MAAM,WAAW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