import { opIdOf, AbortablePromise, EngineError, EngineErrorCode, type CustomMetadata, type CustomMetadataPatch, type CustomMetadataService, type CustomMetadataUpdateResult, type DocumentMetadata, type MetadataPatch, type MetadataService, type MetadataUpdateResult, type MutationMeta, type SessionEventPublisher, type WriteOptions, } from '@embedpdf/engine-core/runtime'; import { CustomMetadataSchema, CustomMetadataUpdateResultSchema, DocumentMetadataSchema, MetadataUpdateResultSchema, wirePaths, tokenPinOf, type TokenPin, } from '@embedpdf/engine-core/wire'; import type { ManifestAccessor } from './CloudDocumentHandle'; import type { CloudWrites } from './CloudWrites'; import { planesInherited } from './planes'; import type { HttpClient } from '../transport/HttpClient'; interface MetadataDeps { http: HttpClient; docId: string; layerName: string; isClosed: () => boolean; manifest: ManifestAccessor; publisher: SessionEventPublisher; writes: CloudWrites; } /** One half of the Info dict: the leaf it reads and the route it writes. */ interface MetadataLeaf { docPath: (docId: string, metadataVersion: number, pin: TokenPin) => string; layerPath: (docId: string, layerName: string, metadataVersion: number, pin: TokenPin) => string; updatePath: (docId: string, layerName: string) => string; parse: (raw: unknown) => T; parseResult: (raw: unknown) => R; } const STANDARD: MetadataLeaf = { docPath: wirePaths.docMetadata, layerPath: wirePaths.layerMetadata, updatePath: wirePaths.layerMetadataUpdate, parse: (raw) => DocumentMetadataSchema.parse(raw), parseResult: (raw) => MetadataUpdateResultSchema.parse(raw), }; const CUSTOM: MetadataLeaf = { docPath: wirePaths.docCustomMetadata, layerPath: wirePaths.layerCustomMetadata, updatePath: wirePaths.layerCustomMetadataUpdate, parse: (raw) => CustomMetadataSchema.parse(raw), parseResult: (raw) => CustomMetadataUpdateResultSchema.parse(raw), }; function closedError(docId: string): EngineError { return new EngineError(EngineErrorCode.DocNotOpen, `document ${docId} is closed`); } /** * The read. The JSON lives at a content-addressed `…@metadataVersion=N` leaf * (not in the manifest); the manifest only publishes the `metadataVersion` * pointer, which both halves of the dict share. So the read pulls it from * the cached manifest, fetches the leaf, and on a 404 (stale pointer) * transparently refreshes the manifest and retries once. `metadataVersion` * bumps only on metadata writes, so the leaf stays cached across page and * annotation edits. */ function readLeaf(deps: MetadataDeps, leaf: MetadataLeaf): AbortablePromise { if (deps.isClosed()) return AbortablePromise.rejectReason(closedError(deps.docId)); return AbortablePromise.run(async (signal) => { const buildPath = async (s: AbortSignal): Promise => { const manifest = await deps.manifest.get(s); // Plane-scope rule: the leaf depends on the `metadata` plane — while // inherited, one doc-level URL serves every visitor. const pin = tokenPinOf('metadata', manifest.engine); return planesInherited(manifest, ['metadata']) ? leaf.docPath(deps.docId, manifest.metadataVersion, pin) : leaf.layerPath(deps.docId, deps.layerName, manifest.metadataVersion, pin); }; return deps.http.getJsonWithRefresh( buildPath, leaf.parse, async (s) => { await deps.manifest.refresh(s); }, signal, ); }); } /** * The write. It only advances docVersion + metadataVersion (no per-page pin * changes, no layoutVersion), so the cached manifest is patched in place — * no refetch. `publish` gets the write's `opId`. */ function writeLeaf( deps: MetadataDeps, leaf: MetadataLeaf, patch: MetadataPatch | CustomMetadataPatch, options: WriteOptions | undefined, publish: (result: R, opId: string) => void, ): AbortablePromise { if (deps.isClosed()) return AbortablePromise.rejectReason(closedError(deps.docId)); return AbortablePromise.run(async (signal) => { const opId = opIdOf(options); return deps.writes.run(opId, signal, async (write) => { const result = await write.send((sent) => deps.http.postJson( leaf.updatePath(deps.docId, deps.layerName), patch, leaf.parseResult, signal, sent, ), ); deps.manifest.apply(result.meta, ['metadata']); publish(result, opId); return result; }); }); } class CloudCustomMetadataService implements CustomMetadataService { constructor(private readonly deps: MetadataDeps) {} get(): AbortablePromise { return readLeaf(this.deps, CUSTOM); } update( patch: CustomMetadataPatch, options?: WriteOptions, ): AbortablePromise { return writeLeaf(this.deps, CUSTOM, patch, options, (result, opId) => this.deps.publisher.publishWrite(opId, { type: 'metadata.customUpdated', ...result }), ); } } export class CloudMetadataService implements MetadataService { readonly custom: CustomMetadataService; private readonly deps: MetadataDeps; constructor( http: HttpClient, docId: string, layerName: string, isClosed: () => boolean, manifest: ManifestAccessor, publisher: SessionEventPublisher, writes: CloudWrites, ) { this.deps = { http, docId, layerName, isClosed, manifest, publisher, writes }; this.custom = new CloudCustomMetadataService(this.deps); } get(): AbortablePromise { return readLeaf(this.deps, STANDARD); } update(patch: MetadataPatch, options?: WriteOptions): AbortablePromise { return writeLeaf(this.deps, STANDARD, patch, options, (result, opId) => this.deps.publisher.publishWrite(opId, { type: 'metadata.updated', ...result }), ); } }