@elytracms/studio 0.0.96 → 0.0.97
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/convex/cms.ts +153 -13
- package/convex/delivery-folded-drift.test.ts +104 -0
- package/convex/delivery.ts +24 -8
- package/convex/depth-codec-lookalike.test.ts +192 -0
- package/convex/fixture-accounts.test.ts +305 -0
- package/convex/fixtureAccounts.ts +298 -0
- package/convex/incarnation.test.ts +149 -0
- package/convex/ingest.test.ts +145 -3
- package/convex/ingest.ts +123 -17
- package/convex/receipt-races.test.ts +184 -0
- package/convex/records-zod-copy.test.ts +76 -0
- package/convex/schema.ts +20 -1
- package/convex/strict-delete.test.ts +129 -0
- package/dist/components/cms/cms-store.d.ts +4 -1
- package/dist/components/cms/cms-store.js +11 -13
- package/dist/components/cms/cms-store.js.map +1 -1
- package/dist/components/cms/use-document-draft.d.ts +41 -2
- package/dist/components/cms/use-document-draft.js +60 -18
- package/dist/components/cms/use-document-draft.js.map +1 -1
- package/dist/lib/collection-view/collection-view-source.d.ts +5 -2
- package/dist/lib/collection-view/collection-view-source.js.map +1 -1
- package/dist/lib/engine-version.d.ts +1 -1
- package/dist/lib/engine-version.js +1 -1
- package/dist/lib/engine-version.js.map +1 -1
- package/dist/lib/i18n/messages.de.js +2 -0
- package/dist/lib/i18n/messages.de.js.map +1 -1
- package/dist/lib/i18n/messages.en.d.ts +2 -0
- package/dist/lib/i18n/messages.en.js +2 -0
- package/dist/lib/i18n/messages.en.js.map +1 -1
- package/dist/lib/operations/cms-persistence.d.ts +41 -2
- package/dist/lib/operations/cms-persistence.js +111 -24
- package/dist/lib/operations/cms-persistence.js.map +1 -1
- package/dist/lib/persistence/convex-adapter.js +27 -1
- package/dist/lib/persistence/convex-adapter.js.map +1 -1
- package/dist/lib/persona/labels.js +1 -0
- package/dist/lib/persona/labels.js.map +1 -1
- package/package.json +4 -3
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cms-persist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G;YACb,IAAI,GAAG,EAAE,CAAC;gBACR,MAAM,KAAK,GAAG,OAAO,CAAC,GAAG,CAAC,WAAW,CAAC,GAAG,CAAC,CAAC,CAAA;gBAC3C,IAAI,KAAK,IAAI,KAAK,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC;oBAAE,QAAQ,CAAC,KAAK,CAAC,CAAA;YACtD,CAAC;YACD,MAAM,KAAK,CAAC,KAAK,EAAE,CAAA;QACrB,CAAC;KACF,CAAA;AACH,CAAC","sourcesContent":["import {\n applyDocumentPatches,\n documentKey,\n formatValuePath,\n isValuePathPrefix,\n readValueAt,\n selfTypeDocument,\n semanticValueEqual,\n touchedPaths,\n valuePathsOverlap,\n} from '@elytracms/core/cms-core'\nimport type {\n CmsDocument,\n CollectionDef,\n DocumentPatch,\n DocumentRef,\n PropFieldLookup,\n RefusedPatch,\n ValuePath,\n} from '@elytracms/core/cms-core'\nimport type { CmsDocumentRecord } from '@elytracms/core/persistence'\nimport type { OperationError, OperationResult, OperationsClient } from './operations-package'\nimport { createPersistQueue } from './persist-queue'\n\n/**\n * CMS session → operations persistence (EC-141 → EC-595 part A2 → EC-647): the PATCH QUEUE.\n *\n * The CMS session keeps documents as optimistic, synchronous state; every write is\n * mirrored onto the operations layer through the revisioned aggregate's two verbs\n * (EC-595, ratified 2026-10-24): `documents.patch` for editing, `documents.replace`\n * for whole-document writers (create, import, the slot alias). There is no document\n * diffing anywhere: every writer EMITS the patches it made at its source (the form's\n * field path, the canvas's node patches, the AI proposal's field changes, bulk\n * set-field, transfer) and hands them to {@link CmsPersister.commit}.\n *\n * **Per document, the persister keeps** the server row it last adopted (`base`), the\n * committed-but-unacknowledged writes (each with the revision it was AUTHORED against),\n * the refused paths awaiting a decision, and the writes it made itself (the own-write\n * ledger). It derives the session's view of the document from them:\n *\n * display = base.document ⊕ unresolved conflicts (mine) ⊕ in-flight ⊕ queued\n *\n * by re-applying the patches with THE merge (`applyDocumentPatches`, `since: []`) — the\n * same pure function both stores run (a queued whole-document write resets the view to\n * its snapshot at its place in the order). So local edits win on their paths until they\n * are flushed (EC-595 point 7), and a server row adopted underneath them (a write\n * result, a subscription push, a conflict's `current`) shows everywhere else at once.\n *\n * **A value and the revision it was authored against travel together (EC-647).** Every\n * view this persister shows is registered with the revision it is at\n * ({@link CmsPersister.revisionOfView} — the shown document object IS the token), and a\n * writer hands each patch over WITH the revision of the view it was authored on\n * (`bases`, required). The persister never substitutes a newer revision for it — not at\n * commit (the old `bases ?? tracked revision` default), not at send (the old\n * `queued.base ?? entry.base.revision`), not in a whole-document `replace` (which read\n * the tracked revision at SEND time — Codex F10), and not for an untracked document\n * (which sent at whatever revision a later read returned). A write that cannot name the\n * revision it was authored against is refused, visibly — it never borrows one.\n *\n * - **A position under one of this session's own unacknowledged writes** (queued, in\n * flight, or an open conflict's \"mine\") was authored against THAT write's base: the\n * view showed mine there, not a colleague's change that may sit underneath it. The\n * later write takes the earlier base, so a colleague's hidden change is still refused\n * on it (same-field supersession has always kept the earlier base for this reason).\n * - **The own-write ledger.** A base may be LIFTED, at send time, across revisions this\n * persister wrote — and only those: across a run of consecutive own revisions right\n * after it (nothing foreign happened in between), or to an own write's revision when\n * the patch only touches positions that write covered and the write was sent at or\n * below the patch's base (the store refused every foreign change of those positions in\n * between, or the write would not have applied). Without it, the session's second\n * edit of a position, made at the revision its first was authored against, would be\n * refused by its own first write.\n * - **The provisional view** (`undefined` authoring revision): a document whose view\n * has no revision yet — our own create in flight, or a document the session never\n * tracked (a staged transfer). Writes on it are based on the revision our create\n * landed at, or — untracked — on a read of the document that EQUALS the view they were\n * authored on; anything else is refused as a conflict per position.\n *\n * Consecutive runs of equal (lifted) base are sent in commit order, one\n * `documents.patch` call per run; a queued whole-document write is sent in its place in\n * that order.\n *\n * **A refused path is a conflict ON THAT FIELD** ({@link DocumentConflict}): the\n * session shows \"changed by X — take theirs / keep mine\"; until the user decides, the\n * field keeps showing mine (and further edits of it replace mine without being sent);\n * keep-mine re-sends at the current base — the ONE deliberate \"at the current base\"\n * write: the user chose it after seeing theirs; take-theirs drops mine. Never a\n * whole-document dialog, never a silent overwrite.\n */\n\n/** One refused patch awaiting the user's decision (EC-595 binding point 5). */\nexport interface DocumentConflict {\n /** Stable id for the UI (`<key>|<path>`); one conflict per path. */\n readonly id: string\n readonly ref: DocumentRef\n /** The refused patch — \"mine\". */\n readonly patch: DocumentPatch\n /** The submitted target path. */\n readonly path: ValuePath\n /** The value at that path on the server NOW — \"theirs\" (`undefined` = absent). */\n readonly theirs: unknown\n /** `conflict` — changed since the base; `invalid` — never resolved (e.g. its node is gone). */\n readonly reason: RefusedPatch['reason']\n /** The server revision the refusal was made at. */\n readonly revision: number\n /** Who changed the path (the patch log's actor), once resolved; `undefined` while unknown. */\n readonly actor?: string\n}\n\n/** How one {@link CmsPersister.commit} ended once its patches were acknowledged. */\nexport type CommitOutcome =\n | { readonly status: 'applied'; readonly record: CmsDocumentRecord }\n /** Refused per field — the conflicts stay open on the document for the user to resolve. */\n | { readonly status: 'refused'; readonly conflicts: readonly DocumentConflict[] }\n /** A transport / authorization failure, or a write that named no authoring revision (also reported through `onError`). */\n | { readonly status: 'failed'; readonly error: OperationError }\n\nexport interface CmsPersister {\n /** Adopt a server row as this session's base for its document (hydration, a create result). */\n track(row: TrackedRow): void\n /** The revision the session's view of a document is at now (`undefined` = untracked). */\n revisionOf(ref: DocumentRef): number | undefined\n /** The session's view of a tracked document (base ⊕ local), or `undefined`. */\n documentOf(ref: DocumentRef): CmsDocument | undefined\n /**\n * EC-647 — the revision a document value this persister SHOWED is at: every view it\n * emits (`onDocument`, {@link documentOf}) and every row it tracks is registered with\n * its revision, so a writer holding the value it displayed holds its revision too —\n * the pair cannot drift apart. `undefined` for a value the persister never showed (a\n * copy, a fixture), or a provisional view (our own create in flight, an untracked\n * document).\n */\n revisionOfView(view: CmsDocument): number | undefined\n /**\n * Commit patches a writer made and flush them. The session's view updates\n * synchronously (via `onDocument`); the patches persist in order through\n * `documents.patch`. `bases` — REQUIRED, one per patch: the revision of the view the\n * writer authored that patch against (an editor field: the revision its draft was at\n * when the user STARTED that edit; the canvas: the revision of the value its delta is\n * measured from; a table row: {@link revisionOfView} of the row it showed; an AI\n * proposal: the revision of the read it was built from). `undefined` entries mean the\n * view was provisional (see the module doc) — on a document this session tracks and\n * did not create, such a patch is refused. `view` — the session's current document,\n * the provisional view of a document this session holds no revision for (a staged\n * transfer).\n */\n commit(\n ref: DocumentRef,\n patches: readonly DocumentPatch[],\n bases: readonly (number | undefined)[],\n view?: CmsDocument,\n ): Promise<CommitOutcome>\n /** Adopt a server row one of the session's OWN direct writes returned (publish, restore). */\n adoptRecord(record: CmsDocumentRecord): void\n /** Create a document (insert-if-absent: `documents.replace` `{ ifAbsent: true }`). */\n create(document: CmsDocument): void\n /**\n * Write a whole document at the revision it was AUTHORED against (EC-647 — the\n * snapshot and its revision travel together; Codex F10): an import, the slot alias. A\n * move since then — by anyone but this session's own writes — is refused as a\n * conflict, never overwritten. `revision` `undefined`: the snapshot was authored on a\n * provisional view (our own pending create; insert-if-absent when untracked). Sent in\n * its place among the session's queued patches.\n */\n replace(document: CmsDocument, revision: number | undefined): void\n deleteDocument(ref: DocumentRef): void\n unpublishDocument(ref: DocumentRef): void\n /**\n * Adopt a server row pushed by the document subscription (EC-595 point 7): applied\n * under the local patches (local wins until flushed); held while a write is in flight\n * and applied after it, so an echo of our own write never races its result.\n * `undefined` = the document is gone.\n */\n adoptSnapshot(ref: DocumentRef, record: CmsDocumentRecord | undefined): void\n /** The unresolved conflicts on a document. */\n conflicts(ref: DocumentRef): readonly DocumentConflict[]\n /** Resolve a conflict: `theirs` adopts the server value; `mine` re-sends at the current base. */\n resolveConflict(ref: DocumentRef, conflictId: string, choice: 'theirs' | 'mine'): void\n /** Await every queued write (of one document, or all). The FORCED FLUSH's persistence half. */\n flush(ref?: DocumentRef): Promise<void>\n}\n\nexport interface CmsPersisterOptions {\n projectId: string\n getOperations: () => Promise<OperationsClient>\n /** The session's collections (read lazily via a ref) — the create/import canonicaliser's lens. */\n getCollections: () => readonly CollectionDef[]\n /** Component-prop field-defs (EC-277), so a created document's composition props are canonical too. */\n lookupManifest?: PropFieldLookup\n /** A failed / denied write that is not a per-field conflict — rendered by the session, never silent. */\n onError: (error: OperationError) => void\n /**\n * The session's view of a document changed (an optimistic commit, an adopted server\n * row, a resolved conflict) — `undefined` when the document is gone. Synchronous. The\n * document object is registered with its revision ({@link CmsPersister.revisionOfView}).\n */\n onDocument?: (ref: DocumentRef, document: CmsDocument | undefined) => void\n /**\n * A server row was adopted (EC-449 and friends): the session stamps the chokepoint's\n * `hasUnpublishedChanges`, `updatedAt`, `publishedAt` from it — and, since the row\n * carries the CANONICAL saved values, the session adopts those too (EC-586\n * found-but-left: the studio never adopted the saved canonical document).\n */\n onRecord?: (record: CmsDocumentRecord) => void\n /** A document's conflict list changed. */\n onConflicts?: (ref: DocumentRef, conflicts: readonly DocumentConflict[]) => void\n}\n\n/** What the session hydrated for a document: its value and the revision it is at. */\nexport type TrackedRow = Pick<CmsDocumentRecord, 'document' | 'revision'>\n\n/** A committed patch and the revision it was AUTHORED against (EC-647 — never a tracked one). */\ninterface QueuedPatch {\n readonly kind: 'patch'\n readonly patch: DocumentPatch\n /** `undefined`: authored on the provisional view (our own pending create / an untracked document). */\n base: number | undefined\n /** The commits waiting on this patch (a superseded value write hands its waiters on). */\n readonly settle: ((outcome: CommitOutcome) => void)[]\n}\n\n/** A whole-document write, queued in its place among the patches (EC-647). */\ninterface QueuedReplace {\n readonly kind: 'replace'\n readonly document: CmsDocument\n /** The revision the snapshot was authored against (`undefined`: on the provisional view). */\n base: number | undefined\n}\n\ntype QueuedWrite = QueuedPatch | QueuedReplace\n\n/** One write THIS persister made and the store acknowledged (EC-647 — the own-write ledger). */\ninterface OwnWrite {\n readonly revision: number\n /** The base revision it was sent at (`undefined`: insert-if-absent, or a write with no base). */\n readonly sentBase: number | undefined\n /**\n * The positions its APPLIED patches touched: `undefined` = the whole document (a\n * replace / create — lifted across only as a consecutive own revision); `[]` = none\n * (an unpublish).\n */\n readonly paths: readonly ValuePath[] | undefined\n}\n\n/** How many own writes a document's ledger keeps (an older base just stops lifting — a conflict, never a borrow). */\nconst OWN_WRITES_KEPT = 256\n\n/** A patch's identity within one call: op + target path (no two value writes of one path share a run). */\nfunction targetKey(op: DocumentPatch['op'], path: ValuePath): string {\n return `${op} ${formatValuePath(path)}`\n}\n\nfunction patchTarget(patch: DocumentPatch): ValuePath {\n return patch.op === 'insert' ? [...patch.at.parent, { kind: 'node', id: patch.node.id }] : patch.path\n}\n\ninterface Entry {\n readonly ref: DocumentRef\n base: TrackedRow | undefined\n /** The session's document while no server row is adopted yet (a create in flight, an untracked doc). */\n provisional: CmsDocument | undefined\n /** Committed, not yet sent — patches and whole-document writes, in commit order. */\n queue: QueuedWrite[]\n /** Sent, awaiting the result. */\n inFlight: QueuedPatch[]\n /** A queued whole-document write that was sent, awaiting the result. */\n inFlightReplace: QueuedReplace | undefined\n /** A whole-document write (create / replace / unpublish / delete) in flight. */\n busy: boolean\n conflicts: DocumentConflict[]\n /** The base each open conflict's \"mine\" was authored against (by conflict id). */\n conflictBases: Map<string, number | undefined>\n /** A subscription row that arrived during a write (`null` = gone); adopted after it. */\n held: CmsDocumentRecord | null | undefined\n /** A drain is queued. */\n scheduled: boolean\n deleted: boolean\n /** Our own create of this document is in flight. */\n creating: boolean\n /** The revision our own create landed at (the base of every write authored on its provisional view). */\n created: number | undefined\n /** The own-write ledger (newest last). */\n own: OwnWrite[]\n}\n\nfunction conflictId(ref: DocumentRef, path: ValuePath): string {\n return `${documentKey(ref)}|${formatValuePath(path)}`\n}\n\n/** Paths two patches have in common (either touches a prefix of the other's). */\nfunction patchesOverlap(a: DocumentPatch, b: DocumentPatch): boolean {\n return touchedPaths(a).some((p) => touchedPaths(b).some((q) => valuePathsOverlap(p, q)))\n}\n\n/** A `set`/`unset` on exactly one path — the shape a later edit of the same field supersedes. */\nfunction isValueWrite(patch: DocumentPatch): patch is Extract<DocumentPatch, { op: 'set' | 'unset' }> {\n return patch.op === 'set' || patch.op === 'unset'\n}\n\nfunction samePath(a: ValuePath, b: ValuePath): boolean {\n return a.length === b.length && valuePathsOverlap(a, b)\n}\n\n/** The earlier of two authoring bases (`undefined` — the provisional view — is the earliest of all). */\nfunction earlierBase(a: number | undefined, b: number | undefined): number | undefined {\n return a === undefined || b === undefined ? undefined : Math.min(a, b)\n}\n\n/** The refusal of a write that names no revision it was authored against (EC-647). */\nfunction unauthoredError(ref: DocumentRef): OperationError {\n return {\n code: 'conflict',\n key: documentKey(ref),\n message:\n 'A change was not saved: it does not say which revision of the document it was made on, so it could overwrite a change made since (EC-647).',\n messageRef: { key: 'cms.conflict.unauthored' },\n }\n}\n\nexport function createCmsPersister(options: CmsPersisterOptions): CmsPersister {\n const queue = createPersistQueue((error) => {\n options.onError({\n code: 'unknown',\n message: error instanceof Error ? error.message : String(error),\n })\n })\n const entries = new Map<string, Entry>()\n /** EC-647: every document value this persister showed or tracked → the revision it is at. */\n const shown = new WeakMap<CmsDocument, number>()\n\n function entryOf(ref: DocumentRef): Entry {\n const key = documentKey(ref)\n let entry = entries.get(key)\n if (!entry) {\n entry = {\n ref: { collection: ref.collection, id: ref.id },\n base: undefined,\n provisional: undefined,\n queue: [],\n inFlight: [],\n inFlightReplace: undefined,\n busy: false,\n conflicts: [],\n conflictBases: new Map(),\n held: undefined,\n scheduled: false,\n deleted: false,\n creating: false,\n created: undefined,\n own: [],\n }\n entries.set(key, entry)\n }\n return entry\n }\n\n /** EC-586: THE write canonicaliser over a whole document a writer hands us (create/import). */\n function canonical(doc: CmsDocument): CmsDocument {\n const collection = options.getCollections().find((c) => c.id === doc.collection)\n if (!collection) return doc\n return selfTypeDocument(doc, collection, options.lookupManifest ? { lookupManifest: options.lookupManifest } : {})\n }\n\n /** The queued patches (not whole-document writes). */\n function queuedPatches(entry: Entry): QueuedPatch[] {\n return entry.queue.filter((queued): queued is QueuedPatch => queued.kind === 'patch')\n }\n\n /**\n * The session's view: base ⊕ unresolved mine ⊕ in-flight ⊕ queued (the pure merge, no\n * log; a whole-document write resets it to its snapshot). Registered with the revision\n * it is at (EC-647) — the base's; a provisional view has none.\n */\n function display(entry: Entry): CmsDocument | undefined {\n const baseDocument = entry.base?.document ?? entry.provisional\n if (entry.deleted || !baseDocument) return undefined\n let document = baseDocument\n let patches: DocumentPatch[] = entry.conflicts.map((conflict) => conflict.patch)\n const pending: QueuedWrite[] = [\n ...entry.inFlight,\n ...(entry.inFlightReplace ? [entry.inFlightReplace] : []),\n ...entry.queue,\n ]\n for (const queued of pending) {\n if (queued.kind === 'replace') {\n // The snapshot was authored over everything before it (the editor's draft).\n patches = []\n document = queued.document\n } else patches.push(queued.patch)\n }\n if (patches.length > 0) document = applyDocumentPatches({ document, patches, since: [] }).document\n if (entry.base) shown.set(document, entry.base.revision)\n return document\n }\n\n function emitDocument(entry: Entry): void {\n if (entry.deleted) return\n const view = display(entry)\n if (view) options.onDocument?.(entry.ref, view)\n }\n\n function emitConflicts(entry: Entry): void {\n options.onConflicts?.(entry.ref, [...entry.conflicts])\n }\n\n /** Adopt a server row as the base (never a lower revision), re-derive the view. */\n function adopt(entry: Entry, record: CmsDocumentRecord): void {\n if (entry.base && record.revision < entry.base.revision) return\n entry.base = record\n shown.set(record.document, record.revision)\n options.onRecord?.(record)\n emitDocument(entry)\n }\n\n /** After a write: apply a subscription row that arrived meanwhile, if newer. */\n function adoptHeld(entry: Entry): void {\n const held = entry.held\n entry.held = undefined\n if (held === undefined) return\n if (held === null) {\n markGone(entry)\n return\n }\n if (!entry.base || held.revision > entry.base.revision) adopt(entry, held)\n }\n\n function settleAll(queued: readonly QueuedPatch[], outcome: CommitOutcome): void {\n for (const item of queued) for (const settle of item.settle) settle(outcome)\n }\n\n /** Drop every queued write, settling its waiters (the document is gone, or the writes cannot be based). */\n function dropQueued(entry: Entry, outcome: CommitOutcome, which: (queued: QueuedWrite) => boolean = () => true): void {\n const dropped = entry.queue.filter(which)\n entry.queue = entry.queue.filter((queued) => !which(queued))\n settleAll(\n dropped.filter((queued): queued is QueuedPatch => queued.kind === 'patch'),\n outcome,\n )\n }\n\n function markGone(entry: Entry): void {\n if (entry.deleted) return\n entry.deleted = true\n dropQueued(entry, {\n status: 'failed',\n error: { code: 'not-found', message: 'The document is gone.', entity: 'cms-document', key: documentKey(entry.ref) },\n })\n options.onDocument?.(entry.ref, undefined)\n }\n\n function schedule(entry: Entry): void {\n if (entry.scheduled) return\n entry.scheduled = true\n queue.push(async () => {\n entry.scheduled = false\n await drain(entry)\n adoptHeld(entry)\n })\n }\n\n /** EC-647: record one of this persister's acknowledged writes (the own-write ledger). */\n function recordOwn(entry: Entry, write: OwnWrite): void {\n entry.own.push(write)\n if (entry.own.length > OWN_WRITES_KEPT) entry.own.splice(0, entry.own.length - OWN_WRITES_KEPT)\n }\n\n /**\n * EC-647 — THE lift: the base a write authored at `base` is SENT at. Only across this\n * persister's own writes (see the module doc): a run of consecutive own revisions\n * right after the base, or an own write that covered every position `paths` touch and\n * was sent at or below the base. Never across a revision anyone else wrote.\n */\n function lift(entry: Entry, base: number, paths: readonly ValuePath[] | undefined): number {\n let lifted = base\n for (;;) {\n if (entry.own.some((write) => write.revision === lifted + 1)) {\n lifted += 1\n continue\n }\n const covering = paths\n ? entry.own.find(\n (write) =>\n write.revision > lifted &&\n write.paths !== undefined &&\n write.sentBase !== undefined &&\n write.sentBase <= lifted &&\n paths.every((path) => write.paths!.some((covered) => isValuePathPrefix(covered, path))),\n )\n : undefined\n if (!covering) return lifted\n lifted = covering.revision\n }\n }\n\n /**\n * EC-647 — the base a write is QUEUED with: the revision it was authored against, or\n * the earlier base of an own unacknowledged write on the same positions (the view\n * showed mine there, not whatever may sit underneath it).\n */\n function authoredBase(entry: Entry, patch: DocumentPatch | undefined, authored: number | undefined): number | undefined {\n let base = authored\n const overlaps = (other: DocumentPatch) => patch === undefined || patchesOverlap(other, patch)\n for (const queued of [...entry.inFlight, ...entry.queue]) {\n if (queued.kind === 'replace' || overlaps(queued.patch)) base = earlierBase(base, queued.base)\n }\n if (entry.inFlightReplace) base = earlierBase(base, entry.inFlightReplace.base)\n for (const conflict of entry.conflicts) {\n if (overlaps(conflict.patch)) base = earlierBase(base, entry.conflictBases.get(conflict.id))\n }\n return base\n }\n\n /** Whether a write may be authored on a provisional view (our own create, or an untracked document). */\n function provisionalAllowed(entry: Entry): boolean {\n return entry.creating || entry.created !== undefined || !entry.base\n }\n\n /** Our own create landed (or failed): base every write authored on its provisional view. */\n function baseOnCreated(entry: Entry): void {\n if (entry.created === undefined) return\n for (const queued of entry.queue) if (queued.base === undefined) queued.base = entry.created\n }\n\n /**\n * EC-647 — writes authored on the provisional view of a document this session holds no\n * revision for (a staged transfer): read it; when it still EQUALS the view they were\n * authored on, that read's revision is theirs — otherwise each is refused as a\n * conflict on its position (theirs = the read). Never \"whatever revision the read\n * returns\". `false` when the read failed (the writes stay queued, the error shows).\n */\n async function baseOnRead(entry: Entry, operations: OperationsClient): Promise<boolean> {\n if (!entry.queue.some((queued) => queued.kind === 'patch' && queued.base === undefined)) return true\n if (entry.created !== undefined) {\n baseOnCreated(entry)\n return true\n }\n if (entry.base) {\n // A tracked document this session did not create: commit already refused these.\n const error = unauthoredError(entry.ref)\n dropQueued(entry, { status: 'failed', error }, (queued) => queued.kind === 'patch' && queued.base === undefined)\n options.onError(error)\n return true\n }\n const read = await operations.documents.get({ projectId: options.projectId, ref: entry.ref })\n if (!read.ok) {\n options.onError(read.error)\n return false\n }\n const record = read.value\n const authoredOn = entry.provisional\n if (authoredOn && semanticValueEqual(record.document, authoredOn)) {\n for (const queued of entry.queue) if (queued.kind === 'patch' && queued.base === undefined) queued.base = record.revision\n } else {\n const refused: DocumentConflict[] = []\n for (const queued of queuedPatches(entry)) {\n if (queued.base !== undefined) continue\n const path = patchTarget(queued.patch)\n const conflict = upsertConflict(\n entry,\n {\n patch: queued.patch,\n reason: 'conflict',\n path,\n current: readValueAt(record.document, path),\n detail: 'the document changed since the view this edit was made on',\n },\n record.revision,\n record.revision,\n )\n refused.push(conflict)\n for (const settle of queued.settle) settle({ status: 'refused', conflicts: [conflict] })\n }\n entry.queue = entry.queue.filter((queued) => !(queued.kind === 'patch' && queued.base === undefined))\n if (refused.length > 0) emitConflicts(entry)\n }\n adopt(entry, record)\n return true\n }\n\n /** Who changed a refused path — the newest patch-log row in (base, current] touching it. Best-effort. */\n async function resolveActors(entry: Entry, sentBase: number, refused: readonly DocumentConflict[]): Promise<void> {\n try {\n const operations = await options.getOperations()\n const log = await operations.documents.listPatches({\n projectId: options.projectId,\n ref: entry.ref,\n afterRevision: sentBase,\n })\n if (!log.ok) return\n let changed = false\n entry.conflicts = entry.conflicts.map((conflict) => {\n if (conflict.actor !== undefined || !refused.some((r) => r.id === conflict.id)) return conflict\n const row = [...log.value]\n .reverse()\n .find(\n (candidate) =>\n candidate.kind === 'replace' ||\n candidate.patches.some((patch) =>\n touchedPaths(patch).some((path) => valuePathsOverlap(path, conflict.path)),\n ),\n )\n if (!row?.actor) return conflict\n changed = true\n return { ...conflict, actor: row.actor }\n })\n if (changed) emitConflicts(entry)\n } catch {\n // The actor is decoration on a conflict the user can already resolve.\n }\n }\n\n /** Send one queued whole-document write at the revision its snapshot was authored against. `false` → stop draining. */\n async function sendReplace(entry: Entry, operations: OperationsClient, write: QueuedReplace): Promise<boolean> {\n const precondition =\n write.base !== undefined\n ? { revision: lift(entry, write.base, undefined) }\n : entry.created !== undefined\n ? { revision: lift(entry, entry.created, undefined) }\n : !entry.base\n ? { ifAbsent: true as const }\n : undefined\n entry.queue.shift()\n if (!precondition) {\n // A tracked document this session did not create, written whole from a view with no revision.\n options.onError(unauthoredError(entry.ref))\n emitDocument(entry)\n return true\n }\n entry.inFlightReplace = write\n entry.busy = true\n try {\n const result = await operations.documents.replace({\n projectId: options.projectId,\n document: write.document,\n precondition,\n })\n entry.inFlightReplace = undefined\n if (result.ok) {\n recordOwn(entry, {\n revision: result.value.revision,\n sentBase: 'revision' in precondition ? precondition.revision : undefined,\n paths: undefined,\n })\n adopt(entry, result.value)\n } else {\n if (result.error.code === 'conflict' && 'current' in result.error && result.error.current) {\n adopt(entry, result.error.current)\n } else emitDocument(entry)\n options.onError(result.error)\n }\n } finally {\n entry.inFlightReplace = undefined\n entry.busy = false\n adoptHeld(entry)\n }\n return true\n }\n\n /** Send the queue — runs of equal (lifted) base, whole-document writes in their place — until it is empty or a write fails. */\n async function drain(entry: Entry): Promise<void> {\n while (entry.queue.length > 0 && !entry.deleted) {\n const operations = await options.getOperations()\n if (!(await baseOnRead(entry, operations))) return\n const head = entry.queue[0]\n if (!head) return\n if (head.kind === 'replace') {\n await sendReplace(entry, operations, head)\n continue\n }\n const sendBase = (queued: QueuedPatch) => lift(entry, queued.base!, touchedPaths(queued.patch))\n const first = sendBase(head)\n let end = 1\n while (end < entry.queue.length) {\n const next = entry.queue[end]!\n if (next.kind !== 'patch' || sendBase(next) !== first) break\n end += 1\n }\n const run = entry.queue.splice(0, end) as QueuedPatch[]\n entry.inFlight = run\n const result = await operations.documents.patch({\n projectId: options.projectId,\n ref: entry.ref,\n baseRevision: first,\n patches: run.map((queued) => queued.patch),\n })\n entry.inFlight = []\n if (result.ok) {\n recordOwn(entry, {\n revision: result.value.revision,\n sentBase: first,\n paths: run.flatMap((queued) => touchedPaths(queued.patch)),\n })\n adopt(entry, result.value)\n adoptHeld(entry)\n settleAll(run, { status: 'applied', record: result.value })\n continue\n }\n const error = result.error\n if (error.code === 'conflict' && error.refused && error.current) {\n const current = error.current\n // Refusals are matched to the run by op + target path (the operation re-parses\n // and canonicalises the patches, so object identity does not survive the call).\n const refusedByKey = new Map(\n error.refused.map((refused) => [targetKey(refused.patch.op, refused.path), refused]),\n )\n const applied: QueuedPatch[] = []\n const conflicts: DocumentConflict[] = []\n for (const queued of run) {\n const refused = refusedByKey.get(targetKey(queued.patch.op, patchTarget(queued.patch)))\n if (!refused) {\n applied.push(queued)\n continue\n }\n // MINE is what the user wrote (the queued patch), not the canonicalised echo.\n const conflict = upsertConflict(entry, { ...refused, patch: queued.patch }, current.revision, queued.base)\n conflicts.push(conflict)\n for (const settle of queued.settle) settle({ status: 'refused', conflicts: [conflict] })\n }\n // A partially applied run IS a write of ours (the row it returns is after it);\n // a wholly refused one wrote nothing — its row is someone else's revision.\n if (applied.length > 0) {\n recordOwn(entry, {\n revision: current.revision,\n sentBase: first,\n paths: applied.flatMap((queued) => touchedPaths(queued.patch)),\n })\n }\n adopt(entry, current)\n adoptHeld(entry)\n emitConflicts(entry)\n settleAll(applied, { status: 'applied', record: current })\n void resolveActors(entry, first, conflicts)\n continue\n }\n if (error.code === 'conflict' && 'current' in error && error.current === null) {\n // The document was deleted since — nothing to write into.\n markGone(entry)\n options.onError(error)\n settleAll(run, { status: 'failed', error })\n return\n }\n // A transport / authorization failure: the patches stay local (shown, unsent) and\n // the error is visible; the next commit or forced flush retries them. The commits\n // waiting on them learn of the failure now.\n settleAll(run, { status: 'failed', error })\n entry.queue.unshift(...run.map((queued) => ({ ...queued, settle: [] })))\n adoptHeld(entry)\n options.onError(error)\n return\n }\n }\n\n function upsertConflict(\n entry: Entry,\n refused: RefusedPatch,\n revision: number,\n base: number | undefined,\n ): DocumentConflict {\n const conflict: DocumentConflict = {\n id: conflictId(entry.ref, refused.path),\n ref: entry.ref,\n patch: refused.patch,\n path: refused.path,\n theirs: refused.current,\n reason: refused.reason,\n revision,\n }\n entry.conflicts = [...entry.conflicts.filter((c) => c.id !== conflict.id), conflict]\n entry.conflictBases.set(conflict.id, base)\n return conflict\n }\n\n function command(entry: Entry, run: (operations: OperationsClient) => Promise<OperationResult<unknown>>): void {\n queue.push(async () => {\n const operations = await options.getOperations()\n entry.busy = true\n try {\n const result = await run(operations)\n if (!result.ok) options.onError(result.error)\n } finally {\n entry.busy = false\n adoptHeld(entry)\n }\n })\n }\n\n return {\n track(row) {\n const entry = entryOf(row.document)\n shown.set(row.document, row.revision)\n if (!entry.base || row.revision > entry.base.revision) entry.base = row\n },\n revisionOf: (ref) => entries.get(documentKey(ref))?.base?.revision,\n documentOf: (ref) => {\n const entry = entries.get(documentKey(ref))\n return entry ? display(entry) : undefined\n },\n revisionOfView: (view) => shown.get(view),\n adoptRecord(record) {\n const entry = entryOf(record.document)\n if (entry.deleted) return\n if (!entry.base || record.revision > entry.base.revision) adopt(entry, record)\n },\n commit(ref, patches, bases, view) {\n const entry = entryOf(ref)\n if (patches.length === 0 || entry.deleted) {\n return Promise.resolve<CommitOutcome>({\n status: 'failed',\n error: { code: 'not-found', message: 'The document is gone.', entity: 'cms-document', key: documentKey(ref) },\n })\n }\n if (!Array.isArray(bases)) {\n // EC-647: a writer that names no authoring revision at all — never given the tracked one.\n const error = unauthoredError(ref)\n options.onError(error)\n return Promise.resolve<CommitOutcome>({ status: 'failed', error })\n }\n if (!entry.base && !entry.provisional && view) entry.provisional = view\n let conflictsChanged = false\n let unauthored = false\n const waits: Promise<CommitOutcome>[] = []\n for (const [index, patch] of patches.entries()) {\n const authored = bases[index]\n let settle!: (outcome: CommitOutcome) => void\n waits.push(new Promise<CommitOutcome>((resolve) => (settle = resolve)))\n if (authored === undefined && !provisionalAllowed(entry)) {\n // EC-647: authored on a view with no revision, on a document this session\n // tracks and did not create — it cannot be checked, so it is not sent.\n unauthored = true\n settle({ status: 'failed', error: unauthoredError(ref) })\n continue\n }\n // A field with an unresolved conflict: the new value replaces MINE, unsent —\n // the user decides (keep mine sends it), never an implicit overwrite of theirs.\n const open = entry.conflicts.find((conflict) => patchesOverlap(conflict.patch, patch))\n if (open && isValueWrite(patch) && isValueWrite(open.patch) && samePath(open.patch.path, patch.path)) {\n const replaced: DocumentConflict = { ...open, patch }\n entry.conflicts = entry.conflicts.map((c) => (c === open ? replaced : c))\n conflictsChanged = true\n settle({ status: 'refused', conflicts: [replaced] })\n continue\n }\n const base = authoredBase(entry, patch, authored)\n // A later value write of the same field supersedes an unsent one (keeping the\n // EARLIER base — the user never saw a foreign value of a field they were typing\n // in). Only after the last queued whole-document write: one before it is sent\n // before the snapshot that was authored over it.\n if (isValueWrite(patch)) {\n let after = 0\n entry.queue.forEach((queued, at) => {\n if (queued.kind === 'replace') after = at + 1\n })\n const pending = entry.queue.findIndex(\n (queued, at) =>\n at >= after && queued.kind === 'patch' && isValueWrite(queued.patch) && samePath(queued.patch.path, patch.path),\n )\n if (pending >= 0) {\n const superseded = entry.queue[pending] as QueuedPatch\n entry.queue[pending] = {\n kind: 'patch',\n patch,\n base: earlierBase(superseded.base, base),\n settle: [...superseded.settle, settle],\n }\n continue\n }\n }\n entry.queue.push({ kind: 'patch', patch, base, settle: [settle] })\n }\n if (unauthored) options.onError(unauthoredError(ref))\n emitDocument(entry)\n if (conflictsChanged) emitConflicts(entry)\n schedule(entry)\n // The commit's outcome: failed if any of its patches failed, refused if any was.\n return Promise.all(waits).then((outcomes): CommitOutcome => {\n const failed = outcomes.find((o) => o.status === 'failed')\n if (failed) return failed\n const refused = outcomes.flatMap((o) => (o.status === 'refused' ? o.conflicts : []))\n if (refused.length > 0) return { status: 'refused', conflicts: refused }\n return outcomes[outcomes.length - 1]!\n })\n },\n create(document) {\n const doc = canonical(document)\n const entry = entryOf(doc)\n // A fresh document: nothing of an earlier incarnation of this ref carries over.\n entry.deleted = false\n entry.base = undefined\n entry.own = []\n entry.created = undefined\n entry.creating = true\n // Optimistic: the session shows the document at once; the base is the created row.\n entry.provisional = doc\n options.onDocument?.(entry.ref, doc)\n queue.push(async () => {\n const operations = await options.getOperations()\n entry.busy = true\n try {\n const result = await operations.documents.replace({\n projectId: options.projectId,\n document: doc,\n precondition: { ifAbsent: true },\n })\n if (result.ok) {\n entry.created = result.value.revision\n recordOwn(entry, { revision: result.value.revision, sentBase: undefined, paths: undefined })\n baseOnCreated(entry)\n adopt(entry, result.value)\n } else {\n options.onError(result.error)\n // EC-647: the writes authored on the document we meant to create have no\n // revision to be based on — never the revision of a row someone else wrote.\n dropQueued(entry, { status: 'failed', error: result.error }, (queued) => queued.base === undefined)\n }\n } finally {\n entry.creating = false\n entry.busy = false\n adoptHeld(entry)\n }\n if (entry.queue.length > 0) await drain(entry)\n })\n },\n replace(document, revision) {\n const doc = canonical(document)\n const entry = entryOf(doc)\n if (!entry.base && !entry.provisional) entry.provisional = doc\n // Queued in its place: the patches committed before it are sent first (the snapshot\n // holds them), the ones committed after it are sent after it (it does not). EC-647\n // (Codex F10): one with no authoring revision on a document this session tracks and\n // did not create is refused there, in order — never sent at the tracked revision.\n entry.queue.push({ kind: 'replace', document: doc, base: authoredBase(entry, undefined, revision) })\n emitDocument(entry)\n schedule(entry)\n },\n deleteDocument(ref) {\n const entry = entryOf(ref)\n dropQueued(entry, {\n status: 'failed',\n error: { code: 'not-found', message: 'The document is gone.', entity: 'cms-document', key: documentKey(ref) },\n })\n entry.conflicts = []\n entry.conflictBases.clear()\n entry.deleted = true\n emitConflicts(entry)\n command(entry, (operations) => operations.documents.delete({ projectId: options.projectId, ref }))\n },\n unpublishDocument(ref) {\n const entry = entryOf(ref)\n queue.push(async () => {\n await drain(entry)\n const operations = await options.getOperations()\n entry.busy = true\n try {\n const result = await operations.documents.unpublish({ projectId: options.projectId, ref })\n if (result.ok) {\n recordOwn(entry, { revision: result.value.revision, sentBase: undefined, paths: [] })\n adopt(entry, result.value)\n } else options.onError(result.error)\n } finally {\n entry.busy = false\n adoptHeld(entry)\n }\n })\n },\n adoptSnapshot(ref, record) {\n const entry = entryOf(ref)\n if (entry.inFlight.length > 0 || entry.busy || entry.scheduled) {\n // Hold it: the write's own result decides first; the newer of the two wins.\n if (record === undefined) entry.held = null\n else if (!entry.held || record.revision > entry.held.revision) entry.held = record\n return\n }\n if (record === undefined) {\n if (entry.base) markGone(entry)\n return\n }\n if (!entry.base || record.revision > entry.base.revision) adopt(entry, record)\n },\n conflicts: (ref) => entries.get(documentKey(ref))?.conflicts ?? [],\n resolveConflict(ref, id, choice) {\n const entry = entries.get(documentKey(ref))\n if (!entry) return\n const conflict = entry.conflicts.find((c) => c.id === id)\n if (!conflict) return\n entry.conflicts = entry.conflicts.filter((c) => c !== conflict)\n entry.conflictBases.delete(conflict.id)\n if (choice === 'mine') {\n // Keep mine: re-send at the CURRENT base — a visible, explicit second write, and\n // the one deliberate \"at the current base\" write (EC-647): the user chose it\n // after seeing theirs.\n entry.queue.push({ kind: 'patch', patch: conflict.patch, base: entry.base?.revision, settle: [] })\n schedule(entry)\n }\n emitDocument(entry)\n emitConflicts(entry)\n },\n async flush(ref) {\n if (ref) {\n const entry = entries.get(documentKey(ref))\n if (entry && entry.queue.length > 0) schedule(entry)\n }\n await queue.flush()\n },\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"cms-persistence.js","sourceRoot":"","sources":["../../../src/lib/operations/cms-persistence.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,oBAAoB,EACpB,WAAW,EACX,eAAe,EACf,iBAAiB,EACjB,WAAW,EACX,gBAAgB,EAChB,kBAAkB,EAClB,YAAY,EACZ,iBAAiB,GAClB,MAAM,0BAA0B,CAAA;AAYjC,OAAO,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAA;AAuPpD,qHAAqH;AACrH,MAAM,eAAe,GAAG,GAAG,CAAA;AAiB3B;;;;;;GAMG;AACH,SAAS,YAAY,CAAC,UAA0B,EAAE,IAA2B;IAC3E,IAAI,EAAE,GAAG,UAAU,CAAC,KAAK,CAAA;IACzB,KAAK,MAAM,KAAK,IAAI,UAAU,CAAC,MAAM,EAAE,CAAC;QACtC,IAAI,IAAI,KAAK,SAAS,IAAI,KAAK,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,iBAAiB,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC,EAAE,CAAC;YAC1F,EAAE,GAAG,WAAW,CAAC,EAAE,EAAE,KAAK,CAAC,IAAI,CAAC,CAAA;QAClC,CAAC;IACH,CAAC;IACD,OAAO,EAAE,CAAA;AACX,CAAC;AAED,0GAA0G;AAC1G,SAAS,SAAS,CAAC,EAAuB,EAAE,IAAe;I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MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,KAAK,QAAQ,CAAC,CAAA;YAC/D,KAAK,CAAC,aAAa,CAAC,MAAM,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAA;YACvC,IAAI,MAAM,KAAK,MAAM,EAAE,CAAC;gBACtB,iFAAiF;gBACjF,6EAA6E;gBAC7E,uBAAuB;gBACvB,KAAK,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,OAAO,EAAE,KAAK,EAAE,QAAQ,CAAC,KAAK,EAAE,IAAI,EAAE,KAAK,CAAC,IAAI,EAAE,QAAQ,EAAE,MAAM,EAAE,EAAE,EAAE,CAAC,CAAA;gBAClG,QAAQ,CAAC,KAAK,CAAC,CAAA;YACjB,CAAC;YACD,YAAY,CAAC,KAAK,CAAC,CAAA;YACnB,aAAa,CAAC,KAAK,CAAC,CAAA;QACtB,CAAC;QACD,KAAK,CAAC,KAAK,CAAC,GAAG;YACb,IAAI,GAAG,EAAE,CAAC;gBACR,MAAM,KAAK,GAAG,OAAO,CAAC,GAAG,CAAC,WAAW,CAAC,GAAG,CAAC,CAAC,CAAA;gBAC3C,IAAI,KAAK,IAAI,KAAK,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC;oBAAE,QAAQ,CAAC,KAAK,CAAC,CAAA;YACtD,CAAC;YACD,MAAM,KAAK,CAAC,KAAK,EAAE,CAAA;QACrB,CAAC;KACF,CAAA;AACH,CAAC","sourcesContent":["import {\n applyDocumentPatches,\n documentKey,\n formatValuePath,\n isValuePathPrefix,\n readValueAt,\n selfTypeDocument,\n semanticValueEqual,\n touchedPaths,\n valuePathsOverlap,\n} from '@elytracms/core/cms-core'\nimport type {\n CmsDocument,\n CollectionDef,\n DocumentPatch,\n DocumentRef,\n PropFieldLookup,\n RefusedPatch,\n ValuePath,\n} from '@elytracms/core/cms-core'\nimport type { CmsDocumentRecord } from '@elytracms/core/persistence'\nimport type { OperationError, OperationResult, OperationsClient } from './operations-package'\nimport { createPersistQueue } from './persist-queue'\n\n/**\n * CMS session → operations persistence (EC-141 → EC-595 part A2 → EC-647): the PATCH QUEUE.\n *\n * The CMS session keeps documents as optimistic, synchronous state; every write is\n * mirrored onto the operations layer through the revisioned aggregate's two verbs\n * (EC-595, ratified 2026-10-24): `documents.patch` for editing, `documents.replace`\n * for whole-document writers (create, import, the slot alias). There is no document\n * diffing anywhere: every writer EMITS the patches it made at its source (the form's\n * field path, the canvas's node patches, the AI proposal's field changes, bulk\n * set-field, transfer) and hands them to {@link CmsPersister.commit}.\n *\n * **Per document, the persister keeps** the server row it last adopted (`base`), the\n * committed-but-unacknowledged writes (each with the revision it was AUTHORED against),\n * the refused paths awaiting a decision, and the writes it made itself (the own-write\n * ledger). It derives the session's view of the document from them:\n *\n * display = base.document ⊕ unresolved conflicts (mine) ⊕ in-flight ⊕ queued\n *\n * by re-applying the patches with THE merge (`applyDocumentPatches`, `since: []`) — the\n * same pure function both stores run (a queued whole-document write resets the view to\n * its snapshot at its place in the order). So local edits win on their paths until they\n * are flushed (EC-595 point 7), and a server row adopted underneath them (a write\n * result, a subscription push, a conflict's `current`) shows everywhere else at once.\n *\n * **A value and the revision it was authored against travel together (EC-647).** Every\n * view this persister shows is registered with the revision it is at\n * ({@link CmsPersister.revisionOfView} — the shown document object IS the token), and a\n * writer hands each patch over WITH the revision of the view it was authored on\n * (`bases`, required). The persister never substitutes a newer revision for it — not at\n * commit (the old `bases ?? tracked revision` default), not at send (the old\n * `queued.base ?? entry.base.revision`), not in a whole-document `replace` (which read\n * the tracked revision at SEND time — Codex F10), and not for an untracked document\n * (which sent at whatever revision a later read returned). A write that cannot name the\n * revision it was authored against is refused, visibly — it never borrows one.\n *\n * - **A view's token is per position (EC-667, Codex F18).** A view that shows a pending\n * write is a COMPOSITE: no single underlying revision names it. Each shown view is\n * registered with its provenance at display time — the base's revision, or under a\n * pending whole-document write its snapshot's authoring revision, and over that each\n * own unacknowledged write shown (queued, in flight, an open conflict's \"mine\") with\n * the base it was authored at. `revisionOfView(view, path)` is the revision the content\n * at `path` was authored against (the earliest of the writes covering it);\n * `revisionOfView(view)` — a whole-document writer — the EARLIEST of all. The record is\n * immutable, so it outlives the pending write: an edit started on a view that showed a\n * snapshot keeps the snapshot's revision after the snapshot is refused or fails\n * (before EC-667 the composite was named by the base's revision — a colleague's change\n * adopted underneath a pending snapshot lent the edit its revision, and the edit,\n * authored on the old content, overwrote it).\n * - **A position under one of this session's own unacknowledged writes** (queued, in\n * flight, or an open conflict's \"mine\") was authored against THAT write's base: the\n * view showed mine there, not a colleague's change that may sit underneath it. The\n * later write takes the earlier base, so a colleague's hidden change is still refused\n * on it (same-field supersession has always kept the earlier base for this reason).\n * - **The own-write ledger.** A base may be LIFTED, at send time, across revisions this\n * persister wrote — and only those: across a run of consecutive own revisions right\n * after it (nothing foreign happened in between), or to an own write's revision when\n * the patch only touches positions that write covered and the write was sent at or\n * below the patch's base (the store refused every foreign change of those positions in\n * between, or the write would not have applied). Without it, the session's second\n * edit of a position, made at the revision its first was authored against, would be\n * refused by its own first write.\n * - **The provisional view** (`undefined` authoring revision): a document whose view\n * has no revision yet — our own create in flight, or a document the session never\n * tracked (a staged transfer). Writes on it are based on the revision our create\n * landed at, or — untracked — on a read of the document that EQUALS the view they were\n * authored on; anything else is refused as a conflict per position.\n *\n * Consecutive runs of equal (lifted) base are sent in commit order, one\n * `documents.patch` call per run; a queued whole-document write is sent in its place in\n * that order.\n *\n * **A refused path is a conflict ON THAT FIELD** ({@link DocumentConflict}): the\n * session shows \"changed by X — take theirs / keep mine\"; until the user decides, the\n * field keeps showing mine (and further edits of it replace mine without being sent);\n * keep-mine re-sends at the current base — the ONE deliberate \"at the current base\"\n * write: the user chose it after seeing theirs; take-theirs drops mine. Never a\n * whole-document dialog, never a silent overwrite.\n */\n\n/** One refused patch awaiting the user's decision (EC-595 binding point 5). */\nexport interface DocumentConflict {\n /** Stable id for the UI (`<key>|<path>`); one conflict per path. */\n readonly id: string\n readonly ref: DocumentRef\n /** The refused patch — \"mine\". */\n readonly patch: DocumentPatch\n /** The submitted target path. */\n readonly path: ValuePath\n /** The value at that path on the server NOW — \"theirs\" (`undefined` = absent). */\n readonly theirs: unknown\n /** `conflict` — changed since the base; `invalid` — never resolved (e.g. its node is gone). */\n readonly reason: RefusedPatch['reason']\n /** The server revision the refusal was made at. */\n readonly revision: number\n /** Who changed the path (the patch log's actor), once resolved; `undefined` while unknown. */\n readonly actor?: string\n}\n\n/** How one {@link CmsPersister.commit} ended once its patches were acknowledged. */\nexport type CommitOutcome =\n | { readonly status: 'applied'; readonly record: CmsDocumentRecord }\n /** Refused per field — the conflicts stay open on the document for the user to resolve. */\n | { readonly status: 'refused'; readonly conflicts: readonly DocumentConflict[] }\n /** A transport / authorization failure, or a write that named no authoring revision (also reported through `onError`). */\n | { readonly status: 'failed'; readonly error: OperationError }\n\nexport interface CmsPersister {\n /** Adopt a server row as this session's base for its document (hydration, a create result). */\n track(row: TrackedRow): void\n /**\n * The revision of the server row the session last adopted for a document (`undefined` =\n * untracked). A document deleted since still answers its removed lifetime's last\n * revision (EC-673): a publish conditioned on it is refused, never sent unconditionally\n * into a re-creation this session never showed — so whether to create or replace is\n * never decided on it alone ({@link importWrite} decides on the row the session shows).\n */\n revisionOf(ref: DocumentRef): number | undefined\n /** The session's view of a tracked document (base ⊕ local), or `undefined`. */\n documentOf(ref: DocumentRef): CmsDocument | undefined\n /**\n * EC-647 — the revision a document value this persister SHOWED is at: every view it\n * emits (`onDocument`, {@link documentOf}) and every row it tracks is registered with\n * its revision, so a writer holding the value it displayed holds its revision too —\n * the pair cannot drift apart. `undefined` for a value the persister never showed (a\n * copy, a fixture), or a provisional view (our own create in flight, an untracked\n * document).\n *\n * EC-667 — per position: `path` given, the revision the content the view shows AT\n * `path` was authored against (an editor's first keystroke there); without it, the\n * EARLIEST authoring revision of any position the view shows — the token of a\n * whole-document writer (a replace, an import). A view showing a pending write is never\n * named by the base's revision alone (see the module doc).\n */\n revisionOfView(view: CmsDocument, path?: ValuePath): number | undefined\n /**\n * Commit patches a writer made and flush them. The session's view updates\n * synchronously (via `onDocument`); the patches persist in order through\n * `documents.patch`. `bases` — REQUIRED, one per patch: the revision of the view the\n * writer authored that patch against (an editor field: the revision its draft was at\n * when the user STARTED that edit; the canvas: the revision of the value its delta is\n * measured from; a table row: {@link revisionOfView} of the row it showed; an AI\n * proposal: the revision of the read it was built from). `undefined` entries mean the\n * view was provisional (see the module doc) — on a document this session tracks and\n * did not create, such a patch is refused. `view` — the session's current document,\n * the provisional view of a document this session holds no revision for (a staged\n * transfer).\n */\n commit(\n ref: DocumentRef,\n patches: readonly DocumentPatch[],\n bases: readonly (number | undefined)[],\n view?: CmsDocument,\n ): Promise<CommitOutcome>\n /** Adopt a server row one of the session's OWN direct writes returned (publish, restore). */\n adoptRecord(record: CmsDocumentRecord): void\n /** Create a document (insert-if-absent: `documents.replace` `{ ifAbsent: true }`). */\n create(document: CmsDocument): void\n /**\n * Write a whole document at the revision it was AUTHORED against (EC-647 — the\n * snapshot and its revision travel together; Codex F10): an import, the slot alias. A\n * move since then — by anyone but this session's own writes — is refused as a\n * conflict, never overwritten. `revision` `undefined`: the snapshot was authored on a\n * provisional view (our own pending create; insert-if-absent when untracked). Sent in\n * its place among the session's queued patches.\n */\n replace(document: CmsDocument, revision: number | undefined): void\n deleteDocument(ref: DocumentRef): void\n unpublishDocument(ref: DocumentRef): void\n /**\n * Adopt a server row pushed by the document subscription (EC-595 point 7): applied\n * under the local patches (local wins until flushed); held while a write is in flight\n * and applied after it, so an echo of our own write never races its result.\n * `undefined` = the document is gone.\n */\n adoptSnapshot(ref: DocumentRef, record: CmsDocumentRecord | undefined): void\n /** The unresolved conflicts on a document. */\n conflicts(ref: DocumentRef): readonly DocumentConflict[]\n /** Resolve a conflict: `theirs` adopts the server value; `mine` re-sends at the current base. */\n resolveConflict(ref: DocumentRef, conflictId: string, choice: 'theirs' | 'mine'): void\n /** Await every queued write (of one document, or all). The FORCED FLUSH's persistence half. */\n flush(ref?: DocumentRef): Promise<void>\n}\n\nexport interface CmsPersisterOptions {\n projectId: string\n getOperations: () => Promise<OperationsClient>\n /** The session's collections (read lazily via a ref) — the create/import canonicaliser's lens. */\n getCollections: () => readonly CollectionDef[]\n /** Component-prop field-defs (EC-277), so a created document's composition props are canonical too. */\n lookupManifest?: PropFieldLookup\n /** A failed / denied write that is not a per-field conflict — rendered by the session, never silent. */\n onError: (error: OperationError) => void\n /**\n * The session's view of a document changed (an optimistic commit, an adopted server\n * row, a resolved conflict) — `undefined` when the document is gone. Synchronous. The\n * document object is registered with its revision ({@link CmsPersister.revisionOfView}).\n */\n onDocument?: (ref: DocumentRef, document: CmsDocument | undefined) => void\n /**\n * A server row was adopted (EC-449 and friends): the session stamps the chokepoint's\n * `hasUnpublishedChanges`, `updatedAt`, `publishedAt` from it — and, since the row\n * carries the CANONICAL saved values, the session adopts those too (EC-586\n * found-but-left: the studio never adopted the saved canonical document).\n */\n onRecord?: (record: CmsDocumentRecord) => void\n /** A document's conflict list changed. */\n onConflicts?: (ref: DocumentRef, conflicts: readonly DocumentConflict[]) => void\n}\n\n/** What the session hydrated for a document: its value and the revision it is at. */\nexport type TrackedRow = Pick<CmsDocumentRecord, 'document' | 'revision'>\n\n/** A committed patch and the revision it was AUTHORED against (EC-647 — never a tracked one). */\ninterface QueuedPatch {\n readonly kind: 'patch'\n readonly patch: DocumentPatch\n /** `undefined`: authored on the provisional view (our own pending create / an untracked document). */\n base: number | undefined\n /** The commits waiting on this patch (a superseded value write hands its waiters on). */\n readonly settle: ((outcome: CommitOutcome) => void)[]\n}\n\n/** A whole-document write, queued in its place among the patches (EC-647). */\ninterface QueuedReplace {\n readonly kind: 'replace'\n readonly document: CmsDocument\n /** The revision the snapshot was authored against (`undefined`: on the provisional view). */\n base: number | undefined\n}\n\ntype QueuedWrite = QueuedPatch | QueuedReplace\n\n/** One write THIS persister made and the store acknowledged (EC-647 — the own-write ledger). */\ninterface OwnWrite {\n readonly revision: number\n /** The base revision it was sent at (`undefined`: insert-if-absent, or a write with no base). */\n readonly sentBase: number | undefined\n /**\n * The positions its APPLIED patches touched: `undefined` = the whole document (a\n * replace / create — lifted across only as a consecutive own revision); `[]` = none\n * (an unpublish).\n */\n readonly paths: readonly ValuePath[] | undefined\n}\n\n/** How many own writes a document's ledger keeps (an older base just stops lifting — a conflict, never a borrow). */\nconst OWN_WRITES_KEPT = 256\n\n/**\n * EC-667 — what a view this persister SHOWED was authored against, position by position,\n * recorded when it is shown (the shown object is the token; the record never changes).\n */\ninterface ViewProvenance {\n /**\n * The revision every position no entry of {@link writes} covers was authored at: the\n * base's — or, under a pending whole-document write, its snapshot's authoring revision\n * (`undefined`: none).\n */\n readonly floor: number | undefined\n /** This session's own unacknowledged writes shown over it: the positions each touched and the base it was authored at. */\n readonly writes: readonly { readonly paths: readonly ValuePath[]; readonly base: number | undefined }[]\n}\n\n/**\n * EC-667 — the revision the content a view shows at `path` was authored against: the\n * earliest of the floor and every shown write covering `path` (a write at `path` or at\n * an ancestor of it). `undefined` path — a whole-document writer — the earliest of all.\n * A write at a DESCENDANT of `path` does not lower it: that position's own token is\n * lower, and the write still pending when an edit of `path` commits lowers it there.\n */\nfunction provenanceAt(provenance: ViewProvenance, path: ValuePath | undefined): number | undefined {\n let at = provenance.floor\n for (const write of provenance.writes) {\n if (path === undefined || write.paths.some((covered) => isValuePathPrefix(covered, path))) {\n at = earlierBase(at, write.base)\n }\n }\n return at\n}\n\n/** A patch's identity within one call: op + target path (no two value writes of one path share a run). */\nfunction targetKey(op: DocumentPatch['op'], path: ValuePath): string {\n return `${op} ${formatValuePath(path)}`\n}\n\nfunction patchTarget(patch: DocumentPatch): ValuePath {\n return patch.op === 'insert' ? [...patch.at.parent, { kind: 'node', id: patch.node.id }] : patch.path\n}\n\ninterface Entry {\n readonly ref: DocumentRef\n base: TrackedRow | undefined\n /** The session's document while no server row is adopted yet (a create in flight, an untracked doc). */\n provisional: CmsDocument | undefined\n /** Committed, not yet sent — patches and whole-document writes, in commit order. */\n queue: QueuedWrite[]\n /** Sent, awaiting the result. */\n inFlight: QueuedPatch[]\n /** A queued whole-document write that was sent, awaiting the result. */\n inFlightReplace: QueuedReplace | undefined\n /** A whole-document write (create / replace / unpublish / delete) in flight. */\n busy: boolean\n conflicts: DocumentConflict[]\n /** The base each open conflict's \"mine\" was authored against (by conflict id). */\n conflictBases: Map<string, number | undefined>\n /** A subscription row that arrived during a write (`null` = gone); adopted after it. */\n held: CmsDocumentRecord | null | undefined\n /** A drain is queued. */\n scheduled: boolean\n deleted: boolean\n /** Our own create of this document is in flight. */\n creating: boolean\n /** The revision our own create landed at (the base of every write authored on its provisional view). */\n created: number | undefined\n /** The own-write ledger (newest last). */\n own: OwnWrite[]\n}\n\nfunction conflictId(ref: DocumentRef, path: ValuePath): string {\n return `${documentKey(ref)}|${formatValuePath(path)}`\n}\n\n/** Paths two patches have in common (either touches a prefix of the other's). */\nfunction patchesOverlap(a: DocumentPatch, b: DocumentPatch): boolean {\n return touchedPaths(a).some((p) => touchedPaths(b).some((q) => valuePathsOverlap(p, q)))\n}\n\n/** A `set`/`unset` on exactly one path — the shape a later edit of the same field supersedes. */\nfunction isValueWrite(patch: DocumentPatch): patch is Extract<DocumentPatch, { op: 'set' | 'unset' }> {\n return patch.op === 'set' || patch.op === 'unset'\n}\n\nfunction samePath(a: ValuePath, b: ValuePath): boolean {\n return a.length === b.length && valuePathsOverlap(a, b)\n}\n\n/** The earlier of two authoring bases (`undefined` — the provisional view — is the earliest of all). */\nfunction earlierBase(a: number | undefined, b: number | undefined): number | undefined {\n return a === undefined || b === undefined ? undefined : Math.min(a, b)\n}\n\n/**\n * An import's whole-document write (EC-595 A2 → EC-647 → EC-673): a row the session SHOWS\n * and holds a revision for is REPLACED at the revision of the row it showed (the one the\n * import was judged against); any other row is CREATED (insert-if-absent).\n *\n * EC-673: the decision is the SHOWN row's, never the tracked revision alone. A document\n * deleted earlier in the session is not shown, but its entry can still answer a\n * revision — the editor's Delete and a colleague's delete keep the deleted lifetime's\n * base, and the list's bulk Delete never tells the persister at all. Deciding on that\n * revision sent the import down `replace`: queued on a deleted entry and skipped, or\n * refused as unauthored with the deleted lifetime's values shown again. A replace with no\n * shown row could never be right anyway — it names no revision it was authored against.\n */\nexport function importWrite(\n persister: Pick<CmsPersister, 'revisionOf' | 'revisionOfView' | 'replace' | 'create'>,\n document: CmsDocument,\n shown: CmsDocument | undefined,\n): void {\n if (shown && persister.revisionOf(document) !== undefined) {\n persister.replace(document, persister.revisionOfView(shown))\n } else persister.create(document)\n}\n\n/** A write against a document this session no longer holds (deleted here or elsewhere). */\nfunction goneError(ref: DocumentRef): OperationError {\n return { code: 'not-found', message: 'The document is gone.', entity: 'cms-document', key: documentKey(ref) }\n}\n\n/** The refusal of a write that names no revision it was authored against (EC-647). */\nfunction unauthoredError(ref: DocumentRef): OperationError {\n return {\n code: 'conflict',\n key: documentKey(ref),\n message:\n 'A change was not saved: it does not say which revision of the document it was made on, so it could overwrite a change made since (EC-647).',\n messageRef: { key: 'cms.conflict.unauthored' },\n }\n}\n\nexport function createCmsPersister(options: CmsPersisterOptions): CmsPersister {\n const queue = createPersistQueue((error) => {\n options.onError({\n code: 'unknown',\n message: error instanceof Error ? error.message : String(error),\n })\n })\n const entries = new Map<string, Entry>()\n /** EC-647 / EC-667: every document value this persister showed or tracked → what it was authored against. */\n const shown = new WeakMap<CmsDocument, ViewProvenance>()\n /** A server row's document: every position at its revision. */\n const registerRow = (row: TrackedRow) => shown.set(row.document, { floor: row.revision, writes: [] })\n\n function entryOf(ref: DocumentRef): Entry {\n const key = documentKey(ref)\n let entry = entries.get(key)\n if (!entry) {\n entry = {\n ref: { collection: ref.collection, id: ref.id },\n base: undefined,\n provisional: undefined,\n queue: [],\n inFlight: [],\n inFlightReplace: undefined,\n busy: false,\n conflicts: [],\n conflictBases: new Map(),\n held: undefined,\n scheduled: false,\n deleted: false,\n creating: false,\n created: undefined,\n own: [],\n }\n entries.set(key, entry)\n }\n return entry\n }\n\n /** EC-586: THE write canonicaliser over a whole document a writer hands us (create/import). */\n function canonical(doc: CmsDocument): CmsDocument {\n const collection = options.getCollections().find((c) => c.id === doc.collection)\n if (!collection) return doc\n return selfTypeDocument(doc, collection, options.lookupManifest ? { lookupManifest: options.lookupManifest } : {})\n }\n\n /** The queued patches (not whole-document writes). */\n function queuedPatches(entry: Entry): QueuedPatch[] {\n return entry.queue.filter((queued): queued is QueuedPatch => queued.kind === 'patch')\n }\n\n /**\n * The session's view: base ⊕ unresolved mine ⊕ in-flight ⊕ queued (the pure merge, no\n * log; a whole-document write resets it to its snapshot). Registered with what it was\n * authored against, position by position (EC-647 → EC-667: the base's revision, a\n * pending snapshot's, each shown write's base); a provisional view has none.\n */\n function display(entry: Entry): CmsDocument | undefined {\n const baseDocument = entry.base?.document ?? entry.provisional\n if (entry.deleted || !baseDocument) return undefined\n let document = baseDocument\n let floor = entry.base?.revision\n let patches: DocumentPatch[] = entry.conflicts.map((conflict) => conflict.patch)\n let writes: ViewProvenance['writes'][number][] = entry.conflicts.map((conflict) => ({\n paths: touchedPaths(conflict.patch),\n base: entry.conflictBases.get(conflict.id),\n }))\n const pending: QueuedWrite[] = [\n ...entry.inFlight,\n ...(entry.inFlightReplace ? [entry.inFlightReplace] : []),\n ...entry.queue,\n ]\n for (const queued of pending) {\n if (queued.kind === 'replace') {\n // The snapshot was authored over everything before it (the editor's draft): every\n // position now shows content authored at the SNAPSHOT's revision (EC-667).\n patches = []\n writes = []\n document = queued.document\n floor = queued.base\n } else {\n patches.push(queued.patch)\n writes.push({ paths: touchedPaths(queued.patch), base: queued.base })\n }\n }\n if (patches.length > 0) document = applyDocumentPatches({ document, patches, since: [] }).document\n if (entry.base) shown.set(document, { floor, writes })\n return document\n }\n\n function emitDocument(entry: Entry): void {\n if (entry.deleted) return\n const view = display(entry)\n if (view) options.onDocument?.(entry.ref, view)\n }\n\n function emitConflicts(entry: Entry): void {\n options.onConflicts?.(entry.ref, [...entry.conflicts])\n }\n\n /** Adopt a server row as the base (never a lower revision), re-derive the view. */\n function adopt(entry: Entry, record: CmsDocumentRecord): void {\n if (entry.base && record.revision < entry.base.revision) return\n entry.base = record\n registerRow(record)\n options.onRecord?.(record)\n emitDocument(entry)\n }\n\n /** After a write: apply a subscription row that arrived meanwhile, if newer. */\n function adoptHeld(entry: Entry): void {\n const held = entry.held\n entry.held = undefined\n if (held === undefined) return\n if (held === null) {\n markGone(entry)\n return\n }\n if (!entry.base || held.revision > entry.base.revision) adopt(entry, held)\n }\n\n function settleAll(queued: readonly QueuedPatch[], outcome: CommitOutcome): void {\n for (const item of queued) for (const settle of item.settle) settle(outcome)\n }\n\n /** Drop every queued write, settling its waiters (the document is gone, or the writes cannot be based). */\n function dropQueued(entry: Entry, outcome: CommitOutcome, which: (queued: QueuedWrite) => boolean = () => true): void {\n const dropped = entry.queue.filter(which)\n entry.queue = entry.queue.filter((queued) => !which(queued))\n settleAll(\n dropped.filter((queued): queued is QueuedPatch => queued.kind === 'patch'),\n outcome,\n )\n }\n\n function markGone(entry: Entry): void {\n if (entry.deleted) return\n entry.deleted = true\n dropQueued(entry, { status: 'failed', error: goneError(entry.ref) })\n options.onDocument?.(entry.ref, undefined)\n }\n\n /**\n * EC-673 — writes queued on a document this session no longer holds (one put back by a\n * failed send after a delete, a \"keep mine\" on a document that went away): refused and\n * REPORTED, never left in the queue for the drain to skip — nor sent into a later\n * re-create of the id, whose first revision the own-write ledger would lift them across.\n */\n function refuseQueued(entry: Entry): void {\n if (entry.queue.length === 0) return\n const error = goneError(entry.ref)\n dropQueued(entry, { status: 'failed', error })\n options.onError(error)\n }\n\n function schedule(entry: Entry): void {\n if (entry.scheduled) return\n entry.scheduled = true\n queue.push(async () => {\n entry.scheduled = false\n await drain(entry)\n adoptHeld(entry)\n })\n }\n\n /** EC-647: record one of this persister's acknowledged writes (the own-write ledger). */\n function recordOwn(entry: Entry, write: OwnWrite): void {\n entry.own.push(write)\n if (entry.own.length > OWN_WRITES_KEPT) entry.own.splice(0, entry.own.length - OWN_WRITES_KEPT)\n }\n\n /**\n * EC-647 — THE lift: the base a write authored at `base` is SENT at. Only across this\n * persister's own writes (see the module doc): a run of consecutive own revisions\n * right after the base, or an own write that covered every position `paths` touch and\n * was sent at or below the base. Never across a revision anyone else wrote.\n */\n function lift(entry: Entry, base: number, paths: readonly ValuePath[] | undefined): number {\n let lifted = base\n for (;;) {\n if (entry.own.some((write) => write.revision === lifted + 1)) {\n lifted += 1\n continue\n }\n const covering = paths\n ? entry.own.find(\n (write) =>\n write.revision > lifted &&\n write.paths !== undefined &&\n write.sentBase !== undefined &&\n write.sentBase <= lifted &&\n paths.every((path) => write.paths!.some((covered) => isValuePathPrefix(covered, path))),\n )\n : undefined\n if (!covering) return lifted\n lifted = covering.revision\n }\n }\n\n /**\n * EC-647 — the base a write is QUEUED with: the revision it was authored against, or\n * the earlier base of an own unacknowledged write on the same positions (the view\n * showed mine there, not whatever may sit underneath it).\n */\n function authoredBase(entry: Entry, patch: DocumentPatch | undefined, authored: number | undefined): number | undefined {\n let base = authored\n const overlaps = (other: DocumentPatch) => patch === undefined || patchesOverlap(other, patch)\n for (const queued of [...entry.inFlight, ...entry.queue]) {\n if (queued.kind === 'replace' || overlaps(queued.patch)) base = earlierBase(base, queued.base)\n }\n if (entry.inFlightReplace) base = earlierBase(base, entry.inFlightReplace.base)\n for (const conflict of entry.conflicts) {\n if (overlaps(conflict.patch)) base = earlierBase(base, entry.conflictBases.get(conflict.id))\n }\n return base\n }\n\n /** Whether a write may be authored on a provisional view (our own create, or an untracked document). */\n function provisionalAllowed(entry: Entry): boolean {\n return entry.creating || entry.created !== undefined || !entry.base\n }\n\n /** Our own create landed (or failed): base every write authored on its provisional view. */\n function baseOnCreated(entry: Entry): void {\n if (entry.created === undefined) return\n for (const queued of entry.queue) if (queued.base === undefined) queued.base = entry.created\n }\n\n /**\n * EC-647 — writes authored on the provisional view of a document this session holds no\n * revision for (a staged transfer): read it; when it still EQUALS the view they were\n * authored on, that read's revision is theirs — otherwise each is refused as a\n * conflict on its position (theirs = the read). Never \"whatever revision the read\n * returns\". `false` when the read failed (the writes stay queued, the error shows).\n */\n async function baseOnRead(entry: Entry, operations: OperationsClient): Promise<boolean> {\n if (!entry.queue.some((queued) => queued.kind === 'patch' && queued.base === undefined)) return true\n if (entry.created !== undefined) {\n baseOnCreated(entry)\n return true\n }\n if (entry.base) {\n // A tracked document this session did not create: commit already refused these.\n const error = unauthoredError(entry.ref)\n dropQueued(entry, { status: 'failed', error }, (queued) => queued.kind === 'patch' && queued.base === undefined)\n options.onError(error)\n return true\n }\n const read = await operations.documents.get({ projectId: options.projectId, ref: entry.ref })\n if (!read.ok) {\n options.onError(read.error)\n return false\n }\n const record = read.value\n const authoredOn = entry.provisional\n if (authoredOn && semanticValueEqual(record.document, authoredOn)) {\n for (const queued of entry.queue) if (queued.kind === 'patch' && queued.base === undefined) queued.base = record.revision\n } else {\n const refused: DocumentConflict[] = []\n for (const queued of queuedPatches(entry)) {\n if (queued.base !== undefined) continue\n const path = patchTarget(queued.patch)\n const conflict = upsertConflict(\n entry,\n {\n patch: queued.patch,\n reason: 'conflict',\n path,\n current: readValueAt(record.document, path),\n detail: 'the document changed since the view this edit was made on',\n },\n record.revision,\n record.revision,\n )\n refused.push(conflict)\n for (const settle of queued.settle) settle({ status: 'refused', conflicts: [conflict] })\n }\n entry.queue = entry.queue.filter((queued) => !(queued.kind === 'patch' && queued.base === undefined))\n if (refused.length > 0) emitConflicts(entry)\n }\n adopt(entry, record)\n return true\n }\n\n /** Who changed a refused path — the newest patch-log row in (base, current] touching it. Best-effort. */\n async function resolveActors(entry: Entry, sentBase: number, refused: readonly DocumentConflict[]): Promise<void> {\n try {\n const operations = await options.getOperations()\n const log = await operations.documents.listPatches({\n projectId: options.projectId,\n ref: entry.ref,\n afterRevision: sentBase,\n })\n if (!log.ok) return\n let changed = false\n entry.conflicts = entry.conflicts.map((conflict) => {\n if (conflict.actor !== undefined || !refused.some((r) => r.id === conflict.id)) return conflict\n const row = [...log.value]\n .reverse()\n .find(\n (candidate) =>\n candidate.kind === 'replace' ||\n candidate.patches.some((patch) =>\n touchedPaths(patch).some((path) => valuePathsOverlap(path, conflict.path)),\n ),\n )\n if (!row?.actor) return conflict\n changed = true\n return { ...conflict, actor: row.actor }\n })\n if (changed) emitConflicts(entry)\n } catch {\n // The actor is decoration on a conflict the user can already resolve.\n }\n }\n\n /** Send one queued whole-document write at the revision its snapshot was authored against. `false` → stop draining. */\n async function sendReplace(entry: Entry, operations: OperationsClient, write: QueuedReplace): Promise<boolean> {\n const precondition =\n write.base !== undefined\n ? { revision: lift(entry, write.base, undefined) }\n : entry.created !== undefined\n ? { revision: lift(entry, entry.created, undefined) }\n : !entry.base\n ? { ifAbsent: true as const }\n : undefined\n entry.queue.shift()\n if (!precondition) {\n // A tracked document this session did not create, written whole from a view with no revision.\n options.onError(unauthoredError(entry.ref))\n emitDocument(entry)\n return true\n }\n entry.inFlightReplace = write\n entry.busy = true\n try {\n const result = await operations.documents.replace({\n projectId: options.projectId,\n document: write.document,\n precondition,\n })\n entry.inFlightReplace = undefined\n if (result.ok) {\n recordOwn(entry, {\n revision: result.value.revision,\n sentBase: 'revision' in precondition ? precondition.revision : undefined,\n paths: undefined,\n })\n adopt(entry, result.value)\n } else {\n if (result.error.code === 'conflict' && 'current' in result.error && result.error.current) {\n adopt(entry, result.error.current)\n } else emitDocument(entry)\n options.onError(result.error)\n }\n } finally {\n entry.inFlightReplace = undefined\n entry.busy = false\n adoptHeld(entry)\n }\n return true\n }\n\n /** Send the queue — runs of equal (lifted) base, whole-document writes in their place — until it is empty or a write fails. */\n async function drain(entry: Entry): Promise<void> {\n while (entry.queue.length > 0) {\n if (entry.deleted) {\n refuseQueued(entry)\n return\n }\n const operations = await options.getOperations()\n if (!(await baseOnRead(entry, operations))) return\n const head = entry.queue[0]\n if (!head) return\n if (head.kind === 'replace') {\n await sendReplace(entry, operations, head)\n continue\n }\n const sendBase = (queued: QueuedPatch) => lift(entry, queued.base!, touchedPaths(queued.patch))\n const first = sendBase(head)\n let end = 1\n while (end < entry.queue.length) {\n const next = entry.queue[end]!\n if (next.kind !== 'patch' || sendBase(next) !== first) break\n end += 1\n }\n const run = entry.queue.splice(0, end) as QueuedPatch[]\n entry.inFlight = run\n const result = await operations.documents.patch({\n projectId: options.projectId,\n ref: entry.ref,\n baseRevision: first,\n patches: run.map((queued) => queued.patch),\n })\n entry.inFlight = []\n if (result.ok) {\n recordOwn(entry, {\n revision: result.value.revision,\n sentBase: first,\n paths: run.flatMap((queued) => touchedPaths(queued.patch)),\n })\n adopt(entry, result.value)\n adoptHeld(entry)\n settleAll(run, { status: 'applied', record: result.value })\n continue\n }\n const error = result.error\n if (error.code === 'conflict' && error.refused && error.current) {\n const current = error.current\n // Refusals are matched to the run by op + target path (the operation re-parses\n // and canonicalises the patches, so object identity does not survive the call).\n const refusedByKey = new Map(\n error.refused.map((refused) => [targetKey(refused.patch.op, refused.path), refused]),\n )\n const applied: QueuedPatch[] = []\n const conflicts: DocumentConflict[] = []\n for (const queued of run) {\n const refused = refusedByKey.get(targetKey(queued.patch.op, patchTarget(queued.patch)))\n if (!refused) {\n applied.push(queued)\n continue\n }\n // MINE is what the user wrote (the queued patch), not the canonicalised echo.\n const conflict = upsertConflict(entry, { ...refused, patch: queued.patch }, current.revision, queued.base)\n conflicts.push(conflict)\n for (const settle of queued.settle) settle({ status: 'refused', conflicts: [conflict] })\n }\n // A partially applied run IS a write of ours (the row it returns is after it);\n // a wholly refused one wrote nothing — its row is someone else's revision.\n if (applied.length > 0) {\n recordOwn(entry, {\n revision: current.revision,\n sentBase: first,\n paths: applied.flatMap((queued) => touchedPaths(queued.patch)),\n })\n }\n adopt(entry, current)\n adoptHeld(entry)\n emitConflicts(entry)\n settleAll(applied, { status: 'applied', record: current })\n void resolveActors(entry, first, conflicts)\n continue\n }\n if (error.code === 'conflict' && 'current' in error && error.current === null) {\n // The document was deleted since — nothing to write into.\n markGone(entry)\n options.onError(error)\n settleAll(run, { status: 'failed', error })\n return\n }\n // A transport / authorization failure: the patches stay local (shown, unsent) and\n // the error is visible; the next commit or forced flush retries them. The commits\n // waiting on them learn of the failure now.\n settleAll(run, { status: 'failed', error })\n entry.queue.unshift(...run.map((queued) => ({ ...queued, settle: [] })))\n adoptHeld(entry)\n options.onError(error)\n return\n }\n }\n\n function upsertConflict(\n entry: Entry,\n refused: RefusedPatch,\n revision: number,\n base: number | undefined,\n ): DocumentConflict {\n const conflict: DocumentConflict = {\n id: conflictId(entry.ref, refused.path),\n ref: entry.ref,\n patch: refused.patch,\n path: refused.path,\n theirs: refused.current,\n reason: refused.reason,\n revision,\n }\n entry.conflicts = [...entry.conflicts.filter((c) => c.id !== conflict.id), conflict]\n entry.conflictBases.set(conflict.id, base)\n return conflict\n }\n\n function command(entry: Entry, run: (operations: OperationsClient) => Promise<OperationResult<unknown>>): void {\n queue.push(async () => {\n const operations = await options.getOperations()\n entry.busy = true\n try {\n const result = await run(operations)\n if (!result.ok) options.onError(result.error)\n } finally {\n entry.busy = false\n adoptHeld(entry)\n }\n })\n }\n\n return {\n track(row) {\n const entry = entryOf(row.document)\n registerRow(row)\n if (!entry.base || row.revision > entry.base.revision) entry.base = row\n },\n revisionOf: (ref) => entries.get(documentKey(ref))?.base?.revision,\n documentOf: (ref) => {\n const entry = entries.get(documentKey(ref))\n return entry ? display(entry) : undefined\n },\n revisionOfView: (view, path) => {\n const provenance = shown.get(view)\n return provenance ? provenanceAt(provenance, path) : undefined\n },\n adoptRecord(record) {\n const entry = entryOf(record.document)\n if (entry.deleted) return\n if (!entry.base || record.revision > entry.base.revision) adopt(entry, record)\n },\n commit(ref, patches, bases, view) {\n const entry = entryOf(ref)\n if (patches.length === 0) return Promise.resolve<CommitOutcome>({ status: 'failed', error: goneError(ref) })\n if (entry.deleted) {\n // EC-673: a write that cannot be sent is reported, not only settled — the editor's\n // committer and the transfer dialog do not read the outcome.\n const error = goneError(ref)\n options.onError(error)\n return Promise.resolve<CommitOutcome>({ status: 'failed', error })\n }\n if (!Array.isArray(bases)) {\n // EC-647: a writer that names no authoring revision at all — never given the tracked one.\n const error = unauthoredError(ref)\n options.onError(error)\n return Promise.resolve<CommitOutcome>({ status: 'failed', error })\n }\n if (!entry.base && !entry.provisional && view) entry.provisional = view\n let conflictsChanged = false\n let unauthored = false\n const waits: Promise<CommitOutcome>[] = []\n for (const [index, patch] of patches.entries()) {\n const authored = bases[index]\n let settle!: (outcome: CommitOutcome) => void\n waits.push(new Promise<CommitOutcome>((resolve) => (settle = resolve)))\n if (authored === undefined && !provisionalAllowed(entry)) {\n // EC-647: authored on a view with no revision, on a document this session\n // tracks and did not create — it cannot be checked, so it is not sent.\n unauthored = true\n settle({ status: 'failed', error: unauthoredError(ref) })\n continue\n }\n // A field with an unresolved conflict: the new value replaces MINE, unsent —\n // the user decides (keep mine sends it), never an implicit overwrite of theirs.\n const open = entry.conflicts.find((conflict) => patchesOverlap(conflict.patch, patch))\n if (open && isValueWrite(patch) && isValueWrite(open.patch) && samePath(open.patch.path, patch.path)) {\n const replaced: DocumentConflict = { ...open, patch }\n entry.conflicts = entry.conflicts.map((c) => (c === open ? replaced : c))\n conflictsChanged = true\n settle({ status: 'refused', conflicts: [replaced] })\n continue\n }\n const base = authoredBase(entry, patch, authored)\n // A later value write of the same field supersedes an unsent one (keeping the\n // EARLIER base — the user never saw a foreign value of a field they were typing\n // in). Only after the last queued whole-document write: one before it is sent\n // before the snapshot that was authored over it.\n if (isValueWrite(patch)) {\n let after = 0\n entry.queue.forEach((queued, at) => {\n if (queued.kind === 'replace') after = at + 1\n })\n const pending = entry.queue.findIndex(\n (queued, at) =>\n at >= after && queued.kind === 'patch' && isValueWrite(queued.patch) && samePath(queued.patch.path, patch.path),\n )\n if (pending >= 0) {\n const superseded = entry.queue[pending] as QueuedPatch\n entry.queue[pending] = {\n kind: 'patch',\n patch,\n base: earlierBase(superseded.base, base),\n settle: [...superseded.settle, settle],\n }\n continue\n }\n }\n entry.queue.push({ kind: 'patch', patch, base, settle: [settle] })\n }\n if (unauthored) options.onError(unauthoredError(ref))\n emitDocument(entry)\n if (conflictsChanged) emitConflicts(entry)\n schedule(entry)\n // The commit's outcome: failed if any of its patches failed, refused if any was.\n return Promise.all(waits).then((outcomes): CommitOutcome => {\n const failed = outcomes.find((o) => o.status === 'failed')\n if (failed) return failed\n const refused = outcomes.flatMap((o) => (o.status === 'refused' ? o.conflicts : []))\n if (refused.length > 0) return { status: 'refused', conflicts: refused }\n return outcomes[outcomes.length - 1]!\n })\n },\n create(document) {\n const doc = canonical(document)\n const entry = entryOf(doc)\n // A fresh document: nothing of an earlier incarnation of this ref carries over —\n // EC-673: its queued writes (refused and reported, never sent into this one) and its\n // open conflicts (a colleague's delete keeps them; their \"mine\" is not laid over this one).\n if (entry.deleted) {\n refuseQueued(entry)\n if (entry.conflicts.length > 0) {\n entry.conflicts = []\n entry.conflictBases.clear()\n emitConflicts(entry)\n }\n }\n entry.deleted = false\n entry.base = undefined\n entry.own = []\n entry.created = undefined\n entry.creating = true\n // Optimistic: the session shows the document at once; the base is the created row.\n entry.provisional = doc\n options.onDocument?.(entry.ref, doc)\n queue.push(async () => {\n const operations = await options.getOperations()\n entry.busy = true\n try {\n const result = await operations.documents.replace({\n projectId: options.projectId,\n document: doc,\n precondition: { ifAbsent: true },\n })\n if (result.ok) {\n entry.created = result.value.revision\n recordOwn(entry, { revision: result.value.revision, sentBase: undefined, paths: undefined })\n baseOnCreated(entry)\n adopt(entry, result.value)\n } else {\n options.onError(result.error)\n // EC-647: the writes authored on the document we meant to create have no\n // revision to be based on — never the revision of a row someone else wrote.\n dropQueued(entry, { status: 'failed', error: result.error }, (queued) => queued.base === undefined)\n }\n } finally {\n entry.creating = false\n entry.busy = false\n adoptHeld(entry)\n }\n if (entry.queue.length > 0) await drain(entry)\n })\n },\n replace(document, revision) {\n const doc = canonical(document)\n const entry = entryOf(doc)\n if (entry.deleted) {\n // EC-673: a document this session no longer holds has nothing to replace — refused\n // and reported here, never queued for a drain that skips it (or a re-create of the\n // id that would send it). A new document of the id is a `create`.\n options.onError(goneError(entry.ref))\n return\n }\n if (!entry.base && !entry.provisional) entry.provisional = doc\n // Queued in its place: the patches committed before it are sent first (the snapshot\n // holds them), the ones committed after it are sent after it (it does not). EC-647\n // (Codex F10): one with no authoring revision on a document this session tracks and\n // did not create is refused there, in order — never sent at the tracked revision.\n entry.queue.push({ kind: 'replace', document: doc, base: authoredBase(entry, undefined, revision) })\n emitDocument(entry)\n schedule(entry)\n },\n deleteDocument(ref) {\n const entry = entryOf(ref)\n dropQueued(entry, { status: 'failed', error: goneError(ref) })\n entry.conflicts = []\n entry.conflictBases.clear()\n entry.deleted = true\n emitConflicts(entry)\n command(entry, (operations) => operations.documents.delete({ projectId: options.projectId, ref }))\n },\n unpublishDocument(ref) {\n const entry = entryOf(ref)\n queue.push(async () => {\n await drain(entry)\n const operations = await options.getOperations()\n entry.busy = true\n try {\n const result = await operations.documents.unpublish({ projectId: options.projectId, ref })\n if (result.ok) {\n recordOwn(entry, { revision: result.value.revision, sentBase: undefined, paths: [] })\n adopt(entry, result.value)\n } else options.onError(result.error)\n } finally {\n entry.busy = false\n adoptHeld(entry)\n }\n })\n },\n adoptSnapshot(ref, record) {\n const entry = entryOf(ref)\n if (entry.inFlight.length > 0 || entry.busy || entry.scheduled) {\n // Hold it: the write's own result decides first; the newer of the two wins.\n if (record === undefined) entry.held = null\n else if (!entry.held || record.revision > entry.held.revision) entry.held = record\n return\n }\n if (record === undefined) {\n if (entry.base) markGone(entry)\n return\n }\n if (!entry.base || record.revision > entry.base.revision) adopt(entry, record)\n },\n conflicts: (ref) => entries.get(documentKey(ref))?.conflicts ?? [],\n resolveConflict(ref, id, choice) {\n const entry = entries.get(documentKey(ref))\n if (!entry) return\n const conflict = entry.conflicts.find((c) => c.id === id)\n if (!conflict) return\n entry.conflicts = entry.conflicts.filter((c) => c !== conflict)\n entry.conflictBases.delete(conflict.id)\n if (choice === 'mine') {\n // Keep mine: re-send at the CURRENT base — a visible, explicit second write, and\n // the one deliberate \"at the current base\" write (EC-647): the user chose it\n // after seeing theirs.\n entry.queue.push({ kind: 'patch', patch: conflict.patch, base: entry.base?.revision, settle: [] })\n schedule(entry)\n }\n emitDocument(entry)\n emitConflicts(entry)\n },\n async flush(ref) {\n if (ref) {\n const entry = entries.get(documentKey(ref))\n if (entry && entry.queue.length > 0) schedule(entry)\n }\n await queue.flush()\n },\n }\n}\n"]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { ConvexError } from 'convex/values';
|
|
2
2
|
import { DRAFT_VARIANT, documentKey, documentSchema } from '@elytracms/core/cms-core';
|
|
3
|
-
import { PRESENCE_TTL_MS, RecordNotFoundError, PersistenceValidationError, StrictReferencePreconditionError, presenceInputSchema, assetCreateDefaults, assetRecordFromRow, compareReferenceEntries, persistenceIssueSchema, presentWriteKeys, recordEntryFromWire, validateForPersistence, versionNotPinnableError, } from '@elytracms/core/persistence';
|
|
3
|
+
import { PRESENCE_TTL_MS, RecordNotFoundError, PersistenceValidationError, RevisionPreconditionError, StrictReferencePreconditionError, presenceInputSchema, assetCreateDefaults, assetRecordFromRow, compareReferenceEntries, persistenceIssueSchema, presentWriteKeys, recordEntryFromWire, validateForPersistence, versionNotPinnableError, } from '@elytracms/core/persistence';
|
|
4
4
|
import { normalizeInviteEmail } from '@elytracms/core/persistence';
|
|
5
5
|
import { createUuidIdFactory } from '@elytracms/core/determinism';
|
|
6
6
|
import { SUBSCRIPTION_UNAUTHENTICATED_MESSAGE, queryRef, mutationRef } from './convex-client.js';
|
|
@@ -127,6 +127,8 @@ class ConvexCmsRepository {
|
|
|
127
127
|
at: this.clock(),
|
|
128
128
|
// EC-649: re-checked in the mutation's transaction (data-only, EC-565 1e).
|
|
129
129
|
...(options.strictTargets?.length ? { strictTargets: wireRefs(options.strictTargets) } : {}),
|
|
130
|
+
// EC-663: the hidden-clear, applied in the same transaction as the pin.
|
|
131
|
+
...(options.patches?.length ? { patches: [...options.patches] } : {}),
|
|
130
132
|
}));
|
|
131
133
|
if (result.status === 'missing') {
|
|
132
134
|
throw new RecordNotFoundError('cms-document', `${projectId}/${documentKey(ref)}`);
|
|
@@ -274,6 +276,16 @@ class ConvexCmsRepository {
|
|
|
274
276
|
const wire = {
|
|
275
277
|
...(precondition?.revision !== undefined ? { revision: precondition.revision } : {}),
|
|
276
278
|
...(precondition?.publishedReferrers ? { publishedReferrers: wireReferrers(precondition.publishedReferrers) } : {}),
|
|
279
|
+
// EC-668: the draft referrers the guard judged, re-checked in the mutation's transaction.
|
|
280
|
+
...(precondition?.draftReferrers
|
|
281
|
+
? {
|
|
282
|
+
draftReferrers: precondition.draftReferrers.map((referrer) => ({
|
|
283
|
+
collection: referrer.ref.collection,
|
|
284
|
+
id: referrer.ref.id,
|
|
285
|
+
revision: referrer.revision,
|
|
286
|
+
})),
|
|
287
|
+
}
|
|
288
|
+
: {}),
|
|
277
289
|
};
|
|
278
290
|
const result = (await this.client.mutation(mutationRef('cms:deleteDocument'), {
|
|
279
291
|
collection: ref.collection,
|
|
@@ -342,10 +354,15 @@ class ConvexCmsRepository {
|
|
|
342
354
|
publishedAt: now,
|
|
343
355
|
// EC-649: re-checked in the mutation's transaction (data-only, EC-565 1e).
|
|
344
356
|
...(precondition?.strictTargets?.length ? { strictTargets: wireRefs(precondition.strictTargets) } : {}),
|
|
357
|
+
// EC-663: and the caller's revision.
|
|
358
|
+
...(precondition?.revision !== undefined ? { expectedRevision: precondition.revision } : {}),
|
|
345
359
|
}));
|
|
346
360
|
if (result.status === 'missing') {
|
|
347
361
|
throw new RecordNotFoundError('cms-document', `${projectId}/${documentKey(ref)}`);
|
|
348
362
|
}
|
|
363
|
+
if (result.status === 'conflict') {
|
|
364
|
+
throw new RevisionPreconditionError(`${projectId}/${documentKey(ref)}`, docRecordFromDoc(result.current, projectId));
|
|
365
|
+
}
|
|
349
366
|
if (result.status === 'missing-version') {
|
|
350
367
|
throw new RecordNotFoundError('cms-document-version', `${projectId}/${documentKey(ref)}#${version}`);
|
|
351
368
|
}
|
|
@@ -360,6 +377,11 @@ class ConvexCmsRepository {
|
|
|
360
377
|
}
|
|
361
378
|
async unpublishDocument(projectId, ref, precondition) {
|
|
362
379
|
const existing = await this.getDocument(projectId, ref);
|
|
380
|
+
// EC-663: a stale revision refuses before the not-published check, as in the in-memory store
|
|
381
|
+
// (the mutation re-checks it in its transaction).
|
|
382
|
+
if (precondition?.revision !== undefined && existing.revision !== precondition.revision) {
|
|
383
|
+
throw new RevisionPreconditionError(`${projectId}/${documentKey(ref)}`, existing);
|
|
384
|
+
}
|
|
363
385
|
if (existing.publishedVersion === undefined) {
|
|
364
386
|
throw new PersistenceValidationError('Document is not currently published.', [
|
|
365
387
|
{
|
|
@@ -377,10 +399,14 @@ class ConvexCmsRepository {
|
|
|
377
399
|
...(precondition?.publishedReferrers
|
|
378
400
|
? { publishedReferrers: wireReferrers(precondition.publishedReferrers) }
|
|
379
401
|
: {}),
|
|
402
|
+
...(precondition?.revision !== undefined ? { expectedRevision: precondition.revision } : {}),
|
|
380
403
|
}));
|
|
381
404
|
if ('status' in result && result.status === 'unjudged-referrers') {
|
|
382
405
|
throw new StrictReferencePreconditionError('unjudged-referrers', `${projectId}/${documentKey(ref)}`, result.refs);
|
|
383
406
|
}
|
|
407
|
+
if ('status' in result && result.status === 'conflict') {
|
|
408
|
+
throw new RevisionPreconditionError(`${projectId}/${documentKey(ref)}`, docRecordFromDoc(result.current, projectId));
|
|
409
|
+
}
|
|
384
410
|
return docRecordFromDoc(result, projectId);
|
|
385
411
|
}
|
|
386
412
|
}
|