foldkit-sync 0.15.0 → 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/README.md +558 -40
  2. package/dist/diagnostics.d.ts +74 -3
  3. package/dist/diagnostics.d.ts.map +1 -1
  4. package/dist/diagnostics.js +60 -4
  5. package/dist/diagnostics.js.map +1 -1
  6. package/dist/do.d.ts +49 -7
  7. package/dist/do.d.ts.map +1 -1
  8. package/dist/do.js +91 -8
  9. package/dist/do.js.map +1 -1
  10. package/dist/errors.d.ts +92 -1
  11. package/dist/errors.d.ts.map +1 -1
  12. package/dist/errors.js +87 -1
  13. package/dist/errors.js.map +1 -1
  14. package/dist/index.d.ts +9 -5
  15. package/dist/index.d.ts.map +1 -1
  16. package/dist/index.js +6 -2
  17. package/dist/index.js.map +1 -1
  18. package/dist/journal.d.ts +52 -27
  19. package/dist/journal.d.ts.map +1 -1
  20. package/dist/journal.js +176 -64
  21. package/dist/journal.js.map +1 -1
  22. package/dist/make.d.ts +48 -17
  23. package/dist/make.d.ts.map +1 -1
  24. package/dist/make.js +11 -4
  25. package/dist/make.js.map +1 -1
  26. package/dist/migrations.d.ts +37 -0
  27. package/dist/migrations.d.ts.map +1 -0
  28. package/dist/migrations.js +56 -0
  29. package/dist/migrations.js.map +1 -0
  30. package/dist/mount.d.ts +1 -1
  31. package/dist/mount.d.ts.map +1 -1
  32. package/dist/mount.js +12 -6
  33. package/dist/mount.js.map +1 -1
  34. package/dist/refusal.d.ts +33 -0
  35. package/dist/refusal.d.ts.map +1 -0
  36. package/dist/refusal.js +47 -0
  37. package/dist/refusal.js.map +1 -0
  38. package/dist/serverJournal.d.ts +143 -0
  39. package/dist/serverJournal.d.ts.map +1 -0
  40. package/dist/serverJournal.js +503 -0
  41. package/dist/serverJournal.js.map +1 -0
  42. package/dist/sync.d.ts +132 -11
  43. package/dist/sync.d.ts.map +1 -1
  44. package/dist/sync.js +273 -64
  45. package/dist/sync.js.map +1 -1
  46. package/dist/transport.d.ts +5 -5
  47. package/dist/transport.d.ts.map +1 -1
  48. package/dist/transport.js.map +1 -1
  49. package/package.json +11 -8
