foldkit-sync 0.3.0 → 0.4.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.
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":[],"sources":["../src/errors.ts","../src/indexedDb.ts","../src/mount.ts","../src/ids.ts","../src/transport.ts","../src/sync.ts","../src/make.ts","../src/lww.ts","../src/presence.ts"],"sourcesContent":["import { Schema } from 'effect'\n\n/** The persisted storage could not be read or written. */\nexport class StorageError extends Schema.TaggedError<StorageError>()('StorageError', {\n message: Schema.String,\n cause: Schema.optional(Schema.Unknown),\n}) {}\n\n/** The stored clock state targets a schema version this build does not support. */\nexport class UnsupportedClockVersionError extends Schema.TaggedError<UnsupportedClockVersionError>()(\n 'UnsupportedClockVersionError',\n {\n schemaVersion: Schema.NullOr(Schema.Number),\n message: Schema.String,\n },\n) {}\n\n/** The storage holds a different replica's state. */\nexport class WrongReplicaStorageError extends Schema.TaggedError<WrongReplicaStorageError>()(\n 'WrongReplicaStorageError',\n {\n documentId: Schema.String,\n replicaId: Schema.String,\n message: Schema.String,\n },\n) {}\n\n/** The persisted replica history is internally inconsistent. */\nexport class InvalidReplicaHistoryError extends Schema.TaggedError<InvalidReplicaHistoryError>()(\n 'InvalidReplicaHistoryError',\n {\n message: Schema.String,\n cause: Schema.optional(Schema.Unknown),\n },\n) {}\n\n/** The server's exchange response did not match the protocol schema. */\nexport class InvalidExchangeError extends Schema.TaggedError<InvalidExchangeError>()(\n 'InvalidExchangeError',\n {\n message: Schema.String,\n cause: Schema.optional(Schema.Unknown),\n },\n) {}\n\n/** A persisted pending operation could not have been produced by this replica. */\nexport class InvalidOutboxError extends Schema.TaggedError<InvalidOutboxError>()(\n 'InvalidOutboxError',\n {\n message: Schema.String,\n },\n) {}\n\n/** The server sent a checkpoint older than the replica's cursor. */\nexport class CheckpointRegressionError extends Schema.TaggedError<CheckpointRegressionError>()(\n 'CheckpointRegressionError',\n {\n cursor: Schema.Number,\n checkpointCursor: Schema.Number,\n message: Schema.String,\n },\n) {}\n\n/** Committed operations were not contiguous from the replica's cursor. */\nexport class CommittedOrderError extends Schema.TaggedError<CommittedOrderError>()(\n 'CommittedOrderError',\n {\n expected: Schema.Number,\n actual: Schema.Number,\n message: Schema.String,\n },\n) {}\n\n/** The server rejected an operation the replica never sent. */\nexport class ForeignRejectionError extends Schema.TaggedError<ForeignRejectionError>()(\n 'ForeignRejectionError',\n {\n opId: Schema.String,\n message: Schema.String,\n },\n) {}\n\n/**\n * The server answered an operation this request never sent, or both\n * acknowledged and rejected it. Acting on either would let a faulty or hostile\n * server delete local work.\n */\nexport class ForeignAcknowledgementError extends Schema.TaggedError<ForeignAcknowledgementError>()(\n 'ForeignAcknowledgementError',\n {\n opId: Schema.String,\n message: Schema.String,\n },\n) {}\n\n/** The replica was closed while work was still being submitted. */\nexport class ReplicaClosedError extends Schema.TaggedError<ReplicaClosedError>()(\n 'ReplicaClosedError',\n {\n message: Schema.String,\n },\n) {}\n\n/** The stored replica state targets a protocol or schema version this build does not support. */\nexport class UnsupportedReplicaVersionError extends Schema.TaggedError<UnsupportedReplicaVersionError>()(\n 'UnsupportedReplicaVersionError',\n {\n protocolVersion: Schema.NullOr(Schema.Number),\n schemaVersion: Schema.NullOr(Schema.Number),\n message: Schema.String,\n },\n) {}\n\n/**\n * `replay` threw for a submitted Message, so it could never be applied here or\n * on any other replica; nothing was written.\n */\nexport class ReplayError extends Schema.TaggedError<ReplayError>()('ReplayError', {\n message: Schema.String,\n cause: Schema.optional(Schema.Unknown),\n}) {}\n\nexport type ReplicaError =\n | StorageError\n | ReplayError\n | WrongReplicaStorageError\n | InvalidReplicaHistoryError\n | InvalidExchangeError\n | UnsupportedReplicaVersionError\n | InvalidOutboxError\n | CheckpointRegressionError\n | CommittedOrderError\n | ForeignRejectionError\n | ForeignAcknowledgementError\n | ReplicaClosedError\n","import { Config, Effect, type Scope } from 'effect'\nimport { StorageError } from './errors.js'\n\n/** Persists a replica's state with compare-and-swap on its revision. */\nexport interface Storage {\n load: () => Effect.Effect<unknown, StorageError>\n save: (state: unknown, expectedRevision: number | null) => Effect.Effect<void, StorageError>\n /** Idempotent; the caller closes the connection explicitly. */\n close: Effect.Effect<void>\n}\n\nconst storageError = (message: string, cause: unknown): StorageError =>\n new StorageError({\n message: `${message}: ${cause instanceof Error ? cause.message : String(cause)}`,\n cause,\n })\n\nconst openDatabase = (\n name: string,\n factory: IDBFactory,\n): Effect.Effect<IDBDatabase, StorageError> =>\n Effect.tryPromise({\n try: () =>\n new Promise<IDBDatabase>((resolve, reject) => {\n const request = factory.open(name, 1)\n request.onupgradeneeded = () => request.result.createObjectStore('replica')\n request.onsuccess = () => resolve(request.result)\n request.onerror = () => reject(request.error)\n // Without this, a version upgrade blocked by another open connection\n // never settles and the effect hangs.\n request.onblocked = () =>\n reject(new Error('IndexedDB upgrade is blocked by another connection'))\n }),\n catch: cause => storageError('Could not open the storage', cause),\n })\n\n/** One database per document/replica; CAS prevents two tabs from sharing a writer identity. */\nexport const indexedDb = Effect.fn('Storage.indexedDb')(function* (\n name: Config.Config<string> | string,\n factory: IDBFactory = globalThis.indexedDB,\n) {\n const databaseName =\n typeof name === 'string'\n ? name\n : yield* name.pipe(\n Effect.catchTag('ConfigError', cause =>\n Effect.fail(storageError('Could not read the storage name', cause)),\n ),\n )\n const database = yield* Effect.acquireRelease(openDatabase(databaseName, factory), database =>\n Effect.sync(() => database.close()),\n )\n database.onversionchange = () => database.close()\n const storage: Storage = {\n load: () =>\n Effect.tryPromise({\n try: () =>\n new Promise((resolve, reject) => {\n const transaction = database.transaction('replica', 'readonly')\n const request = transaction.objectStore('replica').get('state')\n transaction.oncomplete = () => resolve(request.result)\n transaction.onabort = () =>\n reject(transaction.error ?? new Error('IndexedDB read aborted'))\n }),\n catch: cause => storageError('Could not read the replica', cause),\n }),\n save: (state, expectedRevision) =>\n Effect.tryPromise({\n try: () =>\n new Promise<void>((resolve, reject) => {\n const transaction = database.transaction('replica', 'readwrite', {\n durability: 'strict',\n })\n const store = transaction.objectStore('replica')\n const request = store.get('state')\n let conflict = false\n request.onsuccess = () => {\n const current = request.result as { revision: number } | undefined\n if ((current?.revision ?? null) !== expectedRevision) {\n conflict = true\n transaction.abort()\n return\n }\n store.put(state, 'state')\n }\n transaction.oncomplete = () => resolve()\n transaction.onabort = () =>\n reject(\n conflict\n ? new Error('Replica was changed by another writer')\n : (transaction.error ?? new Error('IndexedDB write aborted')),\n )\n }),\n catch: cause => storageError('Could not save the replica', cause),\n }),\n close: Effect.sync(() => database.close()),\n }\n return storage\n})\n","/**\n * `Sync.mount`: runs a Foldkit application over a replica with one reducer.\n *\n * A durable Message is a state-only, deterministic transition of the shared\n * projection (the derived replay enforces it), so the application's own `update`\n * is applied at once and the Message is persisted afterwards in a Command. The\n * shared slice is re-installed from the replica when an exchange changes it or\n * a persist fails, through one private Message the application never sees.\n */\nimport { Effect, Exit, Layer, Schema, Stream } from 'effect'\nimport type { Document, HtmlBuilder } from 'foldkit/html'\nimport * as Navigation from 'foldkit/navigation'\nimport type { UrlRequest } from 'foldkit/navigation'\nimport * as Port from 'foldkit/port'\nimport * as Runtime from 'foldkit/runtime'\nimport * as Subscription from 'foldkit/subscription'\nimport type { Subscriptions } from 'foldkit/subscription'\nimport type * as Update from 'foldkit/update'\nimport * as Url from 'foldkit/url'\nimport type { RunnableApplication } from 'foldkit-surface'\nimport type { ReplicaError } from './errors.js'\nimport type { DefinedSync } from './make.js'\nimport type { Replica, ReplicaStatus } from './sync.js'\n\nconst REFRESH = 'foldkit-sync/Refresh'\nconst PERSISTED = 'foldkit-sync/Persisted'\nconst FAILED = 'foldkit-sync/PersistenceFailed'\nconst NAVIGATE = 'foldkit-sync/Navigate'\nconst NAVIGATED = 'foldkit-sync/Navigated'\n\ntype Private =\n | { readonly _tag: typeof REFRESH }\n | { readonly _tag: typeof PERSISTED }\n | { readonly _tag: typeof FAILED; readonly error: ReplicaError }\n | { readonly _tag: typeof NAVIGATE; readonly request: UrlRequest }\n | { readonly _tag: typeof NAVIGATED }\n\n/**\n * The URL as part of the application: `onUrlChange` names the Message the\n * runtime sends for the current URL at start and on every navigation (so a\n * `foldkit-mirror` URL mirror reads back in), `init` reduces the URL into the\n * Model before the first render, and `onUrlRequest` names the Message for a\n * link click; omitted, the mount follows the link itself (an internal one is\n * pushed, an external one loaded).\n */\nexport interface MountUrl<Model, Message> {\n readonly init?: ((model: Model, url: Url.Url) => Model) | undefined\n readonly onUrlChange: (url: Url.Url) => Message\n readonly onUrlRequest?: ((request: UrlRequest) => Message) | undefined\n}\n\nexport interface MountOptions<Model, Message, Shared, Resources> {\n /** An open replica of this contract; `mount` does not close it. */\n readonly replica: Replica<Message, Shared>\n /** The element the application renders into; Foldkit requires it to have an `id`. */\n readonly container: HTMLElement\n readonly view: (model: Model, h: HtmlBuilder<Message>) => Document\n readonly subscriptions?: Subscriptions<Model, Message, Resources> | undefined\n readonly resources?: Layer.Layer<Resources> | undefined\n /** Route the URL through the application; without it the mount ignores the URL. */\n readonly url?: MountUrl<Model, Message> | undefined\n /**\n * Reflects a refused or failed persist in the Model, after the durable edit\n * has been reverted. Omitted, the edit is reverted silently.\n */\n readonly onPersistenceFailure?: ((model: Model, error: ReplicaError) => Model) | undefined\n}\n\nexport interface Mounted<Model, Message> {\n /** Sends an application Message through the runtime; the `Exit` reports a decode failure. */\n readonly dispatch: (message: Message) => Exit.Exit<void, unknown>\n /** The Model after the last transition. */\n readonly model: () => Model\n /** Notified after every transition; with `model` and `dispatch`, the host an agent binds to. */\n readonly subscribe: (listener: () => void) => () => void\n /**\n * Every application Message the runtime applies, from any origin, so an\n * agent contract that declares a `completion` can see the Message that\n * finishes its work. The mount's private Messages are not reported.\n */\n readonly observe: (listener: (message: Message) => void) => () => void\n /** Waits for in-flight persists, then disposes the runtime. The replica stays open. */\n readonly dispose: () => Promise<void>\n}\n\n/** Exchanges and rejections change what the replica holds; a submit only echoes a local edit. */\nconst sharedChanged = (previous: ReplicaStatus | undefined, next: ReplicaStatus): boolean =>\n previous === undefined ||\n previous.cursor !== next.cursor ||\n previous.rejected.length !== next.rejected.length ||\n previous.rejected.some((id, index) => id !== next.rejected[index])\n\n/** The application's Message union, as `Surface.application` types it. */\ntype MessageOf<App> =\n App extends RunnableApplication<any, any, any, any> ? Schema.Schema.Type<App['Message']> : never\n\nexport const mount = <\n Model,\n F extends Schema.Struct.Fields,\n Cases extends Record<string, Schema.Struct.Fields>,\n Fields extends Schema.Struct.Fields,\n Ms extends readonly unknown[],\n Resources = never,\n Principal = unknown,\n>(\n app: RunnableApplication<Model, F, Cases, Resources>,\n sync: DefinedSync<\n Model,\n Fields,\n MessageOf<RunnableApplication<Model, F, Cases, Resources>>,\n Ms,\n Principal\n >,\n options: MountOptions<\n Model,\n MessageOf<RunnableApplication<Model, F, Cases, Resources>>,\n Schema.Struct.Type<Fields>,\n Resources\n >,\n): Mounted<Model, MessageOf<RunnableApplication<Model, F, Cases, Resources>>> => {\n // Foldkit reports a missing id only inside the runtime fiber, where nothing\n // renders and nothing is thrown; fail here instead.\n if (options.container.id === '')\n throw new Error('Sync.mount: the container needs an id (`container.id = \"app\"`)')\n type Message = MessageOf<RunnableApplication<Model, F, Cases, Resources>>\n // The application's Messages are tagged structs; the generic cannot say so.\n type Tagged = { readonly _tag: string }\n type RuntimeMessage = (Message & Tagged) | Private\n const { replica } = options\n const durable = new Set(sync.contract.messages)\n const install = (model: Model): Model =>\n sync.projection.set(model, Effect.runSync(replica.shared))\n\n const inFlight = new Set<Promise<void>>()\n let latest: Model = install(app.initial)\n const modelListeners = new Set<() => void>()\n const messageListeners = new Set<(message: Message) => void>()\n\n const update = (\n model: Model,\n message: RuntimeMessage,\n ): Update.Return<Model, RuntimeMessage, Resources> => {\n switch (message._tag) {\n case REFRESH:\n return { model: install(model) }\n case PERSISTED:\n return { model }\n case FAILED: {\n const { error } = message as Extract<Private, { readonly _tag: typeof FAILED }>\n const reverted = install(model)\n return { model: options.onPersistenceFailure?.(reverted, error) ?? reverted }\n }\n case NAVIGATE: {\n // A link the application did not claim: follow it. The runtime then\n // reports the new URL through `onUrlChange`.\n const { request } = message as Extract<Private, { readonly _tag: typeof NAVIGATE }>\n const follow =\n request._tag === 'Internal'\n ? Navigation.pushUrl(Url.toString(request.url))\n : Navigation.load(request.href)\n return {\n model,\n commands: [\n {\n name: 'foldkit-sync/navigate',\n effect: follow.pipe(Effect.as({ _tag: NAVIGATED } as RuntimeMessage)),\n },\n ],\n }\n }\n case NAVIGATED:\n return { model }\n default: {\n for (const listener of messageListeners) listener(message as Message)\n const result = app.update(model, message as Message) as Update.Return<\n Model,\n RuntimeMessage,\n Resources\n >\n if (!durable.has(message._tag)) return result\n const persist = {\n name: 'foldkit-sync/persist',\n effect: Effect.gen(function* () {\n // Tracked so `dispose` can wait instead of interrupting a persist.\n let settle!: () => void\n const done = new Promise<void>(resolve => {\n settle = resolve\n })\n inFlight.add(done)\n const outcome = yield* Effect.result(replica.submit(message as Message))\n inFlight.delete(done)\n settle()\n return outcome._tag === 'Success'\n ? ({ _tag: PERSISTED } as RuntimeMessage)\n : ({ _tag: FAILED, error: outcome.failure } as RuntimeMessage)\n }),\n }\n return { model: result.model, commands: [...(result.commands ?? []), persist] }\n }\n }\n }\n\n const ports = {\n inbound: { message: Port.inbound(app.Message as unknown as Schema.Codec<Message, unknown>) },\n }\n const own = Subscription.make<Model, RuntimeMessage, Resources>()(() => ({\n message: Port.subscription(ports.inbound.message, message => message as RuntimeMessage),\n // The replica's status carries the cursor and rejections, which is exactly\n // when the shared slice held locally can differ from the replica's.\n refresh: Subscription.persistent<RuntimeMessage, Resources>(\n replica.statusChanges.pipe(\n Stream.mapAccum(\n (): ReplicaStatus | undefined => undefined,\n (previous, status): readonly [ReplicaStatus, ReadonlyArray<RuntimeMessage>] => [\n status,\n sharedChanged(previous, status) ? [{ _tag: REFRESH }] : [],\n ],\n ),\n ),\n ),\n // `modelToDependencies` runs on every transition, so it doubles as the Model\n // getter the runtime does not expose.\n latest: {\n dependenciesSchema: Schema.Struct({}),\n modelToDependencies: (model: Model) => {\n latest = model\n for (const listener of modelListeners) listener()\n return {}\n },\n dependenciesToStream: () => Stream.never,\n },\n }))\n const subscriptions =\n options.subscriptions === undefined\n ? own\n : Subscription.aggregate<Model, RuntimeMessage, Resources>()(\n options.subscriptions as Subscriptions<Model, RuntimeMessage, Resources>,\n own,\n )\n\n const view = (model: Model, h: HtmlBuilder<RuntimeMessage>): Document =>\n // Sound: the view constructs only application Messages, a subset of the\n // runtime's union.\n options.view(model, h as unknown as HtmlBuilder<Message>)\n const common = {\n Model: app.Model as unknown as Schema.Codec<Model, any, unknown, unknown>,\n container: options.container,\n ports,\n update,\n subscriptions,\n ...(options.resources === undefined ? {} : { resources: options.resources }),\n view,\n }\n const url = options.url\n const program =\n url === undefined\n ? Runtime.makeApplication({ ...common, init: () => ({ model: latest }) })\n : Runtime.makeApplication({\n ...common,\n routing: {\n onUrlChange: (at: Url.Url) => url.onUrlChange(at) as RuntimeMessage,\n onUrlRequest: (request: UrlRequest): RuntimeMessage =>\n url.onUrlRequest === undefined\n ? { _tag: NAVIGATE, request }\n : (url.onUrlRequest(request) as RuntimeMessage),\n },\n init: (at: Url.Url) => {\n latest = url.init === undefined ? latest : url.init(latest, at)\n return { model: latest }\n },\n })\n const handle = Runtime.embed(program)\n\n return {\n dispatch: message => handle.ports.message.send(message),\n model: () => latest,\n subscribe: listener => {\n modelListeners.add(listener)\n return () => modelListeners.delete(listener)\n },\n observe: listener => {\n messageListeners.add(listener)\n return () => messageListeners.delete(listener)\n },\n dispose: async () => {\n await Promise.all([...inFlight])\n handle.dispose()\n },\n }\n}\n","import { Schema } from 'effect'\n\n/** Identifies the replicated document a replica or operation belongs to. */\nexport const DocumentId = Schema.NonEmptyString.pipe(Schema.brand('@foldkit-sync/DocumentId'))\nexport type DocumentId = typeof DocumentId.Type\n\n/** Identifies one replica (writer identity) within a document. */\nexport const ReplicaId = Schema.NonEmptyString.pipe(Schema.brand('@foldkit-sync/ReplicaId'))\nexport type ReplicaId = typeof ReplicaId.Type\n\n/** The stable identity of one operation within a document. */\nexport const OpId = Schema.NonEmptyString.pipe(Schema.brand('@foldkit-sync/OpId'))\nexport type OpId = typeof OpId.Type\n\n/**\n * A position in the committed document order. `0` is the start; a committed\n * operation's `serverSequence` and a replica's `cursor` are the same family.\n */\nexport const Sequence = Schema.Number.check(\n Schema.isInt(),\n Schema.isGreaterThanOrEqualTo(0),\n Schema.isLessThanOrEqualTo(Number.MAX_SAFE_INTEGER),\n).pipe(Schema.brand('@foldkit-sync/Sequence'))\nexport type Sequence = typeof Sequence.Type\n\n/** A replica's own operation counter within a document; 1-based. */\nexport const LocalSequence = Schema.Number.check(\n Schema.isInt(),\n Schema.isGreaterThanOrEqualTo(1),\n Schema.isLessThanOrEqualTo(Number.MAX_SAFE_INTEGER),\n).pipe(Schema.brand('@foldkit-sync/LocalSequence'))\nexport type LocalSequence = typeof LocalSequence.Type\n\nexport const documentId = (value: string): DocumentId => Schema.decodeUnknownSync(DocumentId)(value)\nexport const replicaId = (value: string): ReplicaId => Schema.decodeUnknownSync(ReplicaId)(value)\nexport const opId = (value: string): OpId => Schema.decodeUnknownSync(OpId)(value)\nexport const sequence = (value: number): Sequence => Schema.decodeUnknownSync(Sequence)(value)\nexport const localSequence = (value: number): LocalSequence =>\n Schema.decodeUnknownSync(LocalSequence)(value)\n","import { Context, Duration, Effect, Layer, Schedule, Schema } from 'effect'\nimport { sequence } from './ids.js'\nimport type { Operation, TransportClient } from './sync.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}\n\nexport interface ExchangeReply {\n readonly id: string\n readonly result?: unknown\n readonly error?: string\n}\n\nexport interface TransportShape {\n readonly exchange: (\n cursor: number,\n pending: ReadonlyArray<Operation>,\n ) => Effect.Effect<unknown, TransportError>\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\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: (cursor: number, pending: ReadonlyArray<Operation>) => unknown | Promise<unknown>,\n): Layer.Layer<Transport> =>\n Layer.succeed(Transport, {\n exchange: (cursor, pending) =>\n Effect.tryPromise({ try: () => Promise.resolve(handler(cursor, pending)), catch: failure }),\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) =>\n Effect.tryPromise({\n try: () => transport.exchange(sequence(cursor), pending),\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) => Effect.runPromise(transport.exchange(cursor, pending)),\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. Returns a function\n * that stops serving.\n */\nexport const serveSocket = (\n socket: SocketLike,\n options: {\n readonly exchange: (\n cursor: number,\n pending: ReadonlyArray<Operation>,\n ) => unknown | Promise<unknown>\n },\n): (() => void) => {\n const send = (reply: ExchangeReply): 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 } = parsed as { id?: unknown; cursor?: unknown; pending?: unknown }\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 ) {\n send({ id, error: 'Invalid exchange frame' })\n return\n }\n const frame: ExchangeFrame = { id, cursor, pending: pending as ReadonlyArray<Operation> }\n void (async () => {\n try {\n const result = await options.exchange(frame.cursor, frame.pending)\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 stopClose = socket.onClose(() => stopMessage())\n return () => {\n stopMessage()\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\nexport interface SocketOptions {\n readonly url: string\n /** Injectable for tests; defaults to the platform `WebSocket`. */\n readonly makeSocket?: ((url: string) => SocketLike) | undefined\n /** Reconnect attempts after a close before queued work fails. Default 5. */\n readonly maxRetries?: number | undefined\n /** Base delay of the exponential reconnect backoff. Default `50 millis`. */\n readonly retryBase?: 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 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. Once the retries are exhausted (or the layer closes) queued work fails\n * with a `TransportError`; a queue over `maxQueue` fails new exchanges with\n * backpressure. The socket is released when the layer's scope ends.\n */\nexport const layerSocket = (options: SocketOptions): Layer.Layer<Transport, TransportError> =>\n Layer.effect(\n Transport,\n Effect.fn('Transport.layerSocket')(function* () {\n const makeSocket = options.makeSocket ?? nativeSocket\n const maxQueue = options.maxQueue ?? 64\n const retry = Schedule.exponential(options.retryBase ?? '50 millis').pipe(\n Schedule.jittered,\n Schedule.upTo({ times: options.maxRetries ?? 5 }),\n )\n\n interface Entry {\n readonly id: string\n readonly cursor: number\n readonly pending: ReadonlyArray<Operation>\n readonly resume: (effect: Effect.Effect<unknown, TransportError>) => void\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 // Once the reconnect schedule is exhausted there is no fiber left to\n // service the queue, so the transport is terminal until the layer is\n // recreated; a later exchange fails with this rather than waiting forever.\n let terminalError: TransportError | undefined\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 } 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(options.url)\n socket = next\n ready = next.onOpen === undefined\n const offOpen = next.onOpen?.(() => {\n ready = true\n flush()\n })\n const offMessage = next.onMessage(data => {\n let reply: ExchangeReply\n try {\n reply = JSON.parse(data) as ExchangeReply\n } catch {\n return\n }\n const entry = inFlight.get(reply.id)\n if (entry === undefined) return\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 // Keep every unanswered frame for the next connection.\n requeue()\n reject(new Error('transport closed'))\n })\n if (ready) flush()\n }),\n catch: () => new TransportError({ message: 'transport closed' }),\n })\n\n yield* Effect.forkScoped(\n connect.pipe(\n Effect.retry(retry),\n Effect.catch(error =>\n Effect.sync(() => {\n if (disposed) return\n terminalError = error\n failAll(error.message)\n }),\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 return Transport.of({\n exchange: (cursor, pending) =>\n Effect.callback<unknown, TransportError>(resume => {\n if (disposed) {\n resume(Effect.fail(new TransportError({ message: 'transport closed' })))\n return\n }\n if (terminalError !== undefined) {\n resume(Effect.fail(terminalError))\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, 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 })(),\n )\n","import { Effect, Exit, Metric, PubSub, Queue, Ref, Schema, Stream, SynchronizedRef } from 'effect'\nimport {\n CheckpointRegressionError,\n CommittedOrderError,\n ForeignAcknowledgementError,\n ForeignRejectionError,\n InvalidExchangeError,\n InvalidOutboxError,\n InvalidReplicaHistoryError,\n ReplayError,\n ReplicaClosedError,\n UnsupportedReplicaVersionError,\n WrongReplicaStorageError,\n type ReplicaError,\n} from './errors.js'\nimport type { Storage } from './indexedDb.js'\nimport {\n DocumentId,\n LocalSequence,\n OpId,\n ReplicaId,\n Sequence,\n localSequence,\n sequence,\n} from './ids.js'\nimport { Transport, TransportError } from './transport.js'\n\n/** Wire and persisted-format versions. A bump must handle the older value explicitly. */\nconst PROTOCOL_VERSION = 1\nconst SCHEMA_VERSION = 1\n\n/** A client-authored operation envelope. `message` is the application's encoded Message. */\nconst OperationSchema = Schema.Struct({\n protocolVersion: Schema.Literal(PROTOCOL_VERSION),\n schemaVersion: Schema.Literal(SCHEMA_VERSION),\n documentId: DocumentId,\n replicaId: ReplicaId,\n localSequence: LocalSequence,\n opId: OpId,\n baseCursor: Sequence,\n message: Schema.Unknown,\n})\nexport type Operation = typeof OperationSchema.Type\n\n/** An operation the server committed, with its authoritative order and actor. */\nconst CommittedSchema = Schema.Struct({\n ...OperationSchema.fields,\n serverSequence: Sequence.check(Schema.isGreaterThanOrEqualTo(1)),\n actorId: Schema.NonEmptyString,\n})\n/** Named to avoid colliding with `foldkit-durable`'s `Committed`. */\nexport type CommittedOperation = typeof CommittedSchema.Type\n\nconst decodeOperation = Schema.decodeUnknownSync(OperationSchema, { onExcessProperty: 'error' })\nconst decodeCommitted = Schema.decodeUnknownSync(CommittedSchema, { onExcessProperty: 'error' })\n\n/**\n * How many committed-operation ids a replica retains for duplicate detection.\n * Committed sequences are contiguous and the server enforces `opId`\n * uniqueness, so this is defence in depth; bounding it keeps replica state from\n * growing without limit on a log that is never checkpointed.\n */\nconst COMMITTED_ID_WINDOW = 1024\n\n/** Counters and a histogram an application can scrape. */\nexport const syncMetrics = {\n exchanges: Metric.counter('foldkit_sync_exchanges_total'),\n applied: Metric.counter('foldkit_sync_commits_applied_total'),\n checkpoints: Metric.counter('foldkit_sync_checkpoints_adopted_total'),\n exchangePending: Metric.histogram('foldkit_sync_exchange_pending', {\n boundaries: [1, 4, 16, 64, 256, 1024],\n }),\n}\n\nexport interface Checkpoint<Shared> {\n readonly cursor: Sequence\n readonly model: Shared\n}\n\nexport interface Exchange<Shared> {\n /** Server-committed operations as they arrived; validated against `CommittedOperation` on adoption. */\n readonly operations: ReadonlyArray<unknown>\n readonly rejected: ReadonlyArray<OpId>\n /** Sends from the request that are durably committed, so the replica can drop them. */\n readonly acknowledged?: ReadonlyArray<OpId> | undefined\n /** The snapshot a replica predating compaction adopts in place of the log. */\n readonly checkpoint?: Checkpoint<Shared> | undefined\n}\n\nexport interface ReplicaState<Shared> {\n readonly protocolVersion: typeof PROTOCOL_VERSION\n readonly schemaVersion: typeof SCHEMA_VERSION\n readonly documentId: DocumentId\n readonly replicaId: ReplicaId\n readonly revision: number\n readonly nextLocalSequence: LocalSequence\n readonly cursor: Sequence\n readonly committed: Shared\n readonly committedIds: ReadonlyArray<string>\n readonly pending: ReadonlyArray<Operation>\n}\n\n/**\n * What the promise-based edge adapter consumes; the Effect `Transport` service\n * is the primary seam.\n */\nexport interface TransportClient {\n exchange(cursor: Sequence, pending: ReadonlyArray<Operation>): Promise<unknown>\n}\n\n/** A redacted view of a replica's state, for a UI to explain and recover. */\nexport interface ReplicaStatus {\n readonly pending: number\n readonly cursor: Sequence\n /** The last exchange failure, cleared by a successful exchange. */\n readonly lastError: string | undefined\n /** Operations the server refused, most recent first. */\n readonly rejected: ReadonlyArray<OpId>\n}\n\n/**\n * A consistent status and optimistic-shared pair, read from one replica state.\n * `Replica.changes` emits it so a UI can hold a single subscription.\n */\nexport interface ReplicaSnapshot<Shared> {\n readonly status: ReplicaStatus\n readonly shared: Shared\n}\n\nexport interface Replica<Message, Shared> {\n /** The optimistic projection: committed state with pending operations replayed. */\n readonly shared: Effect.Effect<Shared>\n readonly pending: Effect.Effect<ReadonlyArray<Operation>>\n readonly cursor: Effect.Effect<Sequence>\n /**\n * Waiting/recovery information without exposing Messages or the Model. It is a\n * snapshot; `statusChanges` re-emits it after every submit and exchange.\n */\n readonly status: Effect.Effect<ReplicaStatus>\n /** The status, re-emitted after every submit and exchange. */\n readonly statusChanges: Stream.Stream<ReplicaStatus>\n /**\n * The status and the optimistic shared value together, re-emitted after every\n * submit and exchange, so a UI can subscribe once instead of to both.\n */\n readonly changes: Stream.Stream<ReplicaSnapshot<Shared>>\n readonly submit: (message: Message) => Effect.Effect<void, ReplicaError>\n /** Reconciles against the server. The `Transport` service must be provided. */\n readonly synchronize: Effect.Effect<void, ReplicaError | TransportError, Transport>\n /**\n * The exchange loop: exchanges once, then after every `submit`, until the\n * replica closes or the fiber is interrupted. A transport failure is recorded\n * in `status.lastError` and retried on the next wake, so the fiber never\n * fails. Fork it with `Effect.forkScoped` and provide `Transport`.\n */\n readonly start: Effect.Effect<void, never, Transport>\n readonly close: Effect.Effect<void>\n}\n\nexport interface SyncDefinition<Message, Shared, MessageEncoded, SharedEncoded> {\n readonly documentId: DocumentId\n readonly message: Schema.Codec<Message, MessageEncoded, never, never>\n readonly shared: Schema.Codec<Shared, SharedEncoded, never, never>\n readonly empty: Shared\n readonly durable: (message: Message) => boolean\n readonly replay: (shared: Shared, message: Message) => Shared\n}\n\nexport interface Sync<Message, Shared> {\n readonly documentId: DocumentId\n /**\n * Low-level wire codecs for adapters and the transport. Most applications use\n * `journalContract` and `openReplica`; these are exposed for a custom\n * transport or a server that must speak the operation envelope directly.\n */\n readonly codec: {\n readonly normalizeOperation: (input: unknown) => Operation\n readonly operationFrom: (input: unknown, documentId: DocumentId) => Operation\n readonly committedFrom: (input: unknown, documentId: DocumentId) => CommittedOperation\n readonly decodeExchange: (input: unknown) => Exchange<Shared>\n }\n /** The codecs and pure reducer `foldkit-durable`'s `makeJournal` consumes. */\n readonly journalContract: () => JournalContract<Operation, Shared>\n readonly openReplica: (\n replicaId: ReplicaId,\n storage: Storage,\n ) => Effect.Effect<Replica<Message, Shared>, ReplicaError>\n}\n\n/** Structural match for `foldkit-durable`'s journal options; Sync stays independent. */\nexport interface JournalContract<Operation, Shared> {\n readonly operation: {\n /** Operations are stored in their encoded form, so this is the identity. */\n readonly encode: (operation: Operation) => Operation\n readonly decode: (input: unknown) => Operation\n }\n readonly snapshot: {\n readonly encode: (snapshot: Shared) => unknown\n readonly decode: (input: unknown) => Shared\n }\n readonly empty: () => Shared\n readonly reduce: (snapshot: Shared, operation: Operation) => Shared\n}\n\n/**\n * Binds the replicated-state protocol to one application contract.\n *\n * The returned codecs decide what is a valid operation and what the shared\n * projection means; the replica owns the local outbox, optimistic projection,\n * and reconciliation as Effects, and never runs a second reducer.\n */\nexport const defineSync = <Message, Shared, MessageEncoded, SharedEncoded>(\n definition: SyncDefinition<Message, Shared, MessageEncoded, SharedEncoded>,\n): Sync<Message, Shared> => {\n const documentId = definition.documentId\n const decodeMessage = Schema.decodeUnknownSync(definition.message, { onExcessProperty: 'error' })\n const encodeMessage = Schema.encodeSync(definition.message)\n const decodeShared = Schema.decodeUnknownSync(definition.shared, { onExcessProperty: 'error' })\n const encodeShared = Schema.encodeSync(definition.shared)\n\n const ReplicaStateSchema = Schema.Struct({\n protocolVersion: Schema.Literal(PROTOCOL_VERSION),\n schemaVersion: Schema.Literal(SCHEMA_VERSION),\n documentId: DocumentId,\n replicaId: ReplicaId,\n revision: Schema.Number,\n nextLocalSequence: LocalSequence,\n cursor: Sequence,\n committed: definition.shared,\n committedIds: Schema.Array(Schema.String),\n pending: Schema.Array(OperationSchema),\n })\n const CheckpointSchema = Schema.Struct({ cursor: Sequence, model: definition.shared })\n const ExchangeSchema = Schema.Struct({\n operations: Schema.Array(Schema.Unknown),\n rejected: Schema.Array(OpId),\n acknowledged: Schema.optional(Schema.Array(OpId)),\n checkpoint: Schema.optional(CheckpointSchema),\n })\n const decodeState = Schema.decodeUnknownSync(ReplicaStateSchema, { onExcessProperty: 'error' })\n const encodeState = Schema.encodeSync(ReplicaStateSchema)\n const VersionProbe = Schema.Struct({\n protocolVersion: Schema.optional(Schema.Number),\n schemaVersion: Schema.optional(Schema.Number),\n })\n /**\n * Tells a version this build does not understand apart from malformed data,\n * so the caller gets an actionable failure and the stored state is preserved.\n */\n const unsupportedVersion = (input: unknown): UnsupportedReplicaVersionError | undefined => {\n let found: {\n readonly protocolVersion?: number | undefined\n readonly schemaVersion?: number | undefined\n }\n try {\n found = Schema.decodeUnknownSync(VersionProbe)(input)\n } catch {\n return undefined\n }\n if (found.protocolVersion === PROTOCOL_VERSION && found.schemaVersion === SCHEMA_VERSION)\n return undefined\n const protocolVersion = found.protocolVersion ?? null\n const schemaVersion = found.schemaVersion ?? null\n return new UnsupportedReplicaVersionError({\n protocolVersion,\n schemaVersion,\n message: `Stored replica uses protocol ${protocolVersion ?? '?'} / schema ${schemaVersion ?? '?'}; this build supports ${PROTOCOL_VERSION}/${SCHEMA_VERSION}`,\n })\n }\n const decodeExchange = (input: unknown): Exchange<Shared> =>\n Schema.decodeUnknownSync(ExchangeSchema, { onExcessProperty: 'error' })(\n input,\n ) as Exchange<Shared>\n\n const checkIdentity = (operation: Operation): void => {\n // `LocalSequence` already rejects a non-positive counter; this checks the\n // derived identity.\n if (operation.opId !== `${operation.replicaId}:${operation.localSequence}`) {\n throw new Error('Invalid operation identity')\n }\n }\n const decodeDurable = (message: unknown): Message => {\n const decoded = decodeMessage(message)\n if (!definition.durable(decoded)) throw new Error('Message is local-only')\n return decoded\n }\n const shape = <O extends Operation>(operation: O): O => {\n checkIdentity(operation)\n return { ...operation, message: encodeMessage(decodeDurable(operation.message)) }\n }\n const assertDocument = <O extends Operation>(operation: O, key: DocumentId): O => {\n if (operation.documentId !== key) throw new Error('Wrong document')\n return operation\n }\n const normalizeOperation = (input: unknown): Operation => shape(decodeOperation(input))\n const operationFrom = (input: unknown, key: DocumentId): Operation =>\n assertDocument(normalizeOperation(input), key)\n /**\n * A committed operation arrives with its message already encoded, so decode it\n * once for the contract check and hand it to `replay` instead of decoding and\n * re-encoding it on the way through `shape`.\n */\n const decodeCommittedOperation = (\n input: unknown,\n key: DocumentId,\n ): { readonly committed: CommittedOperation; readonly message: Message } => {\n const committed = assertDocument(decodeCommitted(input), key)\n checkIdentity(committed)\n return { committed, message: decodeDurable(committed.message) }\n }\n const committedFrom = (input: unknown, key: DocumentId): CommittedOperation =>\n decodeCommittedOperation(input, key).committed\n\n const journalContract = (): JournalContract<Operation, Shared> => ({\n // Operations are stored in their encoded form: `normalizeOperation` has\n // already encoded the Message and validated the identity.\n operation: { encode: operation => operation, decode: normalizeOperation },\n snapshot: { encode: encodeShared, decode: decodeShared },\n empty: () => definition.empty,\n reduce: (snapshot, operation) => definition.replay(snapshot, decodeMessage(operation.message)),\n })\n\n const optimistic = (state: ReplicaState<Shared>): Shared =>\n state.pending.reduce(\n (model, operation) => definition.replay(model, decodeMessage(operation.message)),\n state.committed,\n )\n\n const openReplica = Effect.fn('Sync.openReplica')(\n function* (replicaId: ReplicaId, storage: Storage) {\n yield* Effect.annotateCurrentSpan({ documentId, replicaId })\n const saved = yield* storage.load()\n const initial: ReplicaState<Shared> = {\n protocolVersion: PROTOCOL_VERSION,\n schemaVersion: SCHEMA_VERSION,\n documentId,\n replicaId,\n revision: 0,\n nextLocalSequence: localSequence(1),\n cursor: sequence(0),\n committed: definition.empty,\n committedIds: [],\n pending: [],\n }\n const state: ReplicaState<Shared> =\n saved === undefined\n ? initial\n : yield* Effect.try({\n try: () => decodeState(saved),\n catch: cause =>\n unsupportedVersion(saved) ??\n new InvalidReplicaHistoryError({\n message: 'Stored replica state is invalid',\n cause,\n }),\n })\n if (state.documentId !== documentId || state.replicaId !== replicaId)\n return yield* new WrongReplicaStorageError({\n documentId,\n replicaId,\n message: 'The stored replica belongs to a different document or replica',\n })\n const committedIds = new Set(state.committedIds)\n if (state.nextLocalSequence < 1 || committedIds.size !== state.committedIds.length)\n return yield* new InvalidReplicaHistoryError({ message: 'Invalid replica history' })\n const pendingIds = new Set<string>()\n for (const pending of state.pending) {\n const operation = yield* Effect.try({\n try: () => operationFrom(pending, documentId),\n catch: () => new InvalidOutboxError({ message: 'Invalid outbox' }),\n })\n if (\n operation.replicaId !== replicaId ||\n operation.localSequence >= state.nextLocalSequence ||\n committedIds.has(operation.opId) ||\n pendingIds.has(operation.opId)\n )\n return yield* new InvalidOutboxError({ message: 'Invalid outbox' })\n pendingIds.add(operation.opId)\n }\n // Storage holds the schema's encoded side, so a transforming `shared`\n // codec round-trips: decode on load, encode before every save. Encoding\n // also rejects an invalid `empty` on first creation rather than at reload.\n const store = Effect.fn('Sync.store')(function* (\n next: ReplicaState<Shared>,\n expectedRevision: number | null,\n ) {\n const encoded = yield* Effect.try({\n try: () => encodeState(next),\n catch: cause =>\n new InvalidReplicaHistoryError({\n message: 'Could not encode the replica state',\n cause,\n }),\n })\n yield* storage.save(encoded, expectedRevision)\n })\n if (saved === undefined) yield* store(state, null)\n\n const stateRef = yield* SynchronizedRef.make(state)\n const closed = yield* Ref.make(false)\n const lastError = yield* Ref.make<string | undefined>(undefined)\n const rejectedOps = yield* Ref.make<ReadonlyArray<OpId>>([])\n // One pending wake-up is enough: the loop exchanges the whole outbox.\n const wake = yield* Queue.sliding<void>(1)\n const statusSignals = yield* PubSub.sliding<void>(1)\n // The projection is pure over an immutable state, so a cached value is\n // reused until a write replaces the state object. A UI reads `shared` far\n // more often than it writes, and replaying a large outbox per read is\n // quadratic (see `bench/projection.bench.ts`).\n const projection = yield* Ref.make<\n { readonly state: ReplicaState<Shared>; readonly shared: Shared } | undefined\n >(undefined)\n const snapshot = Effect.fn('Sync.snapshot')(function* () {\n const current = yield* SynchronizedRef.get(stateRef)\n const cached = yield* Ref.get(projection)\n let projected: Shared\n if (cached !== undefined && cached.state === current) projected = cached.shared\n else {\n projected = optimistic(current)\n yield* Ref.set(projection, { state: current, shared: projected })\n }\n return {\n status: {\n pending: current.pending.length,\n cursor: current.cursor,\n lastError: yield* Ref.get(lastError),\n rejected: yield* Ref.get(rejectedOps),\n },\n shared: projected,\n }\n })()\n const shared = Effect.map(snapshot, value => value.shared)\n const status = Effect.map(snapshot, value => value.status)\n\n // `SynchronizedRef.modifyEffect` installs the returned state itself, so\n // persisting must not also set the ref (that would re-enter the lock).\n const persist = (next: ReplicaState<Shared>, current: ReplicaState<Shared>) =>\n store(next, current.revision)\n\n const submit = Effect.fn('Sync.submit')(function* (message: Message) {\n yield* Effect.annotateCurrentSpan({ documentId, replicaId })\n const result = yield* SynchronizedRef.modifyEffect(stateRef, current =>\n Effect.gen(function* () {\n if (yield* Ref.get(closed))\n return yield* new ReplicaClosedError({ message: 'Replica is closed' })\n const operation = yield* Effect.try({\n try: () =>\n operationFrom(\n {\n protocolVersion: PROTOCOL_VERSION,\n schemaVersion: SCHEMA_VERSION,\n documentId,\n replicaId,\n localSequence: current.nextLocalSequence,\n opId: `${replicaId}:${current.nextLocalSequence}`,\n baseCursor: current.cursor,\n message: encodeMessage(message),\n },\n documentId,\n ),\n catch: () => new InvalidOutboxError({ message: 'Invalid outbox' }),\n })\n // Replay before writing: a Message replay refuses can never be\n // applied, here or on another replica, so it must not reach the\n // outbox. The result is the next optimistic projection, so the\n // cache is seeded instead of replaying the outbox on the next read.\n // Rebuilding the projection replays the outbox, which can throw\n // too (an upgrade that changed `update` for a pending Message), so\n // it sits inside the same typed error as the new Message's replay.\n const cached = yield* Ref.get(projection)\n const replayed = yield* Effect.try({\n try: () =>\n definition.replay(\n cached !== undefined && cached.state === current\n ? cached.shared\n : optimistic(current),\n message,\n ),\n catch: cause =>\n new ReplayError({\n message: cause instanceof Error ? cause.message : 'Replay failed',\n cause,\n }),\n })\n // Validated and encoded by `persist`; decoding here would demand the\n // encoded side and break a transforming `shared` codec.\n const next: ReplicaState<Shared> = {\n ...current,\n revision: current.revision + 1,\n nextLocalSequence: localSequence(current.nextLocalSequence + 1),\n pending: [...current.pending, operation],\n }\n yield* persist(next, current)\n yield* Ref.set(projection, { state: next, shared: replayed })\n yield* Queue.offer(wake, undefined)\n return [undefined, next] as const\n }),\n )\n // Outside the lock, so a `statusChanges` subscriber reads the new state.\n yield* PubSub.publish(statusSignals, undefined)\n return result\n })\n\n const synchronize = Effect.fn('Sync.synchronize')(function* () {\n yield* Effect.annotateCurrentSpan({ documentId })\n const transport = yield* Transport\n if (yield* Ref.get(closed))\n return yield* new ReplicaClosedError({ message: 'Replica is closed' })\n const sent = yield* SynchronizedRef.get(stateRef)\n yield* Metric.update(syncMetrics.exchanges, 1)\n yield* Metric.update(syncMetrics.exchangePending, sent.pending.length)\n const response = yield* Effect.gen(function* () {\n const raw = yield* transport.exchange(sent.cursor, sent.pending)\n // The response is untrusted: a malformed shape is a typed failure, not\n // a defect that escapes the declared error channel.\n return yield* Effect.try({\n try: () => decodeExchange(raw),\n catch: cause =>\n new InvalidExchangeError({ message: 'Invalid sync exchange response', cause }),\n })\n }).pipe(\n Effect.tapError(error =>\n Effect.gen(function* () {\n yield* Effect.logWarning('sync exchange failed', {\n documentId,\n replicaId,\n error: error.message,\n })\n yield* Ref.set(lastError, error.message)\n }),\n ),\n )\n yield* SynchronizedRef.modifyEffect(stateRef, current =>\n Effect.gen(function* () {\n // A `close` during the exchange must not persist its result.\n if (yield* Ref.get(closed))\n return yield* new ReplicaClosedError({ message: 'Replica is closed' })\n let cursor = current.cursor\n let committed = current.committed\n // A checkpoint folds committed history into its snapshot, so the\n // retained id set starts over from it.\n const ids =\n response.checkpoint === undefined ? new Set(current.committedIds) : new Set<string>()\n if (response.checkpoint !== undefined) {\n if (response.checkpoint.cursor < cursor)\n return yield* new CheckpointRegressionError({\n cursor,\n checkpointCursor: response.checkpoint.cursor,\n message: 'Checkpoint is behind the replica',\n })\n committed = response.checkpoint.model\n cursor = response.checkpoint.cursor\n yield* Metric.update(syncMetrics.checkpoints, 1)\n yield* Effect.logDebug('sync checkpoint adopted', { documentId, replicaId, cursor })\n }\n const acknowledged = new Set(response.acknowledged ?? [])\n const rejected = new Set(response.rejected)\n const sentIds = new Set(sent.pending.map(operation => operation.opId))\n for (const id of acknowledged)\n if (!sentIds.has(id))\n return yield* new ForeignAcknowledgementError({\n opId: id,\n message: 'Server acknowledged an operation that was not sent',\n })\n for (const id of rejected) {\n if (!sentIds.has(id))\n return yield* new ForeignRejectionError({\n opId: id,\n message: 'Server rejected an operation that was not sent',\n })\n // An id cannot be both; removal would be ambiguous and a faulty\n // server must not be able to make a pending operation vanish.\n if (acknowledged.has(id))\n return yield* new ForeignAcknowledgementError({\n opId: id,\n message: 'Server both acknowledged and rejected an operation',\n })\n }\n let applied = 0\n for (const raw of response.operations) {\n const { committed: operation, message } = yield* Effect.try({\n try: () => decodeCommittedOperation(raw, documentId),\n catch: cause =>\n new InvalidReplicaHistoryError({ message: 'Invalid committed operation', cause }),\n })\n if (operation.serverSequence <= cursor) continue\n if (operation.serverSequence !== cursor + 1 || ids.has(operation.opId))\n return yield* new CommittedOrderError({\n expected: cursor + 1,\n actual: operation.serverSequence,\n message: 'Invalid committed order',\n })\n committed = definition.replay(committed, message)\n ids.add(operation.opId)\n cursor = operation.serverSequence\n applied += 1\n }\n if (applied > 0) yield* Metric.update(syncMetrics.applied, applied)\n // Validated and encoded by `persist`, for the same reason as submit.\n const next: ReplicaState<Shared> = {\n ...current,\n revision: current.revision + 1,\n committed,\n cursor,\n committedIds: [...ids].slice(-COMMITTED_ID_WINDOW),\n pending: current.pending.filter(\n operation =>\n !ids.has(operation.opId) &&\n !acknowledged.has(operation.opId) &&\n !rejected.has(operation.opId),\n ),\n }\n yield* persist(next, current)\n return [undefined, next] as const\n }),\n )\n yield* Ref.set(lastError, undefined)\n if (response.rejected.length > 0)\n yield* Ref.update(rejectedOps, previous =>\n [...response.rejected, ...previous].slice(0, 32),\n )\n yield* PubSub.publish(statusSignals, undefined)\n })()\n\n const start: Effect.Effect<void, never, Transport> = Effect.gen(function* () {\n yield* synchronize.pipe(Effect.catch(() => Effect.void))\n while (!(yield* Ref.get(closed))) {\n yield* Queue.take(wake)\n if (yield* Ref.get(closed)) return\n yield* synchronize.pipe(Effect.catch(() => Effect.void))\n }\n })\n\n return {\n shared,\n pending: Effect.map(SynchronizedRef.get(stateRef), state => state.pending),\n cursor: Effect.map(SynchronizedRef.get(stateRef), state => state.cursor),\n status,\n statusChanges: Stream.concat(\n Stream.fromEffect(status),\n Stream.fromPubSub(statusSignals).pipe(Stream.mapEffect(() => status)),\n ),\n changes: Stream.concat(\n Stream.fromEffect(snapshot),\n Stream.fromPubSub(statusSignals).pipe(Stream.mapEffect(() => snapshot)),\n ),\n submit,\n synchronize,\n start,\n close: Effect.fn('Sync.close')(function* () {\n yield* Ref.set(closed, true)\n // Wake `start` so it can observe `closed` and return.\n yield* Queue.offer(wake, undefined)\n yield* storage.close\n })(),\n }\n },\n (effect, _replicaId, storage) =>\n // Close a partially initialized storage on any failure, including a\n // defect, so a failed open cannot leak the connection.\n effect.pipe(\n Effect.onExit(exit =>\n Exit.isSuccess(exit) ? Effect.void : storage.close.pipe(Effect.ignore),\n ),\n ),\n )\n\n return {\n documentId,\n codec: { normalizeOperation, operationFrom, committedFrom, decodeExchange },\n journalContract,\n openReplica,\n }\n}\n","/**\n * The Foldkit-facing sync layer: `Sync.forApplication(App).make(config)`\n * compiles an application, a writable projection, and a durable Message subset\n * into the low-level `defineSync` contract, and exposes a read-only Surface over\n * the same projection.\n */\nimport { Schema } from 'effect'\nimport {\n MessageSet,\n Projection,\n Surface,\n type AppScope,\n type Contract,\n type MergeConstructors,\n type MergeFields,\n type RunnableApplication,\n type WritableProjection,\n} from 'foldkit-surface'\nimport type { DocumentId } from './ids.js'\nimport { defineSync, type JournalContract, type Operation, type Sync } from './sync.js'\n\ntype MessageConstructor<Message> = (...args: never[]) => Message\n\n/** The Message union a tuple of constructors produces. */\nexport type MsgOf<Ms extends readonly unknown[]> = Ms[number] extends (...args: never[]) => infer M\n ? M\n : never\n\ntype AppMessage<\n AppModel,\n F extends Schema.Struct.Fields,\n Cases extends Record<string, Schema.Struct.Fields>,\n> = Schema.Schema.Type<AppScope<AppModel, F, Cases>['Message']>\n\n/** Reads the tag off a Foldkit Message constructor without constructing one. */\nconst messageTag = (constructor: unknown): string | undefined => {\n const literal = (constructor as { fields?: { _tag?: { ast?: { literal?: unknown } } } }).fields\n ?._tag?.ast?.literal\n return typeof literal === 'string' ? literal : undefined\n}\n\n/** The `_tag` literal of the Message a constructor produces. */\ntype TagOf<C> = C extends (...args: never[]) => infer M\n ? M extends { readonly _tag: infer T extends string }\n ? T\n : never\n : never\n\n/**\n * A journal contract that also carries the declared authorization policy, in\n * the shape `makeJournal` takes, so `makeJournal({ ...contract })` applies it.\n */\nexport interface PolicyJournalContract<Operation, Shared, Principal> extends JournalContract<\n Operation,\n Shared\n> {\n readonly authorize?: (request: {\n readonly principal: Principal\n readonly operation: Operation\n readonly snapshot: Shared\n }) => boolean\n}\n\n/** What a per-variant `authorize` rule sees before the journal commits. */\nexport interface AuthorizeRequest<Principal, Message, Shared> {\n readonly principal: Principal\n readonly message: Message\n readonly shared: Shared\n}\n\n/**\n * Per-variant policy, keyed by durable tag: `message` is that variant exactly,\n * `shared` the authoritative snapshot. A variant without a rule is allowed; the\n * server may still refuse on its own grounds.\n */\nexport type AuthorizePolicy<\n Principal,\n Fields extends Schema.Struct.Fields,\n Ms extends readonly unknown[],\n> = {\n readonly [K in TagOf<Ms[number]>]?: (\n request: AuthorizeRequest<\n Principal,\n Extract<MsgOf<Ms>, { readonly _tag: K }>,\n Schema.Struct.Type<Fields>\n >,\n ) => boolean\n}\n\ninterface BaseOptions<\n Principal,\n Fields extends Schema.Struct.Fields,\n Ms extends readonly unknown[],\n> {\n readonly documentId: DocumentId\n /** Name for the generated `surface`; defaults to the document id. */\n readonly name?: string\n /**\n * Replaces the replay derived from the application's `update`. It is a pure\n * reducer over the shared subset; only durable Messages reach it, and it runs\n * during admission, replay, and optimistic projection. It is not guarded: the\n * author owns its agreement with `update`.\n */\n readonly replay?: (\n shared: Schema.Struct.Type<NoInfer<Fields>>,\n message: MsgOf<NoInfer<Ms>>,\n ) => Schema.Struct.Type<NoInfer<Fields>>\n /** Authorization the server journal applies before committing; see `AuthorizePolicy`. */\n readonly authorize?: AuthorizePolicy<Principal, NoInfer<Fields>, NoInfer<Ms>>\n}\n\nexport interface MakeOptions<\n AppModel,\n Fields extends Schema.Struct.Fields,\n Subset,\n Ms extends readonly MessageConstructor<any>[],\n Principal = unknown,\n> extends BaseOptions<Principal, Fields, Ms> {\n /** The writable projection of the shared fields. */\n readonly shared: WritableProjection<AppModel, Fields>\n /** The Message subset the replica durably records and replays. */\n readonly durable: MessageSet<AppModel, any, Subset, Ms>\n}\n\n/**\n * One feature's contribution to a document: the fields it shares and the\n * Messages it records. `compose` merges fragments into one, to spread into\n * `make`; a field declared twice with a different codec or a tag declared twice\n * is rejected there.\n */\nexport interface SyncFragment<\n AppModel,\n Fields extends Schema.Struct.Fields,\n Subset,\n Ms extends readonly MessageConstructor<any>[],\n> {\n readonly shared: WritableProjection<AppModel, Fields>\n readonly durable: MessageSet<AppModel, any, Subset, Ms>\n}\n\ntype SharedOf<Fs extends readonly SyncFragment<any, any, any, any>[]> = {\n readonly [K in keyof Fs]: Fs[K]['shared']\n}\ntype DurableOf<Fs extends readonly SyncFragment<any, any, any, any>[]> = {\n readonly [K in keyof Fs]: Fs[K]['durable']\n}\n/** The merged shared fields of several fragments. */\nexport type FragmentFields<Fs extends readonly SyncFragment<any, any, any, any>[]> = MergeFields<\n SharedOf<Fs>\n>\n/** The concatenated durable constructors of several fragments. */\nexport type FragmentConstructors<Fs extends readonly SyncFragment<any, any, any, any>[]> =\n MergeConstructors<DurableOf<Fs>>\n\n/** The union of Messages several fragments record. */\nexport type FragmentMessages<Fs extends readonly SyncFragment<any, any, any, any>[]> =\n Fs[number] extends SyncFragment<any, any, infer V, any> ? V : never\n\n/**\n * The value `make` returns: the low-level `Sync` protocol plus the writable\n * projection, the declared Messages, and a read-only Surface over the\n * projection. Exported so a consumer can name the type.\n */\nexport interface DefinedSync<\n AppModel,\n Fields extends Schema.Struct.Fields,\n Message,\n Ms extends readonly unknown[],\n Principal = unknown,\n> extends Sync<Message, Schema.Struct.Type<Fields>> {\n readonly surface: Surface<AppModel, Schema.Struct.Type<Fields>, MsgOf<Ms>, void>\n readonly projection: WritableProjection<AppModel, Fields>\n readonly messages: Ms\n /** For `Module`: this contract owns the shared projection's paths and records the durable tags. */\n readonly contract: Contract\n /** The durable journal's codecs, reducer, and, when declared, authorization. */\n readonly journalContract: () => PolicyJournalContract<\n Operation,\n Schema.Struct.Type<Fields>,\n Principal\n >\n}\n\n/** The sync constructors specialized to one application. */\nexport interface ApplicationSync<\n AppModel,\n F extends Schema.Struct.Fields,\n Cases extends Record<string, Schema.Struct.Fields>,\n Principal = unknown,\n> {\n /**\n * Fixes the `Principal` that `authorize` rules see. A `Principal` cannot be a\n * positional type argument beside an inferred Model, so it is supplied here:\n * `Sync.forApplication(App).withPrincipal<User>()`. Type-only.\n */\n readonly withPrincipal: <P>() => ApplicationSync<AppModel, F, Cases, P>\n /** One feature's shared fields and durable Messages, for `compose`. */\n readonly fragment: <\n Fields extends Schema.Struct.Fields,\n Subset,\n Ms extends readonly MessageConstructor<AppMessage<AppModel, F, Cases>>[],\n >(config: {\n readonly shared: WritableProjection<AppModel, Fields>\n readonly durable: MessageSet<AppModel, any, Subset, Ms>\n }) => SyncFragment<AppModel, Fields, Subset, Ms>\n /**\n * Merges fragments into one: `make({ documentId, ...compose(Todos, Members) })`.\n * A field declared twice with a different codec, a tag declared twice, or a\n * fragment from another application throws.\n */\n readonly compose: <const Fs extends readonly SyncFragment<AppModel, any, any, any>[]>(\n ...fragments: Fs\n ) => SyncFragment<AppModel, FragmentFields<Fs>, FragmentMessages<Fs>, FragmentConstructors<Fs>>\n readonly make: <\n Fields extends Schema.Struct.Fields,\n Subset,\n Ms extends readonly MessageConstructor<AppMessage<AppModel, F, Cases>>[],\n >(\n options: MakeOptions<AppModel, Fields, Subset, Ms, Principal>,\n ) => DefinedSync<AppModel, Fields, AppMessage<AppModel, F, Cases>, Ms, Principal>\n}\n\n/**\n * Replay derived from the application's own `update`: install the shared slice\n * into the initial Model, apply the Message, and read the slice back.\n *\n * A durable Message must be a deterministic, state-only transition of the shared\n * projection. Replay refuses one that returns a Command (a live effect cannot be\n * replayed) or that changes a Model field outside the projection (the change\n * would be silently lost), so a Message that needs either stays local and emits\n * a durable fact once the effect settles.\n */\nconst derivedReplay = <\n AppModel,\n F extends Schema.Struct.Fields,\n Cases extends Record<string, Schema.Struct.Fields>,\n Fields extends Schema.Struct.Fields,\n>(\n app: RunnableApplication<AppModel, F, Cases, any>,\n shared: WritableProjection<AppModel, Fields>,\n): ((\n value: Schema.Struct.Type<Fields>,\n message: AppMessage<AppModel, F, Cases>,\n) => Schema.Struct.Type<Fields>) => {\n const { initial, update } = app\n // Per-field equivalences for the fields the projection does not own outright,\n // built once, so a violation names the fields and replay (which runs per\n // pending operation on every optimistic read) does not re-compare the shared\n // slice against itself. A partially shared field is still compared.\n const owned = new Set(shared.dependencies.filter(path => path.length === 1).map(path => path[0]))\n const fields = Object.entries(app.Model.fields)\n .filter(([key]) => !owned.has(key))\n .map(\n ([key, field]) =>\n [key, Schema.toEquivalence(field as unknown as Schema.Schema<unknown>)] as const,\n )\n return (value, message) => {\n const result = update(shared.set(initial, value), message)\n const tag = (message as { readonly _tag?: string })._tag\n if (result.commands !== undefined && result.commands.length > 0)\n throw new Error(\n `Sync.forApplication: durable \"${tag}\" returned ${result.commands.length} Command(s); a durable transition is state-only`,\n )\n const next = shared.get(result.model)\n // Writing the projection back into the baseline reproduces `update`'s\n // result exactly when it touched only shared fields.\n const written = shared.set(initial, next) as Record<string, unknown>\n const actual = result.model as Record<string, unknown>\n const changed = fields.filter(([key, equal]) => !equal(actual[key], written[key]))\n if (changed.length > 0)\n throw new Error(\n `Sync.forApplication: durable \"${tag}\" changed Model fields outside the shared projection: ${changed.map(([key]) => key).join(', ')}`,\n )\n return next\n }\n}\n\n/**\n * Merges fragments into one. The primitives reject a conflicting field, a\n * duplicate tag, and a subset from another application.\n */\nconst composeFragments = (\n fragments: readonly SyncFragment<any, any, any, any>[],\n): SyncFragment<any, any, any, any> => {\n const compose = Projection.compose as (\n ...projections: readonly WritableProjection<any, any>[]\n ) => WritableProjection<any, any>\n const union = MessageSet.union as (\n ...subsets: readonly MessageSet<any, any, any, any>[]\n ) => MessageSet<any, any, any, any>\n return {\n shared: compose(...fragments.map(fragment => fragment.shared)),\n durable: union(...fragments.map(fragment => fragment.durable)),\n }\n}\n\n/**\n * Specializes the sync constructors to a `Surface.application`, so\n * `Sync.forApplication(App).make({ documentId, shared, durable })` derives the\n * shared codec, the initial snapshot, the durable predicate, and replay from\n * the application, and refuses a subset that belongs to another application.\n * `defineSync` remains the protocol primitive when there is no application to\n * derive from.\n */\nexport const forApplication = <\n AppModel,\n F extends Schema.Struct.Fields,\n Cases extends Record<string, Schema.Struct.Fields>,\n>(\n app: RunnableApplication<AppModel, F, Cases, any>,\n): ApplicationSync<AppModel, F, Cases> => build(app)\n\nconst build = <\n AppModel,\n F extends Schema.Struct.Fields,\n Cases extends Record<string, Schema.Struct.Fields>,\n Principal,\n>(\n app: RunnableApplication<AppModel, F, Cases, any>,\n): ApplicationSync<AppModel, F, Cases, Principal> => {\n type Message = AppMessage<AppModel, F, Cases>\n const decodeMessage = Schema.decodeUnknownSync(\n app.Message as unknown as Schema.Codec<Message, unknown>,\n )\n\n const make = (\n options: MakeOptions<AppModel, any, any, any, Principal>,\n ): DefinedSync<AppModel, any, Message, any, Principal> => {\n type Shared = Record<string, unknown>\n const { shared, durable } = options\n\n // Two applications can have structurally identical Message unions, so the\n // types cannot separate them; the owner token can.\n if (durable.owner !== app.owner)\n throw new Error('Sync.make: the durable subset belongs to a different application')\n\n const replay: (value: Shared, message: Message) => Shared =\n options.replay === undefined\n ? derivedReplay(app, shared)\n : // `durable` has already rejected anything outside the declared subset.\n (value, message) => options.replay!(value, message as never)\n const durableTags = new Set(\n (durable.constructors as readonly unknown[])\n .map(messageTag)\n .filter((tag): tag is string => tag !== undefined),\n )\n // `AppScope` does not constrain its schemas' services; a Foldkit Message union\n // and a Struct are pure, so the low-level contract's `never` is satisfied.\n const sync = defineSync<Message, Shared, unknown, unknown>({\n documentId: options.documentId,\n message: app.Message as unknown as Schema.Codec<Message, unknown>,\n shared: shared.schema as unknown as Schema.Codec<Shared, unknown>,\n empty: shared.get(app.initial),\n durable: message => {\n const tag = (message as { readonly _tag?: string })._tag\n return tag !== undefined && durableTags.has(tag)\n },\n replay,\n })\n\n const rules = options.authorize as\n Record<string, (request: AuthorizeRequest<Principal, Message, Shared>) => boolean> | undefined\n const journalContract = (): PolicyJournalContract<Operation, Shared, Principal> => {\n const base = sync.journalContract()\n if (rules === undefined) return base\n return {\n ...base,\n authorize: ({ principal, operation, snapshot }) => {\n const message = decodeMessage(operation.message)\n const rule = rules[(message as { readonly _tag: string })._tag]\n return rule === undefined ? true : rule({ principal, message, shared: snapshot })\n },\n }\n }\n\n const readOnly: Projection<AppModel, Shared> = {\n Model: shared.schema,\n dependencies: shared.dependencies,\n requirements: [],\n connections: [],\n read: shared.get,\n }\n const surface = Surface.make(app, options.name ?? String(options.documentId), {\n model: () => readOnly,\n messages: durable.constructors,\n })\n const contract: Contract = {\n kind: 'sync',\n name: surface.name,\n owner: app.owner,\n owns: shared.dependencies,\n observes: shared.dependencies,\n messages: [...durable.tags],\n requirements: [],\n }\n return {\n ...sync,\n journalContract,\n surface,\n projection: shared,\n messages: durable.constructors,\n contract,\n }\n }\n\n return {\n withPrincipal: <P>() => build<AppModel, F, Cases, P>(app),\n fragment: config => {\n if (config.durable.owner !== app.owner)\n throw new Error('Sync.fragment: the durable subset belongs to a different application')\n return { shared: config.shared, durable: config.durable }\n },\n compose: ((...fragments: readonly SyncFragment<any, any, any, any>[]) =>\n composeFragments(fragments)) as ApplicationSync<AppModel, F, Cases, Principal>['compose'],\n make: make as ApplicationSync<AppModel, F, Cases, Principal>['make'],\n }\n}\n","import { Effect, Exit, Ref, Schema, SynchronizedRef } from 'effect'\nimport { StorageError, UnsupportedClockVersionError } from './errors.js'\nimport { DocumentId, ReplicaId } from './ids.js'\nimport type { Storage } from './indexedDb.js'\n\n/** A logical write time; replica ids break concurrent ties using UTF-16 order. */\nconst Stamp = Schema.Struct({\n counter: Schema.Number.check(\n Schema.isInt(),\n Schema.isGreaterThanOrEqualTo(0),\n Schema.isLessThanOrEqualTo(Number.MAX_SAFE_INTEGER),\n ),\n replicaId: ReplicaId,\n})\n\n/** The persisted clock format. A bump must handle the older value explicitly. */\nconst CLOCK_SCHEMA_VERSION = 1\n\nconst ClockState = Schema.Struct({\n schemaVersion: Schema.Literal(CLOCK_SCHEMA_VERSION),\n documentId: DocumentId,\n replicaId: ReplicaId,\n // The high-water counter also serves as the storage's CAS revision.\n revision: Stamp.fields.counter,\n})\nexport type LwwClockState = typeof ClockState.Type\n\nexport interface LwwClock {\n /** Persists a timestamp beyond the saved counter and supplied observation. */\n next: (observedCounter?: number) => Effect.Effect<typeof Stamp.Type, StorageError>\n /** Drains accepted allocations, then closes storage. Repeated calls no-op. */\n close: Effect.Effect<void>\n}\n\nconst decodeClock = Schema.decodeUnknownSync(ClockState, { onExcessProperty: 'error' })\nconst decodeCounter = Schema.decodeUnknownSync(Stamp.fields.counter)\n\nconst clockError = (message: string, cause: unknown): StorageError =>\n new StorageError({\n message: `${message}: ${cause instanceof Error ? cause.message : String(cause)}`,\n cause,\n })\n\nconst VersionProbe = Schema.Struct({ schemaVersion: Schema.optional(Schema.Number) })\n/**\n * Tells a version this build does not understand apart from malformed data, so\n * the caller gets an actionable failure and the stored state is preserved.\n */\nconst unsupportedVersion = (input: unknown): UnsupportedClockVersionError | undefined => {\n let found: { readonly schemaVersion?: number | undefined }\n try {\n found = Schema.decodeUnknownSync(VersionProbe)(input)\n } catch {\n return undefined\n }\n if (found.schemaVersion === CLOCK_SCHEMA_VERSION) return undefined\n return new UnsupportedClockVersionError({\n schemaVersion: found.schemaVersion ?? null,\n message: `Stored clock uses schema ${found.schemaVersion ?? '?'}; this build supports ${CLOCK_SCHEMA_VERSION}`,\n })\n}\n\n/**\n * Opens a durable clock over the caller's storage.\n *\n * Allocations are serialized through a `SynchronizedRef` and each persists before\n * its stamp is returned. A crash after the save may skip a timestamp but never\n * reuse one. Storage is owned by the caller; a failed open closes it so a partial\n * initialization does not leak the connection.\n */\nexport const openLwwClock = Effect.fn('Lww.openClock')(\n function* (options: {\n readonly documentId: DocumentId\n readonly replicaId: ReplicaId\n readonly storage: Storage\n }) {\n const { documentId, replicaId, storage } = options\n yield* Effect.annotateCurrentSpan({ documentId, replicaId })\n const initial = decodeClock({\n schemaVersion: CLOCK_SCHEMA_VERSION,\n documentId,\n replicaId,\n revision: 0,\n })\n const saved = yield* storage.load()\n const state = yield* Effect.try({\n try: () => (saved === undefined ? initial : decodeClock(saved)),\n catch: cause =>\n unsupportedVersion(saved) ?? clockError('Stored clock state is invalid', cause),\n })\n if (state.documentId !== documentId || state.replicaId !== replicaId)\n return yield* new StorageError({ message: 'Wrong clock storage' })\n if (saved === undefined) yield* storage.save(state, null)\n\n const stateRef = yield* SynchronizedRef.make(state)\n const closed = yield* Ref.make(false)\n\n const next = Effect.fn('Lww.next')(function* (observedCounter = 0) {\n if (yield* Ref.get(closed)) return yield* new StorageError({ message: 'Clock is closed' })\n return yield* SynchronizedRef.modifyEffect(stateRef, current =>\n Effect.gen(function* () {\n // Re-check under the lock: a `close` that set the flag while this\n // allocation was queued must not save to a closed connection.\n if (yield* Ref.get(closed)) return yield* new StorageError({ message: 'Clock is closed' })\n const allocated = yield* Effect.try({\n try: () =>\n decodeClock({\n ...current,\n revision: Math.max(current.revision, decodeCounter(observedCounter)) + 1,\n }),\n catch: cause => clockError('Invalid clock allocation', cause),\n })\n yield* storage.save(allocated, current.revision)\n return [{ counter: allocated.revision, replicaId }, allocated] as const\n }),\n )\n })\n\n const close = Effect.fn('Lww.close')(function* () {\n const alreadyClosed = yield* Ref.modify(closed, current => [current, true] as const)\n if (alreadyClosed) return\n // Drains any accepted allocation before releasing the connection.\n yield* SynchronizedRef.modifyEffect(stateRef, current =>\n Effect.succeed([undefined, current] as const),\n )\n yield* storage.close\n })()\n\n return { next, close }\n },\n (effect, options) =>\n // Close a partially initialized storage on any failure, including a defect,\n // so a failed open cannot leak the connection.\n effect.pipe(\n Effect.onExit(exit =>\n Exit.isSuccess(exit) ? Effect.void : options.storage.close.pipe(Effect.ignore),\n ),\n ),\n)\n\n/**\n * A schema and reducer helper for a last-writer-wins register.\n * Allocate a unique stamp per write before dispatch, and retain it in the Message.\n * Merge is for decoded values; the application's schema validates wire input.\n */\nexport const lwwRegister = <Value, Encoded, RD, RE>(\n value: Schema.Codec<Value, Encoded, RD, RE>,\n) => {\n const schema = Schema.Struct({ stamp: Stamp, value })\n type Register = typeof schema.Type\n const equivalent = Schema.toEquivalence(value)\n\n const merge = (left: Register, right: Register): Register => {\n if (left.stamp.counter !== right.stamp.counter)\n return left.stamp.counter > right.stamp.counter ? left : right\n if (left.stamp.replicaId !== right.stamp.replicaId)\n return left.stamp.replicaId > right.stamp.replicaId ? left : right\n // Reusing a write identity for different values would make arrival order win.\n if (!equivalent(left.value, right.value)) throw new Error('Conflicting LWW write identity')\n return left\n }\n\n return { schema, merge }\n}\n","import { Clock, Duration, Effect, Fiber, PubSub, Ref, Stream, type Scope } from 'effect'\nimport type { SocketLike } from './transport.js'\n\n/** One peer's presence. A `null` value means the peer left. */\nexport interface PresenceUpdate<Update> {\n readonly id: string\n readonly value: Update | null\n}\n\n/**\n * The ephemeral channel presence travels on.\n *\n * `updates` is the inbound bus a peer consumes; `publish` sends one to the bus.\n * Splitting them keeps an inbound update from being echoed straight back out.\n * This is deliberately not the durable transport: presence is broadcast, never\n * journaled, so a dropped or duplicated update is harmless.\n */\nexport interface PresenceChannel<Update> {\n readonly updates: PubSub.PubSub<PresenceUpdate<Update>>\n readonly publish: (update: PresenceUpdate<Update>) => Effect.Effect<void>\n}\n\nexport interface PresenceOptions<Update> {\n /** This peer's identity on the channel. */\n readonly id: string\n /** How long a peer may go without refreshing before it is dropped. */\n readonly ttl: Duration.Input\n /**\n * Validates the untrusted value a peer sends before it is stored. Presence\n * crosses a wire, so this is required rather than trusting the type\n * parameter; a value it rejects is dropped.\n */\n readonly decodeValue: (value: unknown) => Update\n readonly channel?: PresenceChannel<Update> | undefined\n}\n\nexport interface PresencePeer<Update> {\n readonly id: string\n readonly value: Update\n readonly updatedAt: number\n}\n\nexport interface Presence<Update> {\n /** Sets this peer's value and broadcasts it. */\n readonly set: (value: Update) => Effect.Effect<void>\n /** Removes this peer and broadcasts the departure. */\n readonly leave: Effect.Effect<void>\n /** Live peers, self included, with stale ones excluded. */\n readonly peers: Effect.Effect<ReadonlyArray<PresencePeer<Update>>>\n /** Drops expired peers; notifies if any went. */\n readonly prune: Effect.Effect<void>\n /** Notified when the peer set changes. */\n readonly subscribe: (listener: () => void) => () => void\n /**\n * The live peers, re-emitted whenever the set changes. The `Stream` form of\n * `subscribe`, for a consumer that composes with Effect.\n */\n readonly changes: Stream.Stream<ReadonlyArray<PresencePeer<Update>>>\n /** Stops consuming the channel; the enclosing scope also does this on exit. */\n readonly close: Effect.Effect<void>\n}\n\n/**\n * Tracks ephemeral peers with a time-to-live.\n *\n * Nothing here touches the durable log: presence is state a peer refreshes, and\n * a peer that stops refreshing is dropped, not replayed. Time comes from the\n * `Clock`, so a `TestClock` drives the TTL deterministically.\n */\nexport const createPresence = Effect.fn('Presence.create')(function* <Update>(\n options: PresenceOptions<Update>,\n) {\n const ttl = Duration.toMillis(options.ttl)\n const peers = yield* Ref.make(new Map<string, PresencePeer<Update>>())\n const closed = yield* Ref.make(false)\n const signals = yield* PubSub.sliding<void>(1)\n const listeners = new Set<() => void>()\n /** A subscriber must never fail an update. */\n const notify = (): Effect.Effect<void> =>\n Effect.gen(function* () {\n for (const listener of [...listeners]) {\n try {\n listener()\n } catch {\n // Deliberately swallowed.\n }\n }\n yield* PubSub.publish(signals, undefined)\n })\n const expired = (peer: PresencePeer<Update>, at: number): boolean => at - peer.updatedAt > ttl\n\n const put = (id: string, value: Update, at: number): Effect.Effect<void> =>\n Ref.update(peers, map => {\n const next = new Map(map)\n next.set(id, { id, value, updatedAt: at })\n return next\n })\n const remove = (id: string): Effect.Effect<boolean> =>\n Ref.modify(peers, map => {\n if (!map.has(id)) return [false, map] as const\n const next = new Map(map)\n next.delete(id)\n return [true, next] as const\n })\n\n const receive = Effect.fn('Presence.receive')(function* (update: PresenceUpdate<Update>) {\n if (update.id === options.id) return\n if (update.value === null) {\n if (yield* remove(update.id)) yield* notify()\n return\n }\n let value: Update\n try {\n value = options.decodeValue(update.value)\n } catch {\n // A peer's value that fails the contract is dropped, never stored.\n return\n }\n yield* put(update.id, value, yield* Clock.currentTimeMillis)\n yield* notify()\n })\n\n const channel = options.channel\n const consuming =\n channel === undefined\n ? undefined\n : yield* Stream.runForEach(Stream.fromPubSub(channel.updates), receive).pipe(\n Effect.forkScoped,\n )\n\n const set = Effect.fn('Presence.set')(function* (value: Update) {\n if (yield* Ref.get(closed)) return\n yield* put(options.id, value, yield* Clock.currentTimeMillis)\n if (channel !== undefined) yield* channel.publish({ id: options.id, value })\n yield* notify()\n })\n\n const leave = Effect.fn('Presence.leave')(function* () {\n if (yield* Ref.get(closed)) return\n yield* remove(options.id)\n if (channel !== undefined) yield* channel.publish({ id: options.id, value: null })\n yield* notify()\n })()\n\n const peerList = Effect.fn('Presence.peers')(function* () {\n const at = yield* Clock.currentTimeMillis\n const map = yield* Ref.get(peers)\n return [...map.values()].filter(peer => !expired(peer, at)).map(peer => ({ ...peer }))\n })()\n\n const prune = Effect.fn('Presence.prune')(function* () {\n if (yield* Ref.get(closed)) return\n const at = yield* Clock.currentTimeMillis\n const changed = yield* Ref.modify(peers, map => {\n let removed = false\n const next = new Map(map)\n for (const [id, peer] of map) {\n if (expired(peer, at)) {\n next.delete(id)\n removed = true\n }\n }\n return [removed, next] as const\n })\n if (changed) yield* notify()\n })()\n\n const close = Effect.fn('Presence.close')(function* () {\n if (yield* Ref.get(closed)) return\n yield* Ref.set(closed, true)\n if (consuming !== undefined) yield* Fiber.interrupt(consuming)\n yield* Effect.sync(() => listeners.clear())\n yield* PubSub.shutdown(signals)\n })()\n\n return {\n set,\n leave,\n peers: peerList,\n prune,\n subscribe: (listener: () => void) => {\n listeners.add(listener)\n return () => listeners.delete(listener)\n },\n changes: Stream.concat(\n Stream.fromEffect(peerList),\n Stream.fromPubSub(signals).pipe(Stream.mapEffect(() => peerList)),\n ),\n close,\n }\n})\n\n/** An in-process channel, for tests and single-process demos. */\nexport const loopbackPresenceChannel = Effect.fn('Presence.loopbackChannel')(function* <Update>() {\n const updates = yield* PubSub.unbounded<PresenceUpdate<Update>>()\n return {\n updates,\n publish: (update: PresenceUpdate<Update>) => PubSub.publish(updates, update),\n }\n})\n\n/** Broadcasts presence updates among connected peers. */\nexport interface PresenceHub<Update> {\n /** Registers a peer's send; returns a leave function. */\n join(send: (update: PresenceUpdate<Update>) => void): () => void\n /** Fans an update out to every joined peer. */\n publish(update: PresenceUpdate<Update>): void\n}\n\nexport const createPresenceHub = <Update>(): PresenceHub<Update> => {\n const peers = new Set<(update: PresenceUpdate<Update>) => void>()\n return {\n join: send => {\n peers.add(send)\n return () => peers.delete(send)\n },\n publish: update => {\n for (const send of [...peers]) {\n try {\n send(update)\n } catch {\n // One broken peer must not starve the rest of the fan-out.\n }\n }\n },\n }\n}\n\nconst frameType = 'presence'\n\n/** A presence frame. `id` is set by the server that owns the identity. */\ninterface PresenceFrame<Update> {\n readonly id: string | undefined\n readonly value: Update | null\n}\n\n/** Decodes a presence frame, ignoring anything else a socket may carry. */\nconst decodePresence = <Update>(data: string): PresenceFrame<Update> | undefined => {\n let frame: Record<string, unknown>\n try {\n frame = JSON.parse(data) as Record<string, unknown>\n } catch {\n return undefined\n }\n const payload = frame[frameType]\n if (typeof payload !== 'object' || payload === null) return undefined\n const { id, value } = payload as { id?: unknown; value?: unknown }\n return { id: typeof id === 'string' ? id : undefined, value: (value ?? null) as Update | null }\n}\n\n/**\n * A presence channel fed by stamped frames from the server, sent back without an\n * id: the server owns peer identity, so a client cannot assert another's.\n */\nexport const socketPresenceChannel = <Update>(\n socket: SocketLike,\n): Effect.Effect<PresenceChannel<Update>, never, Scope.Scope> =>\n Effect.gen(function* () {\n const updates = yield* PubSub.unbounded<PresenceUpdate<Update>>()\n yield* Effect.acquireRelease(\n Effect.sync(() =>\n socket.onMessage(data => {\n const frame = decodePresence<Update>(data)\n // An unstamped frame is not from the server and carries no identity.\n if (frame === undefined || frame.id === undefined) return\n PubSub.publishUnsafe(updates, { id: frame.id, value: frame.value })\n }),\n ),\n off => Effect.sync(off),\n )\n return {\n updates,\n publish: update =>\n Effect.sync(() => socket.send(JSON.stringify({ [frameType]: { value: update.value } }))),\n }\n })\n\n/** Serves presence frames on an accepted socket, stamping the connection's identity. */\nexport const servePresence = <Update>(\n socket: SocketLike,\n hub: PresenceHub<Update>,\n options: { readonly peerId: string },\n): (() => void) => {\n const send = (update: PresenceUpdate<Update>): void =>\n socket.send(JSON.stringify({ [frameType]: { id: update.id, value: update.value } }))\n const leave = hub.join(send)\n const off = socket.onMessage(data => {\n const frame = decodePresence<Update>(data)\n // The connection owns the identity; a client-supplied id is ignored.\n if (frame !== undefined) hub.publish({ id: options.peerId, value: frame.value })\n })\n return () => {\n off()\n leave()\n }\n}\n"],"mappings":";;;;;;;;;AAGA,IAAa,eAAb,cAAkC,OAAO,YAA0B,CAAC,CAAC,gBAAgB;CACnF,SAAS,OAAO;CAChB,OAAO,OAAO,SAAS,OAAO,OAAO;AACvC,CAAC,CAAC,CAAC,CAAC;;AAGJ,IAAa,+BAAb,cAAkD,OAAO,YAA0C,CAAC,CAClG,gCACA;CACE,eAAe,OAAO,OAAO,OAAO,MAAM;CAC1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AE,IAAI,UAAU;CACtB,OAAO;EAAE,IAAI,OAAO,OAAO,WAAW,KAAK,KAAA;EAAW,OAAQ,SAAS;CAAuB;AAChG;;;;;AAMA,MAAa,yBACX,WAEA,OAAO,IAAI,aAAa;CACtB,MAAM,UAAU,OAAO,OAAO,UAAkC;CAChE,OAAO,OAAO,eACZ,OAAO,WACL,OAAO,WAAU,SAAQ;EACvB,MAAM,QAAQ,eAAuB,IAAI;EAEzC,IAAI,UAAU,KAAA,KAAa,MAAM,OAAO,KAAA,GAAW;EACnD,OAAO,cAAc,SAAS;GAAE,IAAI,MAAM;GAAI,OAAO,MAAM;EAAM,CAAC;CACpE,CAAC,CACH,IACA,QAAO,OAAO,KAAK,GAAG,CACxB;CACA,OAAO;EACL;EACA,UAAS,WACP,OAAO,WAAW,OAAO,KAAK,KAAK,UAAU,GAAG,YAAY,EAAE,OAAO,OAAO,MAAM,EAAE,CAAC,CAAC,CAAC;CAC3F;AACF,CAAC;;AAGH,MAAa,iBACX,QACA,KACA,YACiB;CACjB,MAAM,QAAQ,WACZ,OAAO,KAAK,KAAK,UAAU,GAAG,YAAY;EAAE,IAAI,OAAO;EAAI,OAAO,OAAO;CAAM,EAAE,CAAC,CAAC;CACrF,MAAM,QAAQ,IAAI,KAAK,IAAI;CAC3B,MAAM,MAAM,OAAO,WAAU,SAAQ;EACnC,MAAM,QAAQ,eAAuB,IAAI;EAEzC,IAAI,UAAU,KAAA,GAAW,IAAI,QAAQ;GAAE,IAAI,QAAQ;GAAQ,OAAO,MAAM;EAAM,CAAC;CACjF,CAAC;CACD,aAAa;EACX,IAAI;EACJ,MAAM;CACR;AACF"}
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../src/errors.ts","../src/indexedDb.ts","../src/ids.ts","../src/lww.ts","../src/transport.ts","../src/sync.ts","../src/make.ts","../src/mount.ts","../src/presence.ts","../src/index.ts"],"sourcesContent":["import { Schema } from 'effect'\n\n/** The persisted storage could not be read or written. */\nexport class StorageError extends Schema.TaggedError<StorageError>()('StorageError', {\n message: Schema.String,\n cause: Schema.optional(Schema.Unknown),\n}) {}\n\n/** The stored clock state targets a schema version this build does not support. */\nexport class UnsupportedClockVersionError extends Schema.TaggedError<UnsupportedClockVersionError>()(\n 'UnsupportedClockVersionError',\n {\n schemaVersion: Schema.NullOr(Schema.Number),\n message: Schema.String,\n },\n) {}\n\n/** The storage holds a different replica's state. */\nexport class WrongReplicaStorageError extends Schema.TaggedError<WrongReplicaStorageError>()(\n 'WrongReplicaStorageError',\n {\n documentId: Schema.String,\n replicaId: Schema.String,\n message: Schema.String,\n },\n) {}\n\n/** The persisted replica history is internally inconsistent. */\nexport class InvalidReplicaHistoryError extends Schema.TaggedError<InvalidReplicaHistoryError>()(\n 'InvalidReplicaHistoryError',\n {\n message: Schema.String,\n cause: Schema.optional(Schema.Unknown),\n },\n) {}\n\n/** The server's exchange response did not match the protocol schema. */\nexport class InvalidExchangeError extends Schema.TaggedError<InvalidExchangeError>()(\n 'InvalidExchangeError',\n {\n message: Schema.String,\n cause: Schema.optional(Schema.Unknown),\n },\n) {}\n\n/** A persisted pending operation could not have been produced by this replica. */\nexport class InvalidOutboxError extends Schema.TaggedError<InvalidOutboxError>()(\n 'InvalidOutboxError',\n {\n message: Schema.String,\n },\n) {}\n\n/** The server sent a checkpoint older than the replica's cursor. */\nexport class CheckpointRegressionError extends Schema.TaggedError<CheckpointRegressionError>()(\n 'CheckpointRegressionError',\n {\n cursor: Schema.Number,\n checkpointCursor: Schema.Number,\n message: Schema.String,\n },\n) {}\n\n/** Committed operations were not contiguous from the replica's cursor. */\nexport class CommittedOrderError extends Schema.TaggedError<CommittedOrderError>()(\n 'CommittedOrderError',\n {\n expected: Schema.Number,\n actual: Schema.Number,\n message: Schema.String,\n },\n) {}\n\n/** The server rejected an operation the replica never sent. */\nexport class ForeignRejectionError extends Schema.TaggedError<ForeignRejectionError>()(\n 'ForeignRejectionError',\n {\n opId: Schema.String,\n message: Schema.String,\n },\n) {}\n\n/**\n * The server answered an operation this request never sent, or both\n * acknowledged and rejected it. Acting on either would let a faulty or hostile\n * server delete local work.\n */\nexport class ForeignAcknowledgementError extends Schema.TaggedError<ForeignAcknowledgementError>()(\n 'ForeignAcknowledgementError',\n {\n opId: Schema.String,\n message: Schema.String,\n },\n) {}\n\n/** The replica was closed while work was still being submitted. */\nexport class ReplicaClosedError extends Schema.TaggedError<ReplicaClosedError>()(\n 'ReplicaClosedError',\n {\n message: Schema.String,\n },\n) {}\n\n/** The stored replica state targets a protocol or schema version this build does not support. */\nexport class UnsupportedReplicaVersionError extends Schema.TaggedError<UnsupportedReplicaVersionError>()(\n 'UnsupportedReplicaVersionError',\n {\n protocolVersion: Schema.NullOr(Schema.Number),\n schemaVersion: Schema.NullOr(Schema.Number),\n message: Schema.String,\n },\n) {}\n\n/**\n * `replay` threw for a submitted Message, so it could never be applied here or\n * on any other replica; nothing was written.\n */\nexport class ReplayError extends Schema.TaggedError<ReplayError>()('ReplayError', {\n message: Schema.String,\n cause: Schema.optional(Schema.Unknown),\n}) {}\n\nexport type ReplicaError =\n | StorageError\n | ReplayError\n | WrongReplicaStorageError\n | InvalidReplicaHistoryError\n | InvalidExchangeError\n | UnsupportedReplicaVersionError\n | InvalidOutboxError\n | CheckpointRegressionError\n | CommittedOrderError\n | ForeignRejectionError\n | ForeignAcknowledgementError\n | ReplicaClosedError\n","import { Config, Effect, type Scope } from 'effect'\nimport { StorageError } from './errors.js'\n\n/** Persists a replica's state with compare-and-swap on its revision. */\nexport interface Storage {\n load: () => Effect.Effect<unknown, StorageError>\n save: (state: unknown, expectedRevision: number | null) => Effect.Effect<void, StorageError>\n /** Idempotent; the caller closes the connection explicitly. */\n close: Effect.Effect<void>\n}\n\nconst storageError = (message: string, cause: unknown): StorageError =>\n new StorageError({\n message: `${message}: ${cause instanceof Error ? cause.message : String(cause)}`,\n cause,\n })\n\nconst openDatabase = (\n name: string,\n factory: IDBFactory,\n): Effect.Effect<IDBDatabase, StorageError> =>\n Effect.tryPromise({\n try: () =>\n new Promise<IDBDatabase>((resolve, reject) => {\n const request = factory.open(name, 1)\n request.onupgradeneeded = () => request.result.createObjectStore('replica')\n request.onsuccess = () => resolve(request.result)\n request.onerror = () => reject(request.error)\n // Without this, a version upgrade blocked by another open connection\n // never settles and the effect hangs.\n request.onblocked = () =>\n reject(new Error('IndexedDB upgrade is blocked by another connection'))\n }),\n catch: cause => storageError('Could not open the storage', cause),\n })\n\n/** One database per document/replica; CAS prevents two tabs from sharing a writer identity. */\nexport const indexedDb = Effect.fn('Storage.indexedDb')(function* (\n name: Config.Config<string> | string,\n factory: IDBFactory = globalThis.indexedDB,\n) {\n const databaseName =\n typeof name === 'string'\n ? name\n : yield* name.pipe(\n Effect.catchTag('ConfigError', cause =>\n Effect.fail(storageError('Could not read the storage name', cause)),\n ),\n )\n const database = yield* Effect.acquireRelease(openDatabase(databaseName, factory), database =>\n Effect.sync(() => database.close()),\n )\n database.onversionchange = () => database.close()\n const storage: Storage = {\n load: () =>\n Effect.tryPromise({\n try: () =>\n new Promise((resolve, reject) => {\n const transaction = database.transaction('replica', 'readonly')\n const request = transaction.objectStore('replica').get('state')\n transaction.oncomplete = () => resolve(request.result)\n transaction.onabort = () =>\n reject(transaction.error ?? new Error('IndexedDB read aborted'))\n }),\n catch: cause => storageError('Could not read the replica', cause),\n }),\n save: (state, expectedRevision) =>\n Effect.tryPromise({\n try: () =>\n new Promise<void>((resolve, reject) => {\n const transaction = database.transaction('replica', 'readwrite', {\n durability: 'strict',\n })\n const store = transaction.objectStore('replica')\n const request = store.get('state')\n let conflict = false\n request.onsuccess = () => {\n const current = request.result as { revision: number } | undefined\n if ((current?.revision ?? null) !== expectedRevision) {\n conflict = true\n transaction.abort()\n return\n }\n store.put(state, 'state')\n }\n transaction.oncomplete = () => resolve()\n transaction.onabort = () =>\n reject(\n conflict\n ? new Error('Replica was changed by another writer')\n : (transaction.error ?? new Error('IndexedDB write aborted')),\n )\n }),\n catch: cause => storageError('Could not save the replica', cause),\n }),\n close: Effect.sync(() => database.close()),\n }\n return storage\n})\n","import { Schema } from 'effect'\n\n/** Identifies the replicated document a replica or operation belongs to. */\nexport const DocumentId = Schema.NonEmptyString.pipe(Schema.brand('@foldkit-sync/DocumentId'))\nexport type DocumentId = typeof DocumentId.Type\n\n/** Identifies one replica (writer identity) within a document. */\nexport const ReplicaId = Schema.NonEmptyString.pipe(Schema.brand('@foldkit-sync/ReplicaId'))\nexport type ReplicaId = typeof ReplicaId.Type\n\n/** The stable identity of one operation within a document. */\nexport const OpId = Schema.NonEmptyString.pipe(Schema.brand('@foldkit-sync/OpId'))\nexport type OpId = typeof OpId.Type\n\n/**\n * A position in the committed document order. `0` is the start; a committed\n * operation's `serverSequence` and a replica's `cursor` are the same family.\n */\nexport const Sequence = Schema.Number.check(\n Schema.isInt(),\n Schema.isGreaterThanOrEqualTo(0),\n Schema.isLessThanOrEqualTo(Number.MAX_SAFE_INTEGER),\n).pipe(Schema.brand('@foldkit-sync/Sequence'))\nexport type Sequence = typeof Sequence.Type\n\n/** A replica's own operation counter within a document; 1-based. */\nexport const LocalSequence = Schema.Number.check(\n Schema.isInt(),\n Schema.isGreaterThanOrEqualTo(1),\n Schema.isLessThanOrEqualTo(Number.MAX_SAFE_INTEGER),\n).pipe(Schema.brand('@foldkit-sync/LocalSequence'))\nexport type LocalSequence = typeof LocalSequence.Type\n\n/**\n * Decode-and-brand helpers. A branded schema constructs the same value with\n * `DocumentId.make('todos')`, which is the spelling to lead with; these stay\n * for callers that already have them.\n */\nexport const documentId = (value: string): DocumentId => Schema.decodeUnknownSync(DocumentId)(value)\nexport const replicaId = (value: string): ReplicaId => Schema.decodeUnknownSync(ReplicaId)(value)\nexport const opId = (value: string): OpId => Schema.decodeUnknownSync(OpId)(value)\nexport const sequence = (value: number): Sequence => Schema.decodeUnknownSync(Sequence)(value)\nexport const localSequence = (value: number): LocalSequence =>\n Schema.decodeUnknownSync(LocalSequence)(value)\n","import { Effect, Exit, Ref, Schema, SynchronizedRef } from 'effect'\nimport { StorageError, UnsupportedClockVersionError } from './errors.js'\nimport { DocumentId, ReplicaId } from './ids.js'\nimport type { Storage } from './indexedDb.js'\n\n/** A logical write time; replica ids break concurrent ties using UTF-16 order. */\nconst Stamp = Schema.Struct({\n counter: Schema.Number.check(\n Schema.isInt(),\n Schema.isGreaterThanOrEqualTo(0),\n Schema.isLessThanOrEqualTo(Number.MAX_SAFE_INTEGER),\n ),\n replicaId: ReplicaId,\n})\n\n/** The persisted clock format. A bump must handle the older value explicitly. */\nconst CLOCK_SCHEMA_VERSION = 1\n\nconst ClockState = Schema.Struct({\n schemaVersion: Schema.Literal(CLOCK_SCHEMA_VERSION),\n documentId: DocumentId,\n replicaId: ReplicaId,\n // The high-water counter also serves as the storage's CAS revision.\n revision: Stamp.fields.counter,\n})\nexport type LwwClockState = typeof ClockState.Type\n\nexport interface LwwClock {\n /** Persists a timestamp beyond the saved counter and supplied observation. */\n next: (observedCounter?: number) => Effect.Effect<typeof Stamp.Type, StorageError>\n /** Drains accepted allocations, then closes storage. Repeated calls no-op. */\n close: Effect.Effect<void>\n}\n\nconst decodeClock = Schema.decodeUnknownSync(ClockState, { onExcessProperty: 'error' })\nconst decodeCounter = Schema.decodeUnknownSync(Stamp.fields.counter)\n\nconst clockError = (message: string, cause: unknown): StorageError =>\n new StorageError({\n message: `${message}: ${cause instanceof Error ? cause.message : String(cause)}`,\n cause,\n })\n\nconst VersionProbe = Schema.Struct({ schemaVersion: Schema.optional(Schema.Number) })\n/**\n * Tells a version this build does not understand apart from malformed data, so\n * the caller gets an actionable failure and the stored state is preserved.\n */\nconst unsupportedVersion = (input: unknown): UnsupportedClockVersionError | undefined => {\n let found: { readonly schemaVersion?: number | undefined }\n try {\n found = Schema.decodeUnknownSync(VersionProbe)(input)\n } catch {\n return undefined\n }\n if (found.schemaVersion === CLOCK_SCHEMA_VERSION) return undefined\n return new UnsupportedClockVersionError({\n schemaVersion: found.schemaVersion ?? null,\n message: `Stored clock uses schema ${found.schemaVersion ?? '?'}; this build supports ${CLOCK_SCHEMA_VERSION}`,\n })\n}\n\n/**\n * Opens a durable clock over the caller's storage.\n *\n * Allocations are serialized through a `SynchronizedRef` and each persists before\n * its stamp is returned. A crash after the save may skip a timestamp but never\n * reuse one. Storage is owned by the caller; a failed open closes it so a partial\n * initialization does not leak the connection.\n */\nexport const openLwwClock = Effect.fn('Lww.openClock')(\n function* (options: {\n readonly documentId: DocumentId\n readonly replicaId: ReplicaId\n readonly storage: Storage\n }) {\n const { documentId, replicaId, storage } = options\n yield* Effect.annotateCurrentSpan({ documentId, replicaId })\n const initial = decodeClock({\n schemaVersion: CLOCK_SCHEMA_VERSION,\n documentId,\n replicaId,\n revision: 0,\n })\n const saved = yield* storage.load()\n const state = yield* Effect.try({\n try: () => (saved === undefined ? initial : decodeClock(saved)),\n catch: cause =>\n unsupportedVersion(saved) ?? clockError('Stored clock state is invalid', cause),\n })\n if (state.documentId !== documentId || state.replicaId !== replicaId)\n return yield* new StorageError({ message: 'Wrong clock storage' })\n if (saved === undefined) yield* storage.save(state, null)\n\n const stateRef = yield* SynchronizedRef.make(state)\n const closed = yield* Ref.make(false)\n\n const next = Effect.fn('Lww.next')(function* (observedCounter = 0) {\n if (yield* Ref.get(closed)) return yield* new StorageError({ message: 'Clock is closed' })\n return yield* SynchronizedRef.modifyEffect(stateRef, current =>\n Effect.gen(function* () {\n // Re-check under the lock: a `close` that set the flag while this\n // allocation was queued must not save to a closed connection.\n if (yield* Ref.get(closed)) return yield* new StorageError({ message: 'Clock is closed' })\n const allocated = yield* Effect.try({\n try: () =>\n decodeClock({\n ...current,\n revision: Math.max(current.revision, decodeCounter(observedCounter)) + 1,\n }),\n catch: cause => clockError('Invalid clock allocation', cause),\n })\n yield* storage.save(allocated, current.revision)\n return [{ counter: allocated.revision, replicaId }, allocated] as const\n }),\n )\n })\n\n const close = Effect.fn('Lww.close')(function* () {\n const alreadyClosed = yield* Ref.modify(closed, current => [current, true] as const)\n if (alreadyClosed) return\n // Drains any accepted allocation before releasing the connection.\n yield* SynchronizedRef.modifyEffect(stateRef, current =>\n Effect.succeed([undefined, current] as const),\n )\n yield* storage.close\n })()\n\n return { next, close }\n },\n (effect, options) =>\n // Close a partially initialized storage on any failure, including a defect,\n // so a failed open cannot leak the connection.\n effect.pipe(\n Effect.onExit(exit =>\n Exit.isSuccess(exit) ? Effect.void : options.storage.close.pipe(Effect.ignore),\n ),\n ),\n)\n\n/**\n * A schema and reducer helper for a last-writer-wins register.\n * Allocate a unique stamp per write before dispatch, and retain it in the Message.\n * Merge is for decoded values; the application's schema validates wire input.\n */\nexport const lwwRegister = <Value, Encoded, RD, RE>(\n value: Schema.Codec<Value, Encoded, RD, RE>,\n) => {\n const schema = Schema.Struct({ stamp: Stamp, value })\n type Register = typeof schema.Type\n const equivalent = Schema.toEquivalence(value)\n\n const merge = (left: Register, right: Register): Register => {\n if (left.stamp.counter !== right.stamp.counter)\n return left.stamp.counter > right.stamp.counter ? left : right\n if (left.stamp.replicaId !== right.stamp.replicaId)\n return left.stamp.replicaId > right.stamp.replicaId ? left : right\n // Reusing a write identity for different values would make arrival order win.\n if (!equivalent(left.value, right.value)) throw new Error('Conflicting LWW write identity')\n return left\n }\n\n return { schema, merge }\n}\n","import { Context, Duration, Effect, Layer, Schedule, Schema } from 'effect'\nimport { sequence } from './ids.js'\nimport type { Operation, TransportClient } from './sync.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}\n\nexport interface ExchangeReply {\n readonly id: string\n readonly result?: unknown\n readonly error?: string\n}\n\nexport interface TransportShape {\n readonly exchange: (\n cursor: number,\n pending: ReadonlyArray<Operation>,\n ) => Effect.Effect<unknown, TransportError>\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\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: (cursor: number, pending: ReadonlyArray<Operation>) => unknown | Promise<unknown>,\n): Layer.Layer<Transport> =>\n Layer.succeed(Transport, {\n exchange: (cursor, pending) =>\n Effect.tryPromise({ try: () => Promise.resolve(handler(cursor, pending)), catch: failure }),\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) =>\n Effect.tryPromise({\n try: () => transport.exchange(sequence(cursor), pending),\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) => Effect.runPromise(transport.exchange(cursor, pending)),\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. Returns a function\n * that stops serving.\n */\nexport const serveSocket = (\n socket: SocketLike,\n options: {\n readonly exchange: (\n cursor: number,\n pending: ReadonlyArray<Operation>,\n ) => unknown | Promise<unknown>\n },\n): (() => void) => {\n const send = (reply: ExchangeReply): 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 } = parsed as { id?: unknown; cursor?: unknown; pending?: unknown }\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 ) {\n send({ id, error: 'Invalid exchange frame' })\n return\n }\n const frame: ExchangeFrame = { id, cursor, pending: pending as ReadonlyArray<Operation> }\n void (async () => {\n try {\n const result = await options.exchange(frame.cursor, frame.pending)\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 stopClose = socket.onClose(() => stopMessage())\n return () => {\n stopMessage()\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\nexport interface SocketOptions {\n readonly url: string\n /** Injectable for tests; defaults to the platform `WebSocket`. */\n readonly makeSocket?: ((url: string) => SocketLike) | undefined\n /** Reconnect attempts after a close before queued work fails. Default 5. */\n readonly maxRetries?: number | undefined\n /** Base delay of the exponential reconnect backoff. Default `50 millis`. */\n readonly retryBase?: 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 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. Once the retries are exhausted (or the layer closes) queued work fails\n * with a `TransportError`; a queue over `maxQueue` fails new exchanges with\n * backpressure. The socket is released when the layer's scope ends.\n */\nexport const layerSocket = (options: SocketOptions): Layer.Layer<Transport, TransportError> =>\n Layer.effect(\n Transport,\n Effect.fn('Transport.layerSocket')(function* () {\n const makeSocket = options.makeSocket ?? nativeSocket\n const maxQueue = options.maxQueue ?? 64\n const retry = Schedule.exponential(options.retryBase ?? '50 millis').pipe(\n Schedule.jittered,\n Schedule.upTo({ times: options.maxRetries ?? 5 }),\n )\n\n interface Entry {\n readonly id: string\n readonly cursor: number\n readonly pending: ReadonlyArray<Operation>\n readonly resume: (effect: Effect.Effect<unknown, TransportError>) => void\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 // Once the reconnect schedule is exhausted there is no fiber left to\n // service the queue, so the transport is terminal until the layer is\n // recreated; a later exchange fails with this rather than waiting forever.\n let terminalError: TransportError | undefined\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 } 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(options.url)\n socket = next\n ready = next.onOpen === undefined\n const offOpen = next.onOpen?.(() => {\n ready = true\n flush()\n })\n const offMessage = next.onMessage(data => {\n let reply: ExchangeReply\n try {\n reply = JSON.parse(data) as ExchangeReply\n } catch {\n return\n }\n const entry = inFlight.get(reply.id)\n if (entry === undefined) return\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 // Keep every unanswered frame for the next connection.\n requeue()\n reject(new Error('transport closed'))\n })\n if (ready) flush()\n }),\n catch: () => new TransportError({ message: 'transport closed' }),\n })\n\n yield* Effect.forkScoped(\n connect.pipe(\n Effect.retry(retry),\n Effect.catch(error =>\n Effect.sync(() => {\n if (disposed) return\n terminalError = error\n failAll(error.message)\n }),\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 return Transport.of({\n exchange: (cursor, pending) =>\n Effect.callback<unknown, TransportError>(resume => {\n if (disposed) {\n resume(Effect.fail(new TransportError({ message: 'transport closed' })))\n return\n }\n if (terminalError !== undefined) {\n resume(Effect.fail(terminalError))\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, 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 })(),\n )\n","import { Effect, Exit, Metric, PubSub, Queue, Ref, Schema, Stream, SynchronizedRef } from 'effect'\nimport {\n CheckpointRegressionError,\n CommittedOrderError,\n ForeignAcknowledgementError,\n ForeignRejectionError,\n InvalidExchangeError,\n InvalidOutboxError,\n InvalidReplicaHistoryError,\n ReplayError,\n ReplicaClosedError,\n UnsupportedReplicaVersionError,\n WrongReplicaStorageError,\n type ReplicaError,\n} from './errors.js'\nimport type { Storage } from './indexedDb.js'\nimport {\n DocumentId,\n LocalSequence,\n OpId,\n ReplicaId,\n Sequence,\n localSequence,\n sequence,\n} from './ids.js'\nimport { Transport, TransportError } from './transport.js'\n\n/** Wire and persisted-format versions. A bump must handle the older value explicitly. */\nconst PROTOCOL_VERSION = 1\nconst SCHEMA_VERSION = 1\n\n/** A client-authored operation envelope. `message` is the application's encoded Message. */\nconst OperationSchema = Schema.Struct({\n protocolVersion: Schema.Literal(PROTOCOL_VERSION),\n schemaVersion: Schema.Literal(SCHEMA_VERSION),\n documentId: DocumentId,\n replicaId: ReplicaId,\n localSequence: LocalSequence,\n opId: OpId,\n baseCursor: Sequence,\n message: Schema.Unknown,\n})\nexport type Operation = typeof OperationSchema.Type\n\n/** An operation the server committed, with its authoritative order and actor. */\nconst CommittedSchema = Schema.Struct({\n ...OperationSchema.fields,\n serverSequence: Sequence.check(Schema.isGreaterThanOrEqualTo(1)),\n actorId: Schema.NonEmptyString,\n})\n/** Named to avoid colliding with `foldkit-durable`'s `Committed`. */\nexport type CommittedOperation = typeof CommittedSchema.Type\n\nconst decodeOperation = Schema.decodeUnknownSync(OperationSchema, { onExcessProperty: 'error' })\nconst decodeCommitted = Schema.decodeUnknownSync(CommittedSchema, { onExcessProperty: 'error' })\n\n/**\n * How many committed-operation ids a replica retains for duplicate detection.\n * Committed sequences are contiguous and the server enforces `opId`\n * uniqueness, so this is defence in depth; bounding it keeps replica state from\n * growing without limit on a log that is never checkpointed.\n */\nconst COMMITTED_ID_WINDOW = 1024\n\n/** Counters and a histogram an application can scrape. */\nexport const syncMetrics = {\n exchanges: Metric.counter('foldkit_sync_exchanges_total'),\n applied: Metric.counter('foldkit_sync_commits_applied_total'),\n checkpoints: Metric.counter('foldkit_sync_checkpoints_adopted_total'),\n exchangePending: Metric.histogram('foldkit_sync_exchange_pending', {\n boundaries: [1, 4, 16, 64, 256, 1024],\n }),\n}\n\nexport interface Checkpoint<Shared> {\n readonly cursor: Sequence\n readonly model: Shared\n}\n\nexport interface Exchange<Shared> {\n /** Server-committed operations as they arrived; validated against `CommittedOperation` on adoption. */\n readonly operations: ReadonlyArray<unknown>\n readonly rejected: ReadonlyArray<OpId>\n /** Sends from the request that are durably committed, so the replica can drop them. */\n readonly acknowledged?: ReadonlyArray<OpId> | undefined\n /** The snapshot a replica predating compaction adopts in place of the log. */\n readonly checkpoint?: Checkpoint<Shared> | undefined\n}\n\nexport interface ReplicaState<Shared> {\n readonly protocolVersion: typeof PROTOCOL_VERSION\n readonly schemaVersion: typeof SCHEMA_VERSION\n readonly documentId: DocumentId\n readonly replicaId: ReplicaId\n readonly revision: number\n readonly nextLocalSequence: LocalSequence\n readonly cursor: Sequence\n readonly committed: Shared\n readonly committedIds: ReadonlyArray<string>\n readonly pending: ReadonlyArray<Operation>\n}\n\n/**\n * What the promise-based edge adapter consumes; the Effect `Transport` service\n * is the primary seam.\n */\nexport interface TransportClient {\n exchange(cursor: Sequence, pending: ReadonlyArray<Operation>): Promise<unknown>\n}\n\n/** A redacted view of a replica's state, for a UI to explain and recover. */\nexport interface ReplicaStatus {\n readonly pending: number\n readonly cursor: Sequence\n /** The last exchange failure, cleared by a successful exchange. */\n readonly lastError: string | undefined\n /** Operations the server refused, most recent first. */\n readonly rejected: ReadonlyArray<OpId>\n}\n\n/**\n * A consistent status and optimistic-shared pair, read from one replica state.\n * `Replica.changes` emits it so a UI can hold a single subscription.\n */\nexport interface ReplicaSnapshot<Shared> {\n readonly status: ReplicaStatus\n readonly shared: Shared\n}\n\nexport interface Replica<Message, Shared> {\n /** The optimistic projection: committed state with pending operations replayed. */\n readonly shared: Effect.Effect<Shared>\n readonly pending: Effect.Effect<ReadonlyArray<Operation>>\n readonly cursor: Effect.Effect<Sequence>\n /**\n * Waiting/recovery information without exposing Messages or the Model. It is a\n * snapshot; `statusChanges` re-emits it after every submit and exchange.\n */\n readonly status: Effect.Effect<ReplicaStatus>\n /** The status, re-emitted after every submit and exchange. */\n readonly statusChanges: Stream.Stream<ReplicaStatus>\n /**\n * The status and the optimistic shared value together, re-emitted after every\n * submit and exchange, so a UI can subscribe once instead of to both.\n */\n readonly changes: Stream.Stream<ReplicaSnapshot<Shared>>\n readonly submit: (message: Message) => Effect.Effect<void, ReplicaError>\n /** Reconciles against the server. The `Transport` service must be provided. */\n readonly synchronize: Effect.Effect<void, ReplicaError | TransportError, Transport>\n /**\n * The exchange loop: exchanges once, then after every `submit`, until the\n * replica closes or the fiber is interrupted. A transport failure is recorded\n * in `status.lastError` and retried on the next wake, so the fiber never\n * fails. Fork it with `Effect.forkScoped` and provide `Transport`.\n */\n readonly start: Effect.Effect<void, never, Transport>\n readonly close: Effect.Effect<void>\n}\n\nexport interface SyncDefinition<Message, Shared, MessageEncoded, SharedEncoded> {\n readonly documentId: DocumentId\n readonly message: Schema.Codec<Message, MessageEncoded, never, never>\n readonly shared: Schema.Codec<Shared, SharedEncoded, never, never>\n readonly empty: Shared\n readonly durable: (message: Message) => boolean\n readonly replay: (shared: Shared, message: Message) => Shared\n}\n\nexport interface Sync<Message, Shared> {\n readonly documentId: DocumentId\n /**\n * Low-level wire codecs for adapters and the transport. Most applications use\n * `journalContract` and `openReplica`; these are exposed for a custom\n * transport or a server that must speak the operation envelope directly.\n */\n readonly codec: {\n readonly normalizeOperation: (input: unknown) => Operation\n readonly operationFrom: (input: unknown, documentId: DocumentId) => Operation\n readonly committedFrom: (input: unknown, documentId: DocumentId) => CommittedOperation\n readonly decodeExchange: (input: unknown) => Exchange<Shared>\n }\n /** The codecs and pure reducer `foldkit-durable`'s `makeJournal` consumes. */\n readonly journalContract: () => JournalContract<Operation, Shared>\n readonly openReplica: (\n replicaId: ReplicaId,\n storage: Storage,\n ) => Effect.Effect<Replica<Message, Shared>, ReplicaError>\n}\n\n/** Structural match for `foldkit-durable`'s journal options; Sync stays independent. */\nexport interface JournalContract<Operation, Shared> {\n readonly operation: {\n /** Operations are stored in their encoded form, so this is the identity. */\n readonly encode: (operation: Operation) => Operation\n readonly decode: (input: unknown) => Operation\n }\n readonly snapshot: {\n readonly encode: (snapshot: Shared) => unknown\n readonly decode: (input: unknown) => Shared\n }\n readonly empty: () => Shared\n readonly reduce: (snapshot: Shared, operation: Operation) => Shared\n}\n\n/**\n * Binds the replicated-state protocol to one application contract.\n *\n * The returned codecs decide what is a valid operation and what the shared\n * projection means; the replica owns the local outbox, optimistic projection,\n * and reconciliation as Effects, and never runs a second reducer.\n */\nexport const defineSync = <Message, Shared, MessageEncoded, SharedEncoded>(\n definition: SyncDefinition<Message, Shared, MessageEncoded, SharedEncoded>,\n): Sync<Message, Shared> => {\n const documentId = definition.documentId\n const decodeMessage = Schema.decodeUnknownSync(definition.message, { onExcessProperty: 'error' })\n const encodeMessage = Schema.encodeSync(definition.message)\n const decodeShared = Schema.decodeUnknownSync(definition.shared, { onExcessProperty: 'error' })\n const encodeShared = Schema.encodeSync(definition.shared)\n\n const ReplicaStateSchema = Schema.Struct({\n protocolVersion: Schema.Literal(PROTOCOL_VERSION),\n schemaVersion: Schema.Literal(SCHEMA_VERSION),\n documentId: DocumentId,\n replicaId: ReplicaId,\n revision: Schema.Number,\n nextLocalSequence: LocalSequence,\n cursor: Sequence,\n committed: definition.shared,\n committedIds: Schema.Array(Schema.String),\n pending: Schema.Array(OperationSchema),\n })\n const CheckpointSchema = Schema.Struct({ cursor: Sequence, model: definition.shared })\n const ExchangeSchema = Schema.Struct({\n operations: Schema.Array(Schema.Unknown),\n rejected: Schema.Array(OpId),\n acknowledged: Schema.optional(Schema.Array(OpId)),\n checkpoint: Schema.optional(CheckpointSchema),\n })\n const decodeState = Schema.decodeUnknownSync(ReplicaStateSchema, { onExcessProperty: 'error' })\n const encodeState = Schema.encodeSync(ReplicaStateSchema)\n const VersionProbe = Schema.Struct({\n protocolVersion: Schema.optional(Schema.Number),\n schemaVersion: Schema.optional(Schema.Number),\n })\n /**\n * Tells a version this build does not understand apart from malformed data,\n * so the caller gets an actionable failure and the stored state is preserved.\n */\n const unsupportedVersion = (input: unknown): UnsupportedReplicaVersionError | undefined => {\n let found: {\n readonly protocolVersion?: number | undefined\n readonly schemaVersion?: number | undefined\n }\n try {\n found = Schema.decodeUnknownSync(VersionProbe)(input)\n } catch {\n return undefined\n }\n if (found.protocolVersion === PROTOCOL_VERSION && found.schemaVersion === SCHEMA_VERSION)\n return undefined\n const protocolVersion = found.protocolVersion ?? null\n const schemaVersion = found.schemaVersion ?? null\n return new UnsupportedReplicaVersionError({\n protocolVersion,\n schemaVersion,\n message: `Stored replica uses protocol ${protocolVersion ?? '?'} / schema ${schemaVersion ?? '?'}; this build supports ${PROTOCOL_VERSION}/${SCHEMA_VERSION}`,\n })\n }\n const decodeExchange = (input: unknown): Exchange<Shared> =>\n Schema.decodeUnknownSync(ExchangeSchema, { onExcessProperty: 'error' })(\n input,\n ) as Exchange<Shared>\n\n const checkIdentity = (operation: Operation): void => {\n // `LocalSequence` already rejects a non-positive counter; this checks the\n // derived identity.\n if (operation.opId !== `${operation.replicaId}:${operation.localSequence}`) {\n throw new Error('Invalid operation identity')\n }\n }\n const decodeDurable = (message: unknown): Message => {\n const decoded = decodeMessage(message)\n if (!definition.durable(decoded)) throw new Error('Message is local-only')\n return decoded\n }\n const shape = <O extends Operation>(operation: O): O => {\n checkIdentity(operation)\n return { ...operation, message: encodeMessage(decodeDurable(operation.message)) }\n }\n const assertDocument = <O extends Operation>(operation: O, key: DocumentId): O => {\n if (operation.documentId !== key) throw new Error('Wrong document')\n return operation\n }\n const normalizeOperation = (input: unknown): Operation => shape(decodeOperation(input))\n const operationFrom = (input: unknown, key: DocumentId): Operation =>\n assertDocument(normalizeOperation(input), key)\n /**\n * A committed operation arrives with its message already encoded, so decode it\n * once for the contract check and hand it to `replay` instead of decoding and\n * re-encoding it on the way through `shape`.\n */\n const decodeCommittedOperation = (\n input: unknown,\n key: DocumentId,\n ): { readonly committed: CommittedOperation; readonly message: Message } => {\n const committed = assertDocument(decodeCommitted(input), key)\n checkIdentity(committed)\n return { committed, message: decodeDurable(committed.message) }\n }\n const committedFrom = (input: unknown, key: DocumentId): CommittedOperation =>\n decodeCommittedOperation(input, key).committed\n\n const journalContract = (): JournalContract<Operation, Shared> => ({\n // Operations are stored in their encoded form: `normalizeOperation` has\n // already encoded the Message and validated the identity.\n operation: { encode: operation => operation, decode: normalizeOperation },\n snapshot: { encode: encodeShared, decode: decodeShared },\n empty: () => definition.empty,\n reduce: (snapshot, operation) => definition.replay(snapshot, decodeMessage(operation.message)),\n })\n\n const optimistic = (state: ReplicaState<Shared>): Shared =>\n state.pending.reduce(\n (model, operation) => definition.replay(model, decodeMessage(operation.message)),\n state.committed,\n )\n\n const openReplica = Effect.fn('Sync.openReplica')(\n function* (replicaId: ReplicaId, storage: Storage) {\n yield* Effect.annotateCurrentSpan({ documentId, replicaId })\n const saved = yield* storage.load()\n const initial: ReplicaState<Shared> = {\n protocolVersion: PROTOCOL_VERSION,\n schemaVersion: SCHEMA_VERSION,\n documentId,\n replicaId,\n revision: 0,\n nextLocalSequence: localSequence(1),\n cursor: sequence(0),\n committed: definition.empty,\n committedIds: [],\n pending: [],\n }\n const state: ReplicaState<Shared> =\n saved === undefined\n ? initial\n : yield* Effect.try({\n try: () => decodeState(saved),\n catch: cause =>\n unsupportedVersion(saved) ??\n new InvalidReplicaHistoryError({\n message: 'Stored replica state is invalid',\n cause,\n }),\n })\n if (state.documentId !== documentId || state.replicaId !== replicaId)\n return yield* new WrongReplicaStorageError({\n documentId,\n replicaId,\n message: 'The stored replica belongs to a different document or replica',\n })\n const committedIds = new Set(state.committedIds)\n if (state.nextLocalSequence < 1 || committedIds.size !== state.committedIds.length)\n return yield* new InvalidReplicaHistoryError({ message: 'Invalid replica history' })\n const pendingIds = new Set<string>()\n for (const pending of state.pending) {\n const operation = yield* Effect.try({\n try: () => operationFrom(pending, documentId),\n catch: () => new InvalidOutboxError({ message: 'Invalid outbox' }),\n })\n if (\n operation.replicaId !== replicaId ||\n operation.localSequence >= state.nextLocalSequence ||\n committedIds.has(operation.opId) ||\n pendingIds.has(operation.opId)\n )\n return yield* new InvalidOutboxError({ message: 'Invalid outbox' })\n pendingIds.add(operation.opId)\n }\n // Storage holds the schema's encoded side, so a transforming `shared`\n // codec round-trips: decode on load, encode before every save. Encoding\n // also rejects an invalid `empty` on first creation rather than at reload.\n const store = Effect.fn('Sync.store')(function* (\n next: ReplicaState<Shared>,\n expectedRevision: number | null,\n ) {\n const encoded = yield* Effect.try({\n try: () => encodeState(next),\n catch: cause =>\n new InvalidReplicaHistoryError({\n message: 'Could not encode the replica state',\n cause,\n }),\n })\n yield* storage.save(encoded, expectedRevision)\n })\n if (saved === undefined) yield* store(state, null)\n\n const stateRef = yield* SynchronizedRef.make(state)\n const closed = yield* Ref.make(false)\n const lastError = yield* Ref.make<string | undefined>(undefined)\n const rejectedOps = yield* Ref.make<ReadonlyArray<OpId>>([])\n // One pending wake-up is enough: the loop exchanges the whole outbox.\n const wake = yield* Queue.sliding<void>(1)\n const statusSignals = yield* PubSub.sliding<void>(1)\n // The projection is pure over an immutable state, so a cached value is\n // reused until a write replaces the state object. A UI reads `shared` far\n // more often than it writes, and replaying a large outbox per read is\n // quadratic (see `bench/projection.bench.ts`).\n const projection = yield* Ref.make<\n { readonly state: ReplicaState<Shared>; readonly shared: Shared } | undefined\n >(undefined)\n const snapshot = Effect.fn('Sync.snapshot')(function* () {\n const current = yield* SynchronizedRef.get(stateRef)\n const cached = yield* Ref.get(projection)\n let projected: Shared\n if (cached !== undefined && cached.state === current) projected = cached.shared\n else {\n projected = optimistic(current)\n yield* Ref.set(projection, { state: current, shared: projected })\n }\n return {\n status: {\n pending: current.pending.length,\n cursor: current.cursor,\n lastError: yield* Ref.get(lastError),\n rejected: yield* Ref.get(rejectedOps),\n },\n shared: projected,\n }\n })()\n const shared = Effect.map(snapshot, value => value.shared)\n const status = Effect.map(snapshot, value => value.status)\n\n // `SynchronizedRef.modifyEffect` installs the returned state itself, so\n // persisting must not also set the ref (that would re-enter the lock).\n const persist = (next: ReplicaState<Shared>, current: ReplicaState<Shared>) =>\n store(next, current.revision)\n\n const submit = Effect.fn('Sync.submit')(function* (message: Message) {\n yield* Effect.annotateCurrentSpan({ documentId, replicaId })\n const result = yield* SynchronizedRef.modifyEffect(stateRef, current =>\n Effect.gen(function* () {\n if (yield* Ref.get(closed))\n return yield* new ReplicaClosedError({ message: 'Replica is closed' })\n const operation = yield* Effect.try({\n try: () =>\n operationFrom(\n {\n protocolVersion: PROTOCOL_VERSION,\n schemaVersion: SCHEMA_VERSION,\n documentId,\n replicaId,\n localSequence: current.nextLocalSequence,\n opId: `${replicaId}:${current.nextLocalSequence}`,\n baseCursor: current.cursor,\n message: encodeMessage(message),\n },\n documentId,\n ),\n catch: () => new InvalidOutboxError({ message: 'Invalid outbox' }),\n })\n // Replay before writing: a Message replay refuses can never be\n // applied, here or on another replica, so it must not reach the\n // outbox. The result is the next optimistic projection, so the\n // cache is seeded instead of replaying the outbox on the next read.\n // Rebuilding the projection replays the outbox, which can throw\n // too (an upgrade that changed `update` for a pending Message), so\n // it sits inside the same typed error as the new Message's replay.\n const cached = yield* Ref.get(projection)\n const replayed = yield* Effect.try({\n try: () =>\n definition.replay(\n cached !== undefined && cached.state === current\n ? cached.shared\n : optimistic(current),\n message,\n ),\n catch: cause =>\n new ReplayError({\n message: cause instanceof Error ? cause.message : 'Replay failed',\n cause,\n }),\n })\n // Validated and encoded by `persist`; decoding here would demand the\n // encoded side and break a transforming `shared` codec.\n const next: ReplicaState<Shared> = {\n ...current,\n revision: current.revision + 1,\n nextLocalSequence: localSequence(current.nextLocalSequence + 1),\n pending: [...current.pending, operation],\n }\n yield* persist(next, current)\n yield* Ref.set(projection, { state: next, shared: replayed })\n yield* Queue.offer(wake, undefined)\n return [undefined, next] as const\n }),\n )\n // Outside the lock, so a `statusChanges` subscriber reads the new state.\n yield* PubSub.publish(statusSignals, undefined)\n return result\n })\n\n const synchronize = Effect.fn('Sync.synchronize')(function* () {\n yield* Effect.annotateCurrentSpan({ documentId })\n const transport = yield* Transport\n if (yield* Ref.get(closed))\n return yield* new ReplicaClosedError({ message: 'Replica is closed' })\n const sent = yield* SynchronizedRef.get(stateRef)\n yield* Metric.update(syncMetrics.exchanges, 1)\n yield* Metric.update(syncMetrics.exchangePending, sent.pending.length)\n const response = yield* Effect.gen(function* () {\n const raw = yield* transport.exchange(sent.cursor, sent.pending)\n // The response is untrusted: a malformed shape is a typed failure, not\n // a defect that escapes the declared error channel.\n return yield* Effect.try({\n try: () => decodeExchange(raw),\n catch: cause =>\n new InvalidExchangeError({ message: 'Invalid sync exchange response', cause }),\n })\n }).pipe(\n Effect.tapError(error =>\n Effect.gen(function* () {\n yield* Effect.logWarning('sync exchange failed', {\n documentId,\n replicaId,\n error: error.message,\n })\n yield* Ref.set(lastError, error.message)\n }),\n ),\n )\n yield* SynchronizedRef.modifyEffect(stateRef, current =>\n Effect.gen(function* () {\n // A `close` during the exchange must not persist its result.\n if (yield* Ref.get(closed))\n return yield* new ReplicaClosedError({ message: 'Replica is closed' })\n let cursor = current.cursor\n let committed = current.committed\n // A checkpoint folds committed history into its snapshot, so the\n // retained id set starts over from it.\n const ids =\n response.checkpoint === undefined ? new Set(current.committedIds) : new Set<string>()\n if (response.checkpoint !== undefined) {\n if (response.checkpoint.cursor < cursor)\n return yield* new CheckpointRegressionError({\n cursor,\n checkpointCursor: response.checkpoint.cursor,\n message: 'Checkpoint is behind the replica',\n })\n committed = response.checkpoint.model\n cursor = response.checkpoint.cursor\n yield* Metric.update(syncMetrics.checkpoints, 1)\n yield* Effect.logDebug('sync checkpoint adopted', { documentId, replicaId, cursor })\n }\n const acknowledged = new Set(response.acknowledged ?? [])\n const rejected = new Set(response.rejected)\n const sentIds = new Set(sent.pending.map(operation => operation.opId))\n for (const id of acknowledged)\n if (!sentIds.has(id))\n return yield* new ForeignAcknowledgementError({\n opId: id,\n message: 'Server acknowledged an operation that was not sent',\n })\n for (const id of rejected) {\n if (!sentIds.has(id))\n return yield* new ForeignRejectionError({\n opId: id,\n message: 'Server rejected an operation that was not sent',\n })\n // An id cannot be both; removal would be ambiguous and a faulty\n // server must not be able to make a pending operation vanish.\n if (acknowledged.has(id))\n return yield* new ForeignAcknowledgementError({\n opId: id,\n message: 'Server both acknowledged and rejected an operation',\n })\n }\n let applied = 0\n for (const raw of response.operations) {\n const { committed: operation, message } = yield* Effect.try({\n try: () => decodeCommittedOperation(raw, documentId),\n catch: cause =>\n new InvalidReplicaHistoryError({ message: 'Invalid committed operation', cause }),\n })\n if (operation.serverSequence <= cursor) continue\n if (operation.serverSequence !== cursor + 1 || ids.has(operation.opId))\n return yield* new CommittedOrderError({\n expected: cursor + 1,\n actual: operation.serverSequence,\n message: 'Invalid committed order',\n })\n committed = definition.replay(committed, message)\n ids.add(operation.opId)\n cursor = operation.serverSequence\n applied += 1\n }\n if (applied > 0) yield* Metric.update(syncMetrics.applied, applied)\n // Validated and encoded by `persist`, for the same reason as submit.\n const next: ReplicaState<Shared> = {\n ...current,\n revision: current.revision + 1,\n committed,\n cursor,\n committedIds: [...ids].slice(-COMMITTED_ID_WINDOW),\n pending: current.pending.filter(\n operation =>\n !ids.has(operation.opId) &&\n !acknowledged.has(operation.opId) &&\n !rejected.has(operation.opId),\n ),\n }\n yield* persist(next, current)\n return [undefined, next] as const\n }),\n )\n yield* Ref.set(lastError, undefined)\n if (response.rejected.length > 0)\n yield* Ref.update(rejectedOps, previous =>\n [...response.rejected, ...previous].slice(0, 32),\n )\n yield* PubSub.publish(statusSignals, undefined)\n })()\n\n const start: Effect.Effect<void, never, Transport> = Effect.gen(function* () {\n yield* synchronize.pipe(Effect.catch(() => Effect.void))\n while (!(yield* Ref.get(closed))) {\n yield* Queue.take(wake)\n if (yield* Ref.get(closed)) return\n yield* synchronize.pipe(Effect.catch(() => Effect.void))\n }\n })\n\n return {\n shared,\n pending: Effect.map(SynchronizedRef.get(stateRef), state => state.pending),\n cursor: Effect.map(SynchronizedRef.get(stateRef), state => state.cursor),\n status,\n statusChanges: Stream.concat(\n Stream.fromEffect(status),\n Stream.fromPubSub(statusSignals).pipe(Stream.mapEffect(() => status)),\n ),\n changes: Stream.concat(\n Stream.fromEffect(snapshot),\n Stream.fromPubSub(statusSignals).pipe(Stream.mapEffect(() => snapshot)),\n ),\n submit,\n synchronize,\n start,\n close: Effect.fn('Sync.close')(function* () {\n yield* Ref.set(closed, true)\n // Wake `start` so it can observe `closed` and return.\n yield* Queue.offer(wake, undefined)\n yield* storage.close\n })(),\n }\n },\n (effect, _replicaId, storage) =>\n // Close a partially initialized storage on any failure, including a\n // defect, so a failed open cannot leak the connection.\n effect.pipe(\n Effect.onExit(exit =>\n Exit.isSuccess(exit) ? Effect.void : storage.close.pipe(Effect.ignore),\n ),\n ),\n )\n\n return {\n documentId,\n codec: { normalizeOperation, operationFrom, committedFrom, decodeExchange },\n journalContract,\n openReplica,\n }\n}\n","/**\n * The Foldkit-facing sync layer: `Sync.forApplication(App).make(config)`\n * compiles an application, a writable projection, and a durable Message subset\n * into the low-level `defineSync` contract, and exposes a read-only Surface over\n * the same projection.\n */\nimport { Schema } from 'effect'\nimport {\n MessageSet,\n Projection,\n Surface,\n type AppScope,\n type Contract,\n type MergeConstructors,\n type MergeFields,\n type RunnableApplication,\n type WritableProjection,\n} from 'foldkit-surface'\nimport type { DocumentId } from './ids.js'\nimport { defineSync, type JournalContract, type Operation, type Sync } from './sync.js'\n\ntype MessageConstructor<Message> = (...args: never[]) => Message\n\n/** The Message union a tuple of constructors produces. */\nexport type MsgOf<Ms extends readonly unknown[]> = Ms[number] extends (...args: never[]) => infer M\n ? M\n : never\n\ntype AppMessage<\n AppModel,\n F extends Schema.Struct.Fields,\n Cases extends Record<string, Schema.Struct.Fields>,\n> = Schema.Schema.Type<AppScope<AppModel, F, Cases>['Message']>\n\n/** Reads the tag off a Foldkit Message constructor without constructing one. */\nconst messageTag = (constructor: unknown): string | undefined => {\n const literal = (constructor as { fields?: { _tag?: { ast?: { literal?: unknown } } } }).fields\n ?._tag?.ast?.literal\n return typeof literal === 'string' ? literal : undefined\n}\n\n/** The `_tag` literal of the Message a constructor produces. */\ntype TagOf<C> = C extends (...args: never[]) => infer M\n ? M extends { readonly _tag: infer T extends string }\n ? T\n : never\n : never\n\n/**\n * A journal contract that also carries the declared authorization policy, in\n * the shape `makeJournal` takes, so `makeJournal({ ...contract })` applies it.\n */\nexport interface PolicyJournalContract<Operation, Shared, Principal> extends JournalContract<\n Operation,\n Shared\n> {\n readonly authorize?: (request: {\n readonly principal: Principal\n readonly operation: Operation\n readonly snapshot: Shared\n }) => boolean\n}\n\n/** What a per-variant `authorize` rule sees before the journal commits. */\nexport interface AuthorizeRequest<Principal, Message, Shared> {\n readonly principal: Principal\n readonly message: Message\n readonly shared: Shared\n}\n\n/**\n * Per-variant policy, keyed by durable tag: `message` is that variant exactly,\n * `shared` the authoritative snapshot. A variant without a rule is allowed; the\n * server may still refuse on its own grounds.\n */\nexport type AuthorizePolicy<\n Principal,\n Fields extends Schema.Struct.Fields,\n Ms extends readonly unknown[],\n> = {\n readonly [K in TagOf<Ms[number]>]?: (\n request: AuthorizeRequest<\n Principal,\n Extract<MsgOf<Ms>, { readonly _tag: K }>,\n Schema.Struct.Type<Fields>\n >,\n ) => boolean\n}\n\ninterface BaseOptions<\n Principal,\n Fields extends Schema.Struct.Fields,\n Ms extends readonly unknown[],\n> {\n readonly documentId: DocumentId\n /** Name for the generated `surface`; defaults to the document id. */\n readonly name?: string\n /**\n * Replaces the replay derived from the application's `update`. It is a pure\n * reducer over the shared subset; only durable Messages reach it, and it runs\n * during admission, replay, and optimistic projection. It is not guarded: the\n * author owns its agreement with `update`.\n */\n readonly replay?: (\n shared: Schema.Struct.Type<NoInfer<Fields>>,\n message: MsgOf<NoInfer<Ms>>,\n ) => Schema.Struct.Type<NoInfer<Fields>>\n /** Authorization the server journal applies before committing; see `AuthorizePolicy`. */\n readonly authorize?: AuthorizePolicy<Principal, NoInfer<Fields>, NoInfer<Ms>>\n}\n\nexport interface MakeOptions<\n AppModel,\n Fields extends Schema.Struct.Fields,\n Subset,\n Ms extends readonly MessageConstructor<any>[],\n Principal = unknown,\n> extends BaseOptions<Principal, Fields, Ms> {\n /** The writable projection of the shared fields. */\n readonly shared: WritableProjection<AppModel, Fields>\n /** The Message subset the replica durably records and replays. */\n readonly durable: MessageSet<AppModel, any, Subset, Ms>\n}\n\n/**\n * One feature's contribution to a document: the fields it shares and the\n * Messages it records. `compose` merges fragments into one, to spread into\n * `make`; a field declared twice with a different codec or a tag declared twice\n * is rejected there.\n */\nexport interface SyncFragment<\n AppModel,\n Fields extends Schema.Struct.Fields,\n Subset,\n Ms extends readonly MessageConstructor<any>[],\n> {\n readonly shared: WritableProjection<AppModel, Fields>\n readonly durable: MessageSet<AppModel, any, Subset, Ms>\n}\n\ntype SharedOf<Fs extends readonly SyncFragment<any, any, any, any>[]> = {\n readonly [K in keyof Fs]: Fs[K]['shared']\n}\ntype DurableOf<Fs extends readonly SyncFragment<any, any, any, any>[]> = {\n readonly [K in keyof Fs]: Fs[K]['durable']\n}\n/** The merged shared fields of several fragments. */\nexport type FragmentFields<Fs extends readonly SyncFragment<any, any, any, any>[]> = MergeFields<\n SharedOf<Fs>\n>\n/** The concatenated durable constructors of several fragments. */\nexport type FragmentConstructors<Fs extends readonly SyncFragment<any, any, any, any>[]> =\n MergeConstructors<DurableOf<Fs>>\n\n/** The union of Messages several fragments record. */\nexport type FragmentMessages<Fs extends readonly SyncFragment<any, any, any, any>[]> =\n Fs[number] extends SyncFragment<any, any, infer V, any> ? V : never\n\n/**\n * The value `make` returns: the low-level `Sync` protocol plus the writable\n * projection, the declared Messages, and a read-only Surface over the\n * projection. Exported so a consumer can name the type.\n */\nexport interface DefinedSync<\n AppModel,\n Fields extends Schema.Struct.Fields,\n Message,\n Ms extends readonly unknown[],\n Principal = unknown,\n> extends Sync<Message, Schema.Struct.Type<Fields>> {\n readonly surface: Surface<AppModel, Schema.Struct.Type<Fields>, MsgOf<Ms>, void>\n readonly projection: WritableProjection<AppModel, Fields>\n readonly messages: Ms\n /** For `Module`: this contract owns the shared projection's paths and records the durable tags. */\n readonly contract: Contract\n /** The durable journal's codecs, reducer, and, when declared, authorization. */\n readonly journalContract: () => PolicyJournalContract<\n Operation,\n Schema.Struct.Type<Fields>,\n Principal\n >\n}\n\n/** The sync constructors specialized to one application. */\nexport interface ApplicationSync<\n AppModel,\n F extends Schema.Struct.Fields,\n Cases extends Record<string, Schema.Struct.Fields>,\n Principal = unknown,\n> {\n /**\n * Fixes the `Principal` that `authorize` rules see. A `Principal` cannot be a\n * positional type argument beside an inferred Model, so it is supplied here:\n * `Sync.forApplication(App).withPrincipal<User>()`. Type-only.\n */\n readonly withPrincipal: <P>() => ApplicationSync<AppModel, F, Cases, P>\n /** One feature's shared fields and durable Messages, for `compose`. */\n readonly fragment: <\n Fields extends Schema.Struct.Fields,\n Subset,\n Ms extends readonly MessageConstructor<AppMessage<AppModel, F, Cases>>[],\n >(config: {\n readonly shared: WritableProjection<AppModel, Fields>\n readonly durable: MessageSet<AppModel, any, Subset, Ms>\n }) => SyncFragment<AppModel, Fields, Subset, Ms>\n /**\n * Merges fragments into one: `make({ documentId, ...compose(Todos, Members) })`.\n * A field declared twice with a different codec, a tag declared twice, or a\n * fragment from another application throws.\n */\n readonly compose: <const Fs extends readonly SyncFragment<AppModel, any, any, any>[]>(\n ...fragments: Fs\n ) => SyncFragment<AppModel, FragmentFields<Fs>, FragmentMessages<Fs>, FragmentConstructors<Fs>>\n readonly make: <\n Fields extends Schema.Struct.Fields,\n Subset,\n Ms extends readonly MessageConstructor<AppMessage<AppModel, F, Cases>>[],\n >(\n options: MakeOptions<AppModel, Fields, Subset, Ms, Principal>,\n ) => DefinedSync<AppModel, Fields, AppMessage<AppModel, F, Cases>, Ms, Principal>\n}\n\n/**\n * Replay derived from the application's own `update`: install the shared slice\n * into the initial Model, apply the Message, and read the slice back.\n *\n * A durable Message must be a deterministic, state-only transition of the shared\n * projection. Replay refuses one that returns a Command (a live effect cannot be\n * replayed) or that changes a Model field outside the projection (the change\n * would be silently lost), so a Message that needs either stays local and emits\n * a durable fact once the effect settles.\n */\nconst derivedReplay = <\n AppModel,\n F extends Schema.Struct.Fields,\n Cases extends Record<string, Schema.Struct.Fields>,\n Fields extends Schema.Struct.Fields,\n>(\n app: RunnableApplication<AppModel, F, Cases, any>,\n shared: WritableProjection<AppModel, Fields>,\n): ((\n value: Schema.Struct.Type<Fields>,\n message: AppMessage<AppModel, F, Cases>,\n) => Schema.Struct.Type<Fields>) => {\n const { initial, update } = app\n // Per-field equivalences for the fields the projection does not own outright,\n // built once, so a violation names the fields and replay (which runs per\n // pending operation on every optimistic read) does not re-compare the shared\n // slice against itself. A partially shared field is still compared.\n const owned = new Set(shared.dependencies.filter(path => path.length === 1).map(path => path[0]))\n const fields = Object.entries(app.Model.fields)\n .filter(([key]) => !owned.has(key))\n .map(\n ([key, field]) =>\n [key, Schema.toEquivalence(field as unknown as Schema.Schema<unknown>)] as const,\n )\n return (value, message) => {\n const result = update(shared.set(initial, value), message)\n const tag = (message as { readonly _tag?: string })._tag\n if (result.commands !== undefined && result.commands.length > 0)\n throw new Error(\n `Sync.forApplication: durable \"${tag}\" returned ${result.commands.length} Command(s); a durable transition is state-only`,\n )\n const next = shared.get(result.model)\n // Writing the projection back into the baseline reproduces `update`'s\n // result exactly when it touched only shared fields.\n const written = shared.set(initial, next) as Record<string, unknown>\n const actual = result.model as Record<string, unknown>\n const changed = fields.filter(([key, equal]) => !equal(actual[key], written[key]))\n if (changed.length > 0)\n throw new Error(\n `Sync.forApplication: durable \"${tag}\" changed Model fields outside the shared projection: ${changed.map(([key]) => key).join(', ')}`,\n )\n return next\n }\n}\n\n/**\n * Merges fragments into one. The primitives reject a conflicting field, a\n * duplicate tag, and a subset from another application.\n */\nconst composeFragments = (\n fragments: readonly SyncFragment<any, any, any, any>[],\n): SyncFragment<any, any, any, any> => {\n const compose = Projection.compose as (\n ...projections: readonly WritableProjection<any, any>[]\n ) => WritableProjection<any, any>\n const union = MessageSet.union as (\n ...subsets: readonly MessageSet<any, any, any, any>[]\n ) => MessageSet<any, any, any, any>\n return {\n shared: compose(...fragments.map(fragment => fragment.shared)),\n durable: union(...fragments.map(fragment => fragment.durable)),\n }\n}\n\n/**\n * Specializes the sync constructors to a `Surface.application`, so\n * `Sync.forApplication(App).make({ documentId, shared, durable })` derives the\n * shared codec, the initial snapshot, the durable predicate, and replay from\n * the application, and refuses a subset that belongs to another application.\n * `defineSync` remains the protocol primitive when there is no application to\n * derive from.\n */\nexport const forApplication = <\n AppModel,\n F extends Schema.Struct.Fields,\n Cases extends Record<string, Schema.Struct.Fields>,\n>(\n app: RunnableApplication<AppModel, F, Cases, any>,\n): ApplicationSync<AppModel, F, Cases> => build(app)\n\nconst build = <\n AppModel,\n F extends Schema.Struct.Fields,\n Cases extends Record<string, Schema.Struct.Fields>,\n Principal,\n>(\n app: RunnableApplication<AppModel, F, Cases, any>,\n): ApplicationSync<AppModel, F, Cases, Principal> => {\n type Message = AppMessage<AppModel, F, Cases>\n const decodeMessage = Schema.decodeUnknownSync(\n app.Message as unknown as Schema.Codec<Message, unknown>,\n )\n\n const make = (\n options: MakeOptions<AppModel, any, any, any, Principal>,\n ): DefinedSync<AppModel, any, Message, any, Principal> => {\n type Shared = Record<string, unknown>\n const { shared, durable } = options\n\n // Two applications can have structurally identical Message unions, so the\n // types cannot separate them; the owner token can.\n if (durable.owner !== app.owner)\n throw new Error('Sync.make: the durable subset belongs to a different application')\n\n const replay: (value: Shared, message: Message) => Shared =\n options.replay === undefined\n ? derivedReplay(app, shared)\n : // `durable` has already rejected anything outside the declared subset.\n (value, message) => options.replay!(value, message as never)\n const durableTags = new Set(\n (durable.constructors as readonly unknown[])\n .map(messageTag)\n .filter((tag): tag is string => tag !== undefined),\n )\n // `AppScope` does not constrain its schemas' services; a Foldkit Message union\n // and a Struct are pure, so the low-level contract's `never` is satisfied.\n const sync = defineSync<Message, Shared, unknown, unknown>({\n documentId: options.documentId,\n message: app.Message as unknown as Schema.Codec<Message, unknown>,\n shared: shared.schema as unknown as Schema.Codec<Shared, unknown>,\n empty: shared.get(app.initial),\n durable: message => {\n const tag = (message as { readonly _tag?: string })._tag\n return tag !== undefined && durableTags.has(tag)\n },\n replay,\n })\n\n const rules = options.authorize as\n Record<string, (request: AuthorizeRequest<Principal, Message, Shared>) => boolean> | undefined\n const journalContract = (): PolicyJournalContract<Operation, Shared, Principal> => {\n const base = sync.journalContract()\n if (rules === undefined) return base\n return {\n ...base,\n authorize: ({ principal, operation, snapshot }) => {\n const message = decodeMessage(operation.message)\n const rule = rules[(message as { readonly _tag: string })._tag]\n return rule === undefined ? true : rule({ principal, message, shared: snapshot })\n },\n }\n }\n\n const readOnly: Projection<AppModel, Shared> = {\n Model: shared.schema,\n dependencies: shared.dependencies,\n requirements: [],\n connections: [],\n read: shared.get,\n }\n const surface = Surface.make(app, options.name ?? String(options.documentId), {\n model: () => readOnly,\n messages: durable.constructors,\n })\n const contract: Contract = {\n kind: 'sync',\n name: surface.name,\n owner: app.owner,\n owns: shared.dependencies,\n observes: shared.dependencies,\n messages: [...durable.tags],\n requirements: [],\n }\n return {\n ...sync,\n journalContract,\n surface,\n projection: shared,\n messages: durable.constructors,\n contract,\n }\n }\n\n return {\n withPrincipal: <P>() => build<AppModel, F, Cases, P>(app),\n fragment: config => {\n if (config.durable.owner !== app.owner)\n throw new Error('Sync.fragment: the durable subset belongs to a different application')\n return { shared: config.shared, durable: config.durable }\n },\n compose: ((...fragments: readonly SyncFragment<any, any, any, any>[]) =>\n composeFragments(fragments)) as ApplicationSync<AppModel, F, Cases, Principal>['compose'],\n make: make as ApplicationSync<AppModel, F, Cases, Principal>['make'],\n }\n}\n","/**\n * `Sync.mount`: runs a Foldkit application over a replica with one reducer.\n *\n * A durable Message is a state-only, deterministic transition of the shared\n * projection (the derived replay enforces it), so the application's own `update`\n * is applied at once and the Message is persisted afterwards in a Command. The\n * shared slice is re-installed from the replica when an exchange changes it or\n * a persist fails, through one private Message the application never sees.\n */\nimport { Effect, Exit, Layer, Schema, Stream } from 'effect'\nimport type { Document, HtmlBuilder } from 'foldkit/html'\nimport * as Navigation from 'foldkit/navigation'\nimport type { UrlRequest } from 'foldkit/navigation'\nimport * as Port from 'foldkit/port'\nimport * as Runtime from 'foldkit/runtime'\nimport * as Subscription from 'foldkit/subscription'\nimport type { Subscriptions } from 'foldkit/subscription'\nimport type * as Update from 'foldkit/update'\nimport * as Url from 'foldkit/url'\nimport type { RunnableApplication } from 'foldkit-surface'\nimport type { ReplicaError } from './errors.js'\nimport type { DefinedSync } from './make.js'\nimport type { Replica, ReplicaStatus } from './sync.js'\n\nconst REFRESH = 'foldkit-sync/Refresh'\nconst PERSISTED = 'foldkit-sync/Persisted'\nconst FAILED = 'foldkit-sync/PersistenceFailed'\nconst NAVIGATE = 'foldkit-sync/Navigate'\nconst NAVIGATED = 'foldkit-sync/Navigated'\n\ntype Private =\n | { readonly _tag: typeof REFRESH }\n | { readonly _tag: typeof PERSISTED }\n | { readonly _tag: typeof FAILED; readonly error: ReplicaError }\n | { readonly _tag: typeof NAVIGATE; readonly request: UrlRequest }\n | { readonly _tag: typeof NAVIGATED }\n\n/**\n * The URL as part of the application: `onUrlChange` names the Message the\n * runtime sends for the current URL at start and on every navigation (so a\n * `foldkit-mirror` URL mirror reads back in), `init` reduces the URL into the\n * Model before the first render, and `onUrlRequest` names the Message for a\n * link click; omitted, the mount follows the link itself (an internal one is\n * pushed, an external one loaded).\n */\nexport interface MountUrl<Model, Message> {\n readonly init?: ((model: Model, url: Url.Url) => Model) | undefined\n readonly onUrlChange: (url: Url.Url) => Message\n readonly onUrlRequest?: ((request: UrlRequest) => Message) | undefined\n}\n\nexport interface MountOptions<Model, Message, Shared, Resources> {\n /** An open replica of this contract; `mount` does not close it. */\n readonly replica: Replica<Message, Shared>\n /** The element the application renders into; Foldkit requires it to have an `id`. */\n readonly container: HTMLElement\n readonly view: (model: Model, h: HtmlBuilder<Message>) => Document\n readonly subscriptions?: Subscriptions<Model, Message, Resources> | undefined\n readonly resources?: Layer.Layer<Resources> | undefined\n /** Route the URL through the application; without it the mount ignores the URL. */\n readonly url?: MountUrl<Model, Message> | undefined\n /**\n * Reflects a refused or failed persist in the Model, after the durable edit\n * has been reverted. Omitted, the edit is reverted silently.\n */\n readonly onPersistenceFailure?: ((model: Model, error: ReplicaError) => Model) | undefined\n}\n\nexport interface Mounted<Model, Message> {\n /** Sends an application Message through the runtime; the `Exit` reports a decode failure. */\n readonly dispatch: (message: Message) => Exit.Exit<void, unknown>\n /** The Model after the last transition. */\n readonly model: () => Model\n /** Notified after every transition; with `model` and `dispatch`, the host an agent binds to. */\n readonly subscribe: (listener: () => void) => () => void\n /**\n * Every application Message the runtime applies, from any origin, so an\n * agent contract that declares a `completion` can see the Message that\n * finishes its work. The mount's private Messages are not reported.\n */\n readonly observe: (listener: (message: Message) => void) => () => void\n /** Waits for in-flight persists, then disposes the runtime. The replica stays open. */\n readonly dispose: () => Promise<void>\n}\n\n/** Exchanges and rejections change what the replica holds; a submit only echoes a local edit. */\nconst sharedChanged = (previous: ReplicaStatus | undefined, next: ReplicaStatus): boolean =>\n previous === undefined ||\n previous.cursor !== next.cursor ||\n previous.rejected.length !== next.rejected.length ||\n previous.rejected.some((id, index) => id !== next.rejected[index])\n\n/** The application's Message union, as `Surface.application` types it. */\ntype MessageOf<App> =\n App extends RunnableApplication<any, any, any, any> ? Schema.Schema.Type<App['Message']> : never\n\nexport const mount = <\n Model,\n F extends Schema.Struct.Fields,\n Cases extends Record<string, Schema.Struct.Fields>,\n Fields extends Schema.Struct.Fields,\n Ms extends readonly unknown[],\n Resources = never,\n Principal = unknown,\n>(\n app: RunnableApplication<Model, F, Cases, Resources>,\n sync: DefinedSync<\n Model,\n Fields,\n MessageOf<RunnableApplication<Model, F, Cases, Resources>>,\n Ms,\n Principal\n >,\n options: MountOptions<\n Model,\n MessageOf<RunnableApplication<Model, F, Cases, Resources>>,\n Schema.Struct.Type<Fields>,\n Resources\n >,\n): Mounted<Model, MessageOf<RunnableApplication<Model, F, Cases, Resources>>> => {\n // Foldkit reports a missing id only inside the runtime fiber, where nothing\n // renders and nothing is thrown; fail here instead.\n if (options.container.id === '')\n throw new Error('Sync.mount: the container needs an id (`container.id = \"app\"`)')\n type Message = MessageOf<RunnableApplication<Model, F, Cases, Resources>>\n // The application's Messages are tagged structs; the generic cannot say so.\n type Tagged = { readonly _tag: string }\n type RuntimeMessage = (Message & Tagged) | Private\n const { replica } = options\n const durable = new Set(sync.contract.messages)\n const install = (model: Model): Model =>\n sync.projection.set(model, Effect.runSync(replica.shared))\n\n const inFlight = new Set<Promise<void>>()\n let latest: Model = install(app.initial)\n const modelListeners = new Set<() => void>()\n const messageListeners = new Set<(message: Message) => void>()\n\n const update = (\n model: Model,\n message: RuntimeMessage,\n ): Update.Return<Model, RuntimeMessage, Resources> => {\n switch (message._tag) {\n case REFRESH:\n return { model: install(model) }\n case PERSISTED:\n return { model }\n case FAILED: {\n const { error } = message as Extract<Private, { readonly _tag: typeof FAILED }>\n const reverted = install(model)\n return { model: options.onPersistenceFailure?.(reverted, error) ?? reverted }\n }\n case NAVIGATE: {\n // A link the application did not claim: follow it. The runtime then\n // reports the new URL through `onUrlChange`.\n const { request } = message as Extract<Private, { readonly _tag: typeof NAVIGATE }>\n const follow =\n request._tag === 'Internal'\n ? Navigation.pushUrl(Url.toString(request.url))\n : Navigation.load(request.href)\n return {\n model,\n commands: [\n {\n name: 'foldkit-sync/navigate',\n effect: follow.pipe(Effect.as({ _tag: NAVIGATED } as RuntimeMessage)),\n },\n ],\n }\n }\n case NAVIGATED:\n return { model }\n default: {\n for (const listener of messageListeners) listener(message as Message)\n const result = app.update(model, message as Message) as Update.Return<\n Model,\n RuntimeMessage,\n Resources\n >\n if (!durable.has(message._tag)) return result\n const persist = {\n name: 'foldkit-sync/persist',\n effect: Effect.gen(function* () {\n // Tracked so `dispose` can wait instead of interrupting a persist.\n let settle!: () => void\n const done = new Promise<void>(resolve => {\n settle = resolve\n })\n inFlight.add(done)\n const outcome = yield* Effect.result(replica.submit(message as Message))\n inFlight.delete(done)\n settle()\n return outcome._tag === 'Success'\n ? ({ _tag: PERSISTED } as RuntimeMessage)\n : ({ _tag: FAILED, error: outcome.failure } as RuntimeMessage)\n }),\n }\n return { model: result.model, commands: [...(result.commands ?? []), persist] }\n }\n }\n }\n\n const ports = {\n inbound: { message: Port.inbound(app.Message as unknown as Schema.Codec<Message, unknown>) },\n }\n const own = Subscription.make<Model, RuntimeMessage, Resources>()(() => ({\n message: Port.subscription(ports.inbound.message, message => message as RuntimeMessage),\n // The replica's status carries the cursor and rejections, which is exactly\n // when the shared slice held locally can differ from the replica's.\n refresh: Subscription.persistent<RuntimeMessage, Resources>(\n replica.statusChanges.pipe(\n Stream.mapAccum(\n (): ReplicaStatus | undefined => undefined,\n (previous, status): readonly [ReplicaStatus, ReadonlyArray<RuntimeMessage>] => [\n status,\n sharedChanged(previous, status) ? [{ _tag: REFRESH }] : [],\n ],\n ),\n ),\n ),\n // `modelToDependencies` runs on every transition, so it doubles as the Model\n // getter the runtime does not expose.\n latest: {\n dependenciesSchema: Schema.Struct({}),\n modelToDependencies: (model: Model) => {\n latest = model\n for (const listener of modelListeners) listener()\n return {}\n },\n dependenciesToStream: () => Stream.never,\n },\n }))\n const subscriptions =\n options.subscriptions === undefined\n ? own\n : Subscription.aggregate<Model, RuntimeMessage, Resources>()(\n options.subscriptions as Subscriptions<Model, RuntimeMessage, Resources>,\n own,\n )\n\n const view = (model: Model, h: HtmlBuilder<RuntimeMessage>): Document =>\n // Sound: the view constructs only application Messages, a subset of the\n // runtime's union.\n options.view(model, h as unknown as HtmlBuilder<Message>)\n const common = {\n Model: app.Model as unknown as Schema.Codec<Model, any, unknown, unknown>,\n container: options.container,\n ports,\n update,\n subscriptions,\n ...(options.resources === undefined ? {} : { resources: options.resources }),\n view,\n }\n const url = options.url\n const program =\n url === undefined\n ? Runtime.makeApplication({ ...common, init: () => ({ model: latest }) })\n : Runtime.makeApplication({\n ...common,\n routing: {\n onUrlChange: (at: Url.Url) => url.onUrlChange(at) as RuntimeMessage,\n onUrlRequest: (request: UrlRequest): RuntimeMessage =>\n url.onUrlRequest === undefined\n ? { _tag: NAVIGATE, request }\n : (url.onUrlRequest(request) as RuntimeMessage),\n },\n init: (at: Url.Url) => {\n latest = url.init === undefined ? latest : url.init(latest, at)\n return { model: latest }\n },\n })\n const handle = Runtime.embed(program)\n\n return {\n dispatch: message => handle.ports.message.send(message),\n model: () => latest,\n subscribe: listener => {\n modelListeners.add(listener)\n return () => modelListeners.delete(listener)\n },\n observe: listener => {\n messageListeners.add(listener)\n return () => messageListeners.delete(listener)\n },\n dispose: async () => {\n await Promise.all([...inFlight])\n handle.dispose()\n },\n }\n}\n","import { Clock, Duration, Effect, Fiber, PubSub, Ref, Stream, type Scope } from 'effect'\nimport type { SocketLike } from './transport.js'\n\n/** One peer's presence. A `null` value means the peer left. */\nexport interface PresenceUpdate<Update> {\n readonly id: string\n readonly value: Update | null\n}\n\n/**\n * The ephemeral channel presence travels on.\n *\n * `updates` is the inbound bus a peer consumes; `publish` sends one to the bus.\n * Splitting them keeps an inbound update from being echoed straight back out.\n * This is deliberately not the durable transport: presence is broadcast, never\n * journaled, so a dropped or duplicated update is harmless.\n */\nexport interface PresenceChannel<Update> {\n readonly updates: PubSub.PubSub<PresenceUpdate<Update>>\n readonly publish: (update: PresenceUpdate<Update>) => Effect.Effect<void>\n}\n\nexport interface PresenceOptions<Update> {\n /** This peer's identity on the channel. */\n readonly id: string\n /** How long a peer may go without refreshing before it is dropped. */\n readonly ttl: Duration.Input\n /**\n * Validates the untrusted value a peer sends before it is stored. Presence\n * crosses a wire, so this is required rather than trusting the type\n * parameter; a value it rejects is dropped.\n */\n readonly decodeValue: (value: unknown) => Update\n readonly channel?: PresenceChannel<Update> | undefined\n}\n\nexport interface PresencePeer<Update> {\n readonly id: string\n readonly value: Update\n readonly updatedAt: number\n}\n\nexport interface Presence<Update> {\n /** Sets this peer's value and broadcasts it. */\n readonly set: (value: Update) => Effect.Effect<void>\n /** Removes this peer and broadcasts the departure. */\n readonly leave: Effect.Effect<void>\n /** Live peers, self included, with stale ones excluded. */\n readonly peers: Effect.Effect<ReadonlyArray<PresencePeer<Update>>>\n /** Drops expired peers; notifies if any went. */\n readonly prune: Effect.Effect<void>\n /** Notified when the peer set changes. */\n readonly subscribe: (listener: () => void) => () => void\n /**\n * The live peers, re-emitted whenever the set changes. The `Stream` form of\n * `subscribe`, for a consumer that composes with Effect.\n */\n readonly changes: Stream.Stream<ReadonlyArray<PresencePeer<Update>>>\n /** Stops consuming the channel; the enclosing scope also does this on exit. */\n readonly close: Effect.Effect<void>\n}\n\n/**\n * Tracks ephemeral peers with a time-to-live.\n *\n * Nothing here touches the durable log: presence is state a peer refreshes, and\n * a peer that stops refreshing is dropped, not replayed. Time comes from the\n * `Clock`, so a `TestClock` drives the TTL deterministically.\n */\nexport const createPresence = Effect.fn('Presence.create')(function* <Update>(\n options: PresenceOptions<Update>,\n) {\n const ttl = Duration.toMillis(options.ttl)\n const peers = yield* Ref.make(new Map<string, PresencePeer<Update>>())\n const closed = yield* Ref.make(false)\n const signals = yield* PubSub.sliding<void>(1)\n const listeners = new Set<() => void>()\n /** A subscriber must never fail an update. */\n const notify = (): Effect.Effect<void> =>\n Effect.gen(function* () {\n for (const listener of [...listeners]) {\n try {\n listener()\n } catch {\n // Deliberately swallowed.\n }\n }\n yield* PubSub.publish(signals, undefined)\n })\n const expired = (peer: PresencePeer<Update>, at: number): boolean => at - peer.updatedAt > ttl\n\n const put = (id: string, value: Update, at: number): Effect.Effect<void> =>\n Ref.update(peers, map => {\n const next = new Map(map)\n next.set(id, { id, value, updatedAt: at })\n return next\n })\n const remove = (id: string): Effect.Effect<boolean> =>\n Ref.modify(peers, map => {\n if (!map.has(id)) return [false, map] as const\n const next = new Map(map)\n next.delete(id)\n return [true, next] as const\n })\n\n const receive = Effect.fn('Presence.receive')(function* (update: PresenceUpdate<Update>) {\n if (update.id === options.id) return\n if (update.value === null) {\n if (yield* remove(update.id)) yield* notify()\n return\n }\n let value: Update\n try {\n value = options.decodeValue(update.value)\n } catch {\n // A peer's value that fails the contract is dropped, never stored.\n return\n }\n yield* put(update.id, value, yield* Clock.currentTimeMillis)\n yield* notify()\n })\n\n const channel = options.channel\n const consuming =\n channel === undefined\n ? undefined\n : yield* Stream.runForEach(Stream.fromPubSub(channel.updates), receive).pipe(\n Effect.forkScoped,\n )\n\n const set = Effect.fn('Presence.set')(function* (value: Update) {\n if (yield* Ref.get(closed)) return\n yield* put(options.id, value, yield* Clock.currentTimeMillis)\n if (channel !== undefined) yield* channel.publish({ id: options.id, value })\n yield* notify()\n })\n\n const leave = Effect.fn('Presence.leave')(function* () {\n if (yield* Ref.get(closed)) return\n yield* remove(options.id)\n if (channel !== undefined) yield* channel.publish({ id: options.id, value: null })\n yield* notify()\n })()\n\n const peerList = Effect.fn('Presence.peers')(function* () {\n const at = yield* Clock.currentTimeMillis\n const map = yield* Ref.get(peers)\n return [...map.values()].filter(peer => !expired(peer, at)).map(peer => ({ ...peer }))\n })()\n\n const prune = Effect.fn('Presence.prune')(function* () {\n if (yield* Ref.get(closed)) return\n const at = yield* Clock.currentTimeMillis\n const changed = yield* Ref.modify(peers, map => {\n let removed = false\n const next = new Map(map)\n for (const [id, peer] of map) {\n if (expired(peer, at)) {\n next.delete(id)\n removed = true\n }\n }\n return [removed, next] as const\n })\n if (changed) yield* notify()\n })()\n\n const close = Effect.fn('Presence.close')(function* () {\n if (yield* Ref.get(closed)) return\n yield* Ref.set(closed, true)\n if (consuming !== undefined) yield* Fiber.interrupt(consuming)\n yield* Effect.sync(() => listeners.clear())\n yield* PubSub.shutdown(signals)\n })()\n\n return {\n set,\n leave,\n peers: peerList,\n prune,\n subscribe: (listener: () => void) => {\n listeners.add(listener)\n return () => listeners.delete(listener)\n },\n changes: Stream.concat(\n Stream.fromEffect(peerList),\n Stream.fromPubSub(signals).pipe(Stream.mapEffect(() => peerList)),\n ),\n close,\n }\n})\n\n/** An in-process channel, for tests and single-process demos. */\nexport const loopbackPresenceChannel = Effect.fn('Presence.loopbackChannel')(function* <Update>() {\n const updates = yield* PubSub.unbounded<PresenceUpdate<Update>>()\n return {\n updates,\n publish: (update: PresenceUpdate<Update>) => PubSub.publish(updates, update),\n }\n})\n\n/** Broadcasts presence updates among connected peers. */\nexport interface PresenceHub<Update> {\n /** Registers a peer's send; returns a leave function. */\n join(send: (update: PresenceUpdate<Update>) => void): () => void\n /** Fans an update out to every joined peer. */\n publish(update: PresenceUpdate<Update>): void\n}\n\nexport const createPresenceHub = <Update>(): PresenceHub<Update> => {\n const peers = new Set<(update: PresenceUpdate<Update>) => void>()\n return {\n join: send => {\n peers.add(send)\n return () => peers.delete(send)\n },\n publish: update => {\n for (const send of [...peers]) {\n try {\n send(update)\n } catch {\n // One broken peer must not starve the rest of the fan-out.\n }\n }\n },\n }\n}\n\nconst frameType = 'presence'\n\n/** A presence frame. `id` is set by the server that owns the identity. */\ninterface PresenceFrame<Update> {\n readonly id: string | undefined\n readonly value: Update | null\n}\n\n/** Decodes a presence frame, ignoring anything else a socket may carry. */\nconst decodePresence = <Update>(data: string): PresenceFrame<Update> | undefined => {\n let frame: Record<string, unknown>\n try {\n frame = JSON.parse(data) as Record<string, unknown>\n } catch {\n return undefined\n }\n const payload = frame[frameType]\n if (typeof payload !== 'object' || payload === null) return undefined\n const { id, value } = payload as { id?: unknown; value?: unknown }\n return { id: typeof id === 'string' ? id : undefined, value: (value ?? null) as Update | null }\n}\n\n/**\n * A presence channel fed by stamped frames from the server, sent back without an\n * id: the server owns peer identity, so a client cannot assert another's.\n */\nexport const socketPresenceChannel = <Update>(\n socket: SocketLike,\n): Effect.Effect<PresenceChannel<Update>, never, Scope.Scope> =>\n Effect.gen(function* () {\n const updates = yield* PubSub.unbounded<PresenceUpdate<Update>>()\n yield* Effect.acquireRelease(\n Effect.sync(() =>\n socket.onMessage(data => {\n const frame = decodePresence<Update>(data)\n // An unstamped frame is not from the server and carries no identity.\n if (frame === undefined || frame.id === undefined) return\n PubSub.publishUnsafe(updates, { id: frame.id, value: frame.value })\n }),\n ),\n off => Effect.sync(off),\n )\n return {\n updates,\n publish: update =>\n Effect.sync(() => socket.send(JSON.stringify({ [frameType]: { value: update.value } }))),\n }\n })\n\n/** Serves presence frames on an accepted socket, stamping the connection's identity. */\nexport const servePresence = <Update>(\n socket: SocketLike,\n hub: PresenceHub<Update>,\n options: { readonly peerId: string },\n): (() => void) => {\n const send = (update: PresenceUpdate<Update>): void =>\n socket.send(JSON.stringify({ [frameType]: { id: update.id, value: update.value } }))\n const leave = hub.join(send)\n const off = socket.onMessage(data => {\n const frame = decodePresence<Update>(data)\n // The connection owns the identity; a client-supplied id is ignored.\n if (frame !== undefined) hub.publish({ id: options.peerId, value: frame.value })\n })\n return () => {\n off()\n leave()\n }\n}\n","/**\n * `foldkit-sync` — a local-first replica of a shared Foldkit projection.\n *\n * The application's Message union and update function stay authoritative: sync\n * wraps them rather than introducing a second reducer. The replica owns the\n * local outbox, optimistic projection, and reconciliation; a durable server\n * journal provides authoritative order.\n *\n * `Sync` is the namespace: `Sync.forApplication`, `Sync.mount`,\n * `Sync.transport.socket`. Ids are branded schemas, so they construct through\n * `DocumentId.make('todos')`. Every name is also exported on its own.\n */\nimport { indexedDb } from './indexedDb.js'\nimport { lwwRegister, openLwwClock } from './lww.js'\nimport { forApplication } from './make.js'\nimport { mount } from './mount.js'\nimport {\n createPresence,\n createPresenceHub,\n loopbackPresenceChannel,\n servePresence,\n socketPresenceChannel,\n} from './presence.js'\nimport { defineSync, syncMetrics, type Sync as SyncContract } from './sync.js'\nimport {\n layerFromPromise,\n layerLoopback,\n layerSocket,\n nativeSocket,\n serveSocket,\n toPromise,\n} from './transport.js'\n\n/**\n * The contract `Sync.define` and `Sync.forApplication(App).make` produce: the\n * wire codecs, the server journal's contract, and `openReplica`.\n *\n * This is the type; `Sync` is also the value namespace below, the way\n * `Effect.Effect` is both.\n */\nexport type Sync<Message, Shared> = SyncContract<Message, Shared>\n\n/** The package's public surface, grouped. Each entry is the exported function itself. */\nexport const Sync = {\n /** Derives a sync contract from a Foldkit application: `Sync.forApplication(App).make({…})`. */\n forApplication,\n /** The protocol primitive, for a client with no Foldkit application to derive from. */\n define: defineSync,\n /** Runs a Foldkit application over an open replica with one reducer. */\n mount,\n /** Counters and a histogram an application can scrape. */\n metrics: syncMetrics,\n /** The only storage adapter: one IndexedDB database per document/replica. */\n indexedDb,\n\n /** The `Transport` service's layers, and the bridges to and from a promise client. */\n transport: {\n /** A reconnecting WebSocket client layer. */\n socket: layerSocket,\n /** An in-process layer, for tests and single-process demos. */\n loopback: layerLoopback,\n /** Wraps the promise-based client the replica already speaks. */\n fromPromise: layerFromPromise,\n /** Bridges the service back to that promise client. */\n toPromise,\n /** The server side of one accepted socket connection. */\n serve: serveSocket,\n /** The default socket factory: the platform `WebSocket`. */\n nativeSocket,\n },\n\n /** An ephemeral, TTL'd peer registry, deliberately outside the durable log. */\n presence: {\n make: createPresence,\n /** Broadcasts presence updates among connected peers, on the server. */\n hub: createPresenceHub,\n /** Serves presence frames on an accepted socket, stamping the connection's identity. */\n serve: servePresence,\n socketChannel: socketPresenceChannel,\n loopbackChannel: loopbackPresenceChannel,\n },\n\n /** Last-writer-wins registers (experimental): a per-field merge on logical time. */\n lww: {\n register: lwwRegister,\n /** The durable counter a stamp is allocated from, before dispatch. */\n openClock: openLwwClock,\n },\n}\n\nexport { indexedDb, type Storage } from './indexedDb.js'\nexport { mount, type MountOptions, type MountUrl, type Mounted } from './mount.js'\nexport {\n forApplication,\n type ApplicationSync,\n type AuthorizePolicy,\n type AuthorizeRequest,\n type DefinedSync,\n type FragmentMessages,\n type MakeOptions,\n type MsgOf,\n type PolicyJournalContract,\n type SyncFragment,\n} from './make.js'\nexport {\n DocumentId,\n LocalSequence,\n OpId,\n ReplicaId,\n Sequence,\n documentId,\n localSequence,\n opId,\n replicaId,\n sequence,\n} from './ids.js'\nexport {\n CheckpointRegressionError,\n CommittedOrderError,\n ForeignAcknowledgementError,\n ForeignRejectionError,\n InvalidExchangeError,\n InvalidOutboxError,\n InvalidReplicaHistoryError,\n ReplayError,\n ReplicaClosedError,\n StorageError,\n UnsupportedClockVersionError,\n UnsupportedReplicaVersionError,\n WrongReplicaStorageError,\n type ReplicaError,\n} from './errors.js'\nexport { lwwRegister, openLwwClock, type LwwClock, type LwwClockState } from './lww.js'\nexport {\n createPresence,\n createPresenceHub,\n loopbackPresenceChannel,\n servePresence,\n socketPresenceChannel,\n type Presence,\n type PresenceChannel,\n type PresenceHub,\n type PresenceOptions,\n type PresencePeer,\n type PresenceUpdate,\n} from './presence.js'\nexport {\n layerFromPromise,\n layerLoopback,\n layerSocket,\n nativeSocket,\n serveSocket,\n toPromise,\n Transport,\n TransportError,\n type ExchangeFrame,\n type ExchangeReply,\n type SocketLike,\n type SocketOptions,\n type TransportShape,\n} from './transport.js'\nexport {\n defineSync,\n syncMetrics,\n type Checkpoint,\n type CommittedOperation,\n type Exchange,\n type JournalContract,\n type Operation,\n type Replica,\n type ReplicaSnapshot,\n type ReplicaState,\n type ReplicaStatus,\n type SyncDefinition,\n type TransportClient,\n} from './sync.js'\n"],"mappings":";;;;;;;;;AAGA,IAAa,eAAb,cAAkC,OAAO,YAA0B,CAAC,CAAC,gBAAgB;CACnF,SAAS,OAAO;CAChB,OAAO,OAAO,SAAS,OAAO,OAAO;AACvC,CAAC,CAAC,CAAC,CAAC;;AAGJ,IAAa,+BAAb,cAAkD,OAAO,YAA0C,CAAC,CAClG,gCACA;CACE,eAAe,OAAO,OAAO,OAAO,MAAM;CAC1C,SAAS,OAAO;AAClB,CACF,CAAC,C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