import { AbortablePromise, DEFAULT_BUNDLE_LIMITS, DEFAULT_PDF_SAVE_MODE, EngineError, EngineErrorCode, EventHub, SessionEventPublisher, attachmentVerbs, isPluginId, outlineVerbs, annotationVerbs, formVerbs, pageVerbs, subscribeToType, type DocumentAnnotationsService, type DocumentActionsService, type DocumentAttachmentsService, type DocumentSignaturesService, type DocumentEvent, type DocumentEventStream, type DocumentFontsService, type DocumentFormsService, type DocumentPagesService, type DocumentHandle, type DocumentGrant, type DocumentOutlineService, type DocumentRedactionService, CONTINUOUS_RENDER_POLICY, type DocumentRenderService, type DocumentSecurityService, type MutationMeta, type PageHandle, type PageRef, type DownloadOptions, type CallFacts, type Change, type ChangeResult, type WorkingSetPage, type ObjectNumberPool, type WriteOptions, } from '@embedpdf/engine-core/runtime'; import { DEFAULT_LAYER_NAME, DocumentHeadSchema, DocumentManifestSchema, ObjectNumberReservationResponseSchema, wirePaths, type DocumentHead, tokenPinOf, type DocumentManifest, type EngineValues, type LayerScopePlane, } from '@embedpdf/engine-core/wire'; import { CLOUD_DOCUMENT, type CloudDocument } from './cloudDocument'; import { CloudDocumentActionsService } from './CloudDocumentActionsService'; import { CloudDocumentAnnotationsService } from './CloudDocumentAnnotationsService'; import { CloudDocumentAttachmentsService } from './CloudDocumentAttachmentsService'; import { changeSender, CloudDocumentChanges } from './CloudDocumentChanges'; import { CloudDocumentFontsService } from './CloudDocumentFontsService'; import { CloudDocumentFormsService } from './CloudDocumentFormsService'; import { readCloudOutline } from './CloudDocumentOutlineService'; import { CloudDocumentPagesService } from './CloudDocumentPagesService'; import { CloudDocumentRedactionService } from './CloudDocumentRedactionService'; import { CloudDocumentSearchService } from './CloudDocumentSearchService'; import { CloudDocumentSecurityService } from './CloudDocumentSecurityService'; import { CloudDocumentSignaturesService } from './CloudDocumentSignaturesService'; import { CloudMetadataService } from './CloudMetadataService'; import { CloudObjectNumberPool } from './CloudObjectNumberPool'; import { CloudPageHandle } from './CloudPageHandle'; import { CloudWrites } from './CloudWrites'; import type { GrantSessionSource } from '../grant'; import { auditRowToEvents } from '../realtime/auditRowToEvents'; import { SseClient, type DesyncReason } from '../realtime/SseClient'; import { awaitSignal } from '../shared/awaitSignal'; import type { HttpClient } from '../transport/HttpClient'; /** * Read accessor handed to every `CloudPage…Service`. The closure * captures `this` so the services don't carry a direct reference * back to the document handle (smaller circular-ref surface, easier * to mock in unit tests). */ /** * The manifest as this client holds it: the server's manifest, and the engine * values of the `/head` it was read after, which every cached URL copies. */ export type CloudManifest = DocumentManifest & { readonly engine: EngineValues }; export interface ManifestAccessor { /** Cached manifest (cold-fetched once, kept across requests). */ get(signal: AbortSignal): Promise; /** Force re-fetch of `/head` + `/manifest@docVersion=N`; replaces the cache. */ refresh(signal: AbortSignal): Promise; /** * Absorb mutation-returned state/cache deltas when safe. `owns` names the * planes this mutation kind takes ownership of (the monotone-flip * rule): annotation/form writes own `annotations`; flatten and * redaction-apply own `content + annotations`. The flip runs even when * the version-gated delta merge is skipped — scopes only ever move * base → layer, so any observed mutation proves the plane diverged. */ apply(meta: MutationMeta, owns: readonly LayerScopePlane[]): void; /** A page delete: the advance, plus dropping the deleted pages' manifest * rows so per-page leaf URLs stop resolving locally. */ applyPageDelete(meta: MutationMeta, deletedPages: readonly PageRef[]): void; /** Page insert: the cached manifest has no rows for the fresh page object numbers (the * result carries only their object numbers), so the absorb drops the * cache for a lazy refetch instead of patching. */ applyPageInsert(meta: MutationMeta): void; } export class CloudDocumentHandle implements DocumentHandle { readonly id: string; /** The cloud side, read with `cloudDocument()`: the server modules' routes on this layer. */ readonly [CLOUD_DOCUMENT]: CloudDocument = { module: (id) => { if (!isPluginId(id)) { throw new EngineError( EngineErrorCode.InvalidArg, `"${id}" can't be a module's id: lowercase words joined by '-', not a core name`, ); } const base = `/v1/docs/${encodeURIComponent(this.id)}/layers/${encodeURIComponent(this.layerName)}/${id}/`; return { fetch: (path, init) => this.http.fetchRoute(`${base}${path.replace(/^\/+/, '')}`, init), }; }, }; readonly metadata: CloudMetadataService; readonly annotations: DocumentAnnotationsService; readonly actions: DocumentActionsService; readonly outline: DocumentOutlineService; readonly attachments: DocumentAttachmentsService; readonly signatures: DocumentSignaturesService; readonly forms: DocumentFormsService; readonly fonts: DocumentFontsService; readonly search: CloudDocumentSearchService; readonly pages: DocumentPagesService; /** The page reads behind `pages`, the layout per page among them. */ private readonly pageReads: CloudDocumentPagesService; readonly redaction: DocumentRedactionService; readonly security: DocumentSecurityService; readonly render: DocumentRenderService; readonly events: DocumentEventStream; readonly objectNumbers: ObjectNumberPool; private readonly pool: CloudObjectNumberPool; private readonly writes: CloudWrites; private readonly changes: CloudDocumentChanges; private readonly publisher: SessionEventPublisher; private readonly hub: EventHub; private readonly sessionId: string; private sseClient: SseClient | null = null; private sseSubscribers = 0; private closed = false; /** * Cached current manifest. Populated on first read by `getManifest` * (or any `page().*` call that needs to know a version). Replaced * wholesale on `refreshManifest`. Cleared on `close`. * * Memory model: one DocumentManifest per open handle. Per-page * version reads are O(pages.length) `.find(...)` lookups; if a * profiling pass ever shows that as hot, swap for a Map keyed by * `pageObjectNumber`. Today's documents are page-sparse so the * scan is cheaper than the hash overhead. */ private manifestCache: CloudManifest | null = null; private inflightManifest: Promise | null = null; private manifestFloorVersion = 0; private pendingInitialHead: DocumentHead | null; private readonly stopEngineWatch: () => void; private readonly manifestAccessor: ManifestAccessor; private readonly cloudSecurity: CloudDocumentSecurityService; constructor( private readonly http: HttpClient, id: string, private readonly layerName: string = DEFAULT_LAYER_NAME, initialHead?: DocumentHead, /** * The doc-scoped JWT the engine was opened with, decoded * unverified to populate the security service's local-fallback * `effectiveScope` / `identity` accessors. Optional for backward * compatibility; without it the local-fallback path returns an * empty scope and null identity until /access is called. */ initialToken: string | null = null, /** Called once, when the handle closes (the engine forgets it). */ private readonly onClose: () => void = () => {}, /** A grant session's: the document's `grant`, and the gate its writes pass. */ private readonly grantSession: Pick | null = null, ) { this.id = id; this.pendingInitialHead = initialHead ?? null; this.stopEngineWatch = http.onEngineChanged(() => this.forgetEngineValues()); // The editing session's object numbers: from `/access`, write // responses, the stream's `session` events and the bulk reservation. const pool = new CloudObjectNumberPool({ reserve: (count, signal) => http.postJson( wirePaths.objectNumbers(id, layerName), { count }, (raw) => ObjectNumberReservationResponseSchema.parse(raw), signal, { session: true }, ), }); this.pool = pool; this.objectNumbers = pool; this.writes = new CloudWrites( pool, changeSender(http, id, layerName), grantSession?.writeGate ?? null, ); const security = new CloudDocumentSecurityService( http, id, layerName, initialHead ?? fallbackUnknownHead(id), { isClosed: () => this.closed }, initialToken, { wanted: () => pool.wantedAtAccess(), opened: (edit) => pool.opened(edit) }, ); this.security = security; this.cloudSecurity = security; // The deployment's render lattice rides /v1/access (mutable policy // never lives in immutable manifests). Reuse the cached access block // when present; otherwise establish access on demand — the same call // the CDN path uses, so this can never add a second handshake shape. // A pre-lattice server (no renderPolicy field) enforces nothing: // `continuous` is the honest answer. this.render = { getPolicy: () => AbortablePromise.run(async () => { const cached = security.currentAccess ?? (await security.establishAccess()).access ?? null; const advertised = cached?.renderPolicy; if (!advertised) return CONTINUOUS_RENDER_POLICY; return { kind: 'lattice', fullPage: { widths: advertised.fullPage.widths }, ...(advertised.tiles ? { tiles: advertised.tiles } : {}), ...(advertised.appearances ? { appearances: advertised.appearances } : {}), ...(advertised.maxRenderPixels !== undefined ? { maxRenderPixels: advertised.maxRenderPixels } : {}), formats: advertised.formats, background: advertised.background, enforced: advertised.enforced, }; }), }; const hub = new EventHub(); this.hub = hub; // The handle's session is its client's: the id its writes carry, its // events' origin. A client without one (a test's) still names the origin. const sessionId = http.sessionId ?? `cloud:anon:${id}`; this.sessionId = sessionId; // Your own mutations publish here at POST-confirmation time (kind: // 'local'); the remote channel (SSE) publishes everyone else's into the // same hub. Exactly one event per mutation, either way. The SSE stream // is lazy: it opens on the first subscriber and closes on the last — // non-collaborative usage never holds a connection (browsers cap ~6 // per origin on HTTP/1.1). const subscribe: DocumentEventStream['subscribe'] = (listener) => { const unsubscribe = hub.subscribe(listener); this.retainRemoteStream(); let released = false; return () => { unsubscribe(); if (!released) { released = true; this.releaseRemoteStream(); } }; }; this.events = { subscribe, on: (type, listener) => subscribeToType(subscribe, type, listener), lastServerSequence: () => hub.lastServerSequence(), }; this.publisher = new SessionEventPublisher(hub, sessionId); // A version this handle published itself numbers objects anew too. hub.subscribe((event) => { if (event.type === 'document.versioned') pool.versioned(event.version.sha256); }); // An own write whose delta moved the font list's pin changed the fonts // the list shows: its events end with `fonts.changed`, as locally. const noticeFonts = (meta: MutationMeta) => { if (meta.cacheDelta?.fontsVersion !== undefined) this.publisher.noteFontsChanged(meta.opId); }; this.manifestAccessor = { get: (signal) => this.getManifest(signal), refresh: (signal) => this.refreshManifest(signal), apply: (meta, owns) => { noticeFonts(meta); this.absorbMutation(meta, owns); }, applyPageDelete: (meta, deletedPages) => { noticeFonts(meta); this.absorbPageDelete(meta, deletedPages); }, applyPageInsert: (meta) => { noticeFonts(meta); this.absorbPageInsert(meta); }, }; this.changes = new CloudDocumentChanges( () => this.closed, this.manifestAccessor, this.publisher, this.writes, () => http.serverVersion, ); this.metadata = new CloudMetadataService( http, id, layerName, () => this.closed, this.manifestAccessor, this.publisher, this.writes, ); // The deployment's import limits ride /v1/access, as the render lattice does. const importLimits = async () => (security.currentAccess ?? (await security.establishAccess()).access)?.bundleLimits ?? DEFAULT_BUNDLE_LIMITS; this.annotations = annotationVerbs( new CloudDocumentAnnotationsService( http, id, layerName, () => this.closed, this.manifestAccessor, this.publisher, this.writes, importLimits, ), (change, options) => this.apply(change, options), ); this.actions = new CloudDocumentActionsService( http, id, layerName, () => this.closed, this.manifestAccessor, ); this.outline = outlineVerbs( () => readCloudOutline(http, id, layerName, () => this.closed, this.manifestAccessor), (change, options) => this.apply(change, options), ); this.fonts = new CloudDocumentFontsService( http, id, layerName, () => this.closed, this.manifestAccessor, ); this.attachments = attachmentVerbs( new CloudDocumentAttachmentsService( http, id, layerName, () => this.closed, this.manifestAccessor, ), (change, options) => this.apply(change, options), ); this.signatures = new CloudDocumentSignaturesService( http, id, layerName, () => this.closed, this.manifestAccessor, this.publisher, this.writes, ); this.forms = formVerbs( new CloudDocumentFormsService( http, id, layerName, () => this.closed, this.manifestAccessor, this.publisher, this.writes, importLimits, ), (change, options) => this.apply(change, options), ); this.search = new CloudDocumentSearchService( http, id, layerName, () => this.closed, this.manifestAccessor, ); this.pageReads = new CloudDocumentPagesService( http, id, layerName, () => this.closed, this.manifestAccessor, this.publisher, this.writes, ); this.pages = pageVerbs(this.pageReads, (change, options) => this.apply(change, options)); this.redaction = new CloudDocumentRedactionService( http, id, layerName, () => this.closed, this.manifestAccessor, this.publisher, this.writes, ); } page(ref: PageRef): PageHandle { return new CloudPageHandle( ref, this.http, this.id, this.layerName, () => this.closed, this.manifestAccessor, this.publisher, this.writes, (signal) => this.pageReads.pageLayout(ref, signal), () => this.cloudSecurity.pageLayerRights(), () => this.cloudSecurity.pagePictureRights(), (pages, measure, options) => this.pages.setScale(pages, measure, options), ); } /** * This handle: the cloud engine sends every call as it's made, in * parallel, and the server runs them in arrival order, so a call's facts * change nothing here. */ with(_facts: CallFacts): DocumentHandle { return this; } /** One change as one transaction, or the undo of one (see `DocumentHandle.apply`). */ apply(change: Change, options?: WriteOptions): AbortablePromise { return this.changes.apply(change, options); } get grant(): DocumentGrant | undefined { return this.grantSession?.grant; } /** Ignored: the server learns what's needed from what is asked of it. */ setWorkingSet(_view: string, _pages: readonly WorkingSetPage[]): void {} download(options: DownloadOptions = {}): AbortablePromise { if (this.closed) { return AbortablePromise.rejectReason( new EngineError(EngineErrorCode.DocNotOpen, `document ${this.id} is closed`), ); } const mode = options.mode ?? DEFAULT_PDF_SAVE_MODE; return AbortablePromise.run(async (signal) => { const buildPath = async () => { const manifest = await this.getManifest(signal); return wirePaths.layerDownloadVersioned(this.id, this.layerName, { docVersion: manifest.docVersion, mode, pin: tokenPinOf('download', manifest.engine), }); }; try { return await this.http.getBytes(await buildPath(), signal); } catch (err) { if (!EngineError.is(err, EngineErrorCode.NotFound)) throw err; await this.refreshManifest(signal); return this.http.getBytes(await buildPath(), signal); } }); } /** * Learn what the document's signatures forbid before the caller's first * question: the manifest carries it, so `open()` fetches it up front and * `security.allows()` answers as the server would from the start. A locked * document, which the server won't describe yet, learns it from `unlock()`. */ async learnProtection(signal: AbortSignal): Promise { try { await this.getManifest(signal); } catch (error) { if (EngineError.is(error, EngineErrorCode.DocPasswordRequired)) return; throw error; } } /** * Return the cached manifest, fetching cold-cache once if needed. * Concurrent callers share a single inflight request (singleflight) * so an N-page handle that opens N services in parallel still * triggers exactly one `/head` + `/manifest@docVersion=N` round-trip. */ async getManifest(signal: AbortSignal): Promise { if (this.manifestCache) return this.manifestCache; if (!this.inflightManifest) { this.startManifestFetch({ allowInitialHead: true }); } const promise = this.inflightManifest; if (!promise) { throw new EngineError( EngineErrorCode.Unknown, `manifest fetch was not started for document ${this.id}`, ); } return awaitSignal(promise, signal); } /** * Force re-fetch. Used by the transparent-retry path when a leaf * URL returns 404 (stale version). Replaces `manifestCache` * wholesale so the next `getManifest()` is a Map lookup. */ async refreshManifest(signal: AbortSignal): Promise { const promise = this.startManifestFetch({ allowInitialHead: false }); return awaitSignal(promise, signal); } /** * Monotone plane-scope flip: mark the planes a mutation owns as layer-scoped in * the cached manifest. Scopes only ever move base → layer (no revert op * exists), so flipping is safe under any event ordering — a duplicate or * out-of-order event still proves the plane diverged at some point — and * the manifest fetch stays the authoritative source (the 404 → refresh * rail heals any miss, e.g. a future mutation kind this client doesn't * know about). */ private flipScopes(owns: readonly LayerScopePlane[]): void { const cache = this.manifestCache; const scopes = cache?.scopes; if (!cache || !scopes) return; if (owns.every((plane) => scopes[plane] === 'layer')) return; const next = { ...scopes }; for (const plane of owns) next[plane] = 'layer'; this.manifestCache = { ...cache, scopes: next }; } absorbMutation(meta: MutationMeta, owns: readonly LayerScopePlane[]): void { this.flipScopes(owns); const delta = meta.cacheDelta; if (delta) { this.manifestFloorVersion = Math.max(this.manifestFloorVersion, delta.docVersion); } this.inflightManifest = null; if (!this.manifestCache) return; if (delta) { if (delta.docVersion <= this.manifestCache.docVersion) return; if (delta.previousDocVersion !== this.manifestCache.docVersion) { this.manifestCache = null; return; } } const byPageObjectNumber = new Map( this.manifestCache.pages.map((page) => [page.page.objectNumber, page]), ); if (delta) { for (const page of delta.pages) { const existing = byPageObjectNumber.get(page.page.objectNumber); if (existing) { byPageObjectNumber.set(page.page.objectNumber, { ...existing, cache: page.cache, }); } } } this.manifestCache = { ...this.manifestCache, docVersion: delta?.docVersion ?? this.manifestCache.docVersion, // The document pins of the annotation list and the form: absorbed when // the mutation bumped them, so the next `annotations.list()` or // `forms.list()` addresses the fresh leaf without a 404-refresh round // trip. ...(delta?.annotationsVersion !== undefined ? { annotationsVersion: delta.annotationsVersion } : {}), ...(delta?.formsVersion !== undefined ? { formsVersion: delta.formsVersion } : {}), // The plane pins a page-structure, metadata, attachment, outline, font or content write bumps: // absorbed so the next read addresses the fresh leaf. ...(delta?.layoutVersion !== undefined ? { layoutVersion: delta.layoutVersion } : {}), ...(delta?.metadataVersion !== undefined ? { metadataVersion: delta.metadataVersion } : {}), ...(delta?.attachmentsVersion !== undefined ? { attachmentsVersion: delta.attachmentsVersion } : {}), ...(delta?.outlineVersion !== undefined ? { outlineVersion: delta.outlineVersion } : {}), ...(delta?.fontsVersion !== undefined ? { fontsVersion: delta.fontsVersion } : {}), ...(delta?.contentsVersion !== undefined ? { contentsVersion: delta.contentsVersion } : {}), ...(delta?.viewportsVersion !== undefined ? { viewportsVersion: delta.viewportsVersion } : {}), // The signing fences: every ordinary commit writes an artifact // (`working`), and the layer's write serial when the delta names it. ...(delta?.layerVersion !== undefined ? { layerVersion: delta.layerVersion } : {}), ...(delta?.working !== undefined ? { working: delta.working } : {}), // The manifest is a per-page registry keyed by pageObjectNumber, not a // display-order list — geometry/order now lives in `pages.list()` // (/layout). Keep a deterministic order by page object number so cache merges are // stable; display order is the SDK's concern via PageLayout.index. pages: Array.from(byPageObjectNumber.values()).sort( (a, b) => a.page.objectNumber - b.page.objectNumber, ), }; } /** * Patch the cached manifest after a page delete: the shared advance plus * dropping the deleted pages' manifest rows, so no leaf URL for a retired * page object number can be built from the cache (a stale request would * 404 anyway — this keeps the failure local and instant). Delete changes * the page set: a view that removed content must never resolve base * artifacts again, so content, annotations and forms flip with layout. */ private absorbPageDelete(meta: MutationMeta, deletedPages: readonly PageRef[]): void { this.absorbMutation(meta, ['layout', 'content', 'annotations', 'forms']); if (!this.manifestCache) return; const deleted = new Set(deletedPages.map((page) => page.objectNumber)); this.manifestCache = { ...this.manifestCache, pages: this.manifestCache.pages.filter((page) => !deleted.has(page.page.objectNumber)), }; } /** * Patch bookkeeping after a page insert — the mirror of * {@link absorbPageDelete}, with one asymmetry: delete can patch the * cached manifest losslessly (it only removes rows), but an insert needs * manifest rows for the fresh page object numbers and the result doesn't carry them. So * this absorb flips the planes (insert changes the page set, so like * delete it owns content, annotations and forms alongside layout), raises the * version floor, and drops the cache — the next read refetches a manifest * that includes the new pages' rows. The UI never waits on that refetch: * the mutation result / event already carries the full new layout. */ private absorbPageInsert(meta: MutationMeta): void { this.flipScopes(['layout', 'content', 'annotations', 'forms']); if (meta.cacheDelta) { this.manifestFloorVersion = Math.max(this.manifestFloorVersion, meta.cacheDelta.docVersion); } this.inflightManifest = null; this.manifestCache = null; } private startManifestFetch(opts: { allowInitialHead: boolean }): Promise { const ctrl = new AbortController(); const promise = this.fetchManifest(ctrl.signal, opts); this.inflightManifest = promise; promise .then((manifest) => { if ( manifest.docVersion >= this.manifestFloorVersion && (!this.manifestCache || manifest.docVersion >= this.manifestCache.docVersion) ) { this.manifestCache = manifest; this.cloudSecurity.setProtection(manifest.protection); } }) .catch(() => undefined) .finally(() => { if (this.inflightManifest === promise) { this.inflightManifest = null; } }); return promise; } private async fetchManifest( signal: AbortSignal, opts: { allowInitialHead: boolean }, ): Promise { if (this.closed) { throw new EngineError(EngineErrorCode.DocNotOpen, `document ${this.id} is closed`); } const head = opts.allowInitialHead ? this.consumeInitialHead() : null; if (head) { try { return await this.fetchManifestForHead(head, signal); } catch (err) { if (!EngineError.is(err, EngineErrorCode.NotFound)) throw err; // A mutation may have landed between open() and the first // manifest read. The seed is one-shot, so fall through to the // normal /head path and learn the current docVersion. } } // Refreshes and stale-seed recovery always re-fetch `/head` first // so we learn the current `docVersion`; chasing the manifest with // a stale `:D` would 404 by definition. const freshHead = await this.http.getJson( wirePaths.layerHead(this.id, this.layerName), (raw) => DocumentHeadSchema.parse(raw), signal, ); return this.fetchManifestForHead(freshHead, signal); } private consumeInitialHead(): DocumentHead | null { const head = this.pendingInitialHead; this.pendingInitialHead = null; return head; } private async fetchManifestForHead( head: DocumentHead, signal: AbortSignal, ): Promise { const manifest = await this.http.getJson( wirePaths.layerManifest( this.id, this.layerName, head.docVersion, tokenPinOf('manifest', head.engine), ), (raw) => DocumentManifestSchema.parse(raw), signal, ); return { ...manifest, engine: head.engine }; } /** * The server answered a cached read with another engine value than its * URL named: its values moved (its fonts, a rule, another replica during a * deploy). Read `/head` again before the next cached read. */ private forgetEngineValues(): void { this.inflightManifest = null; this.manifestCache = null; } close(): AbortablePromise { if (this.closed) { return AbortablePromise.resolveValue(undefined); } this.closed = true; this.stopEngineWatch(); this.sseClient?.close(); this.sseClient = null; this.manifestCache = null; this.inflightManifest = null; this.onClose(); return AbortablePromise.resolveValue(undefined); } private retainRemoteStream(): void { this.sseSubscribers += 1; if (this.sseSubscribers > 1 || this.closed || this.sseClient) return; this.sseClient = new SseClient({ http: this.http, path: wirePaths.layerEvents(this.id, this.layerName), // Gapless handshake: resume from the newest cursor we know — events // already seen, else the cached manifest's transactional auditHead. // Null (cold start, no manifest yet) subscribes "from now", which is // exact too: the first manifest fetched afterwards is newer anyway. initialCursor: this.hub.lastServerSequence() ?? this.manifestCache?.auditHead ?? null, onRow: (row) => { // Advance the cached manifest's audit cursor — own echoes and // unknown kinds included — so a later `annotations.list()` never stamps a // cursor older than the pins the absorbed cache hands it. if (this.manifestCache && row.id > this.manifestCache.auditHead) { this.manifestCache = { ...this.manifestCache, auditHead: row.id }; } // A change this connection may not read: the server sent only its // pins, absorbed so reads stay warm. Which family it changed is part // of what was withheld, so both planes flip: never wrong, only // unshared until the next manifest. Its one event, when its pins // moved the font list's, is `fonts.changed`, published below. if (row.withheld) { const meta = (row.payload as { meta?: MutationMeta } | null)?.meta; if (meta && row.originSessionId !== this.sessionId) { this.absorbMutation(meta, ['annotations', 'forms']); } } // A new version, this handle's own included: in stream order, before // the `session` event that hands out its fresh numbers. if (row.kind === 'signature.complete') { const sha = (row.payload as { version?: { sha256?: unknown } }).version?.sha256; if (typeof sha === 'string') this.pool.versioned(sha); } const events = auditRowToEvents(row, this.sessionId); // A kind of change this version doesn't have, from a newer server: // nothing says what it changed, so everything is read again. if (events === null) { this.desynced('unknown-change'); return; } // None for an own echo; one per fact otherwise. for (const event of events) { // Absorb before publish: a listener reading the manifest in its // callback must see post-mutation state (same order as local). this.absorbRemoteEvent(event); this.hub.publish(event); } }, onFullRefresh: (reason) => this.desynced(reason), onAuthLost: () => { // The stream is gone for good under this credential. Local events // keep flowing; remote delivery resumes if the doc is re-opened // with a fresh token. this.sseClient = null; }, onSession: (status) => this.pool.sync(status), onConnected: (connected) => this.pool.connected(connected), }); this.sseClient.open(); } /** * The stream can't be followed change by change from here: drop the cached * manifest, so the next read refetches, and tell subscribers their * event-derived state may be stale. The missed mutations will never arrive * as events. */ private desynced(reason: DesyncReason): void { this.manifestCache = null; this.inflightManifest = null; this.hub.publish({ type: 'stream.desynced', reason, at: new Date().toISOString() }); } private releaseRemoteStream(): void { this.sseSubscribers = Math.max(0, this.sseSubscribers - 1); if (this.sseSubscribers === 0 && this.sseClient) { this.sseClient.close(); this.sseClient = null; } } /** Patch the cached manifest from a remote event's coherence pins — the * same absorb rails local mutations use, so reads stay warm no matter * whose hand caused the change. Every event kind is named below, so a new * one can't be forgotten: a missed one leaves this client reading the * old version from an immutable, cached URL. */ private absorbRemoteEvent(event: DocumentEvent): void { switch (event.type) { case 'pages.scaleSet': // The layout carries the pages' scales. this.absorbMutation(event.meta, ['layout']); return; case 'annotations.created': case 'annotations.updated': case 'annotations.deleted': case 'annotations.restored': case 'annotations.reordered': this.absorbMutation(event.meta, ['annotations']); return; case 'outline.created': case 'outline.updated': case 'outline.moved': case 'outline.deleted': case 'outline.restored': this.absorbMutation(event.meta, ['outline']); return; case 'pages.reordered': case 'pages.rotated': case 'pages.named': this.absorbMutation(event.meta, ['layout']); return; case 'pages.deleted': this.absorbPageDelete(event.meta, event.pages); return; case 'pages.inserted': case 'pages.restored': this.absorbPageInsert(event.meta); return; case 'metadata.updated': case 'metadata.customUpdated': this.absorbMutation(event.meta, ['metadata']); return; case 'attachments.created': case 'attachments.deleted': case 'attachments.restored': this.absorbMutation(event.meta, ['attachments']); return; case 'forms.valueSet': case 'forms.repaired': case 'forms.created': case 'forms.updated': case 'forms.deleted': case 'forms.restored': case 'forms.widgetAdded': case 'forms.widgetRemoved': case 'forms.widgetUpdated': case 'forms.widgetDeleted': case 'forms.widgetRestored': case 'forms.widgetsReordered': case 'forms.calculationsReordered': // Form writes move the form's pins: the affected pages are the // ones whose widgets changed. this.absorbMutation(event.meta, ['forms']); return; case 'pages.flattened': case 'annotations.flattened': // Flatten bakes annotations and form fields into page content. this.absorbMutation(event.meta, ['content', 'annotations', 'forms']); return; case 'signatures.prepared': case 'document.versioned': // Prepare moved the layer's version and working flag; a completion // published a new base. Neither ships a delta: refetch the manifest. this.manifestCache = null; this.inflightManifest = null; return; case 'redaction.applied': // Redaction-apply rewrites content and consumes the marks: every // page plane flips — and this is the security-relevant divergence, // so a remote apply must stop this client's base reads immediately. this.absorbMutation(event.meta, ['content', 'annotations', 'forms']); return; case 'signatures.completed': // Arrives with `document.versioned`, which drops the manifest. return; case 'signatures.cancelled': // Moves no pin a read uses, as an own cancel absorbs nothing. return; case 'signatures.validationInfoAdded': // Only the document version moved: no page and no list a page shows. this.absorbMutation(event.meta, []); return; case 'fonts.changed': // Ends a row whose own events, or its withheld pins, absorbed the // font list's pin already. return; case 'stream.desynced': // The stream's own handler dropped the manifest already. return; default: event satisfies never; } } } function fallbackUnknownHead(id: string): DocumentHead { return { id, baseSha256: '', sizeBytes: 0, docVersion: 1, state: 'ready', encryption: { state: 'unknown', requiresPassword: null }, permissions: { known: false, flags: null, allAllowed: null, openedAs: null, securityHandlerRevision: null, canUpgradeToOwner: false, }, access: { required: true, reasons: ['permissions-unknown'], endpoint: wirePaths.access(id, DEFAULT_LAYER_NAME), }, engine: {}, }; }