package/dist/mount.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"mount.js","names":[],"sources":["../src/mount.ts"],"sourcesContent":["/**\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, Option, Schema, Stream } from 'effect'\nimport { absurd } from 'effect/Function'\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'\nconst DISPATCHED = 'foldkit-sync/Dispatched'\n\ntype Private =\n // Every replica status, applied in order, so `settled` counts one seen only once `update` has it.\n | { readonly _tag: typeof REFRESH; readonly status: ReplicaStatus; readonly changed: boolean }\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 // An application Message sent through `dispatch`, so `settled` counts it in.\n | { readonly _tag: typeof DISPATCHED; readonly message: unknown }\n\n// A key per private tag, so a variant added to `Private` must be added here too.\nconst PRIVATE: Readonly<Record<Private['_tag'], true>> = {\n [REFRESH]: true,\n [PERSISTED]: true,\n [FAILED]: true,\n [NAVIGATE]: true,\n [NAVIGATED]: true,\n [DISPATCHED]: true,\n}\n\nconst isPrivate = (message: { readonly _tag: string }): message is Private =>\n Object.hasOwn(PRIVATE, message._tag)\n\n// A registered symbol, so two copies of this package in one bundle recognize each other's.\nconst FACT = Symbol.for('foldkit-sync/fact')\n\n/**\n * A Command that dispatches `message` as the next transition, which under `Sync.mount`\n * means within this one: the mount applies it straight after the `update` that returned\n * it, and persists it if it is durable, before any other Message is processed. This is\n * how a local intent turns into a durable fact that needs something only the intent's\n * transition knows, such as an id minted from local state, without a later Message\n * seeing the Model before the fact. Elsewhere, or once a parent has mapped the Command,\n * it is an ordinary Command that yields `message`, and so is one a durable Message's\n * update returns: replay would not apply it, and with derived replay the durable Message's\n * persist fails with `ReplayError` as for any Command.\n */\nexport const fact = <Message>(\n message: Message,\n): { readonly name: string; readonly effect: Effect.Effect<Message> } =>\n // Not enumerable, so the spread a mapping Command is copied with drops the marker, and a\n // mapped fact is the ordinary Command it now is rather than the unmapped Message.\n Object.defineProperty({ name: 'foldkit-sync/fact', effect: Effect.succeed(message) }, FACT, {\n value: message,\n enumerable: false,\n })\n\nconst factOf = (command: unknown): { readonly message: unknown } | undefined =>\n typeof command === 'object' && command !== null && FACT in command\n ? { message: (command as { readonly [FACT]: unknown })[FACT] }\n : undefined\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 * Runs when the mount replaces the shared slice outside `update`: an exchange committed,\n * acknowledged or rejected something, or a persist failed and its edit was reverted.\n * `previous` is the Model before; what it returns is the transition, so an application\n * can carry local state across the change (a selection held by what it points at) or\n * return Commands (a DOM the change has to reach). Omitted, the Model is `next`. It is\n * not called for a status that changes nothing the Model shows, such as the first.\n */\n readonly onReinstall?:\n | ((\n next: Model,\n previous: Model,\n change: Reinstall,\n ) => Update.Return<Model, Message, Resources>)\n | undefined\n /**\n * Runs on the Model after every update of the mounted application, a durable\n * Message's and a reinstall's included, and never in replay: for local state\n * derived from the shared slice, which a durable transition may not write\n * (the overlays `foldkit-sync/remote` keeps in Remote). With nothing to\n * change it returns the Model it was given.\n */\n readonly afterUpdate?: ((model: Model) => Update.Return<Model, Message, Resources>) | undefined\n}\n\n/**\n * What a reinstall came from. `reset` is a server reset: the replica's\n * committed history is a new one, so anything an application derived from\n * the old one (reads cached by commit sequence, say) is to be read again.\n */\nexport interface Reinstall {\n readonly reset: boolean\n}\n\n/**\n * The shared slice as the server has confirmed it, outside the Model. It is a\n * source for waiting consumers, the shape `Agent.when({ source })` reads, and\n * not a Projection: it does not render and is not derived from the Model.\n */\nexport interface CommittedView<Shared> {\n readonly get: () => Shared\n /** Told after every exchange, including one that moves no cursor (a checkpoint). */\n readonly subscribe: (listener: () => void) => () => void\n}\n\nexport interface Mounted<Model, Message, Shared = unknown> {\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 /**\n * The shared slice without pending local edits, for an agent that must not\n * report an optimistic edit as done: `Agent.when({ source: mounted.committed, … })`.\n */\n readonly committed: CommittedView<Shared>\n /**\n * Resolves once the Model has caught up with the replica: no persist in\n * flight or unanswered, every replica status the mount was told of seen,\n * and every reinstall it asked for applied. It observes and never does the\n * work. Frames are not its to wait for (`Frames.track` in\n * `foldkit-mixins/testing` is), nor I/O a Command started. Rejects after\n * `dispose`.\n */\n readonly settled: () => Promise<void>\n /** Waits for in-flight persists, then disposes the runtime. The replica stays open. */\n readonly dispose: () => Promise<void>\n}\n\n/**\n * Commits, rejections and acknowledgments change what the replica holds; a\n * submit only echoes a local edit. An acknowledgment that does not return the\n * operation moves no cursor, but it still drops the edit from the outbox.\n */\nconst sharedChanged = (previous: ReplicaStatus | undefined, next: ReplicaStatus): boolean =>\n previous === undefined ||\n previous.cursor !== next.cursor ||\n next.pending < previous.pending ||\n previous.rejected.length !== next.rejected.length ||\n previous.rejected.some((rejection, index) => rejection.opId !== next.rejected[index]?.opId)\n\n/**\n * A durable edit the Model already shows. `started` is the replica's next local\n * sequence when its submit began, `undefined` while it waits for its turn.\n */\nexport interface LocalEdit<Message> {\n readonly message: Message\n started: number | undefined\n}\n\n/**\n * The edits a replica whose next local sequence is `next` does not hold yet.\n * Submits run one at a time, so the one in flight is in the replica exactly\n * when its submit has moved the sequence past `started`.\n */\nexport const unconfirmedEdits = <Message>(\n edits: ReadonlyArray<LocalEdit<Message>>,\n next: number,\n): ReadonlyArray<Message> =>\n edits.filter(edit => edit.started === undefined || next <= edit.started).map(edit => edit.message)\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<\n Model,\n MessageOf<RunnableApplication<Model, F, Cases, Resources>>,\n Schema.Struct.Type<Fields>\n> => {\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 type Shared = Schema.Struct.Type<Fields>\n const { replica } = options\n const durable = new Set(sync.contract.messages)\n\n // Durable edits whose submit has not settled, in dispatch order.\n const edits: Array<LocalEdit<Message>> = []\n // An edit shows before it is stored, so a reload while one waits would lose\n // what the reader saw: the browser asks first, from the first such edit\n // until the last is stored.\n const holdUnload = (event: Event): void => event.preventDefault()\n const unloadGuarded = (guarded: boolean): void => {\n if (typeof window === 'undefined') return\n if (guarded) window.addEventListener('beforeunload', holdUnload)\n else window.removeEventListener('beforeunload', holdUnload)\n }\n // Settles when the latest edit's submit does; the next submit waits for it.\n let tail: Promise<void> = Promise.resolve()\n\n // The replica's `shared` holds every settled edit, and the one in flight once\n // its submit lands; the rest are replayed on top. Read from one snapshot, so\n // a refresh neither hides an edit still waiting for the replica nor applies\n // one the replica already holds.\n // The replica's shared value the Model was last installed from, and whether a durable\n // edit has changed the Model's copy since. The replica keeps one object per state, so\n // the same object with no edit since is the shared slice the Model already shows.\n let installedFrom: Shared | undefined\n let editedSinceInstall = false\n const install = (model: Model): Model => {\n const snapshot = Effect.runSync(replica.snapshot)\n installedFrom = snapshot.shared\n const unconfirmed = unconfirmedEdits(edits, snapshot.nextLocalSequence)\n // Edits replayed on top leave the Model's copy apart from `installedFrom`.\n editedSinceInstall = unconfirmed.length > 0\n const shared = unconfirmed.reduce<Shared>((value, message) => {\n try {\n return sync.replay(value, message)\n } catch {\n // The replica refuses it too; its FAILED re-installs without it.\n return value\n }\n }, snapshot.shared)\n return sync.projection.set(model, shared)\n }\n\n const inFlight = new Set<Promise<void>>()\n // What `settled` waits on: dispatches and persists not yet answered in\n // `update`, and the last replica status `update` applied.\n let dispatchesOwed = 0\n let persistsOwed = 0\n let applied: ReplicaStatus | undefined\n let disposed = false\n const waiters = new Set<{\n readonly resolve: () => void\n readonly reject: (error: Error) => void\n }>()\n const quiet = (): boolean =>\n dispatchesOwed === 0 &&\n persistsOwed === 0 &&\n !sharedChanged(applied, Effect.runSync(replica.status))\n const notifySettled = (): void => {\n if (!quiet()) return\n for (const waiter of [...waiters]) {\n waiters.delete(waiter)\n waiter.resolve()\n }\n }\n /**\n * A private transition that leaves the Model as it was: the runtime sends\n * no Subscription the change, so `settled` is told here, once it returns.\n */\n const unchanged = (model: Model): Update.Return<Model, RuntimeMessage, Resources> => {\n queueMicrotask(notifySettled)\n return { model }\n }\n let latest: Model = install(app.initial)\n const modelListeners = new Set<() => void>()\n const committedListeners = new Set<() => void>()\n const messageListeners = new Set<(message: Message) => void>()\n // Listeners run inside `update`, a Subscription, and the refresh stream. A\n // throwing one must not break those or skip the listeners after it, so its\n // error is reported asynchronously, as an event listener's would be.\n const notifyEach = <A>(listeners: ReadonlySet<(value: A) => void>, value: A): void => {\n for (const listener of [...listeners]) {\n try {\n listener(value)\n } catch (error) {\n queueMicrotask(() => {\n throw error\n })\n }\n }\n }\n const notifyCommitted = (): void => notifyEach(committedListeners, undefined)\n\n const updatePrivate = (\n model: Model,\n message: Private,\n ): Update.Return<Model, RuntimeMessage, Resources> => {\n switch (message._tag) {\n // Installs at once: edits still waiting for the replica are replayed on\n // top, so nothing is deferred behind them.\n case REFRESH: {\n // The server's history changed under the replica: a reset.\n const reset =\n applied !== undefined &&\n Option.isSome(applied.epoch) &&\n Option.isSome(message.status.epoch) &&\n applied.epoch.value !== message.status.epoch.value\n applied = message.status\n // The first status, and any other that changed nothing the Model shows, reinstall\n // nothing, so `onReinstall` hears only of a real change.\n if (\n !message.changed ||\n (!editedSinceInstall && Effect.runSync(replica.snapshot).shared === installedFrom)\n ) {\n return unchanged(model)\n }\n return reinstalled(install(model), model, { reset })\n }\n case PERSISTED:\n persistsOwed--\n return unchanged(model)\n case FAILED: {\n persistsOwed--\n const { error } = message\n const reverted = install(model)\n return reinstalled(options.onPersistenceFailure?.(reverted, error) ?? reverted, model, {\n reset: false,\n })\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\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 case DISPATCHED:\n dispatchesOwed--\n return transition(model, message.message as Message & Tagged)\n default:\n return absurd(message)\n }\n }\n\n const update = (\n model: Model,\n message: RuntimeMessage,\n ): Update.Return<Model, RuntimeMessage, Resources> => {\n const result = isPrivate(message)\n ? updatePrivate(model, message)\n : transition(model, message as Message & Tagged)\n if (options.afterUpdate === undefined) return result\n const after = applyFacts(\n options.afterUpdate(result.model) as Update.Return<Model, RuntimeMessage, Resources>,\n )\n return after.model === result.model && (after.commands ?? []).length === 0\n ? result\n : { model: after.model, commands: [...(result.commands ?? []), ...(after.commands ?? [])] }\n }\n\n const reinstalled = (\n next: Model,\n previous: Model,\n change: Reinstall,\n ): Update.Return<Model, RuntimeMessage, Resources> =>\n options.onReinstall === undefined\n ? { model: next }\n : applyFacts(\n options.onReinstall(next, previous, change) as Update.Return<\n Model,\n RuntimeMessage,\n Resources\n >,\n )\n\n /** The application's transition for one of its Messages, with the persist a durable one needs. */\n const step = (\n model: Model,\n message: Message & Tagged,\n ): Update.Return<Model, RuntimeMessage, Resources> => {\n notifyEach(messageListeners, message)\n const result = app.update(model, message) as Update.Return<Model, RuntimeMessage, Resources>\n if (!durable.has(message._tag)) return result\n editedSinceInstall = true\n persistsOwed++\n const edit: LocalEdit<Message> = { message, started: undefined }\n edits.push(edit)\n if (edits.length === 1) unloadGuarded(true)\n const previous = tail\n let settle!: () => void\n const done = new Promise<void>(resolve => {\n settle = resolve\n })\n tail = done\n const release = (): void => {\n const index = edits.indexOf(edit)\n if (index !== -1) edits.splice(index, 1)\n if (edits.length === 0) unloadGuarded(false)\n inFlight.delete(done)\n settle()\n }\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 inFlight.add(done)\n // One submit at a time, in dispatch order, so `started` is the\n // sequence this edit takes if its submit succeeds.\n yield* Effect.promise(() => previous)\n edit.started = (yield* replica.snapshot).nextLocalSequence\n const outcome = yield* Effect.result(replica.submit(edit.message))\n return outcome._tag === 'Success'\n ? ({ _tag: PERSISTED } as RuntimeMessage)\n : ({ _tag: FAILED, error: outcome.failure } as RuntimeMessage)\n }).pipe(\n // `ensuring`, so a defect in storage still releases the next submit and `dispose`.\n Effect.ensuring(Effect.sync(release)),\n ),\n }\n return { model: result.model, commands: [...(result.commands ?? []), persist] }\n }\n\n /**\n * A Message's transition, with the facts it returned applied after it. A durable\n * Message's are not: replay would not apply them, so they stay ordinary Commands.\n */\n const transition = (\n model: Model,\n message: Message & Tagged,\n ): Update.Return<Model, RuntimeMessage, Resources> => {\n const result = step(model, message)\n return durable.has(message._tag) ? result : applyFacts(result)\n }\n\n /** Applies the facts a transition returned, in order, each as the transition after it. */\n const applyFacts = (\n result: Update.Return<Model, RuntimeMessage, Resources>,\n ): Update.Return<Model, RuntimeMessage, Resources> => {\n let model = result.model\n const kept: Array<Update.Commands<RuntimeMessage, Resources>[number]> = []\n for (const command of result.commands ?? []) {\n const found = factOf(command)\n if (found === undefined) {\n kept.push(command)\n continue\n }\n const next = transition(model, found.message as Message & Tagged)\n model = next.model\n kept.push(...(next.commands ?? []))\n }\n return { model, commands: kept }\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.subscriptionEntry(ports.inbound.message, (message): RuntimeMessage => ({\n _tag: DISPATCHED,\n message,\n })),\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.persistentEntry<RuntimeMessage, Resources>(\n replica.statusChanges.pipe(\n // Every status, not only a changed cursor: a checkpoint at the same\n // cursor still replaces the committed state a waiter reads.\n Stream.tap(() => Effect.sync(notifyCommitted)),\n Stream.mapAccum(\n (): ReplicaStatus | undefined => undefined,\n (previous, status): readonly [ReplicaStatus, ReadonlyArray<RuntimeMessage>] => [\n status,\n [{ _tag: REFRESH, status, changed: sharedChanged(previous, status) }],\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 notifyEach(modelListeners, undefined)\n // After every transition, so `settled` resolves once `model()` has it.\n notifySettled()\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 const encodeMessage = Schema.encodeExit(app.Message as unknown as Schema.Codec<Message, unknown>)\n\n return {\n // The port decodes what it is sent, so it takes the Message encoded: a\n // Message is sent as its type is, Option fields and all.\n dispatch: message =>\n Exit.match(encodeMessage(message), {\n onSuccess: encoded => {\n // Counted before the send, in case the port delivers within it.\n dispatchesOwed++\n const sent = handle.ports.message.send(encoded)\n if (Exit.isFailure(sent)) dispatchesOwed--\n return sent\n },\n onFailure: cause => Exit.failCause(cause),\n }),\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 committed: {\n get: () => Effect.runSync(replica.committed),\n subscribe: listener => {\n committedListeners.add(listener)\n return () => committedListeners.delete(listener)\n },\n },\n settled: () => {\n if (disposed) return Promise.reject(new Error('Sync.mount: settled() after dispose'))\n if (quiet()) return Promise.resolve()\n return new Promise<void>((resolve, reject) => waiters.add({ resolve, reject }))\n },\n dispose: async () => {\n disposed = true\n for (const waiter of [...waiters]) {\n waiters.delete(waiter)\n waiter.reject(new Error('Sync.mount: disposed before it settled'))\n }\n await Promise.all([...inFlight])\n handle.dispose()\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAyBA,MAAM,UAAU;AAChB,MAAM,YAAY;AAClB,MAAM,SAAS;AACf,MAAM,WAAW;AACjB,MAAM,YAAY;AAClB,MAAM,aAAa;AAanB,MAAM,UAAmD;EACtD,UAAU;EACV,YAAY;EACZ,SAAS;EACT,WAAW;EACX,YAAY;EACZ,aAAa;AAChB;AAEA,MAAM,aAAa,YACjB,OAAO,OAAO,SAAS,QAAQ,IAAI;AAGrC,MAAM,OAAO,OAAO,IAAI,mBAAmB;;;;;;;;;;;;AAa3C,MAAa,QACX,YAIA,OAAO,eAAe;CAAE,MAAM;CAAqB,QAAQ,OAAO,QAAQ,OAAO;AAAE,GAAG,MAAM;CAC1F,OAAO;CACP,YAAY;AACd,CAAC;AAEH,MAAM,UAAU,YACd,OAAO,YAAY,YAAY,YAAY,QAAQ,QAAQ,UACvD,EAAE,SAAU,QAAyC,MAAM,IAC3D,KAAA;;;;;;AAgHN,MAAM,iBAAiB,UAAqC,SAC1D,aAAa,KAAA,KACb,SAAS,WAAW,KAAK,UACzB,KAAK,UAAU,SAAS,WACxB,SAAS,SAAS,WAAW,KAAK,SAAS,UAC3C,SAAS,SAAS,MAAM,WAAW,UAAU,UAAU,SAAS,KAAK,SAAS,MAAM,EAAE,IAAI;;;;;;AAgB5F,MAAa,oBACX,OACA,SAEA,MAAM,QAAO,SAAQ,KAAK,YAAY,KAAA,KAAa,QAAQ,KAAK,OAAO,CAAC,CAAC,KAAI,SAAQ,KAAK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O;EACzB;CACF,CAAC;CACP,MAAM,SAAS,QAAQ,MAAM,OAAO;CACpC,MAAM,gBAAgB,OAAO,WAAW,IAAI,OAAoD;CAEhG,OAAO;EAGL,WAAU,YACR,KAAK,MAAM,cAAc,OAAO,GAAG;GACjC,YAAW,YAAW;IAEpB;IACA,MAAM,OAAO,OAAO,MAAM,QAAQ,KAAK,OAAO;IAC9C,IAAI,KAAK,UAAU,IAAI,GAAG;IAC1B,OAAO;GACT;GACA,YAAW,UAAS,KAAK,UAAU,KAAK;EAC1C,CAAC;EACH,aAAa;EACb,YAAW,aAAY;GACrB,eAAe,IAAI,QAAQ;GAC3B,aAAa,eAAe,OAAO,QAAQ;EAC7C;EACA,UAAS,aAAY;GACnB,iBAAiB,IAAI,QAAQ;GAC7B,aAAa,iBAAiB,OAAO,QAAQ;EAC/C;EACA,WAAW;GACT,WAAW,OAAO,QAAQ,QAAQ,SAAS;GAC3C,YAAW,aAAY;IACrB,mBAAmB,IAAI,QAAQ;IAC/B,aAAa,mBAAmB,OAAO,QAAQ;GACjD;EACF;EACA,eAAe;GACb,IAAI,UAAU,OAAO,QAAQ,uBAAO,IAAI,MAAM,qCAAqC,CAAC;GACpF,IAAI,MAAM,GAAG,OAAO,QAAQ,QAAQ;GACpC,OAAO,IAAI,SAAe,SAAS,WAAW,QAAQ,IAAI;IAAE;IAAS;GAAO,CAAC,CAAC;EAChF;EACA,SAAS,YAAY;GACnB,WAAW;GACX,KAAK,MAAM,UAAU,CAAC,GAAG,OAAO,GAAG;IACjC,QAAQ,OAAO,MAAM;IACrB,OAAO,uBAAO,IAAI,MAAM,wCAAwC,CAAC;GACnE;GACA,MAAM,QAAQ,IAAI,CAAC,GAAG,QAAQ,CAAC;GAC/B,OAAO,QAAQ;EACjB;CACF;AACF"}
1
+ {"version":3,"file":"mount.js","names":[],"sources":["../src/mount.ts"],"sourcesContent":["/**\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, Option, Result, Schema, Stream } from 'effect'\nimport { absurd } from 'effect/Function'\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'\nconst DISPATCHED = 'foldkit-sync/Dispatched'\n\ntype Private =\n // Every replica status, applied in order, so `settled` counts one seen only once `update` has it.\n | { readonly _tag: typeof REFRESH; readonly status: ReplicaStatus; readonly changed: boolean }\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 // An application Message sent through `dispatch`, so `settled` counts it in.\n | { readonly _tag: typeof DISPATCHED; readonly message: unknown }\n\n// A key per private tag, so a variant added to `Private` must be added here too.\nconst PRIVATE: Readonly<Record<Private['_tag'], true>> = {\n [REFRESH]: true,\n [PERSISTED]: true,\n [FAILED]: true,\n [NAVIGATE]: true,\n [NAVIGATED]: true,\n [DISPATCHED]: true,\n}\n\nconst isPrivate = (message: { readonly _tag: string }): message is Private =>\n Object.hasOwn(PRIVATE, message._tag)\n\n// A registered symbol, so two copies of this package in one bundle recognize each other's.\nconst FACT = Symbol.for('foldkit-sync/fact')\n\n/**\n * A Command that dispatches `message` as the next transition, which under `Sync.mount`\n * means within this one: the mount applies it straight after the `update` that returned\n * it, and persists it if it is durable, before any other Message is processed. This is\n * how a local intent turns into a durable fact that needs something only the intent's\n * transition knows, such as an id minted from local state, without a later Message\n * seeing the Model before the fact. Elsewhere, or once a parent has mapped the Command,\n * it is an ordinary Command that yields `message`, and so is one a durable Message's\n * update returns: replay would not apply it, and with derived replay the durable Message's\n * persist fails with `ReplayError` as for any Command.\n */\nexport const fact = <Message>(\n message: Message,\n): { readonly name: string; readonly effect: Effect.Effect<Message> } =>\n // Not enumerable, so the spread a mapping Command is copied with drops the marker, and a\n // mapped fact is the ordinary Command it now is rather than the unmapped Message.\n Object.defineProperty({ name: 'foldkit-sync/fact', effect: Effect.succeed(message) }, FACT, {\n value: message,\n enumerable: false,\n })\n\nconst factOf = (command: unknown): { readonly message: unknown } | undefined =>\n typeof command === 'object' && command !== null && FACT in command\n ? { message: (command as { readonly [FACT]: unknown })[FACT] }\n : undefined\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 * Runs when the mount replaces the shared slice outside `update`: an exchange committed,\n * acknowledged or rejected something, or a persist failed and its edit was reverted.\n * `previous` is the Model before; what it returns is the transition, so an application\n * can carry local state across the change (a selection held by what it points at) or\n * return Commands (a DOM the change has to reach). Omitted, the Model is `next`. It is\n * not called for a status that changes nothing the Model shows, such as the first.\n */\n readonly onReinstall?:\n | ((\n next: Model,\n previous: Model,\n change: Reinstall,\n ) => Update.Return<Model, Message, Resources>)\n | undefined\n /**\n * Runs on the Model after every update of the mounted application, a durable\n * Message's and a reinstall's included, and never in replay: for local state\n * derived from the shared slice, which a durable transition may not write\n * (the overlays `foldkit-sync/remote` keeps in Remote). With nothing to\n * change it returns the Model it was given.\n */\n readonly afterUpdate?: ((model: Model) => Update.Return<Model, Message, Resources>) | undefined\n}\n\n/**\n * What a reinstall came from. `reset` is a server reset: the replica's\n * committed history is a new one, so anything an application derived from\n * the old one (reads cached by commit sequence, say) is to be read again.\n */\nexport interface Reinstall {\n readonly reset: boolean\n}\n\n/**\n * The shared slice as the server has confirmed it, outside the Model. It is a\n * source for waiting consumers, the shape `Agent.when({ source })` reads, and\n * not a Projection: it does not render and is not derived from the Model.\n */\nexport interface CommittedView<Shared> {\n readonly get: () => Shared\n /** Told after every exchange, including one that moves no cursor (a checkpoint). */\n readonly subscribe: (listener: () => void) => () => void\n}\n\nexport interface Mounted<Model, Message, Shared = unknown> {\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 /**\n * The shared slice without pending local edits, for an agent that must not\n * report an optimistic edit as done: `Agent.when({ source: mounted.committed, … })`.\n */\n readonly committed: CommittedView<Shared>\n /**\n * Resolves once the Model has caught up with the replica: no persist in\n * flight or unanswered, every replica status the mount was told of seen,\n * and every reinstall it asked for applied. It observes and never does the\n * work. Frames are not its to wait for (`Frames.track` in\n * `foldkit-mixins/testing` is), nor I/O a Command started. Rejects after\n * `dispose`.\n */\n readonly settled: () => Promise<void>\n /** Waits for in-flight persists, then disposes the runtime. The replica stays open. */\n readonly dispose: () => Promise<void>\n}\n\n/**\n * Commits, rejections and acknowledgments change what the replica holds; a\n * submit only echoes a local edit. An acknowledgment that does not return the\n * operation moves no cursor, but it still drops the edit from the outbox.\n */\nconst sharedChanged = (previous: ReplicaStatus | undefined, next: ReplicaStatus): boolean =>\n previous === undefined ||\n previous.cursor !== next.cursor ||\n next.pending < previous.pending ||\n previous.rejected.length !== next.rejected.length ||\n previous.rejected.some((rejection, index) => rejection.opId !== next.rejected[index]?.opId)\n\n/**\n * A durable edit the Model already shows. `started` is the replica's next local\n * sequence when its submit began, `undefined` while it waits for its turn.\n */\nexport interface LocalEdit<Message> {\n readonly message: Message\n started: number | undefined\n}\n\n/**\n * The edits a replica whose next local sequence is `next` does not hold yet.\n * Submits run one at a time, so the one in flight is in the replica exactly\n * when its submit has moved the sequence past `started`.\n */\nexport const unconfirmedEdits = <Message>(\n edits: ReadonlyArray<LocalEdit<Message>>,\n next: number,\n): ReadonlyArray<Message> =>\n edits.filter(edit => edit.started === undefined || next <= edit.started).map(edit => edit.message)\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 Authorized extends boolean = false,\n SMs extends readonly 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 Authorized,\n SMs\n >,\n options: MountOptions<\n Model,\n MessageOf<RunnableApplication<Model, F, Cases, Resources>>,\n Schema.Struct.Type<Fields>,\n Resources\n >,\n): Mounted<\n Model,\n MessageOf<RunnableApplication<Model, F, Cases, Resources>>,\n Schema.Struct.Type<Fields>\n> => {\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 type Shared = Schema.Struct.Type<Fields>\n const { replica } = options\n const durable = new Set(sync.contract.messages)\n\n // Durable edits whose submit has not settled, in dispatch order.\n const edits: Array<LocalEdit<Message>> = []\n // An edit shows before it is stored, so a reload while one waits would lose\n // what the reader saw: the browser asks first, from the first such edit\n // until the last is stored.\n const holdUnload = (event: Event): void => event.preventDefault()\n const unloadGuarded = (guarded: boolean): void => {\n if (typeof window === 'undefined') return\n if (guarded) window.addEventListener('beforeunload', holdUnload)\n else window.removeEventListener('beforeunload', holdUnload)\n }\n // Settles when the latest edit's submit does; the next submit waits for it.\n let tail: Promise<void> = Promise.resolve()\n\n // The replica's `shared` holds every settled edit, and the one in flight once\n // its submit lands; the rest are replayed on top. Read from one snapshot, so\n // a refresh neither hides an edit still waiting for the replica nor applies\n // one the replica already holds.\n // The replica's shared value the Model was last installed from, and whether a durable\n // edit has changed the Model's copy since. The replica keeps one object per state, so\n // the same object with no edit since is the shared slice the Model already shows.\n let installedFrom: Shared | undefined\n let editedSinceInstall = false\n const install = (model: Model): Model => {\n const snapshot = Effect.runSync(replica.snapshot)\n installedFrom = snapshot.shared\n const unconfirmed = unconfirmedEdits(edits, snapshot.nextLocalSequence)\n // Edits replayed on top leave the Model's copy apart from `installedFrom`.\n editedSinceInstall = unconfirmed.length > 0\n const shared = unconfirmed.reduce<Shared>((value, message) => {\n try {\n return sync.replay(value, message)\n } catch {\n // The replica refuses it too; its FAILED re-installs without it.\n return value\n }\n }, snapshot.shared)\n return sync.projection.set(model, shared)\n }\n\n const inFlight = new Set<Promise<void>>()\n // What `settled` waits on: dispatches and persists not yet answered in\n // `update`, and the last replica status `update` applied.\n let dispatchesOwed = 0\n let persistsOwed = 0\n let applied: ReplicaStatus | undefined\n let disposed = false\n const waiters = new Set<{\n readonly resolve: () => void\n readonly reject: (error: Error) => void\n }>()\n const quiet = (): boolean =>\n dispatchesOwed === 0 &&\n persistsOwed === 0 &&\n !sharedChanged(applied, Effect.runSync(replica.status))\n const notifySettled = (): void => {\n if (!quiet()) return\n for (const waiter of [...waiters]) {\n waiters.delete(waiter)\n waiter.resolve()\n }\n }\n /**\n * A private transition that leaves the Model as it was: the runtime sends\n * no Subscription the change, so `settled` is told here, once it returns.\n */\n const unchanged = (model: Model): Update.Return<Model, RuntimeMessage, Resources> => {\n queueMicrotask(notifySettled)\n return { model }\n }\n let latest: Model = install(app.initial)\n const modelListeners = new Set<() => void>()\n const committedListeners = new Set<() => void>()\n const messageListeners = new Set<(message: Message) => void>()\n // Listeners run inside `update`, a Subscription, and the refresh stream. A\n // throwing one must not break those or skip the listeners after it, so its\n // error is reported asynchronously, as an event listener's would be.\n const notifyEach = <A>(listeners: ReadonlySet<(value: A) => void>, value: A): void => {\n for (const listener of [...listeners]) {\n try {\n listener(value)\n } catch (error) {\n queueMicrotask(() => {\n throw error\n })\n }\n }\n }\n const notifyCommitted = (): void => notifyEach(committedListeners, undefined)\n\n const updatePrivate = (\n model: Model,\n message: Private,\n ): Update.Return<Model, RuntimeMessage, Resources> => {\n switch (message._tag) {\n // Installs at once: edits still waiting for the replica are replayed on\n // top, so nothing is deferred behind them.\n case REFRESH: {\n // The server's history changed under the replica: a reset.\n const reset =\n applied !== undefined &&\n Option.isSome(applied.epoch) &&\n Option.isSome(message.status.epoch) &&\n applied.epoch.value !== message.status.epoch.value\n applied = message.status\n // The first status, and any other that changed nothing the Model shows, reinstall\n // nothing, so `onReinstall` hears only of a real change.\n if (\n !message.changed ||\n (!editedSinceInstall && Effect.runSync(replica.snapshot).shared === installedFrom)\n ) {\n return unchanged(model)\n }\n return reinstalled(install(model), model, { reset })\n }\n case PERSISTED:\n persistsOwed--\n return unchanged(model)\n case FAILED: {\n persistsOwed--\n const { error } = message\n const reverted = install(model)\n return reinstalled(options.onPersistenceFailure?.(reverted, error) ?? reverted, model, {\n reset: false,\n })\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\n const follow = Navigation.UrlRequest.match(request, {\n Internal: ({ url }) => Navigation.pushUrl(Url.toString(url)),\n External: ({ href }) => Navigation.load(href),\n })\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 case DISPATCHED:\n dispatchesOwed--\n return transition(model, message.message as Message & Tagged)\n default:\n return absurd(message)\n }\n }\n\n const update = (\n model: Model,\n message: RuntimeMessage,\n ): Update.Return<Model, RuntimeMessage, Resources> => {\n const result = isPrivate(message)\n ? updatePrivate(model, message)\n : transition(model, message as Message & Tagged)\n if (options.afterUpdate === undefined) return result\n const after = applyFacts(\n options.afterUpdate(result.model) as Update.Return<Model, RuntimeMessage, Resources>,\n )\n return after.model === result.model && (after.commands ?? []).length === 0\n ? result\n : { model: after.model, commands: [...(result.commands ?? []), ...(after.commands ?? [])] }\n }\n\n const reinstalled = (\n next: Model,\n previous: Model,\n change: Reinstall,\n ): Update.Return<Model, RuntimeMessage, Resources> =>\n options.onReinstall === undefined\n ? { model: next }\n : applyFacts(\n options.onReinstall(next, previous, change) as Update.Return<\n Model,\n RuntimeMessage,\n Resources\n >,\n )\n\n /** The application's transition for one of its Messages, with the persist a durable one needs. */\n const step = (\n model: Model,\n message: Message & Tagged,\n ): Update.Return<Model, RuntimeMessage, Resources> => {\n notifyEach(messageListeners, message)\n const result = app.update(model, message) as Update.Return<Model, RuntimeMessage, Resources>\n if (!durable.has(message._tag)) return result\n editedSinceInstall = true\n persistsOwed++\n const edit: LocalEdit<Message> = { message, started: undefined }\n edits.push(edit)\n if (edits.length === 1) unloadGuarded(true)\n const previous = tail\n let settle!: () => void\n const done = new Promise<void>(resolve => {\n settle = resolve\n })\n tail = done\n const release = (): void => {\n const index = edits.indexOf(edit)\n if (index !== -1) edits.splice(index, 1)\n if (edits.length === 0) unloadGuarded(false)\n inFlight.delete(done)\n settle()\n }\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 inFlight.add(done)\n // One submit at a time, in dispatch order, so `started` is the\n // sequence this edit takes if its submit succeeds.\n yield* Effect.promise(() => previous)\n edit.started = (yield* replica.snapshot).nextLocalSequence\n const outcome = yield* Effect.result(replica.submit(edit.message))\n return Result.match(outcome, {\n onSuccess: () => ({ _tag: PERSISTED }) as RuntimeMessage,\n onFailure: error => ({ _tag: FAILED, error }) as RuntimeMessage,\n })\n }).pipe(\n // `ensuring`, so a defect in storage still releases the next submit and `dispose`.\n Effect.ensuring(Effect.sync(release)),\n ),\n }\n return { model: result.model, commands: [...(result.commands ?? []), persist] }\n }\n\n /**\n * A Message's transition, with the facts it returned applied after it. A durable\n * Message's are not: replay would not apply them, so they stay ordinary Commands.\n */\n const transition = (\n model: Model,\n message: Message & Tagged,\n ): Update.Return<Model, RuntimeMessage, Resources> => {\n const result = step(model, message)\n return durable.has(message._tag) ? result : applyFacts(result)\n }\n\n /** Applies the facts a transition returned, in order, each as the transition after it. */\n const applyFacts = (\n result: Update.Return<Model, RuntimeMessage, Resources>,\n ): Update.Return<Model, RuntimeMessage, Resources> => {\n let model = result.model\n const kept: Array<Update.Commands<RuntimeMessage, Resources>[number]> = []\n for (const command of result.commands ?? []) {\n const found = factOf(command)\n if (found === undefined) {\n kept.push(command)\n continue\n }\n const next = transition(model, found.message as Message & Tagged)\n model = next.model\n kept.push(...(next.commands ?? []))\n }\n return { model, commands: kept }\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.subscriptionEntry(ports.inbound.message, (message): RuntimeMessage => ({\n _tag: DISPATCHED,\n message,\n })),\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.persistentEntry<RuntimeMessage, Resources>(\n replica.statusChanges.pipe(\n // Every status, not only a changed cursor: a checkpoint at the same\n // cursor still replaces the committed state a waiter reads.\n Stream.tap(() => Effect.sync(notifyCommitted)),\n Stream.mapAccum(\n (): ReplicaStatus | undefined => undefined,\n (previous, status): readonly [ReplicaStatus, ReadonlyArray<RuntimeMessage>] => [\n status,\n [{ _tag: REFRESH, status, changed: sharedChanged(previous, status) }],\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 notifyEach(modelListeners, undefined)\n // After every transition, so `settled` resolves once `model()` has it.\n notifySettled()\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 const encodeMessage = Schema.encodeExit(app.Message as unknown as Schema.Codec<Message, unknown>)\n\n return {\n // The port decodes what it is sent, so it takes the Message encoded: a\n // Message is sent as its type is, Option fields and all.\n dispatch: message =>\n Exit.match(encodeMessage(message), {\n onSuccess: encoded => {\n // Counted before the send, in case the port delivers within it.\n dispatchesOwed++\n const sent = handle.ports.message.send(encoded)\n if (Exit.isFailure(sent)) dispatchesOwed--\n return sent\n },\n onFailure: cause => Exit.failCause(cause),\n }),\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 committed: {\n get: () => Effect.runSync(replica.committed),\n subscribe: listener => {\n committedListeners.add(listener)\n return () => committedListeners.delete(listener)\n },\n },\n settled: () => {\n if (disposed) return Promise.reject(new Error('Sync.mount: settled() after dispose'))\n if (quiet()) return Promise.resolve()\n return new Promise<void>((resolve, reject) => waiters.add({ resolve, reject }))\n },\n dispose: async () => {\n disposed = true\n for (const waiter of [...waiters]) {\n waiters.delete(waiter)\n waiter.reject(new Error('Sync.mount: disposed before it settled'))\n }\n await Promise.all([...inFlight])\n handle.dispose()\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAyBA,MAAM,UAAU;AAChB,MAAM,YAAY;AAClB,MAAM,SAAS;AACf,MAAM,WAAW;AACjB,MAAM,YAAY;AAClB,MAAM,aAAa;AAanB,MAAM,UAAmD;EACtD,UAAU;EACV,YAAY;EACZ,SAAS;EACT,WAAW;EACX,YAAY;EACZ,aAAa;AAChB;AAEA,MAAM,aAAa,YACjB,OAAO,OAAO,SAAS,QAAQ,IAAI;AAGrC,MAAM,OAAO,OAAO,IAAI,mBAAmB;;;;;;;;;;;;AAa3C,MAAa,QACX,YAIA,OAAO,eAAe;CAAE,MAAM;CAAqB,QAAQ,OAAO,QAAQ,OAAO;AAAE,GAAG,MAAM;CAC1F,OAAO;CACP,YAAY;AACd,CAAC;AAEH,MAAM,UAAU,YACd,OAAO,YAAY,YAAY,YAAY,QAAQ,QAAQ,UACvD,EAAE,SAAU,QAAyC,MAAM,IAC3D,KAAA;;;;;;AAgHN,MAAM,iBAAiB,UAAqC,SAC1D,aAAa,KAAA,KACb,SAAS,WAAW,KAAK,UACzB,KAAK,UAAU,SAAS,WACxB,SAAS,SAAS,WAAW,KAAK,SAAS,UAC3C,SAAS,SAAS,MAAM,WAAW,UAAU,UAAU,SAAS,KAAK,SAAS,MAAM,EAAE,IAAI;;;;;;AAgB5F,MAAa,oBACX,OACA,SAEA,MAAM,QAAO,SAAQ,KAAK,YAAY,KAAA,KAAa,QAAQ,KAAK,OAAO,CAAC,CAAC,KAAI,SAAQ,KAAK,OAAO;AAMnG,MAAa,SAWX,KACA,MASA,YAUG;CAGH,IAAI,QAAQ,UAAU,OAAO,IAC3B,MAAM,IAAI,MAAM,kEAAgE;CAMlF,MAAM,EAAE,YAAY;CACpB,MAAM,UAAU,IAAI,IAAI,KAAK,SAAS,QAAQ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AO;EAGL,WAAU,YACR,KAAK,MAAM,cAAc,OAAO,GAAG;GACjC,YAAW,YAAW;IAEpB;IACA,MAAM,OAAO,OAAO,MAAM,QAAQ,KAAK,OAAO;IAC9C,IAAI,KAAK,UAAU,IAAI,GAAG;IAC1B,OAAO;GACT;GACA,YAAW,UAAS,KAAK,UAAU,KAAK;EAC1C,CAAC;EACH,aAAa;EACb,YAAW,aAAY;GACrB,eAAe,IAAI,QAAQ;GAC3B,aAAa,eAAe,OAAO,QAAQ;EAC7C;EACA,UAAS,aAAY;GACnB,iBAAiB,IAAI,QAAQ;GAC7B,aAAa,iBAAiB,OAAO,QAAQ;EAC/C;EACA,WAAW;GACT,WAAW,OAAO,QAAQ,QAAQ,SAAS;GAC3C,YAAW,aAAY;IACrB,mBAAmB,IAAI,QAAQ;IAC/B,aAAa,mBAAmB,OAAO,QAAQ;GACjD;EACF;EACA,eAAe;GACb,IAAI,UAAU,OAAO,QAAQ,uBAAO,IAAI,MAAM,qCAAqC,CAAC;GACpF,IAAI,MAAM,GAAG,OAAO,QAAQ,QAAQ;GACpC,OAAO,IAAI,SAAe,SAAS,WAAW,QAAQ,IAAI;IAAE;IAAS;GAAO,CAAC,CAAC;EAChF;EACA,SAAS,YAAY;GACnB,WAAW;GACX,KAAK,MAAM,UAAU,CAAC,GAAG,OAAO,GAAG;IACjC,QAAQ,OAAO,MAAM;IACrB,OAAO,uBAAO,IAAI,MAAM,wCAAwC,CAAC;GACnE;GACA,MAAM,QAAQ,IAAI,CAAC,GAAG,QAAQ,CAAC;GAC/B,OAAO,QAAQ;EACjB;CACF;AACF"}
@@ -0,0 +1,33 @@
1
+ import { Schema } from "effect";
2
+ /**
3
+ * `words` cut to fit a refusal, marked with an ellipsis where cut, and never
4
+ * between the halves of a surrogate pair. A rule's reason is the
5
+ * application's, with no bound of its own; an unfit one would fail every
6
+ * exchange that carries it.
7
+ */
8
+ export declare const fitWords: (words: string) => string;
9
+ /** Why the server refused an operation, on `Rejection.refusal`: read it with `SyncRefusal.match`. */
10
+ export declare const SyncRefusal: import("foldkit/schema").TaggedUnion<{
11
+ /** Who sent it may not make it (`authorize` or `admit` refused), with the rule's words when it gave some. */
12
+ readonly Forbidden: {
13
+ reason: Schema.OptionFromOptionalKey<Schema.String>;
14
+ };
15
+ /**
16
+ * It breaks a rule, or the server could not apply it. `message` is a fixed
17
+ * sentence of the server's, never an error's message. `entity`, `rule` and
18
+ * `path` name an Entity's invariant, as Remote's do; `journalExchange`
19
+ * knows none, so it sends them empty.
20
+ */
21
+ readonly Invalid: {
22
+ entity: Schema.OptionFromOptionalNullOr<Schema.String>;
23
+ rule: Schema.OptionFromNullOr<Schema.String>;
24
+ message: Schema.String;
25
+ path: Schema.$Array<Schema.String>;
26
+ };
27
+ /** Written at a Message version no step of the document's history reads. Sent once operations carry a version. */
28
+ readonly Unreadable: {
29
+ version: Schema.Int;
30
+ };
31
+ }>;
32
+ export type SyncRefusal = typeof SyncRefusal.Type;
33
+ //# sourceMappingURL=refusal.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"refusal.d.ts","names":[],"sources":["../src/refusal.ts"],"mappings":";;;;;;;qBAoBa,WAAQ;;qBAQR,sCAAW;;;IAET,QAAM,OAAA,sBAAA,OAAA;;;;;;;;;IAQjB,QAAM,OAAA,yBAAA,OAAA;IACN,MAAI,OAAA,iBAAA,OAAA;IACJ,SAAO,OAAA;IACP,MAAI,OAAA,OAAA,OAAA;;;;IAGQ,SAAO,OAAA;;;YAEX,qBAAqB,YAAY"}
@@ -0,0 +1,47 @@
1
+ import { Schema } from "effect";
2
+ import { defineTaggedUnion } from "foldkit/schema";
3
+ // src/refusal.ts
4
+ /**
5
+ * Why the server refused an operation, in Remote's vocabulary for "not
6
+ * saved": `Forbidden` is Remote's `Denied.Forbidden`, `Invalid` its
7
+ * `Refusal.invalid`, with the same tags, decoded types and encoding, so one
8
+ * function shows a refusal whichever path made it. Sync keeps its own codec
9
+ * because its core does not depend on `foldkit-remote`.
10
+ */
11
+ /** The most UTF-16 units a refusal's words may hold: a refusal is not a document. */
12
+ const WORDS = 500;
13
+ const Words = Schema.String.check(Schema.isMaxLength(WORDS));
14
+ /**
15
+ * `words` cut to fit a refusal, marked with an ellipsis where cut, and never
16
+ * between the halves of a surrogate pair. A rule's reason is the
17
+ * application's, with no bound of its own; an unfit one would fail every
18
+ * exchange that carries it.
19
+ */
20
+ const fitWords = (words) => {
21
+ if (words.length <= WORDS) return words;
22
+ const end = words.charCodeAt(498);
23
+ const cut = end >= 55296 && end <= 56319 ? 498 : 499;
24
+ return `${words.slice(0, cut)}…`;
25
+ };
26
+ /** Why the server refused an operation, on `Rejection.refusal`: read it with `SyncRefusal.match`. */
27
+ const SyncRefusal = defineTaggedUnion({
28
+ /** Who sent it may not make it (`authorize` or `admit` refused), with the rule's words when it gave some. */
29
+ Forbidden: { reason: Schema.OptionFromOptionalKey(Words) },
30
+ /**
31
+ * It breaks a rule, or the server could not apply it. `message` is a fixed
32
+ * sentence of the server's, never an error's message. `entity`, `rule` and
33
+ * `path` name an Entity's invariant, as Remote's do; `journalExchange`
34
+ * knows none, so it sends them empty.
35
+ */
36
+ Invalid: {
37
+ entity: Schema.OptionFromOptionalNullOr(Words),
38
+ rule: Schema.OptionFromNullOr(Words),
39
+ message: Words,
40
+ path: Schema.Array(Words).check(Schema.isMaxLength(16))
41
+ },
42
+ /** Written at a Message version no step of the document's history reads. Sent once operations carry a version. */
43
+ Unreadable: { version: Schema.Int.check(Schema.isGreaterThanOrEqualTo(1)) }
44
+ });
45
+ export { SyncRefusal, fitWords };
46
+
47
+ //# sourceMappingURL=refusal.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"refusal.js","names":[],"sources":["../src/refusal.ts"],"sourcesContent":["/**\n * Why the server refused an operation, in Remote's vocabulary for \"not\n * saved\": `Forbidden` is Remote's `Denied.Forbidden`, `Invalid` its\n * `Refusal.invalid`, with the same tags, decoded types and encoding, so one\n * function shows a refusal whichever path made it. Sync keeps its own codec\n * because its core does not depend on `foldkit-remote`.\n */\nimport { Schema } from 'effect'\nimport { defineTaggedUnion } from 'foldkit/schema'\n\n/** The most UTF-16 units a refusal's words may hold: a refusal is not a document. */\nconst WORDS = 500\nconst Words = Schema.String.check(Schema.isMaxLength(WORDS))\n\n/**\n * `words` cut to fit a refusal, marked with an ellipsis where cut, and never\n * between the halves of a surrogate pair. A rule's reason is the\n * application's, with no bound of its own; an unfit one would fail every\n * exchange that carries it.\n */\nexport const fitWords = (words: string): string => {\n if (words.length <= WORDS) return words\n const end = words.charCodeAt(WORDS - 2)\n const cut = end >= 0xd800 && end <= 0xdbff ? WORDS - 2 : WORDS - 1\n return `${words.slice(0, cut)}…`\n}\n\n/** Why the server refused an operation, on `Rejection.refusal`: read it with `SyncRefusal.match`. */\nexport const SyncRefusal = defineTaggedUnion({\n /** Who sent it may not make it (`authorize` or `admit` refused), with the rule's words when it gave some. */\n Forbidden: { reason: Schema.OptionFromOptionalKey(Words) },\n /**\n * It breaks a rule, or the server could not apply it. `message` is a fixed\n * sentence of the server's, never an error's message. `entity`, `rule` and\n * `path` name an Entity's invariant, as Remote's do; `journalExchange`\n * knows none, so it sends them empty.\n */\n Invalid: {\n entity: Schema.OptionFromOptionalNullOr(Words),\n rule: Schema.OptionFromNullOr(Words),\n message: Words,\n path: Schema.Array(Words).check(Schema.isMaxLength(16)),\n },\n /** Written at a Message version no step of the document's history reads. Sent once operations carry a version. */\n Unreadable: { version: Schema.Int.check(Schema.isGreaterThanOrEqualTo(1)) },\n})\nexport type SyncRefusal = typeof SyncRefusal.Type\n"],"mappings":";;;;;;;;;;;AAWA,MAAM,QAAQ;AACd,MAAM,QAAQ,OAAO,OAAO,MAAM,OAAO,YAAY,KAAK,CAAC;;;;;;;AAQ3D,MAAa,YAAY,UAA0B;CACjD,IAAI,MAAM,UAAU,OAAO,OAAO;CAClC,MAAM,MAAM,MAAM,WAAW,GAAS;CACtC,MAAM,MAAM,OAAO,SAAU,OAAO,QAAS,MAAY;CACzD,OAAO,GAAG,MAAM,MAAM,GAAG,GAAG,EAAE;AAChC;;AAGA,MAAa,cAAc,kBAAkB;;CAE3C,WAAW,EAAE,QAAQ,OAAO,sBAAsB,KAAK,EAAE;;;;;;;CAOzD,SAAS;EACP,QAAQ,OAAO,yBAAyB,KAAK;EAC7C,MAAM,OAAO,iBAAiB,KAAK;EACnC,SAAS;EACT,MAAM,OAAO,MAAM,KAAK,CAAC,CAAC,MAAM,OAAO,YAAY,EAAE,CAAC;CACxD;;CAEA,YAAY,EAAE,SAAS,OAAO,IAAI,MAAM,OAAO,uBAAuB,CAAC,CAAC,EAAE;AAC5E,CAAC"}
@@ -0,0 +1,143 @@
1
+ import { Duration, Effect, Option, Schema } from "effect";
2
+ import { MessageSet, ReportDiagnostic } from "foldkit-surface";
3
+ import { AppendError, AppendResult, Cursor, Journal, JournalError } from "foldkit-durable/core";
4
+ import { DefinedSync, MsgOf, ServerMsgOf } from "./make.js";
5
+ import { Operation, WrittenOperation } from "./sync.js";
6
+ import { ServerKeyReusedError } from "./errors.js";
7
+ /** A committed operation, as a reaction is given it. */
8
+ export interface Trigger<Message> {
9
+ /** The Message at the current version, as every hook sees it. */
10
+ readonly message: Message;
11
+ readonly opId: string;
12
+ readonly sequence: number;
13
+ /** Who committed it: a person's actor, or the server's. */
14
+ readonly actorId: string;
15
+ /**
16
+ * 64 hex characters naming this run, the same on every retry and across
17
+ * restarts: give it to the provider as its idempotency key.
18
+ */
19
+ readonly key: string;
20
+ }
21
+ /**
22
+ * One declared reaction of one document: what it runs on, what it may
23
+ * append, and what its handler needs. Made by `reaction`, given to
24
+ * `serverJournal`.
25
+ */
26
+ export interface Reaction<Document, out R = never> {
27
+ /** The contract it was declared for: `serverJournal` refuses it for another. */
28
+ readonly sync: Document;
29
+ readonly name: string;
30
+ /** The tags it runs on. */
31
+ readonly on: ReadonlySet<string>;
32
+ /** The tags it may append. */
33
+ readonly appends: ReadonlySet<string>;
34
+ /** The services its handler needs; never present. */
35
+ readonly requires?: () => R;
36
+ }
37
+ export interface ReactionOptions<AppModel, On, Appends, R> {
38
+ /** Part of every run's key, so renaming it is a new reaction. Letters, digits, `_` and `-`, at most 64; unique in the document. */
39
+ readonly name: string;
40
+ /** The committed Messages it runs after: a set of the contract's own application. */
41
+ readonly on: MessageSet<AppModel, any, On, any>;
42
+ /** The server-only Messages it may append, checked on every answer. Without it, it appends nothing. */
43
+ readonly appends?: MessageSet<AppModel, any, Appends, any>;
44
+ /** How long one run may take before it counts as failed. Default 10 seconds. */
45
+ readonly timeout?: Duration.Input;
46
+ /** A failing run is parked once it has failed this many times, and for at least `parkAfter`. Default 8. */
47
+ readonly attempts?: number;
48
+ /** How long a run must have been failing before it may be parked, so an outage parks nothing. Default one hour. */
49
+ readonly parkAfter?: Duration.Input;
50
+ /**
51
+ * One external call, or none, and the Messages to append, at most 16. It may
52
+ * run again with the same trigger: pass `trigger.key` to the provider.
53
+ */
54
+ readonly run: (trigger: Trigger<On>) => Effect.Effect<ReadonlyArray<NoInfer<Appends>> | void, unknown, R>;
55
+ }
56
+ /**
57
+ * Declares a reaction of a contract from `Sync.forApplication(App).make`:
58
+ * after each committed Message in `on`, in journal order, `run` is called
59
+ * once at least, and what it answers is appended as the server. A handler
60
+ * that keeps failing is parked after `attempts` failures over `parkAfter`;
61
+ * one whose answer can never commit is parked at once. Throws for a name
62
+ * that is not one, or a set of another application or outside the contract.
63
+ */
64
+ export declare const reaction: <AppModel, Fields extends Schema.Struct.Fields, Message, Ms extends readonly unknown[], ContractPrincipal, Authorized extends boolean, SMs extends readonly unknown[], On extends MsgOf<Ms> | ServerMsgOf<SMs>, Appends extends ServerMsgOf<SMs> = never, R = never>(sync: DefinedSync<AppModel, Fields, Message, Ms, ContractPrincipal, Authorized, SMs>, options: ReactionOptions<AppModel, On, Appends, R>) => Reaction<DefinedSync<AppModel, Fields, Message, Ms, ContractPrincipal, Authorized, SMs>, R>;
65
+ /** A run set aside: it failed for good, or too often. Its reaction went on without it. */
66
+ export interface Parked {
67
+ readonly reaction: string;
68
+ readonly opId: string;
69
+ readonly sequence: number;
70
+ /** Why, as the last failure said it. */
71
+ readonly error: string;
72
+ /** Parked in a history since reset: it can be dismissed, not run again. */
73
+ readonly stale: boolean;
74
+ }
75
+ export interface ServerJournal<ServerOnly, R> {
76
+ /**
77
+ * Appends a server-only Message as the server. `key` names the fact (a
78
+ * webhook event's id, `absorbed/<through>`): a repeat with the same key and
79
+ * Message is answered from history, and one with another Message fails with
80
+ * `ServerKeyReusedError`. A key is a non-empty string of at most 200
81
+ * characters; another is an `InvalidOperationError`.
82
+ */
83
+ readonly appendAsServer: (message: ServerOnly, options: {
84
+ readonly key: string;
85
+ }) => Effect.Effect<AppendResult<Operation>, AppendError | ServerKeyReusedError>;
86
+ /**
87
+ * Runs every reaction from its stored cursor, a page at a time. Never
88
+ * fails: a failed run is reported, and the answer is how long to wait
89
+ * before running again; none when every reaction has caught up. Safe to
90
+ * call at any time, from anywhere in this process: passes of one
91
+ * `serverJournal` run one at a time. Two instances over one store (two
92
+ * isolates over one D1) do not wait for each other.
93
+ */
94
+ readonly react: Effect.Effect<Option.Option<Duration.Duration>, never, R>;
95
+ /**
96
+ * Runs `react` now, after every commit to the document this journal
97
+ * instance hears of, and after the delay `react` answers, until
98
+ * interrupted: a long-lived process's loop. Fork it.
99
+ */
100
+ readonly follow: Effect.Effect<never, never, R>;
101
+ /** The lowest cursor of the declared reactions: compact no further than this. */
102
+ readonly settledThrough: Effect.Effect<Cursor, JournalError>;
103
+ /** The runs set aside, for a person to look at. */
104
+ readonly parked: Effect.Effect<ReadonlyArray<Parked>, JournalError>;
105
+ /**
106
+ * Runs a parked run again, out of order; it leaves the list when it
107
+ * succeeds, and stays, failing, when it does not. A recorded answer is
108
+ * reused, so a refused append retried after the rule changed makes no
109
+ * second external call. A stale one fails with `StaleParkedRunError`.
110
+ */
111
+ readonly retry: (parked: Parked) => Effect.Effect<void, unknown, R>;
112
+ /** Forgets a parked run: its reaction never happens. */
113
+ readonly dismiss: (parked: Parked) => Effect.Effect<void, JournalError>;
114
+ }
115
+ /** The services a list of reactions needs: none for none. */
116
+ export type Requires<Reactions extends ReadonlyArray<Reaction<any, any>>> = [Reactions[number]] extends [never] ? never : Reactions[number] extends Reaction<any, infer R> ? R : never;
117
+ export interface ServerJournalOptions<Document, Principal, Shared, Reactions> {
118
+ readonly sync: Document;
119
+ readonly journal: Journal<Operation, Shared, Principal, WrittenOperation>;
120
+ /**
121
+ * Who the server commits as. Never resolved from a request, and best never
122
+ * changed: the journal binds each `server/` replica id to the first actor
123
+ * that commits from it. After a change of `actorId`, a reaction's append for
124
+ * a new trigger and a new `appendAsServer` key commit as the new actor; a
125
+ * redelivered key is an `IdentityConflictError`, and a run retried after
126
+ * its first append committed under the old actor parks.
127
+ */
128
+ readonly server: Principal;
129
+ readonly reactions?: Reactions;
130
+ /** The most runs one `react` starts, over every reaction; a host with a time limit sets it low. */
131
+ readonly runsPerPass?: number;
132
+ /** Where reactions' failures, parks and skips go; the reporter in context when not given. */
133
+ readonly diagnostics?: ReportDiagnostic | undefined;
134
+ }
135
+ /**
136
+ * The server's side of one document: `appendAsServer`, and the declared
137
+ * reactions with what runs them. Registers each reaction's cursor at the
138
+ * journal's current cursor before it answers, so make it before the journal
139
+ * serves its first exchange: a reaction sees every commit made after this.
140
+ * Throws for a reaction of another contract, two of one name, or a cycle.
141
+ */
142
+ export declare const serverJournal: <AppModel, Fields extends Schema.Struct.Fields, Message, Ms extends readonly unknown[], ContractPrincipal, Authorized extends boolean, SMs extends readonly unknown[], Principal, const Reactions extends ReadonlyArray<Reaction<DefinedSync<AppModel, Fields, Message, Ms, ContractPrincipal, Authorized, SMs>, any>> = []>(options: ServerJournalOptions<DefinedSync<AppModel, Fields, Message, Ms, ContractPrincipal, Authorized, SMs>, Principal, Schema.Struct.Type<Fields>, Reactions>) => Effect.Effect<ServerJournal<ServerMsgOf<SMs>, Requires<Reactions>>, JournalError>;
143
+ //# sourceMappingURL=serverJournal.d.ts.map
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