@embedpdf/engine-services 3.0.0-next.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +192 -0
- package/README.md +18 -0
- package/dist/index.cjs +9904 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +1481 -0
- package/dist/index.d.ts +1481 -0
- package/dist/index.js +9851 -0
- package/dist/index.js.map +1 -0
- package/package.json +61 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","names":["FPDF_ERR_PASSWORD","TRAPPED_TRUE","TRAPPED_FALSE","FPDF_NO_INCREMENTAL","readLine","DEFAULT_CARET_COLOR","DEFAULT_FILE_ATTACHMENT_COLOR","DEFAULT_COLOR","KEY_ROTATION","KEY_UNROTATED_RECT","DEFAULT_FREETEXT_COLOR","DEFAULT_FONT_SIZE","readLinePoints","DEFAULT_REDACT_COLOR","DEFAULT_LABEL_COLOR","DEFAULT_FONT_SIZE","DEFAULT_NOTE_COLOR","DEFAULT_HIGHLIGHT_COLOR","DEFAULT_TEXT_MARKUP_COLOR","MK_BORDER_COLOR","MK_BACKGROUND_COLOR","cache","DEFAULT_OPACITY","DEFAULT_OPACITY","DEFAULT_OPACITY","DEFAULT_LINE_ENDINGS","DEFAULT_OPACITY","CHANGED_WIDGETS_CAPACITY","EMPTY_META"],"sources":["../src/runtime/lifecycle/bootstrap.ts","../src/shared/abort.ts","../src/shared/uuid.ts","../src/shared/pdf-date.ts","../src/runtime/memory/bits.ts","../src/shared/securityPermissions.ts","../src/events/EventHub.ts","../src/document-session/lifecycle/PdfDocumentOpener.ts","../src/document-session/pages/PagePtrPool.ts","../src/document-session/revisions/RevisionAuthority.ts","../src/document-session/DocumentSession.ts","../src/document-session/lifecycle/BaseDocumentRegistry.ts","../src/runtime/memory/scratch.ts","../src/runtime/memory/strings.ts","../src/features/metadata/internal/readMetadataText.ts","../src/features/metadata/internal/readCustomMetadata.ts","../src/features/metadata/internal/readTrappedStatus.ts","../src/features/metadata/MetadataReader.ts","../src/features/metadata/internal/write/writeMetaText.ts","../src/features/metadata/internal/write/writeMetaTrapped.ts","../src/features/metadata/internal/write/applyMetadataPatch.ts","../src/features/metadata/MetadataMutator.ts","../src/runtime/memory/structs.ts","../src/features/actions/ActionModelReader.ts","../src/features/pages/PagesReader.ts","../src/features/pages/PagesMutator.ts","../src/features/pages/PagesExtractor.ts","../src/features/pages/PagesInserter.ts","../src/features/annotations/internal/read/annotationReadContext.ts","../src/features/annotations/internal/annotationFlagBits.ts","../src/features/annotations/internal/lineEnding.ts","../src/features/annotations/internal/read/annotationReadPrimitives.ts","../src/features/annotations/internal/textEditIntent.ts","../src/features/annotations/internal/read/readCaretAnnotation.ts","../src/features/attachments/internal/attachmentPrimitives.ts","../src/features/annotations/internal/annotationIcon.ts","../src/features/annotations/internal/read/readFileAttachmentAnnotation.ts","../src/features/annotations/internal/colorType.ts","../src/features/annotations/internal/freeTextIntent.ts","../src/features/annotations/internal/standardFont.ts","../src/features/annotations/internal/textAlignment.ts","../src/features/annotations/internal/shapeBorderStyle.ts","../src/features/annotations/internal/read/readStyle.ts","../src/features/annotations/internal/read/readAnnotationTransformMetadata.ts","../src/features/annotations/internal/read/readFreeTextAnnotation.ts","../src/features/annotations/internal/inkIntent.ts","../src/features/annotations/internal/read/readInkAnnotation.ts","../src/features/annotations/internal/read/readLineAnnotation.ts","../src/features/annotations/internal/destinationViewCodes.ts","../src/features/annotations/internal/read/readDestination.ts","../src/features/annotations/internal/read/readLinkAnnotation.ts","../src/features/annotations/internal/read/readRedactAnnotation.ts","../src/features/annotations/internal/read/readShapeAnnotation.ts","../src/features/annotations/internal/stampName.ts","../src/features/annotations/internal/read/readStampAnnotation.ts","../src/features/annotations/internal/read/readTextAnnotation.ts","../src/features/annotations/internal/read/readTextMarkupAnnotation.ts","../src/features/annotations/internal/read/readUnsupportedAnnotation.ts","../src/features/annotations/internal/read/readVertexAnnotation.ts","../src/features/annotations/internal/read/readWidgetAnnotation.ts","../src/features/annotations/internal/read/annotationReaderRegistry.ts","../src/features/forms/internal/formModelCache.ts","../src/features/forms/internal/readFormSnapshot.ts","../src/features/annotations/internal/read/joinWidgetField.ts","../src/features/annotations/internal/read/readAnnotationIdentity.ts","../src/features/annotations/internal/replyType.ts","../src/features/annotations/internal/read/readAnnotationRelationship.ts","../src/features/annotations/internal/read/readEmbedMetadata.ts","../src/features/annotations/internal/blendMode.ts","../src/features/annotations/internal/read/readAnnotationBase.ts","../src/features/annotations/internal/read/collectPageAnnotations.ts","../src/features/annotations/AnnotationReader.ts","../src/features/render/deviceRaster.ts","../src/features/annotations/AnnotationAppearanceReader.ts","../src/features/annotations/RawAnnotationReader.ts","../src/features/annotations/internal/write/annotationWritePrimitives.ts","../src/features/annotations/internal/write/writeAnnotationBase.ts","../src/features/annotations/internal/identity/captureOrStampStableId.ts","../src/features/annotations/internal/identity/resolveAnnotationPointer.ts","../src/features/annotations/internal/mutations/computeMutationImpact.ts","../src/features/annotations/internal/read/readAnnotationFromPtr.ts","../src/features/annotations/internal/write/writeCaretAnnotation.ts","../src/features/annotations/internal/write/writeFileAttachmentAnnotation.ts","../src/features/annotations/internal/write/writeDefaultAppearance.ts","../src/features/annotations/internal/write/writeStyle.ts","../src/features/annotations/internal/write/writeEmbedMetadata.ts","../src/features/annotations/internal/write/writeAnnotationTransformMetadata.ts","../src/features/annotations/internal/write/writeFreeTextAnnotation.ts","../src/features/annotations/internal/write/writeInkAnnotation.ts","../src/features/annotations/internal/write/writeLineAnnotation.ts","../src/features/annotations/internal/write/writeLinkAnnotation.ts","../src/features/annotations/internal/write/writeTextMarkupAnnotation.ts","../src/features/annotations/internal/write/writeRedactAnnotation.ts","../src/features/annotations/internal/write/writeShapeAnnotation.ts","../src/features/annotations/internal/write/writeStampAnnotation.ts","../src/features/annotations/internal/write/writeTextAnnotation.ts","../src/features/annotations/internal/write/writeVertexAnnotation.ts","../src/features/annotations/internal/write/writeWidgetAnnotation.ts","../src/features/annotations/internal/write/annotationWriterRegistry.ts","../src/features/annotations/internal/write/writeAnnotationRelationship.ts","../src/features/annotations/AnnotationMutator.ts","../src/features/pages/PagesFlattener.ts","../src/features/redaction/RedactionApplier.ts","../src/features/text/PageTextReader.ts","../src/features/geometry/PageGeometryReader.ts","../src/features/render/PageRenderReader.ts","../src/features/attachments/AttachmentReader.ts","../src/features/attachments/AttachmentMutator.ts","../src/features/security/internal/buildSecurityInfo.ts","../src/features/security/SecurityReader.ts","../src/features/save/internal/pdfSaveMode.ts","../src/features/save/DocumentSaver.ts","../src/features/fonts/FontRegistrar.ts","../src/features/forms/internal/resolveFieldRef.ts","../src/features/forms/FormReader.ts","../src/features/forms/internal/authorWidget.ts","../src/features/forms/internal/fieldFlagBits.ts","../src/features/forms/internal/wideStringArray.ts","../src/features/forms/FormMutator.ts","../src/features/forms/FormsEffectsApplier.ts","../src/features/search/internal/pageCorpusCache.ts","../src/features/search/internal/searchCursor.ts","../src/features/search/SearchReader.ts","../src/features/actions/DocumentActionsReader.ts","../src/features/pieceinfo/PieceInfoAccessor.ts","../src/worker-host/WorkerHost.ts"],"sourcesContent":["import type { PdfRuntimeModule } from '@embedpdf/engine-runtime';\n\nconst initialized = new WeakSet<PdfRuntimeModule>();\n\n/**\n * Initialize the thread-confined PDFium runtime for the calling thread. Each\n * worker thread owns its own PDFium state, so this must run on every thread\n * that uses the runtime. Safe to call multiple times.\n */\nexport function ensureInitialized(runtime: PdfRuntimeModule): void {\n if (initialized.has(runtime)) return;\n runtime.fn.EPDF_InitThread();\n initialized.add(runtime);\n}\n\n/**\n * Tear down PDFium for the calling thread. Lifecycle-strict: every PDFium\n * handle created on this thread must already be closed.\n */\nexport function destroyLibrary(runtime: PdfRuntimeModule): void {\n if (!initialized.has(runtime)) return;\n runtime.fn.EPDF_ShutdownThread();\n initialized.delete(runtime);\n}\n","import { AbortError } from '@embedpdf/engine-core/runtime';\n\n/**\n * Throw if the AbortSignal has been aborted. Service code peppers calls to\n * this between PDFium calls so cooperative cancellation works without\n * needing async/await.\n */\nexport function throwIfAborted(signal: AbortSignal): void {\n if (signal.aborted) {\n const reason = signal.reason;\n if (reason instanceof Error) throw reason;\n throw new AbortError(reason);\n }\n}\n","/**\n * Generate an RFC 4122 v4 UUID using the Web Crypto API surface that's\n * available in every realm we ship to: Node 19+ (global), Web Workers,\n * browsers (https), browsers (http/intranet/file:), and Edge runtimes.\n *\n * Why this implementation, exactly:\n * - `crypto.randomUUID()` was historically gated to *secure contexts*\n * in older browsers and we shipped that bug to production once.\n * `getRandomValues()` has no such restriction.\n * - `import { randomUUID } from 'crypto'` makes Vite externalize the\n * `crypto` module for browser builds and emit a build-time warning;\n * we then crash at runtime in the rare path that hits it.\n * - 16 bytes + RFC 4122 bit-twiddling is six lines and correct.\n *\n * Output is the canonical hex form: `xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx`,\n * where `y` is one of `8/9/a/b` (variant nibble = 10xx).\n */\nexport function generateUuid(): string {\n const bytes = globalThis.crypto.getRandomValues(new Uint8Array(16));\n // RFC 4122 §4.4: version nibble = 4, variant nibble = 10xx.\n bytes[6] = (bytes[6]! & 0x0f) | 0x40;\n bytes[8] = (bytes[8]! & 0x3f) | 0x80;\n const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;\n}\n","/**\n * PDF date string format conversion utilities.\n *\n * PDF stores timestamps as ASCII strings shaped like\n * `D:YYYYMMDDHHmmSSOHH'mm'`, where `O` is `+` / `-` / `Z` (Z means\n * UTC and omits the offset). See ISO 32000 §7.9.4.\n *\n * The wire format used by the engine DTOs is always ISO 8601;\n * readers convert PDF → ISO via {@link pdfDateToIso}, writers convert\n * the other way via {@link formatPdfDate}.\n */\n\n/**\n * Parse a PDF date string `D:YYYYMMDDHHmmSSOHH'mm'` to an ISO 8601\n * string. Returns null if the input is malformed.\n *\n * When the timezone is omitted, PDF defines the relationship to UTC as\n * unknown. Since the engine DTO wire format requires an absolute ISO 8601\n * timestamp, this converter retains the pre-existing fallback of treating\n * an omitted timezone as UTC.\n */\nexport function pdfDateToIso(pdf: string): string | null {\n const match =\n /^D:(\\d{4})(\\d{2})(\\d{2})(\\d{2})(\\d{2})(\\d{2})(?:(Z)|([+-])(\\d{2})'(\\d{2})')?$/.exec(pdf);\n if (!match) return null;\n\n const [, yText, moText, dText, HText, MText, SText, , sign, tzHText, tzMText] = match;\n const y = Number(yText);\n const mo = Number(moText) - 1;\n const d = Number(dText);\n const H = Number(HText);\n const M = Number(MText);\n const S = Number(SText);\n\n // Construct the local wall-clock fields in UTC space. setUTCFullYear is\n // intentional: Date.UTC maps years 0-99 to 1900-1999.\n const wallClock = new Date(0);\n wallClock.setUTCFullYear(y, mo, d);\n wallClock.setUTCHours(H, M, S, 0);\n\n // JavaScript normalizes invalid fields (for example February 31), so\n // compare them after construction rather than accepting the rollover.\n if (\n wallClock.getUTCFullYear() !== y ||\n wallClock.getUTCMonth() !== mo ||\n wallClock.getUTCDate() !== d ||\n wallClock.getUTCHours() !== H ||\n wallClock.getUTCMinutes() !== M ||\n wallClock.getUTCSeconds() !== S\n ) {\n return null;\n }\n\n let offsetMinutes = 0;\n if (sign) {\n const tzH = Number(tzHText);\n const tzM = Number(tzMText);\n if (tzH > 23 || tzM > 59) return null;\n\n offsetMinutes = (tzH * 60 + tzM) * (sign === '+' ? 1 : -1);\n }\n\n return new Date(wallClock.getTime() - offsetMinutes * 60_000).toISOString();\n}\n\n/**\n * Format a JS Date as a PDF date string `D:YYYYMMDDHHmmSSOHH'mm'`.\n *\n * Emits the offset in PDF's funny `OHH'mm'` form, where the apostrophe\n * after the hour is literal and the offset always carries a sign. UTC\n * is emitted as `+00'00'` (not `Z`) for maximum reader compatibility —\n * the `Z` shorthand is allowed by the spec but not universally\n * supported.\n *\n * Always uses the supplied Date's local fields and offset. For\n * server-side stamps callers typically pass `new Date()` (default).\n */\nexport function formatPdfDate(d: Date = new Date()): string {\n if (Number.isNaN(d.getTime())) throw new RangeError('Cannot format an invalid Date');\n\n const pad = (n: number, w = 2) => String(n).padStart(w, '0');\n const year = d.getFullYear();\n if (year < 0 || year > 9999) throw new RangeError('PDF dates require a four-digit year');\n\n const tzMinutes = -d.getTimezoneOffset();\n const sign = tzMinutes >= 0 ? '+' : '-';\n const tzH = pad(Math.floor(Math.abs(tzMinutes) / 60));\n const tzM = pad(Math.abs(tzMinutes) % 60);\n return (\n `D:${pad(year, 4)}${pad(d.getMonth() + 1)}${pad(d.getDate())}` +\n `${pad(d.getHours())}${pad(d.getMinutes())}${pad(d.getSeconds())}` +\n `${sign}${tzH}'${tzM}'`\n );\n}\n","/**\n * Coerce a value to an unsigned 32-bit integer. PDFium permission words\n * arrive as signed JS numbers (the high bit makes them negative); reading\n * them as `u32` restores the bit pattern the PDF spec describes.\n */\nexport function u32(value: number): number {\n return value >>> 0;\n}\n","import { u32 } from '../runtime/memory/bits';\n\n/**\n * PDF Standard security handlers reserve bits 1-2 as 0, and PDFium masks\n * even owner permissions through that convention — so \"all permissions\"\n * for an encrypted document is `0xFFFFFFFC`, not `0xFFFFFFFF`.\n */\nexport const ALL_STANDARD_SECURITY_PERMISSIONS = 0xfffffffc;\n\n/** Coerce PDFium's signed permission word to its unsigned 32-bit value. */\nexport const normalizeU32 = u32;\n\n/** True when `bits` grants every standard security permission. */\nexport function hasAllStandardSecurityPermissions(bits: number): boolean {\n return (\n (u32(bits) & ALL_STANDARD_SECURITY_PERMISSIONS) >>> 0 === ALL_STANDARD_SECURITY_PERMISSIONS\n );\n}\n","import type {\n DocumentEvent,\n DocumentEventInit,\n DocumentEventStream,\n} from '@embedpdf/engine-core/runtime';\n\n/**\n * The in-process implementation of `DocumentEventStream`, shared by both\n * engine shells (one hub per open `DocumentHandle`). The engine that\n * performs a mutation publishes here at confirmation time; the cloud\n * engine's remote channel will also publish here for OTHER sessions'\n * mutations — listeners never learn which transport delivered an event.\n *\n * Delivery contract:\n * - synchronous fan-out in subscription order;\n * - error isolation: a throwing listener is re-thrown on a microtask\n * (so it surfaces to the host's unhandled-error reporting) without\n * blocking other listeners or failing the mutation path;\n * - `lastServerId` tracks the highest remote cursor seen, for the\n * remote channel's reconnect/backfill.\n */\nexport class EventHub implements DocumentEventStream {\n private readonly listeners = new Set<(event: DocumentEvent) => void>();\n private serverId: number | null = null;\n\n constructor(\n /** Where a throwing listener's error goes. Defaults to an async\n * rethrow so it reaches the host's unhandled-error reporting. */\n private readonly onListenerError: (err: unknown) => void = (err) => {\n queueMicrotask(() => {\n throw err;\n });\n },\n ) {}\n\n subscribe(listener: (event: DocumentEvent) => void): () => void {\n this.listeners.add(listener);\n return () => {\n this.listeners.delete(listener);\n };\n }\n\n publish(event: DocumentEvent): void {\n const { serverId } = event.origin;\n if (serverId !== null) {\n this.serverId = this.serverId === null ? serverId : Math.max(this.serverId, serverId);\n }\n // Snapshot so a listener that (un)subscribes mid-fan-out cannot skew\n // delivery for this event.\n for (const listener of [...this.listeners]) {\n try {\n listener(event);\n } catch (err) {\n this.onListenerError(err);\n }\n }\n }\n\n lastServerId(): number | null {\n return this.serverId;\n }\n\n /** Drop every listener (handle close). Idempotent. */\n clear(): void {\n this.listeners.clear();\n }\n}\n\n/**\n * Stamps provenance onto events a mutation path produces. One per open\n * handle: the engine shell constructs it with the instance's `sessionId`\n * (and, on cloud, the authenticated `sub` when known) and hands it to the\n * mutation services — they publish results, never build origins.\n */\nexport class SessionEventPublisher {\n constructor(\n private readonly hub: EventHub,\n private readonly sessionId: string,\n private readonly sub: string | null = null,\n ) {}\n\n /** Publish a mutation THIS engine instance just confirmed. */\n publishLocal(event: DocumentEventInit): void {\n this.hub.publish({\n ...event,\n origin: {\n kind: 'local',\n sessionId: this.sessionId,\n sub: this.sub,\n ts: Date.now(),\n serverId: null,\n },\n } as DocumentEvent);\n }\n}\n","import { EngineError, EngineErrorCode } from '@embedpdf/engine-core/runtime';\nimport type { PdfFileAccessHandle, PdfRuntimeModule, Ptr } from '@embedpdf/engine-runtime';\nimport { NULL_PTR } from '@embedpdf/engine-runtime';\n\nexport type OpenedPdfDocumentKind = 'fat-memory' | 'layer';\n\nconst FPDF_ERR_PASSWORD = 4;\n\nexport interface OpenedPdfDocument {\n readonly kind: OpenedPdfDocumentKind;\n readonly docPtr: Ptr;\n close(): void;\n}\n\nexport interface AcquiredBaseDocument {\n readonly key: string;\n readonly basePtr: Ptr;\n release(): void;\n}\n\nexport type LayerSource =\n | { readonly kind: 'fresh' }\n | { readonly kind: 'raw-delta'; readonly bytes: Uint8Array | ArrayBuffer }\n | { readonly kind: 'artifact'; readonly bytes: Uint8Array | ArrayBuffer }\n | { readonly kind: 'artifact-file'; readonly path: string };\n\nexport class CloseStack {\n private readonly actions: Array<() => void> = [];\n private closed = false;\n\n push(action: () => void): void {\n if (this.closed) {\n action();\n return;\n }\n this.actions.push(action);\n }\n\n close(): void {\n if (this.closed) return;\n this.closed = true;\n let firstError: unknown = null;\n for (let i = this.actions.length - 1; i >= 0; i--) {\n try {\n this.actions[i]?.();\n } catch (error) {\n firstError ??= error;\n }\n }\n this.actions.length = 0;\n if (firstError) throw firstError;\n }\n}\n\nexport function openFatMemoryDocument(\n runtime: PdfRuntimeModule,\n bytes: Uint8Array,\n password: string | null = null,\n): OpenedPdfDocument {\n const { mem, fn } = runtime;\n const stack = new CloseStack();\n const dataPtr = mem.alloc(bytes.byteLength);\n stack.push(() => mem.free(dataPtr));\n\n try {\n mem.writeBytes(dataPtr, bytes);\n const docPtr = fn.FPDF_LoadMemDocument64(dataPtr, bytes.byteLength, password ?? '');\n if (!docPtr) {\n // Distinguish \"locked\" from \"broken\": a password failure is a\n // recoverable state the caller can act on (prompt + unlock), never\n // a generic open failure.\n if (fn.FPDF_GetLastError() === FPDF_ERR_PASSWORD) {\n throw password\n ? new EngineError(EngineErrorCode.DocPasswordIncorrect, 'incorrect document password')\n : new EngineError(EngineErrorCode.DocPasswordRequired, 'document requires a password');\n }\n throw new EngineError(EngineErrorCode.DocOpenFailed, 'failed to open document');\n }\n setRuntimeOwnerPermissionsIfEncrypted(runtime, docPtr);\n stack.push(() => fn.FPDF_CloseDocument(docPtr));\n return { kind: 'fat-memory', docPtr, close: () => stack.close() };\n } catch (error) {\n stack.close();\n throw error;\n }\n}\n\nexport function openLayerDocument(\n runtime: PdfRuntimeModule,\n base: AcquiredBaseDocument,\n layer: LayerSource = { kind: 'fresh' },\n password: string | null = null,\n): OpenedPdfDocument {\n const { mem, fn } = runtime;\n const stack = new CloseStack();\n stack.push(() => base.release());\n\n let layerAccess: PdfFileAccessHandle | null = null;\n const statusPtr = mem.alloc(4);\n try {\n mem.poke(statusPtr, 'i32', -1);\n let docPtr: Ptr;\n if (layer.kind === 'fresh') {\n docPtr = fn.EPDFLayer_OpenLayer(base.basePtr, NULL_PTR, password ?? '', statusPtr);\n } else {\n layerAccess =\n layer.kind === 'artifact-file'\n ? runtime.fileAccess.fromNodeFile(layer.path)\n : runtime.fileAccess.fromMemory(layer.bytes);\n stack.push(() => layerAccess?.close());\n docPtr =\n layer.kind === 'artifact' || layer.kind === 'artifact-file'\n ? fn.EPDFLayer_OpenLayerArtifact(base.basePtr, layerAccess.ptr, password ?? '', statusPtr)\n : fn.EPDFLayer_OpenLayer(base.basePtr, layerAccess.ptr, password ?? '', statusPtr);\n }\n\n const status = Number(mem.peek(statusPtr, 'i32'));\n if (!docPtr || status !== 0) {\n throw layerOpenError(status);\n }\n\n setRuntimeOwnerPermissionsIfEncrypted(runtime, docPtr);\n stack.push(() => fn.FPDF_CloseDocument(docPtr));\n return { kind: 'layer', docPtr, close: () => stack.close() };\n } catch (error) {\n stack.close();\n throw error;\n } finally {\n mem.free(statusPtr);\n }\n}\n\nexport function setRuntimeOwnerPermissionsIfEncrypted(\n runtime: PdfRuntimeModule,\n docPtr: Ptr,\n): void {\n const { fn } = runtime;\n if (fn.EPDF_IsEncrypted && fn.EPDF_SetRuntimeOwnerPermissions && fn.EPDF_IsEncrypted(docPtr)) {\n fn.EPDF_SetRuntimeOwnerPermissions(docPtr, true);\n }\n}\n\nfunction layerOpenError(status: number): EngineError {\n switch (status) {\n case 1:\n return new EngineError(EngineErrorCode.DocPasswordRequired, 'layer requires a password');\n case 2:\n return new EngineError(EngineErrorCode.MalformedPdf, 'layer delta is malformed');\n case 3:\n return new EngineError(\n EngineErrorCode.MalformedPdf,\n 'layer artifact does not match the supplied base document',\n );\n default:\n return new EngineError(EngineErrorCode.DocOpenFailed, 'failed to open layer document');\n }\n}\n","import type { PageObjectNumber } from '@embedpdf/engine-core/runtime';\nimport { EngineError, EngineErrorCode } from '@embedpdf/engine-core/runtime';\nimport type { PdfRuntimeModule, Ptr } from '@embedpdf/engine-runtime';\n\n/**\n * Manages pagePtr lifetime for a single open `DocumentSession`.\n *\n * `acquire(pon)` returns a loaded pagePtr for the given PDF object number,\n * loading it via `EPDFDoc_LoadPageByObjectNumberNormalized` (rotation forced\n * to 0deg so render/text/geometry/annotation coordinates all share one\n * normalized space) if not already in the pool. `release(pon)` decrements the\n * refcount and closes when it reaches\n * zero; `closeAll()` is called by `DocumentSession.close()`.\n *\n * While at least one holder is active the pagePtr is shared (refcounted),\n * so overlapping `acquire(pon)` calls for the same page reuse a single\n * load. Once the refcount reaches zero the page is closed; a later\n * `acquire` reloads it — there is no LRU retention across the zero-ref\n * boundary. A future slice could add that without changing callers.\n */\nexport class PagePtrPool {\n private readonly counts = new Map<PageObjectNumber, { ptr: Ptr; refs: number }>();\n\n constructor(\n private readonly runtime: PdfRuntimeModule,\n private readonly docPtr: Ptr,\n ) {}\n\n acquire(pageObjectNumber: PageObjectNumber): Ptr {\n const { fn } = this.runtime;\n const existing = this.counts.get(pageObjectNumber);\n if (existing) {\n existing.refs++;\n return existing.ptr;\n }\n const ptr = fn.EPDFDoc_LoadPageByObjectNumberNormalized(this.docPtr, pageObjectNumber);\n if (!ptr) {\n throw new EngineError(\n EngineErrorCode.NotFound,\n `no page with object number ${pageObjectNumber}`,\n );\n }\n this.counts.set(pageObjectNumber, { ptr, refs: 1 });\n return ptr;\n }\n\n /**\n * True while at least one holder has the page open. Page-STRUCTURE\n * mutations (delete) assert on this: thread confinement means no other\n * job can be mid-flight, so a held pagePtr during a structural mutation\n * is a leaked `acquire` (an internal bug) — the mutator fails loudly\n * instead of mutating under a live handle.\n */\n isHeld(pageObjectNumber: PageObjectNumber): boolean {\n return this.counts.has(pageObjectNumber);\n }\n\n release(pageObjectNumber: PageObjectNumber): void {\n const entry = this.counts.get(pageObjectNumber);\n if (!entry) return;\n entry.refs--;\n if (entry.refs <= 0) {\n this.runtime.fn.FPDF_ClosePage(entry.ptr);\n this.counts.delete(pageObjectNumber);\n }\n }\n\n closeAll(): void {\n const { fn } = this.runtime;\n for (const { ptr } of this.counts.values()) {\n fn.FPDF_ClosePage(ptr);\n }\n this.counts.clear();\n }\n}\n","import type {\n PageObjectNumber,\n RevisionToken,\n WeakAnnotationState,\n} from '@embedpdf/engine-core/runtime';\nimport {\n EngineError,\n EngineErrorCode,\n UNKNOWN_WEAK_ANNOTATION_STATE,\n revisionTokensEqual,\n} from '@embedpdf/engine-core/runtime';\n\nexport interface RevisionAuthority {\n readonly docSessionId: string;\n token(pageObjectNumber: PageObjectNumber): RevisionToken;\n bump(pageObjectNumber: PageObjectNumber): RevisionToken;\n validate(token: RevisionToken): void;\n weakAnnotationState(pageObjectNumber: PageObjectNumber): WeakAnnotationState;\n recordWeakAnnotationState(pageObjectNumber: PageObjectNumber, state: WeakAnnotationState): void;\n /** Forget a page entirely (generation + weak state). Called when the page\n * is DELETED — its object number is retired, never recycled, so dropping\n * is hygiene, not correctness. */\n drop(pageObjectNumber: PageObjectNumber): void;\n clear(): void;\n}\n\n/**\n * Per-page generation counter. Backs `RevisionToken` so weak\n * `AnnotationRef.kind === 'index'` references can be validated against the\n * exact page state they were minted from.\n *\n * `bump()` is the only mutator; mutation services call it after a\n * structural change to the page (annotation create/delete/reorder).\n * Read paths never mutate the store.\n */\nexport class LocalRevisionAuthority implements RevisionAuthority {\n private readonly generations = new Map<PageObjectNumber, number>();\n private readonly weakAnnotationStates = new Map<PageObjectNumber, WeakAnnotationState>();\n\n constructor(public readonly docSessionId: string) {}\n\n /** Returns the current generation, defaulting to 0 for first read. */\n current(pageObjectNumber: PageObjectNumber): number {\n return this.generations.get(pageObjectNumber) ?? 0;\n }\n\n /** Mints a fresh `RevisionToken` for the page's current generation. */\n token(pageObjectNumber: PageObjectNumber): RevisionToken {\n return {\n docSessionId: this.docSessionId,\n pageObjectNumber,\n generation: this.current(pageObjectNumber),\n };\n }\n\n /**\n * Increments the generation counter for a page. Returns the new token.\n * Called by mutation services after every structural change.\n */\n bump(pageObjectNumber: PageObjectNumber): RevisionToken {\n const next = this.current(pageObjectNumber) + 1;\n this.generations.set(pageObjectNumber, next);\n return this.token(pageObjectNumber);\n }\n\n /**\n * Strict equality check. Throws `EngineError(InvalidReference)` when the\n * caller's token does not match what the store currently holds.\n */\n validate(token: RevisionToken): void {\n if (token.docSessionId !== this.docSessionId) {\n throw new EngineError(\n EngineErrorCode.InvalidReference,\n 'revision token belongs to a different document session',\n { details: { token } },\n );\n }\n const current = this.token(token.pageObjectNumber);\n if (!revisionTokensEqual(current, token)) {\n throw new EngineError(EngineErrorCode.InvalidReference, 'revision token is stale', {\n details: { provided: token, current },\n });\n }\n }\n\n weakAnnotationState(pageObjectNumber: PageObjectNumber): WeakAnnotationState {\n return this.weakAnnotationStates.get(pageObjectNumber) ?? UNKNOWN_WEAK_ANNOTATION_STATE;\n }\n\n recordWeakAnnotationState(pageObjectNumber: PageObjectNumber, state: WeakAnnotationState): void {\n this.weakAnnotationStates.set(pageObjectNumber, state);\n }\n\n drop(pageObjectNumber: PageObjectNumber): void {\n this.generations.delete(pageObjectNumber);\n this.weakAnnotationStates.delete(pageObjectNumber);\n }\n\n clear(): void {\n this.generations.clear();\n this.weakAnnotationStates.clear();\n }\n}\n","import type {\n PageObjectNumber,\n PageState,\n RevisionToken,\n WeakAnnotationState,\n} from '@embedpdf/engine-core/runtime';\nimport {\n EngineError,\n EngineErrorCode,\n knownWeakAnnotationState,\n isValidPageObjectNumber,\n} from '@embedpdf/engine-core/runtime';\nimport type { PdfRuntimeModule, Ptr } from '@embedpdf/engine-runtime';\n\nimport {\n openFatMemoryDocument,\n type OpenedPdfDocument,\n type OpenedPdfDocumentKind,\n} from './lifecycle/PdfDocumentOpener';\nimport { PagePtrPool } from './pages/PagePtrPool';\nimport type { PageRecord } from './pages/PageRecord';\nimport { LocalRevisionAuthority, type RevisionAuthority } from './revisions/RevisionAuthority';\n\n/**\n * Owns the lifecycle of a single open PDFium document and the v3\n * identity machinery: page registry (pageObjectNumber <-> pageIndex),\n * `RevisionAuthority` (per-page generation counters), and `PagePtrPool`\n * (refcounted pagePtr access).\n *\n * Both the local browser Worker and the server worker_thread instantiate\n * this exactly the same way; the only thing that differs is the\n * underlying PdfRuntimeModule (WASM vs native).\n */\nexport class DocumentSession {\n private docPtr: Ptr | null = null;\n private closeDocument: (() => void) | null = null;\n private _kind: OpenedPdfDocumentKind | null = null;\n private readonly _sessionId: string;\n\n /** pon -> record */\n private readonly recordsByObjectNumber = new Map<PageObjectNumber, PageRecord>();\n /** pageIndex -> record */\n private readonly recordsByIndex = new Map<number, PageRecord>();\n private fullyEnumerated = false;\n\n private revisions: RevisionAuthority | null = null;\n private mutationSeqCounter = 0;\n private pages: PagePtrPool | null = null;\n\n constructor(\n private readonly runtime: PdfRuntimeModule,\n sessionId?: string,\n ) {\n this._sessionId = sessionId ?? generateSessionId();\n }\n\n get sessionId(): string {\n return this._sessionId;\n }\n\n get kind(): OpenedPdfDocumentKind | null {\n return this._kind;\n }\n\n isOpen(): boolean {\n return this.docPtr !== null;\n }\n\n open(bytes: Uint8Array, password: string | null = null): void {\n this.openFromHandle(openFatMemoryDocument(this.runtime, bytes, password));\n }\n\n openFromHandle(handle: OpenedPdfDocument): void {\n if (this.docPtr) {\n handle.close();\n throw new EngineError(EngineErrorCode.InvalidArg, 'document already open');\n }\n this.docPtr = handle.docPtr;\n this.closeDocument = () => handle.close();\n this._kind = handle.kind;\n this.revisions = new LocalRevisionAuthority(this._sessionId);\n this.pages = new PagePtrPool(this.runtime, handle.docPtr);\n this.parkedBytes = null;\n }\n\n /**\n * Park this session in the password-locked state: the document could not\n * be loaded because a (correct) password is missing, so the session keeps\n * the already-transferred bytes and waits for an unlock attempt to load\n * them. A locked session occupies its docId key like an open one — every\n * operation except the password check rejects with DocPasswordRequired.\n */\n parkLocked(bytes: Uint8Array): void {\n if (this.docPtr) {\n throw new EngineError(EngineErrorCode.InvalidArg, 'document already open');\n }\n this.parkedBytes = bytes;\n }\n\n isLocked(): boolean {\n return this.docPtr === null && this.parkedBytes !== null;\n }\n\n /** The bytes retained for a later unlock attempt. Locked sessions only. */\n lockedBytes(): Uint8Array {\n if (!this.parkedBytes) {\n throw new EngineError(EngineErrorCode.DocNotOpen, 'document session is not locked');\n }\n return this.parkedBytes;\n }\n\n private parkedBytes: Uint8Array | null = null;\n\n /** Number of pages in the document. */\n pageCount(): number {\n return this.runtime.fn.FPDF_GetPageCount(this.requireDocPtr());\n }\n\n /**\n * Lazily enumerate every page and cache (pageObjectNumber, pageIndex).\n * Necessary before `listRawAll()` and any pon -> pageIndex resolution.\n */\n ensureFullPageRegistry(): void {\n if (this.fullyEnumerated) return;\n const { fn } = this.runtime;\n const docPtr = this.requireDocPtr();\n const count = fn.FPDF_GetPageCount(docPtr);\n for (let i = 0; i < count; i++) {\n if (this.recordsByIndex.has(i)) continue;\n const pon = fn.EPDFDoc_GetPageObjectNumberByIndex(docPtr, i);\n if (!isValidPageObjectNumber(pon)) {\n // Spec violation: ISO 32000-1 §7.7.3.3 requires every\n // /Page to be referenced indirectly from the /Pages tree.\n // PDFium's loader is permissive enough to surface direct\n // page dicts from broken generators, but the engine's\n // identity model requires a real indirect object number,\n // so we refuse the document here with a clear, actionable\n // error rather than silently routing through a weak\n // identity path.\n throw new EngineError(\n EngineErrorCode.MalformedPdf,\n `page at index ${i} is a direct (non-indirect) PDF object; the engine requires every page to have a stable indirect object number`,\n { details: { pageIndex: i, pon } },\n );\n }\n const record: PageRecord = { pageObjectNumber: pon, pageIndex: i };\n this.recordsByIndex.set(i, record);\n this.recordsByObjectNumber.set(pon, record);\n }\n this.fullyEnumerated = true;\n }\n\n /** Lookup; populates the cache for one page only on cache miss. */\n recordByObjectNumber(pageObjectNumber: PageObjectNumber): PageRecord {\n const cached = this.recordsByObjectNumber.get(pageObjectNumber);\n if (cached) return cached;\n\n // Probe the doc by loading the page directly via its object number;\n // walk the index range to find which page index it lives at.\n const { fn } = this.runtime;\n const docPtr = this.requireDocPtr();\n const probePtr = fn.EPDFDoc_LoadPageByObjectNumber(docPtr, pageObjectNumber);\n if (!probePtr) {\n throw new EngineError(\n EngineErrorCode.NotFound,\n `no page with object number ${pageObjectNumber}`,\n );\n }\n fn.FPDF_ClosePage(probePtr);\n\n // Now we know the page exists; fall back to a full enumeration to get\n // its display index. This is O(pageCount) once per session.\n this.ensureFullPageRegistry();\n const found = this.recordsByObjectNumber.get(pageObjectNumber);\n if (!found) {\n throw new EngineError(\n EngineErrorCode.NotFound,\n `page with object number ${pageObjectNumber} present but unindexable`,\n );\n }\n return found;\n }\n\n /** All page records, in display order. Forces full enumeration. */\n allRecords(): PageRecord[] {\n this.ensureFullPageRegistry();\n return Array.from(this.recordsByIndex.entries())\n .sort(([a], [b]) => a - b)\n .map(([, r]) => r);\n }\n\n /**\n * Drop the cached `pageIndex <-> pageObjectNumber` mapping and force a\n * fresh enumeration on next access. Called by `PagesMutator`\n * after `FPDF_MovePages` shuffles page positions; we keep\n * weak-annotation knowledge and per-page revision counters intact, both of\n * which are keyed by durable `pageObjectNumber` and survive a page reorder.\n */\n refreshPageRegistry(): void {\n this.recordsByIndex.clear();\n this.recordsByObjectNumber.clear();\n this.fullyEnumerated = false;\n this.ensureFullPageRegistry();\n }\n\n /** Per-page liveness envelope used by annotation read/mutation results. */\n pageState(pageObjectNumber: PageObjectNumber): PageState {\n // Validate the page exists (throws NotFound for bad pons); liveness is\n // keyed by pon and carries no display order — that lives in PageLayout.\n this.recordByObjectNumber(pageObjectNumber);\n const weakAnnotationState = this.requireRevisions().weakAnnotationState(pageObjectNumber);\n return {\n pageObjectNumber,\n revision: this.requireRevisions().token(pageObjectNumber),\n weakAnnotationState,\n };\n }\n\n /** Set by readers as they discover whether a page has weak annotations. */\n recordWeakFlag(pageObjectNumber: PageObjectNumber, hasWeak: boolean): void {\n this.recordWeakAnnotationState(pageObjectNumber, knownWeakAnnotationState(hasWeak));\n }\n\n recordWeakAnnotationState(pageObjectNumber: PageObjectNumber, state: WeakAnnotationState): void {\n this.requireRevisions().recordWeakAnnotationState(pageObjectNumber, state);\n }\n\n weakAnnotationState(pageObjectNumber: PageObjectNumber): WeakAnnotationState {\n return this.requireRevisions().weakAnnotationState(pageObjectNumber);\n }\n\n /** Bump and return the new revision token; called by mutation paths. */\n bumpRevision(pageObjectNumber: PageObjectNumber): RevisionToken {\n return this.requireRevisions().bump(pageObjectNumber);\n }\n\n /**\n * Monotonic count of successful document mutations in this session.\n * Version key for detached-snapshot caches (e.g. the forms model):\n * a cache entry built at sequence N is exactly valid while the\n * sequence is still N. Coarse on purpose — widgets are annotations\n * and page ops move widgets, so ANY mutation may affect derived\n * form state; per-domain counters are a later optimization.\n */\n mutationSeq(): number {\n return this.mutationSeqCounter;\n }\n\n /** Record one successful mutation; called by mutation paths. */\n noteMutation(): void {\n this.mutationSeqCounter++;\n }\n\n /**\n * Forget a page's per-session state (revision generation + weak-annotation\n * flag). Called by `pages.delete` after the page object is retired; the\n * PON is never recycled, so this is hygiene, not correctness.\n */\n dropPageState(pageObjectNumber: PageObjectNumber): void {\n this.requireRevisions().drop(pageObjectNumber);\n }\n\n validateRevision(token: RevisionToken): void {\n this.requireRevisions().validate(token);\n }\n\n pagePool(): PagePtrPool {\n if (!this.pages) {\n throw new EngineError(EngineErrorCode.DocNotOpen, 'document is not open');\n }\n return this.pages;\n }\n\n requireDocPtr(): Ptr {\n if (!this.docPtr) {\n throw new EngineError(EngineErrorCode.DocNotOpen, 'document is not open');\n }\n return this.docPtr;\n }\n\n /**\n * Park a disposer to run when THIS session closes. Used by operations\n * whose native side leaves the session document referencing another\n * resource — e.g. `pages.insert`: `FPDF_ImportPagesByIndex` does not\n * fully detach imported objects from their source document, so the\n * source doc + its byte buffer must stay alive until the destination\n * can no longer be saved (i.e. until this session closes).\n */\n retainUntilClose(dispose: () => void): void {\n this.retained.push(dispose);\n }\n\n private readonly retained: Array<() => void> = [];\n\n close(): void {\n let firstError: unknown = null;\n try {\n this.pages?.closeAll();\n } catch (error) {\n firstError = error;\n } finally {\n this.pages = null;\n }\n\n try {\n this.closeDocument?.();\n } catch (error) {\n firstError ??= error;\n } finally {\n this.closeDocument = null;\n this.docPtr = null;\n this._kind = null;\n this.parkedBytes = null;\n this.revisions?.clear();\n this.revisions = null;\n this.recordsByIndex.clear();\n this.recordsByObjectNumber.clear();\n this.fullyEnumerated = false;\n }\n\n // Retained resources go LAST (reverse order): the session doc that\n // referenced them is closed above, so they are safe to release now.\n for (let i = this.retained.length - 1; i >= 0; i--) {\n try {\n this.retained[i]();\n } catch (error) {\n firstError ??= error;\n }\n }\n this.retained.length = 0;\n\n if (firstError) throw firstError;\n }\n\n private requireRevisions(): RevisionAuthority {\n if (!this.revisions) {\n throw new EngineError(EngineErrorCode.DocNotOpen, 'document is not open');\n }\n return this.revisions;\n }\n}\n\n// Monotonic per-realm counter: the docSessionId exists only for the local\n// bleed-over check (a revision token minted by one session must not validate\n// against another), so uniqueness is the whole requirement — a counter makes\n// collisions structurally impossible within a realm, and the timestamp\n// distinguishes ids across realm restarts. Deliberately not random: there is\n// no adversary to hide the id from (anyone in-process can call the engine\n// directly), and pulling in crypto would add runtime constraints for nothing.\nlet sessionCounter = 0;\n\nfunction generateSessionId(): string {\n return `sess_${(++sessionCounter).toString(36)}_${Date.now().toString(36)}`;\n}\n","import { EngineError, EngineErrorCode } from '@embedpdf/engine-core/runtime';\nimport type { PdfFileAccessHandle, PdfRuntimeModule, Ptr } from '@embedpdf/engine-runtime';\n\nimport type { AcquiredBaseDocument } from './PdfDocumentOpener';\nimport { CloseStack, setRuntimeOwnerPermissionsIfEncrypted } from './PdfDocumentOpener';\n\ninterface BaseEntry {\n key: string;\n basePtr: Ptr;\n refs: number;\n close: () => void;\n}\n\nexport class BaseDocumentRegistry {\n private readonly entries = new Map<string, BaseEntry>();\n\n constructor(private readonly runtime: PdfRuntimeModule) {}\n\n acquireMemoryBase(opts: {\n key: string;\n bytes: Uint8Array;\n password?: string | null;\n }): AcquiredBaseDocument {\n const existing = this.retain(opts.key);\n if (existing) return existing;\n\n const { mem, fn } = this.runtime;\n const stack = new CloseStack();\n const dataPtr = mem.alloc(opts.bytes.byteLength);\n stack.push(() => mem.free(dataPtr));\n\n try {\n mem.writeBytes(dataPtr, opts.bytes);\n const basePtr = fn.EPDF_LoadMemBaseDocument64(\n dataPtr,\n opts.bytes.byteLength,\n opts.password ?? '',\n );\n if (!basePtr) {\n throw new EngineError(EngineErrorCode.DocOpenFailed, 'failed to open base document');\n }\n setRuntimeOwnerPermissionsIfEncrypted(this.runtime, basePtr);\n stack.push(() => fn.EPDF_ReleaseBaseDocument(basePtr));\n return this.insert(opts.key, basePtr, () => stack.close());\n } catch (error) {\n stack.close();\n throw error;\n }\n }\n\n acquireFileBase(opts: {\n key: string;\n path: string;\n password?: string | null;\n }): AcquiredBaseDocument {\n const existing = this.retain(opts.key);\n if (existing) return existing;\n\n const { fn } = this.runtime;\n const stack = new CloseStack();\n let access: PdfFileAccessHandle | null = null;\n\n try {\n access = this.runtime.fileAccess.fromNodeFile(opts.path);\n stack.push(() => access?.close());\n const basePtr = fn.EPDF_LoadBaseDocument(access.ptr, opts.password ?? '');\n if (!basePtr) {\n throw new EngineError(EngineErrorCode.DocOpenFailed, 'failed to open base document');\n }\n setRuntimeOwnerPermissionsIfEncrypted(this.runtime, basePtr);\n stack.push(() => fn.EPDF_ReleaseBaseDocument(basePtr));\n return this.insert(opts.key, basePtr, () => stack.close());\n } catch (error) {\n stack.close();\n throw error;\n }\n }\n\n releaseAll(): void {\n const entries = Array.from(this.entries.values());\n this.entries.clear();\n let firstError: unknown = null;\n for (const entry of entries) {\n try {\n entry.close();\n } catch (error) {\n firstError ??= error;\n }\n }\n if (firstError) throw firstError;\n }\n\n /** @internal Test-only probe of the per-key share refcount. */\n getRefCountForTesting(key: string): number {\n return this.entries.get(key)?.refs ?? 0;\n }\n\n private retain(key: string): AcquiredBaseDocument | null {\n const entry = this.entries.get(key);\n if (!entry) return null;\n entry.refs++;\n return this.handleFor(entry);\n }\n\n private insert(key: string, basePtr: Ptr, close: () => void): AcquiredBaseDocument {\n const entry: BaseEntry = { key, basePtr, refs: 1, close };\n this.entries.set(key, entry);\n return this.handleFor(entry);\n }\n\n private handleFor(entry: BaseEntry): AcquiredBaseDocument {\n let released = false;\n return {\n key: entry.key,\n basePtr: entry.basePtr,\n release: () => {\n if (released) return;\n released = true;\n const live = this.entries.get(entry.key);\n if (!live) return;\n live.refs--;\n if (live.refs > 0) return;\n this.entries.delete(entry.key);\n live.close();\n },\n };\n }\n}\n","import type { PdfRuntimeMemory, Ptr } from '@embedpdf/engine-runtime';\n\n/**\n * Allocate a scratch buffer, run `body` with it, and always free it.\n *\n * Every PDFium out-parameter call follows the same shape: malloc a\n * buffer, hand its pointer to the native function, read the result back,\n * free the buffer. Hand-rolling that `try/finally` at each call site is\n * how leaks and copy-paste bugs creep in, so it lives here once.\n */\nexport function withScratch<T>(mem: PdfRuntimeMemory, bytes: number, body: (ptr: Ptr) => T): T {\n const ptr = mem.alloc(bytes);\n try {\n return body(ptr);\n } finally {\n mem.free(ptr);\n }\n}\n\n/**\n * Like {@link withScratch} but for native calls that take several\n * out-parameters at once (e.g. `FPDFAnnot_GetColor` with one pointer per\n * channel). Buffers are freed in reverse allocation order.\n */\nexport function withScratchN<T>(\n mem: PdfRuntimeMemory,\n sizes: ReadonlyArray<number>,\n body: (ptrs: Ptr[]) => T,\n): T {\n const ptrs = sizes.map((size) => mem.alloc(size));\n try {\n return body(ptrs);\n } finally {\n for (let i = ptrs.length - 1; i >= 0; i--) {\n mem.free(ptrs[i]);\n }\n }\n}\n","import type { PdfRuntimeMemory, Ptr } from '@embedpdf/engine-runtime';\nimport { NULL_PTR } from '@embedpdf/engine-runtime';\n\nimport { withScratch } from './scratch';\n\n/**\n * Read a PDFium UTF-16LE string getter that uses the standard\n * (probe length, allocate, read) ABI. `call(buf, capacity)` must invoke\n * the native function and return the length in BYTES including the\n * trailing NUL (the value PDFium reports when `capacity` is 0).\n *\n * `emptyAs` decides what a present-but-empty value (`len === 2`, a lone\n * UTF-16 NUL) decodes to. This is the one knob different callers actually\n * disagree on: document Info strings treat `''` as a real value, whereas\n * a page label of `''` is indistinguishable from \"absent\" and reads as\n * `null`. Making it a parameter keeps that decision explicit instead of\n * forking the buffer dance.\n *\n * Returns `null` when the value is absent (`len <= 0`).\n */\nexport function readUtf16String(\n mem: PdfRuntimeMemory,\n call: (buf: Ptr, capacity: number) => number,\n emptyAs: '' | null = '',\n): string | null {\n const len = call(NULL_PTR, 0);\n if (len <= 0) return null; // absent\n if (len === 2) return emptyAs; // lone UTF-16 NUL\n return withScratch(mem, len, (buf) => {\n const written = call(buf, len);\n if (written <= 0) return null;\n return mem.readU16String(buf);\n });\n}\n\n/**\n * UTF-8 sibling of {@link readUtf16String} for the handful of native\n * getters that return UTF-8 (e.g. `EPDF_GetMetaKeyName`). UTF-8 has no\n * fixed empty-NUL width to special-case, so an empty value decodes to\n * `''`; absent (`len <= 0`) is `null`.\n */\nexport function readUtf8String(\n mem: PdfRuntimeMemory,\n call: (buf: Ptr, capacity: number) => number,\n): string | null {\n const len = call(NULL_PTR, 0);\n if (len <= 0) return null;\n return withScratch(mem, len, (buf) => {\n const written = call(buf, len);\n if (written <= 0) return null;\n return mem.readU8String(buf);\n });\n}\n\n/**\n * Write side of the UTF-16 convention: encode `value` into a scratch\n * buffer, hand the pointer to `set`, and always free it. `set` returns\n * the native call's success flag, which is propagated.\n */\nexport function writeUtf16String(\n mem: PdfRuntimeMemory,\n value: string,\n set: (ptr: Ptr) => boolean,\n): boolean {\n const ptr = mem.writeU16String(value);\n try {\n return set(ptr);\n } finally {\n mem.free(ptr);\n }\n}\n","import type { PdfFunctions, PdfRuntimeMemory, Ptr } from '@embedpdf/engine-runtime';\n\nimport { readUtf16String } from '../../../runtime/memory/strings';\n\n/**\n * Read a key from the document's Info dictionary. Returns null if the key\n * does not exist, '' if it exists but is empty, otherwise the UTF-16 string.\n *\n * `EPDF_HasMetaText` distinguishes an absent key (null) from a present\n * empty one (''); the value itself uses the standard UTF-16 getter ABI\n * (see `readUtf16String`, which keeps `''` as a real value here).\n */\nexport function readMetaText(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n docPtr: Ptr,\n key: string,\n): string | null {\n if (!fn.EPDF_HasMetaText(docPtr, key)) return null;\n return readUtf16String(\n mem,\n (buf, capacity) => fn.FPDF_GetMetaText(docPtr, key, buf, capacity),\n '',\n );\n}\n","import type { PdfFunctions, PdfRuntimeMemory, Ptr } from '@embedpdf/engine-runtime';\n\nimport { readMetaText } from './readMetadataText';\nimport { readUtf8String } from '../../../runtime/memory/strings';\n\n/**\n * Read the name of one key in the document's Info dictionary.\n * customOnly = true returns only non-reserved (custom) keys, matching the\n * behavior of `getMetaKeyName` in the legacy engine. Key names come back\n * as UTF-8.\n */\nfunction readMetaKeyName(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n docPtr: Ptr,\n index: number,\n customOnly: boolean,\n): string | null {\n return readUtf8String(mem, (buf, capacity) =>\n fn.EPDF_GetMetaKeyName(docPtr, index, customOnly, buf, capacity),\n );\n}\n\n/**\n * Read all custom metadata key/value pairs from the document's Info\n * dictionary. The wire format guarantees `string` values, so absent keys\n * are dropped (rather than represented as null).\n *\n * Mirrors the legacy `readAllMeta` (engine.ts:4698) but tightens the type\n * to Record<string, string> for the wire format.\n */\nexport function readAllCustomMeta(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n docPtr: Ptr,\n): Record<string, string> {\n const count = Number(fn.EPDF_GetMetaKeyCount(docPtr, true)) | 0;\n const out: Record<string, string> = {};\n for (let i = 0; i < count; i++) {\n const key = readMetaKeyName(fn, mem, docPtr, i, true);\n if (!key) continue;\n const value = readMetaText(fn, mem, docPtr, key);\n if (value == null) continue;\n out[key] = value;\n }\n return out;\n}\n","import type { DocumentMetadataTrapped } from '@embedpdf/engine-core/runtime';\nimport type { PdfFunctions, Ptr } from '@embedpdf/engine-runtime';\n\n// PDFium /Trapped values:\n// 0 = NotSet, 1 = True, 2 = False, 3 = Unknown.\n// The v3 wire DTO has only true/false/unknown, so NotSet folds into 'unknown'.\nconst TRAPPED_TRUE = 1;\nconst TRAPPED_FALSE = 2;\n\nexport function readTrapped(fn: PdfFunctions, docPtr: Ptr): DocumentMetadataTrapped {\n const raw = Number(fn.EPDF_GetMetaTrapped(docPtr));\n if (raw === TRAPPED_TRUE) return 'true';\n if (raw === TRAPPED_FALSE) return 'false';\n return 'unknown';\n}\n","import type { DocumentMetadata } from '@embedpdf/engine-core/runtime';\nimport type { PdfRuntimeModule } from '@embedpdf/engine-runtime';\n\nimport { readAllCustomMeta } from './internal/readCustomMetadata';\nimport { readMetaText } from './internal/readMetadataText';\nimport { readTrapped } from './internal/readTrappedStatus';\nimport type { DocumentSession } from '../../document-session/DocumentSession';\nimport { throwIfAborted } from '../../shared/abort';\nimport { pdfDateToIso } from '../../shared/pdf-date';\n\n/**\n * Synchronous, runtime-agnostic implementation of the metadata read.\n *\n * Lives in @embedpdf/engine-services so it can be reused unchanged by:\n * - @embedpdf/engine (inside a browser Worker, WASM runtime)\n * - @cloudpdf/server (inside a Node worker_thread, native runtime)\n *\n * Async-ness lives at the worker boundary, not here.\n */\nexport class MetadataReader {\n constructor(\n private readonly runtime: PdfRuntimeModule,\n private readonly session: DocumentSession,\n ) {}\n\n read(signal: AbortSignal): DocumentMetadata {\n throwIfAborted(signal);\n const { fn, mem } = this.runtime;\n const doc = this.session.requireDocPtr();\n\n const title = readMetaText(fn, mem, doc, 'Title');\n throwIfAborted(signal);\n const author = readMetaText(fn, mem, doc, 'Author');\n throwIfAborted(signal);\n const subject = readMetaText(fn, mem, doc, 'Subject');\n throwIfAborted(signal);\n const keywords = readMetaText(fn, mem, doc, 'Keywords');\n throwIfAborted(signal);\n const producer = readMetaText(fn, mem, doc, 'Producer');\n throwIfAborted(signal);\n const creator = readMetaText(fn, mem, doc, 'Creator');\n throwIfAborted(signal);\n const creationRaw = readMetaText(fn, mem, doc, 'CreationDate');\n throwIfAborted(signal);\n const modRaw = readMetaText(fn, mem, doc, 'ModDate');\n throwIfAborted(signal);\n const trapped = readTrapped(fn, doc);\n throwIfAborted(signal);\n const custom = readAllCustomMeta(fn, mem, doc);\n\n return {\n title,\n author,\n subject,\n keywords,\n producer,\n creator,\n created: creationRaw ? pdfDateToIso(creationRaw) : null,\n modified: modRaw ? pdfDateToIso(modRaw) : null,\n trapped,\n custom,\n };\n }\n}\n","import type { PdfFunctions, PdfRuntimeMemory, Ptr } from '@embedpdf/engine-runtime';\nimport { NULL_PTR } from '@embedpdf/engine-runtime';\n\nimport { writeUtf16String } from '../../../../runtime/memory/strings';\n\n/**\n * Write (or clear) one key in the document's Info dictionary.\n *\n * value = null -> remove the key (pass NULL_PTR; the fork's\n * `EPDF_SetMetaText` deletes the entry on a null value)\n * value = \"...\" -> set the key to the UTF-16 string (an empty string is\n * a real, present-but-empty value, matching the reader's\n * `emptyAs = ''` decode)\n *\n * Returns the native success flag. Mirrors v2 `setMetaText` (engine.ts),\n * minus v2's \"empty string removes\" quirk — three-state patch semantics\n * keep `null` (clear) and `''` (set empty) distinct.\n */\nexport function writeMetaText(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n docPtr: Ptr,\n key: string,\n value: string | null,\n): boolean {\n if (value === null) {\n return fn.EPDF_SetMetaText(docPtr, key, NULL_PTR);\n }\n return writeUtf16String(mem, value, (ptr) => fn.EPDF_SetMetaText(docPtr, key, ptr));\n}\n","import type { DocumentMetadataTrapped } from '@embedpdf/engine-core/runtime';\nimport type { PdfFunctions, Ptr } from '@embedpdf/engine-runtime';\n\n// PDFium /Trapped values mirror `readTrappedStatus`:\n// 0 = NotSet, 1 = True, 2 = False, 3 = Unknown.\nconst TRAPPED_TRUE = 1;\nconst TRAPPED_FALSE = 2;\nconst TRAPPED_UNKNOWN = 3;\n\n/**\n * Set the document's /Trapped Info entry from the wire enum. The v3 DTO\n * only carries `true | false | unknown`, so there is no \"clear\" form here\n * (unlike v2, which folded null into NotSet/removal); omit `trapped` from\n * the patch to leave it untouched.\n */\nexport function writeMetaTrapped(\n fn: PdfFunctions,\n docPtr: Ptr,\n status: DocumentMetadataTrapped,\n): boolean {\n const code =\n status === 'true' ? TRAPPED_TRUE : status === 'false' ? TRAPPED_FALSE : TRAPPED_UNKNOWN;\n return fn.EPDF_SetMetaTrapped(docPtr, code);\n}\n","import { EngineError, EngineErrorCode, type MetadataPatch } from '@embedpdf/engine-core/runtime';\nimport type { PdfFunctions, PdfRuntimeMemory, Ptr } from '@embedpdf/engine-runtime';\n\nimport { writeMetaText } from './writeMetaText';\nimport { writeMetaTrapped } from './writeMetaTrapped';\nimport { formatPdfDate } from '../../../../shared/pdf-date';\n\n/**\n * Standard Info-dict keys the patch maps to explicitly. Custom keys may\n * not collide with these (a custom write to `Title` would shadow the\n * structured field), so they are skipped with the date keys and /Trapped.\n */\nconst RESERVED_INFO_KEYS = new Set([\n 'Title',\n 'Author',\n 'Subject',\n 'Keywords',\n 'Producer',\n 'Creator',\n 'CreationDate',\n 'ModDate',\n 'Trapped',\n]);\n\n/**\n * Standard string field -> PDF Info key. Date fields and /Trapped are\n * handled separately because they need format conversion / a dedicated\n * native setter.\n */\nconst STRING_FIELDS: ReadonlyArray<[keyof MetadataPatch, string]> = [\n ['title', 'Title'],\n ['author', 'Author'],\n ['subject', 'Subject'],\n ['keywords', 'Keywords'],\n ['producer', 'Producer'],\n ['creator', 'Creator'],\n];\n\n/**\n * A custom key must be writable as a PDF Name and must not shadow a\n * reserved standard key. Mirrors v2 `isValidCustomKey` (helper.ts):\n * non-empty ASCII printable, <= 127 chars, no leading slash.\n */\nfunction isValidCustomKey(key: string): boolean {\n if (!key || key.length > 127) return false;\n if (RESERVED_INFO_KEYS.has(key)) return false;\n if (key[0] === '/') return false;\n for (let i = 0; i < key.length; i++) {\n const c = key.charCodeAt(i);\n if (c < 0x20 || c > 0x7e) return false;\n }\n return true;\n}\n\n/**\n * Apply a three-state {@link MetadataPatch} to the document's Info dict\n * in place. `undefined` leaves a field, `null` clears it, a value sets\n * it (dates are formatted to PDF date syntax). Custom keys are set/cleared\n * per-key; reserved or malformed keys are skipped.\n *\n * Throws {@link EngineError} `Unknown` if any native write fails, so the\n * caller never reports a partially-applied edit as success.\n */\nexport function applyMetadataPatch(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n docPtr: Ptr,\n patch: MetadataPatch,\n): void {\n const fail = (what: string): never => {\n throw new EngineError(EngineErrorCode.Unknown, `failed to write metadata ${what}`);\n };\n\n for (const [field, key] of STRING_FIELDS) {\n const value = patch[field] as string | null | undefined;\n if (value === undefined) continue;\n if (!writeMetaText(fn, mem, docPtr, key, value)) fail(key);\n }\n\n if (patch.created !== undefined) {\n const value = patch.created === null ? null : formatPdfDate(new Date(patch.created));\n if (!writeMetaText(fn, mem, docPtr, 'CreationDate', value)) fail('CreationDate');\n }\n if (patch.modified !== undefined) {\n const value = patch.modified === null ? null : formatPdfDate(new Date(patch.modified));\n if (!writeMetaText(fn, mem, docPtr, 'ModDate', value)) fail('ModDate');\n }\n\n if (patch.trapped !== undefined) {\n if (!writeMetaTrapped(fn, docPtr, patch.trapped)) fail('Trapped');\n }\n\n if (patch.custom !== undefined) {\n for (const [key, value] of Object.entries(patch.custom)) {\n if (!isValidCustomKey(key)) continue;\n if (!writeMetaText(fn, mem, docPtr, key, value)) fail(key);\n }\n }\n}\n","import type { MetadataPatch, MetadataUpdateResult } from '@embedpdf/engine-core/runtime';\nimport type { PdfRuntimeModule } from '@embedpdf/engine-runtime';\n\nimport { applyMetadataPatch } from './internal/write/applyMetadataPatch';\nimport { MetadataReader } from './MetadataReader';\nimport type { DocumentSession } from '../../document-session/DocumentSession';\nimport { throwIfAborted } from '../../shared/abort';\n\n/**\n * Synchronous orchestrator for document metadata writes. Lives next to\n * `MetadataReader` (one orchestrator per feature) so both worker hosts\n * (browser Web Worker and Node `worker_thread`) share the same code path.\n *\n * A metadata write rewrites the document Info dictionary in place. Like\n * `PagesMutator.move`, it is a structural layer edit: it returns the\n * re-read metadata and a `null` cache (the worker never fills cloud\n * coherence pins — the server does, after persisting the artifact and\n * bumping `metadataVersion`).\n */\nexport class MetadataMutator {\n constructor(\n private readonly runtime: PdfRuntimeModule,\n private readonly session: DocumentSession,\n ) {}\n\n update(patch: MetadataPatch, signal: AbortSignal): MetadataUpdateResult {\n throwIfAborted(signal);\n const { fn, mem } = this.runtime;\n const docPtr = this.session.requireDocPtr();\n\n applyMetadataPatch(fn, mem, docPtr, patch);\n throwIfAborted(signal);\n\n // Re-read the canonical metadata off the mutated session via the\n // shared reader (identical output local + cloud). `cache` is null —\n // local engines have no manifest/CDN.\n const metadata = new MetadataReader(this.runtime, this.session).read(signal);\n return { metadata, cache: null };\n }\n}\n","import type { PdfRuntimeMemory, Ptr } from '@embedpdf/engine-runtime';\n\n/** `FS_RECTF { float left, top, right, bottom }` → 16 bytes. */\nexport const RECTF_BYTES = 16;\n/** `FS_SIZEF { float width, height }` → 8 bytes. */\nexport const SIZEF_BYTES = 8;\n/** A single 32-bit float (e.g. a user-unit out-parameter). */\nexport const F32_BYTES = 4;\n/** A single 32-bit int (e.g. a color channel out-parameter). */\nexport const I32_BYTES = 4;\n/** `FS_QUADPOINTSF` — 8 floats → 32 bytes. */\nexport const QUADPOINTSF_BYTES = 32;\n/** `FS_POINTF { float x, y }` → 8 bytes. */\nexport const POINTF_BYTES = 8;\n\nexport interface RectF {\n left: number;\n top: number;\n right: number;\n bottom: number;\n}\n\nexport interface SizeF {\n width: number;\n height: number;\n}\n\n/** Decode an `FS_RECTF` struct that a native call wrote into `ptr`. */\nexport function readRectF(mem: PdfRuntimeMemory, ptr: Ptr): RectF {\n return {\n left: readF32(mem, ptr, 0),\n top: readF32(mem, ptr, 4),\n right: readF32(mem, ptr, 8),\n bottom: readF32(mem, ptr, 12),\n };\n}\n\n/** Decode an `FS_SIZEF` struct that a native call wrote into `ptr`. */\nexport function readSizeF(mem: PdfRuntimeMemory, ptr: Ptr): SizeF {\n return {\n width: readF32(mem, ptr, 0),\n height: readF32(mem, ptr, 4),\n };\n}\n\n/** Read a single 32-bit float at `byteOffset` within `ptr`. */\nexport function readF32(mem: PdfRuntimeMemory, ptr: Ptr, byteOffset = 0): number {\n return Number(mem.peek(ptr, 'f32', byteOffset));\n}\n\n/** Read a single 32-bit int at `byteOffset` within `ptr`. */\nexport function readI32(mem: PdfRuntimeMemory, ptr: Ptr, byteOffset = 0): number {\n return Number(mem.peek(ptr, 'i32', byteOffset));\n}\n","import type {\n ActionReadBudget,\n PdfActionNode,\n PdfActionTree,\n PdfActionType,\n PdfActionWarning,\n} from '@embedpdf/engine-core/runtime';\nimport { EngineError, EngineErrorCode } from '@embedpdf/engine-core/runtime';\nimport {\n NULL_PTR,\n type PdfFunctions,\n type PdfRuntimeMemory,\n type Ptr,\n} from '@embedpdf/engine-runtime';\n\nimport { readUtf16String, readUtf8String } from '../../runtime/memory/strings';\n\nconst DEFAULT_ACTION_READ_BUDGET: ActionReadBudget = {\n maxModels: 512,\n maxNodes: 16_384,\n maxScriptCodeUnits: 16_000_000,\n};\n\nconst ACTION_TYPE_BY_CODE: Record<number, PdfActionType> = {\n 0: 'unknown',\n 1: 'goto',\n 2: 'goto-remote',\n 3: 'goto-embedded',\n 4: 'launch',\n 5: 'thread',\n 6: 'uri',\n 7: 'sound',\n 8: 'movie',\n 9: 'hide',\n 10: 'named',\n 11: 'submit-form',\n 12: 'reset-form',\n 13: 'import-data',\n 14: 'javascript',\n 15: 'set-ocg-state',\n 16: 'rendition',\n 17: 'transition',\n 18: 'goto-3d-view',\n};\n\nconst WARNING_CYCLE_DROPPED = 0x1;\nconst WARNING_MALFORMED_NEXT = 0x2;\nconst WARNING_INCOMPLETE = 0x4;\nconst INVALID_NODE_U32 = 0xffff_ffff;\n\n/** `EPDF_ANNOT_ACTION_ACTIVATE` — the `/A` slot of the per-annotation event\n * table (the same table `readAnnotationBase` walks). */\nexport const ANNOT_ACTION_ACTIVATE = 0;\n\n/** Decode one `EPDF_ACTION_TYPE_*` code — the shared vocabulary consumers\n * (the link-target projection) use so the two surfaces cannot drift. */\nexport function actionTypeFromCode(code: number): PdfActionType {\n return ACTION_TYPE_BY_CODE[code] ?? 'unknown';\n}\n\n/** Is this `EPDFAction_GetRootNode`/`GetNextAt` result a real node id?\n * (`EPDF_ACTION_NODE_INVALID` may surface as -1 or u32 max via cwrap.) */\nexport function isValidActionNodeId(raw: number): boolean {\n return raw !== -1 && raw >>> 0 !== INVALID_NODE_U32;\n}\n\n/** Mutable aggregate budget shared by every action model in one read job. */\nexport class ActionReadBudgetTracker {\n private models = 0;\n private nodes = 0;\n private scriptCodeUnits = 0;\n\n constructor(private readonly limits: ActionReadBudget = DEFAULT_ACTION_READ_BUDGET) {}\n\n addModel(nodeCount: number): void {\n this.models += 1;\n this.nodes += nodeCount;\n this.assertWithinBudget();\n }\n\n addScript(script: string): void {\n this.scriptCodeUnits += script.length;\n this.assertWithinBudget();\n }\n\n private assertWithinBudget(): void {\n if (\n this.models > this.limits.maxModels ||\n this.nodes > this.limits.maxNodes ||\n this.scriptCodeUnits > this.limits.maxScriptCodeUnits\n ) {\n throw new EngineError(\n EngineErrorCode.MalformedPdf,\n 'aggregate PDF action read budget exceeded',\n {\n details: {\n models: this.models,\n nodes: this.nodes,\n scriptCodeUnits: this.scriptCodeUnits,\n limits: this.limits,\n },\n },\n );\n }\n }\n}\n\n/**\n * Convert and close one detached native action model. This is the only\n * native-model walker used by document, page, field, and annotation reads.\n */\nexport function readActionModel(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n modelPtr: Ptr,\n budget: ActionReadBudgetTracker,\n): PdfActionTree | null {\n if (modelPtr === NULL_PTR) return null;\n try {\n const nodeCount = fn.EPDFAction_GetNodeCount(modelPtr);\n if (!Number.isInteger(nodeCount) || nodeCount < 0) {\n throw malformedActionModel('invalid node count', { nodeCount });\n }\n budget.addModel(nodeCount);\n\n const warningFlags = fn.EPDFAction_GetWarningFlags(modelPtr) >>> 0;\n const incomplete = !fn.EPDFAction_IsComplete(modelPtr);\n const rootId = normalizeOptionalNodeId(fn.EPDFAction_GetRootNode(modelPtr), nodeCount);\n const visiting = new Set<number>();\n\n const readNode = (nodeId: number): PdfActionNode => {\n if (visiting.has(nodeId)) {\n throw malformedActionModel('native action model contains a cycle', { nodeId });\n }\n visiting.add(nodeId);\n try {\n const subtype =\n readUtf8String(mem, (buf, capacity) =>\n fn.EPDFAction_GetNodeSubtype(modelPtr, nodeId, buf, capacity),\n ) ?? '';\n const script = fn.EPDFAction_NodeHasJavaScript(modelPtr, nodeId)\n ? (readUtf16String(mem, (buf, capacity) =>\n fn.EPDFAction_GetNodeJavaScript(modelPtr, nodeId, buf, capacity),\n ) ?? '')\n : undefined;\n if (script !== undefined) budget.addScript(script);\n\n const nextCount = fn.EPDFAction_GetNextCount(modelPtr, nodeId);\n if (!Number.isInteger(nextCount) || nextCount < 0) {\n throw malformedActionModel('invalid action child count', { nodeId, nextCount });\n }\n const next: PdfActionNode[] = [];\n for (let index = 0; index < nextCount; index++) {\n const childId = normalizeNodeId(\n fn.EPDFAction_GetNextAt(modelPtr, nodeId, index),\n nodeCount,\n );\n next.push(readNode(childId));\n }\n return {\n type: ACTION_TYPE_BY_CODE[fn.EPDFAction_GetNodeType(modelPtr, nodeId)] ?? 'unknown',\n subtype,\n ...(script !== undefined ? { script } : {}),\n next,\n };\n } finally {\n visiting.delete(nodeId);\n }\n };\n\n return {\n root: rootId === null ? null : readNode(rootId),\n incomplete,\n warningFlags,\n warnings: warningsFromFlags(warningFlags, incomplete),\n };\n } finally {\n fn.EPDFAction_CloseModel(modelPtr);\n }\n}\n\nfunction normalizeOptionalNodeId(raw: number, nodeCount: number): number | null {\n const invalid = raw === -1 || raw === INVALID_NODE_U32 || raw >>> 0 === INVALID_NODE_U32;\n return invalid ? null : normalizeNodeId(raw, nodeCount);\n}\n\nfunction normalizeNodeId(raw: number, nodeCount: number): number {\n if (!Number.isInteger(raw) || raw < 0 || raw >= nodeCount) {\n throw malformedActionModel('native action model returned an invalid node id', {\n raw,\n nodeCount,\n });\n }\n return raw;\n}\n\nfunction warningsFromFlags(flags: number, incomplete: boolean): PdfActionWarning[] {\n const warnings: PdfActionWarning[] = [];\n if ((flags & WARNING_CYCLE_DROPPED) !== 0) warnings.push('cycle-dropped');\n if ((flags & WARNING_MALFORMED_NEXT) !== 0) warnings.push('malformed-next');\n if ((flags & WARNING_INCOMPLETE) !== 0 || incomplete) warnings.push('incomplete');\n return warnings;\n}\n\nfunction malformedActionModel(message: string, details: Record<string, unknown>): EngineError {\n return new EngineError(EngineErrorCode.MalformedPdf, message, { details });\n}\n","import type {\n PageBoxes,\n PageLayout,\n PageListSnapshot,\n PdfRect,\n PdfPageActions,\n} from '@embedpdf/engine-core/runtime';\nimport { normalizePdfRect } from '@embedpdf/engine-core/runtime';\nimport type {\n PdfFunctions,\n PdfRuntimeMemory,\n PdfRuntimeModule,\n Ptr,\n} from '@embedpdf/engine-runtime';\n\nimport type { DocumentSession } from '../../document-session/DocumentSession';\nimport { withScratchN } from '../../runtime/memory/scratch';\nimport { readUtf16String } from '../../runtime/memory/strings';\nimport {\n F32_BYTES,\n RECTF_BYTES,\n SIZEF_BYTES,\n readF32,\n readRectF,\n readSizeF,\n} from '../../runtime/memory/structs';\nimport { throwIfAborted } from '../../shared/abort';\nimport { ActionReadBudgetTracker, readActionModel } from '../actions/ActionModelReader';\n\n// EPDF_PAGE_BOX_TYPE (public/fpdfview.h).\nconst BOX_MEDIA = 0;\nconst BOX_CROP = 1;\nconst BOX_BLEED = 2;\nconst BOX_TRIM = 3;\nconst BOX_ART = 4;\n\n/**\n * Runtime-agnostic page geometry reader. Produces the `pages.list()`\n * snapshot from the lightweight `...ByIndex` PDFium bindings, none of which\n * load or parse a page (no `pagePtr`), so listing stays cheap. Shared\n * verbatim by the local WASM worker and the server native worker, so a\n * given PDF yields an identical `PageListSnapshot` on both engines.\n */\nexport class PagesReader {\n constructor(\n private readonly runtime: PdfRuntimeModule,\n private readonly session: DocumentSession,\n ) {}\n\n read(signal: AbortSignal): PageListSnapshot {\n throwIfAborted(signal);\n const { fn, mem } = this.runtime;\n const docPtr = this.session.requireDocPtr();\n const records = this.session.allRecords();\n const actionBudget = new ActionReadBudgetTracker();\n\n // One scratch buffer per struct kind, reused across every page.\n return withScratchN(\n mem,\n [RECTF_BYTES, SIZEF_BYTES, F32_BYTES],\n ([rectPtr, sizePtr, userUnitPtr]) => {\n const pages: PageLayout[] = records.map((record) => {\n throwIfAborted(signal);\n const index = record.pageIndex;\n const actions = readPageActions(fn, mem, docPtr, record.pageObjectNumber, actionBudget);\n return {\n index,\n pageObjectNumber: record.pageObjectNumber,\n label: readLabel(fn, mem, docPtr, index),\n size: readSize(fn, mem, docPtr, index, sizePtr),\n rotation: readRotation(fn, docPtr, index),\n userUnit: readUserUnit(fn, mem, docPtr, index, userUnitPtr),\n boxes: readBoxes(fn, mem, docPtr, index, rectPtr),\n ...(actions ? { actions } : {}),\n };\n });\n return { pageCount: pages.length, pages };\n },\n );\n }\n}\n\nfunction readPageActions(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n docPtr: Ptr,\n pageObjectNumber: number,\n budget: ActionReadBudgetTracker,\n): PdfPageActions | undefined {\n const actions: PdfPageActions = {};\n const open = readActionModel(\n fn,\n mem,\n fn.EPDFDoc_GetPageActionModel(docPtr, pageObjectNumber, 0),\n budget,\n );\n const close = readActionModel(\n fn,\n mem,\n fn.EPDFDoc_GetPageActionModel(docPtr, pageObjectNumber, 1),\n budget,\n );\n if (open) actions.open = open;\n if (close) actions.close = close;\n return open || close ? actions : undefined;\n}\n\n/**\n * Read one FS_RECTF box and canonicalize to a y-up `PdfRect`\n * (`{ left, bottom, right, top }`, equivalent to `[llx, lly, urx, ury]`) so\n * the lower-left/upper-right invariant holds regardless of how the PDF\n * ordered the corners. Returns null when the optional box is absent.\n */\nfunction readBox(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n docPtr: Ptr,\n index: number,\n boxType: number,\n rectPtr: Ptr,\n): PdfRect | null {\n if (!fn.EPDF_GetPageBoxByIndex(docPtr, index, boxType, rectPtr)) return null;\n // FS_RECTF → y-up `PdfRect`, normalized so the lower-left/upper-right invariant\n // holds regardless of how the PDF ordered the corners.\n return normalizePdfRect(readRectF(mem, rectPtr));\n}\n\nfunction readBoxes(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n docPtr: Ptr,\n index: number,\n rectPtr: Ptr,\n): PageBoxes {\n // MediaBox always resolves (page-tree inheritance + PDFium default).\n // CropBox falls back to MediaBox, so both are guaranteed present.\n const media = readBox(fn, mem, docPtr, index, BOX_MEDIA, rectPtr) ?? {\n left: 0,\n bottom: 0,\n right: 0,\n top: 0,\n };\n const crop = readBox(fn, mem, docPtr, index, BOX_CROP, rectPtr) ?? media;\n const bleed = readBox(fn, mem, docPtr, index, BOX_BLEED, rectPtr);\n const trim = readBox(fn, mem, docPtr, index, BOX_TRIM, rectPtr);\n const art = readBox(fn, mem, docPtr, index, BOX_ART, rectPtr);\n return {\n media,\n crop,\n ...(bleed ? { bleed } : {}),\n ...(trim ? { trim } : {}),\n ...(art ? { art } : {}),\n };\n}\n\nfunction readSize(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n docPtr: Ptr,\n index: number,\n sizePtr: Ptr,\n): { width: number; height: number } {\n if (!fn.EPDF_GetPageSizeByIndexNormalized(docPtr, index, sizePtr)) {\n return { width: 0, height: 0 };\n }\n return readSizeF(mem, sizePtr);\n}\n\nfunction readRotation(fn: PdfFunctions, docPtr: Ptr, index: number): 0 | 90 | 180 | 270 {\n // Returns quarter-turns (0..3), or -1 on error.\n const quarterTurns = fn.EPDF_GetPageRotationByIndex(docPtr, index);\n switch (quarterTurns) {\n case 1:\n return 90;\n case 2:\n return 180;\n case 3:\n return 270;\n default:\n return 0;\n }\n}\n\nfunction readUserUnit(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n docPtr: Ptr,\n index: number,\n userUnitPtr: Ptr,\n): number {\n if (!fn.EPDF_GetPageUserUnitByIndex(docPtr, index, userUnitPtr)) return 1;\n const value = readF32(mem, userUnitPtr, 0);\n return Number.isFinite(value) && value > 0 ? value : 1;\n}\n\nfunction readLabel(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n docPtr: Ptr,\n index: number,\n): string | null {\n // A page label of '' is indistinguishable from \"absent\" for our DTO, so\n // empty reads as null (`emptyAs: null`); the trailing `|| null` also maps\n // a decoded-but-empty buffer to null.\n return (\n readUtf16String(\n mem,\n (buf, capacity) => fn.FPDF_GetPageLabel(docPtr, index, buf, capacity),\n null,\n ) || null\n );\n}\n","import {\n EngineError,\n EngineErrorCode,\n type PageDeleteResult,\n type PageMoveResult,\n type PageObjectNumber,\n type PageRotateResult,\n type PageRotation,\n} from '@embedpdf/engine-core/runtime';\nimport type { PdfRuntimeModule } from '@embedpdf/engine-runtime';\n\nimport { PagesReader } from './PagesReader';\nimport type { DocumentSession } from '../../document-session/DocumentSession';\nimport { throwIfAborted } from '../../shared/abort';\n\n/**\n * Synchronous orchestrator for page-level reads and reorder mutations.\n * Lives next to `AnnotationMutator` (one orchestrator per\n * mutation domain) so both worker hosts (browser Web Worker and Node\n * `worker_thread`) share the same code path.\n *\n * Architectural anchor — locked with the user, do not loosen without\n * re-reading the doc comments on `PageMoveResult` and `RevisionAuthority`:\n *\n * - Pages are addressed by their durable `pageObjectNumber`. There is\n * no \"weak page ref\" model in the engine; therefore there is no\n * document-level revision token, no `DocumentRevisionStore`, and no\n * \"doc-level shouldRefetch\" semantic. Anything that *is* listed\n * here must remain stable across every reorder permutation.\n *\n * - Per-page `RevisionToken`s do NOT bump on `move()`. The /Annots\n * array of each affected page is untouched (PDFium just rewrites\n * pointer entries in the doc-level pages tree), so weak\n * `AnnotationRef.kind === 'index'` references the caller is\n * holding remain valid across a page reorder. This is the right\n * semantic for an editing UI: shuffling pages must NOT silently\n * break a pending highlight edit.\n *\n * - Identity strengthening (the opportunistic `/NM` stamping that\n * applies to weak annotations on `update()` / `move()`) is also\n * intentionally absent here. Pages are durable by construction;\n * there is nothing to upgrade.\n */\nexport class PagesMutator {\n constructor(\n private readonly runtime: PdfRuntimeModule,\n private readonly session: DocumentSession,\n ) {}\n\n /**\n * Reorder pages. Mirrors `FPDF_MovePages`: detach the supplied pages,\n * then re-insert them as a contiguous block at `destIndex` in the\n * post-removal index space, preserving caller order.\n *\n * Atomicity:\n * - `FPDF_MovePages` rejects atomically: if it returns false, no\n * change has happened. We surface that as `InvalidArg`.\n * - On success we refresh the per-session page registry and read the\n * new layout back, which is what the result returns.\n *\n * Validation done up front (the helper repeats these checks; we do\n * them here for clean error messages):\n * - non-empty inputs;\n * - duplicate `pageObjectNumber`s rejected;\n * - every `pon` resolvable via the session's page registry;\n * - `destIndex` in `[0, pageCount - len]`.\n */\n move(\n pageObjectNumbers: PageObjectNumber[],\n destIndex: number,\n signal: AbortSignal,\n ): PageMoveResult {\n throwIfAborted(signal);\n this.requireUniquePons('pages.move', pageObjectNumbers);\n if (destIndex < 0 || !Number.isInteger(destIndex)) {\n throw new EngineError(\n EngineErrorCode.InvalidArg,\n `pages.move destIndex must be a non-negative integer (got ${destIndex})`,\n );\n }\n\n const { fn, mem } = this.runtime;\n const docPtr = this.session.requireDocPtr();\n const totalPages = fn.FPDF_GetPageCount(docPtr);\n const postRemoval = totalPages - pageObjectNumbers.length;\n if (destIndex > postRemoval) {\n throw new EngineError(\n EngineErrorCode.InvalidArg,\n `pages.move destIndex ${destIndex} out of range; post-removal page count is ${postRemoval}`,\n );\n }\n\n // Resolve every pon to its current pageIndex via the session\n // registry. Bad pons throw `NotFound` from the session, which is\n // exactly what we want — the caller asked to move a page that does\n // not exist.\n const fromIndices = pageObjectNumbers.map((pon) => {\n throwIfAborted(signal);\n return this.session.recordByObjectNumber(pon).pageIndex;\n });\n\n // Marshal int[] and call the helper.\n const arrPtr = mem.alloc(4 * fromIndices.length);\n let ok: boolean;\n try {\n for (let i = 0; i < fromIndices.length; i++) {\n mem.poke(arrPtr, 'i32', fromIndices[i], 4 * i);\n }\n ok = fn.FPDF_MovePages(docPtr, arrPtr, fromIndices.length, destIndex);\n } finally {\n mem.free(arrPtr);\n }\n\n if (!ok) {\n // FPDF_MovePages validates atomically: a `false` return means no\n // change happened. Most likely cause is a contiguous-block\n // overlap our up-front checks did not catch — surface it cleanly.\n throw new EngineError(\n EngineErrorCode.InvalidArg,\n `FPDF_MovePages rejected the request (destIndex=${destIndex}, fromIndices=[${fromIndices.join(\n ',',\n )}])`,\n );\n }\n\n // Page positions changed; rebuild the index<->pon map. Per-page\n // revisions and weak-flag bookkeeping survive — both keyed by pon,\n // both untouched by the reorder.\n this.session.refreshPageRegistry();\n\n // A move returns geometry, not liveness: read the new layout off the\n // reordered session via the shared reader (identical output local +\n // cloud). `cache` is null — local engines have no manifest/CDN.\n const layout = new PagesReader(this.runtime, this.session).read(signal);\n return { layout, cache: null };\n }\n\n /**\n * Set the ABSOLUTE display rotation of the supplied pages. Rotation is\n * presentation metadata over normalized content (pages always load with\n * rotation forced to 0 — see `PagePtrPool`), so:\n * - no cached render, text run, or geometry coordinate changes;\n * - per-page `RevisionToken`s do NOT bump;\n * - page identity and order are untouched — no registry refresh.\n *\n * Atomicity: every PON is resolved up front (`NotFound` on caller error),\n * so the apply loop below operates on validated pages only and each write\n * is absolute + idempotent — a retry after an unexpected mid-loop engine\n * fault converges to the requested state. Abort is honored BEFORE the\n * loop, never inside it.\n */\n rotate(\n pageObjectNumbers: PageObjectNumber[],\n rotation: PageRotation,\n signal: AbortSignal,\n ): PageRotateResult {\n throwIfAborted(signal);\n this.requireUniquePons('pages.rotate', pageObjectNumbers);\n if (rotation !== 0 && rotation !== 90 && rotation !== 180 && rotation !== 270) {\n throw new EngineError(\n EngineErrorCode.InvalidArg,\n `pages.rotate rotation must be 0, 90, 180 or 270 (got ${rotation})`,\n );\n }\n\n const { fn } = this.runtime;\n const docPtr = this.session.requireDocPtr();\n for (const pon of pageObjectNumbers) {\n this.session.recordByObjectNumber(pon); // NotFound on unknown pon\n }\n\n // The EPDF helper takes quarter-turns (0..3); the wire speaks degrees.\n const quarterTurns = rotation / 90;\n for (const pon of pageObjectNumbers) {\n if (!fn.EPDFDoc_SetPageRotationByObjectNumber(docPtr, pon, quarterTurns)) {\n throw new EngineError(\n EngineErrorCode.Unknown,\n `EPDFDoc_SetPageRotationByObjectNumber rejected page ${pon} after validation`,\n );\n }\n }\n\n const layout = new PagesReader(this.runtime, this.session).read(signal);\n return { layout, cache: null };\n }\n\n /**\n * Delete pages. Deleted object numbers are RETIRED — the engine nulls the\n * page object rather than freeing the number — so per-page state keyed by\n * PON can never silently attach to an unrelated future page; we still drop\n * the session's revision/weak entries as hygiene. Surviving pages keep\n * their identity and `RevisionToken`s.\n *\n * Guards:\n * - a document must keep at least one page (`InvalidArg`);\n * - every PON must resolve (`NotFound`);\n * - no target page may have a live pooled `pagePtr`. Thread confinement\n * means no other job can be mid-flight, so a held ptr here is a leaked\n * `acquire` — an internal bug we surface loudly instead of deleting\n * under a live handle.\n *\n * Abort is honored BEFORE the apply loop, never inside it.\n */\n delete(pageObjectNumbers: PageObjectNumber[], signal: AbortSignal): PageDeleteResult {\n throwIfAborted(signal);\n this.requireUniquePons('pages.delete', pageObjectNumbers);\n\n const { fn } = this.runtime;\n const docPtr = this.session.requireDocPtr();\n const totalPages = fn.FPDF_GetPageCount(docPtr);\n if (pageObjectNumbers.length >= totalPages) {\n throw new EngineError(\n EngineErrorCode.InvalidArg,\n `pages.delete would remove every page (${pageObjectNumbers.length} of ${totalPages}); a document must keep at least one`,\n );\n }\n\n const pool = this.session.pagePool();\n for (const pon of pageObjectNumbers) {\n this.session.recordByObjectNumber(pon); // NotFound on unknown pon\n if (pool.isHeld(pon)) {\n throw new EngineError(\n EngineErrorCode.Unknown,\n `internal invariant violation: pagePtr for page ${pon} is still held during pages.delete`,\n );\n }\n }\n\n for (const pon of pageObjectNumbers) {\n if (!fn.EPDFDoc_DeletePageByObjectNumber(docPtr, pon)) {\n throw new EngineError(\n EngineErrorCode.Unknown,\n `EPDFDoc_DeletePageByObjectNumber rejected page ${pon} after validation`,\n );\n }\n this.session.dropPageState(pon);\n }\n\n // Page count and order changed; rebuild the index<->pon map. Surviving\n // pages' revisions and weak-flag bookkeeping stay put (keyed by pon).\n this.session.refreshPageRegistry();\n\n const layout = new PagesReader(this.runtime, this.session).read(signal);\n return { layout, cache: null };\n }\n\n /** Shared input check: non-empty, no duplicate PONs. */\n private requireUniquePons(op: string, pageObjectNumbers: PageObjectNumber[]): void {\n if (pageObjectNumbers.length === 0) {\n throw new EngineError(EngineErrorCode.InvalidArg, `${op} requires at least one page`);\n }\n const seen = new Set<PageObjectNumber>();\n for (const pon of pageObjectNumbers) {\n if (seen.has(pon)) {\n throw new EngineError(\n EngineErrorCode.InvalidArg,\n `${op} was given duplicate page object number ${pon}`,\n );\n }\n seen.add(pon);\n }\n }\n}\n","import { EngineError, EngineErrorCode, type PageObjectNumber } from '@embedpdf/engine-core/runtime';\nimport type { PdfRuntimeModule, Ptr } from '@embedpdf/engine-runtime';\n\nimport type { DocumentSession } from '../../document-session/DocumentSession';\nimport { throwIfAborted } from '../../shared/abort';\n\nconst FPDF_NO_INCREMENTAL = 1 << 1;\n\n/**\n * Export a subset of pages as a standalone PDF. A READ over the session:\n * `FPDF_ImportPagesByIndex` copies pages into a scratch document, so the\n * source is untouched — no revision bumps, no registry refresh, no layer\n * artifact. Lives next to `PagesReader`/`PagesMutator` (one file per page\n * verb family) so both worker hosts share the code path.\n */\nexport class PagesExtractor {\n constructor(\n private readonly runtime: PdfRuntimeModule,\n private readonly session: DocumentSession,\n ) {}\n\n /**\n * Copy the given pages, in the supplied caller order, into a new\n * document and serialize it. Validation up front: non-empty, no\n * duplicates, every PON resolvable (`NotFound` from the session on a\n * bad one). The scratch document is always closed, success or throw.\n */\n extract(\n pageObjectNumbers: PageObjectNumber[],\n signal: AbortSignal,\n ): { bytes: ArrayBuffer; size: number } {\n throwIfAborted(signal);\n if (pageObjectNumbers.length === 0) {\n throw new EngineError(EngineErrorCode.InvalidArg, 'pages.extract requires at least one page');\n }\n const seen = new Set<PageObjectNumber>();\n for (const pon of pageObjectNumbers) {\n if (seen.has(pon)) {\n throw new EngineError(\n EngineErrorCode.InvalidArg,\n `pages.extract was given duplicate page object number ${pon}`,\n );\n }\n seen.add(pon);\n }\n\n // Resolve every pon to its CURRENT index via the session registry —\n // NotFound on caller error, and caller order is preserved in the output.\n const indices = pageObjectNumbers.map(\n (pon) => this.session.recordByObjectNumber(pon).pageIndex,\n );\n\n const { fn, mem } = this.runtime;\n const srcPtr = this.session.requireDocPtr();\n\n const destPtr = fn.FPDF_CreateNewDocument();\n if (!destPtr) {\n throw new EngineError(EngineErrorCode.Unknown, 'FPDF_CreateNewDocument failed');\n }\n const idxPtr = mem.alloc(4 * indices.length);\n const sizePtr = mem.alloc(4);\n let pdfPtr: Ptr | null = null;\n try {\n for (let i = 0; i < indices.length; i++) {\n mem.poke(idxPtr, 'i32', indices[i], 4 * i);\n }\n if (!fn.FPDF_ImportPagesByIndex(destPtr, srcPtr, idxPtr, indices.length, 0)) {\n throw new EngineError(\n EngineErrorCode.Unknown,\n `FPDF_ImportPagesByIndex rejected the request (indices=[${indices.join(',')}])`,\n );\n }\n\n mem.poke(sizePtr, 'i32', 0);\n pdfPtr = fn.EPDF_SaveDocumentToOwnedBuffer(destPtr, FPDF_NO_INCREMENTAL, sizePtr);\n const size = Number(mem.peek(sizePtr, 'i32'));\n if (!pdfPtr || size <= 0) {\n throw new EngineError(EngineErrorCode.DocOpenFailed, 'failed to save extracted pages');\n }\n\n const bytes = mem.readBytes(pdfPtr, size);\n const buffer = new ArrayBuffer(bytes.byteLength);\n new Uint8Array(buffer).set(bytes);\n return { bytes: buffer, size };\n } finally {\n if (pdfPtr) fn.EPDF_FreeBuffer(pdfPtr);\n mem.free(sizePtr);\n mem.free(idxPtr);\n fn.FPDF_CloseDocument(destPtr);\n }\n }\n}\n","import {\n EngineError,\n EngineErrorCode,\n type PageInsertResult,\n type PageObjectNumber,\n} from '@embedpdf/engine-core/runtime';\nimport { NULL_PTR } from '@embedpdf/engine-runtime';\nimport type { PdfRuntimeModule, Ptr } from '@embedpdf/engine-runtime';\n\nimport { PagesReader } from './PagesReader';\nimport type { DocumentSession } from '../../document-session/DocumentSession';\nimport { throwIfAborted } from '../../shared/abort';\n\n/**\n * Insert every page of a standalone PDF into the session document. A\n * structural MUTATION (like move/delete): the source bytes are loaded as a\n * throwaway PDFium document, `FPDF_ImportPagesByIndex` deep-copies its\n * pages in at `destIndex`, and the page registry is rebuilt. Pre-existing\n * pages keep their identity and `RevisionToken`s; the inserted copies get\n * fresh object numbers, resolved from the post-insert registry.\n */\nexport class PagesInserter {\n constructor(\n private readonly runtime: PdfRuntimeModule,\n private readonly session: DocumentSession,\n ) {}\n\n insert(bytes: ArrayBuffer, destIndex: number | undefined, signal: AbortSignal): PageInsertResult {\n throwIfAborted(signal);\n if (bytes.byteLength === 0) {\n throw new EngineError(EngineErrorCode.InvalidArg, 'pages.insert requires non-empty bytes');\n }\n\n const { fn, mem } = this.runtime;\n const destPtr = this.session.requireDocPtr();\n const beforeCount = fn.FPDF_GetPageCount(destPtr);\n const at = destIndex ?? beforeCount;\n if (!Number.isInteger(at) || at < 0 || at > beforeCount) {\n throw new EngineError(\n EngineErrorCode.InvalidArg,\n `pages.insert destIndex ${at} out of range [0, ${beforeCount}]`,\n );\n }\n\n // FPDF_ImportPagesByIndex does NOT fully detach imported objects from\n // their source document (imported streams still read through it), so\n // the source doc and its buffer must outlive every future save of the\n // destination. On failure they are released immediately; on success\n // they are parked on the session and released at session close.\n // TODO(fork): a deep-detaching import would let this close eagerly.\n const dataPtr = mem.alloc(bytes.byteLength);\n let srcPtr: Ptr | null = null;\n let insertedCount = 0;\n try {\n mem.writeBytes(dataPtr, new Uint8Array(bytes));\n srcPtr = fn.FPDF_LoadMemDocument(dataPtr, bytes.byteLength, '');\n if (!srcPtr) {\n throw new EngineError(\n EngineErrorCode.MalformedPdf,\n 'pages.insert source PDF could not be opened',\n );\n }\n insertedCount = fn.FPDF_GetPageCount(srcPtr);\n if (insertedCount <= 0) {\n throw new EngineError(EngineErrorCode.InvalidArg, 'pages.insert source PDF has no pages');\n }\n // Null index array + count 0 = \"import every page\", in order.\n if (!fn.FPDF_ImportPagesByIndex(destPtr, srcPtr, NULL_PTR, 0, at)) {\n throw new EngineError(\n EngineErrorCode.Unknown,\n `FPDF_ImportPagesByIndex rejected the insert at index ${at}`,\n );\n }\n const retainedSrc = srcPtr;\n this.session.retainUntilClose(() => {\n fn.FPDF_CloseDocument(retainedSrc);\n mem.free(dataPtr);\n });\n } catch (error) {\n if (srcPtr) fn.FPDF_CloseDocument(srcPtr);\n mem.free(dataPtr);\n throw error;\n }\n\n // Page count and order changed; rebuild the index<->pon map. Existing\n // pages' revisions and weak-flag bookkeeping stay put (keyed by pon).\n this.session.refreshPageRegistry();\n\n const layout = new PagesReader(this.runtime, this.session).read(signal);\n const insertedPageObjectNumbers: PageObjectNumber[] = layout.pages\n .slice(at, at + insertedCount)\n .map((page) => page.pageObjectNumber);\n return { insertedPageObjectNumbers, layout, cache: null };\n }\n}\n","import type { Ptr } from '@embedpdf/engine-runtime';\n\nimport type { DocumentSession } from '../../../../document-session/DocumentSession';\n\n/**\n * Document-scoped capabilities threaded into per-subtype annotation\n * READERS — the read-side mirror of `AnnotationWriteContext`. Most kinds\n * materialise from the `annotPtr` alone and ignore it; the link reader\n * needs the document because destination, action, and URI resolution are\n * document-scoped PDFium operations.\n */\nexport interface AnnotationReadContext {\n readonly docPtr: Ptr;\n}\n\n/** Build the read context both read paths (list loop, mutator read-back) use. */\nexport function readContextFor(session: DocumentSession): AnnotationReadContext {\n return { docPtr: session.requireDocPtr() };\n}\n","import type { AnnotationFlags } from '@embedpdf/engine-core/runtime';\nimport { NO_ANNOTATION_FLAGS } from '@embedpdf/engine-core/runtime';\n\n/**\n * Bit positions of the `/F` (Annotation Flags) entry per ISO 32000 §12.5.3.\n * The single source of truth shared by the flag reader and writer so they\n * can never drift apart.\n */\nexport const ANNOT_FLAG_BITS = {\n invisible: 1 << 0,\n hidden: 1 << 1,\n print: 1 << 2,\n noZoom: 1 << 3,\n noRotate: 1 << 4,\n noView: 1 << 5,\n readOnly: 1 << 6,\n locked: 1 << 7,\n toggleNoView: 1 << 8,\n lockedContents: 1 << 9,\n} as const satisfies Record<keyof AnnotationFlags, number>;\n\nconst FLAG_KEYS = Object.keys(ANNOT_FLAG_BITS) as (keyof AnnotationFlags)[];\n\n/** Expand a raw `/F` bitset into the typed boolean object. */\nexport function bitsToFlags(bits: number): AnnotationFlags {\n if (bits === 0) return { ...NO_ANNOTATION_FLAGS };\n const flags = { ...NO_ANNOTATION_FLAGS };\n for (const key of FLAG_KEYS) {\n flags[key] = (bits & ANNOT_FLAG_BITS[key]) !== 0;\n }\n return flags;\n}\n\n/**\n * Fold a partial flag patch onto an existing `/F` bitset. Only keys present\n * in `partial` are touched; absent keys preserve their current bit. This is\n * what lets `create` start from 0 and `update` merge onto the live value.\n */\nexport function flagsToBits(current: number, partial: Partial<AnnotationFlags>): number {\n let bits = current;\n for (const key of FLAG_KEYS) {\n const value = partial[key];\n if (value === undefined) continue;\n if (value) {\n bits |= ANNOT_FLAG_BITS[key];\n } else {\n bits &= ~ANNOT_FLAG_BITS[key];\n }\n }\n return bits;\n}\n","import type { LineEnding } from '@embedpdf/engine-core/runtime';\n\n/**\n * `FPDF_ANNOT_LINE_END` enum codes from `public/fpdf_annot.h`, mapped to the\n * wire-stable kebab-case `LineEnding` strings. We keep this PDFium-specific\n * mapping in engine-services so engine-core stays free of any PDFium\n * dependency (mirrors `shapeBorderStyle.ts`).\n *\n * None=0, Square=1, Circle=2, Diamond=3, OpenArrow=4, ClosedArrow=5,\n * Butt=6, ROpenArrow=7, RClosedArrow=8, Slash=9, Unknown=10\n *\n * `Unknown` has no wire representation, so it round-trips as `'none'`.\n */\nconst LE_NONE = 0;\nconst LE_SQUARE = 1;\nconst LE_CIRCLE = 2;\nconst LE_DIAMOND = 3;\nconst LE_OPEN_ARROW = 4;\nconst LE_CLOSED_ARROW = 5;\nconst LE_BUTT = 6;\nconst LE_R_OPEN_ARROW = 7;\nconst LE_R_CLOSED_ARROW = 8;\nconst LE_SLASH = 9;\n\nexport function lineEndingToCode(ending: LineEnding): number {\n switch (ending) {\n case 'square':\n return LE_SQUARE;\n case 'circle':\n return LE_CIRCLE;\n case 'diamond':\n return LE_DIAMOND;\n case 'open-arrow':\n return LE_OPEN_ARROW;\n case 'closed-arrow':\n return LE_CLOSED_ARROW;\n case 'butt':\n return LE_BUTT;\n case 'r-open-arrow':\n return LE_R_OPEN_ARROW;\n case 'r-closed-arrow':\n return LE_R_CLOSED_ARROW;\n case 'slash':\n return LE_SLASH;\n case 'none':\n default:\n return LE_NONE;\n }\n}\n\nexport function lineEndingFromCode(code: number): LineEnding {\n switch (code) {\n case LE_SQUARE:\n return 'square';\n case LE_CIRCLE:\n return 'circle';\n case LE_DIAMOND:\n return 'diamond';\n case LE_OPEN_ARROW:\n return 'open-arrow';\n case LE_CLOSED_ARROW:\n return 'closed-arrow';\n case LE_BUTT:\n return 'butt';\n case LE_R_OPEN_ARROW:\n return 'r-open-arrow';\n case LE_R_CLOSED_ARROW:\n return 'r-closed-arrow';\n case LE_SLASH:\n return 'slash';\n case LE_NONE:\n default:\n return 'none';\n }\n}\n","import type {\n AnnotationFlags,\n Color,\n InkList,\n LineEndings,\n LinePoints,\n PdfPoint,\n PdfQuad,\n PdfRect,\n PdfRectDifferences,\n} from '@embedpdf/engine-core/runtime';\nimport {\n NULL_PTR,\n type PdfFunctions,\n type PdfRuntimeMemory,\n type Ptr,\n} from '@embedpdf/engine-runtime';\n\nimport { withScratch, withScratchN } from '../../../../runtime/memory/scratch';\nimport { readUtf16String } from '../../../../runtime/memory/strings';\nimport {\n F32_BYTES,\n I32_BYTES,\n POINTF_BYTES,\n QUADPOINTSF_BYTES,\n RECTF_BYTES,\n readF32,\n readI32,\n readRectF,\n} from '../../../../runtime/memory/structs';\nimport { bitsToFlags } from '../annotationFlagBits';\nimport { lineEndingFromCode } from '../lineEnding';\n\n/**\n * Reads a UTF-16 string entry from an annotation dictionary. Returns\n * `null` if the key is not present, otherwise the (possibly empty) string.\n */\nexport function readAnnotString(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n annotPtr: Ptr,\n key: string,\n): string | null {\n if (!fn.FPDFAnnot_HasKey(annotPtr, key)) return null;\n return readUtf16String(\n mem,\n (buf, capacity) => fn.FPDFAnnot_GetStringValue(annotPtr, key, buf, capacity),\n '',\n );\n}\n\n/**\n * Read /Rect from an annot dict via FPDFAnnot_GetRect.\n * FS_RECTF layout: { float left, top, right, bottom } -> 16 bytes.\n */\nexport function readAnnotRect(fn: PdfFunctions, mem: PdfRuntimeMemory, annotPtr: Ptr): PdfRect {\n return withScratch(mem, RECTF_BYTES, (buf) => {\n if (!fn.FPDFAnnot_GetRect(annotPtr, buf)) {\n return { left: 0, bottom: 0, right: 0, top: 0 };\n }\n return readRectF(mem, buf);\n });\n}\n\nexport function readAnnotFlags(fn: PdfFunctions, annotPtr: Ptr): AnnotationFlags {\n return bitsToFlags(fn.FPDFAnnot_GetFlags(annotPtr));\n}\n\n/**\n * Read an annotation color via the EmbedPDF `EPDFAnnot_GetColor`\n * extension. The `type` arg (FPDFANNOT_COLORTYPE) selects which color to\n * read — `0` (default) is the stroke/fill `/C`, `1` is the interior `/IC`\n * of square/circle/polygon annotations. Unlike the stock\n * `FPDFAnnot_GetColor`, the extension exposes interior color. Returns RGB\n * only — annotation opacity lives in `/CA`, not a per-color alpha.\n *\n * Returns `null` when the requested color entry is absent.\n */\nexport function readAnnotColor(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n annotPtr: Ptr,\n type: number = 0, // FPDFANNOT_COLORTYPE_Color\n): Color | null {\n return withScratchN(mem, [I32_BYTES, I32_BYTES, I32_BYTES], ([r, g, b]) => {\n if (!fn.EPDFAnnot_GetColor(annotPtr, type, r, g, b)) return null;\n return {\n r: readI32(mem, r) & 0xff,\n g: readI32(mem, g) & 0xff,\n b: readI32(mem, b) & 0xff,\n };\n });\n}\n\n/**\n * Read annotation opacity via the EmbedPDF `EPDFAnnot_GetOpacity`\n * extension. Returns a 0..1 value (the native alpha is 0..255). Returns\n * `null` when the annotation has no opacity entry. This is the path that\n * stays consistent across native `EPDFAnnot_GenerateAppearance`, unlike a\n * raw `/CA` number read.\n */\nexport function readAnnotOpacity(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n annotPtr: Ptr,\n): number | null {\n return withScratch(mem, I32_BYTES, (buf) => {\n if (!fn.EPDFAnnot_GetOpacity(annotPtr, buf)) return null;\n return (readI32(mem, buf) & 0xff) / 255;\n });\n}\n\n/**\n * Read the effective border style and width via\n * `EPDFAnnot_GetBorderStyle`, which resolves `/BS`, legacy `/Border`, and\n * the ISO defaults. The return value is the raw `FPDF_ANNOT_BORDER_STYLE`\n * enum code; the width is written into the scratch out-parameter.\n * Style/width string mapping lives in the shape reader (engine-core stays\n * PDFium-free).\n */\nexport function readBorderStyle(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n annotPtr: Ptr,\n): { styleCode: number; width: number } {\n return withScratch(mem, F32_BYTES, (buf) => {\n const styleCode = fn.EPDFAnnot_GetBorderStyle(annotPtr, buf);\n return { styleCode, width: readF32(mem, buf) };\n });\n}\n\n/**\n * Read the dash pattern of a dashed border. Resolves modern `/BS /D` first,\n * then the fourth element of the legacy `/Border` array. Returns an empty\n * array when the effective border is not dashed or has no explicit pattern.\n */\nexport function readBorderDashPattern(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n annotPtr: Ptr,\n): number[] {\n const count = fn.EPDFAnnot_GetBorderDashPatternCount(annotPtr);\n if (count <= 0) return [];\n return withScratch(mem, count * F32_BYTES, (buf) => {\n if (!fn.EPDFAnnot_GetBorderDashPattern(annotPtr, buf, count)) return [];\n const out: number[] = [];\n for (let i = 0; i < count; i++) out.push(readF32(mem, buf, i * F32_BYTES));\n return out;\n });\n}\n\n/**\n * Read the `/BE` cloudy border intensity. Returns `null` when the\n * annotation has no cloudy border effect. The DTO domain is positive-or-null,\n * so a degenerate foreign `/BE /I 0` (no visible clouds) normalizes to `null`\n * rather than leaking an out-of-schema zero; a `/BE` without `/I` reads as 1\n * (the runtime's default).\n */\nexport function readBorderEffect(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n annotPtr: Ptr,\n): number | null {\n return withScratch(mem, F32_BYTES, (buf) => {\n if (!fn.EPDFAnnot_GetBorderEffect(annotPtr, buf)) return null;\n const intensity = readF32(mem, buf);\n return intensity > 0 ? intensity : null;\n });\n}\n\n/**\n * Read the `/RD` rectangle differences. Returns `null` when the\n * annotation has no `/RD` entry. PDFium reports `/RD` in\n * `[left, bottom, right, top]` order; we surface the wire-stable\n * `{ left, top, right, bottom }` shape.\n */\nexport function readRectangleDifferences(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n annotPtr: Ptr,\n): PdfRectDifferences | null {\n return withScratchN(\n mem,\n [F32_BYTES, F32_BYTES, F32_BYTES, F32_BYTES],\n ([left, bottom, right, top]) => {\n if (!fn.EPDFAnnot_GetRectangleDifferences(annotPtr, left, bottom, right, top)) return null;\n return {\n left: readF32(mem, left),\n bottom: readF32(mem, bottom),\n right: readF32(mem, right),\n top: readF32(mem, top),\n };\n },\n );\n}\n\n/**\n * Read the `/Vertices` point list of a polygon/polyline annotation via\n * the two-call `FPDFAnnot_GetVertices` pattern (probe for the count with\n * a NULL buffer, then read into a `count * FS_POINTF` buffer). Returns an\n * empty array when the annotation has no vertices.\n */\nexport function readVertices(fn: PdfFunctions, mem: PdfRuntimeMemory, annotPtr: Ptr): PdfPoint[] {\n const count = fn.FPDFAnnot_GetVertices(annotPtr, NULL_PTR, 0);\n if (count <= 0) return [];\n return withScratch(mem, count * POINTF_BYTES, (buf) => {\n const got = fn.FPDFAnnot_GetVertices(annotPtr, buf, count);\n if (got <= 0) return [];\n const out: PdfPoint[] = [];\n for (let i = 0; i < got; i++) {\n const off = i * POINTF_BYTES;\n out.push({ x: readF32(mem, buf, off), y: readF32(mem, buf, off + 4) });\n }\n return out;\n });\n}\n\n/**\n * Read the `/InkList` of an ink annotation. `FPDFAnnot_GetInkListCount`\n * gives the number of strokes; each stroke is sized with a probe call to\n * `FPDFAnnot_GetInkListPath` (NULL buffer) and then read into a\n * `count * FS_POINTF` buffer. Empty strokes are skipped; the result is an\n * array of non-empty point paths.\n */\nexport function readInkList(fn: PdfFunctions, mem: PdfRuntimeMemory, annotPtr: Ptr): InkList {\n const pathCount = fn.FPDFAnnot_GetInkListCount(annotPtr);\n if (pathCount <= 0) return [];\n const out: InkList = [];\n for (let p = 0; p < pathCount; p++) {\n const count = fn.FPDFAnnot_GetInkListPath(annotPtr, p, NULL_PTR, 0);\n if (count <= 0) continue;\n const stroke = withScratch(mem, count * POINTF_BYTES, (buf) => {\n const got = fn.FPDFAnnot_GetInkListPath(annotPtr, p, buf, count);\n if (got <= 0) return [];\n const pts: PdfPoint[] = [];\n for (let i = 0; i < got; i++) {\n const off = i * POINTF_BYTES;\n pts.push({ x: readF32(mem, buf, off), y: readF32(mem, buf, off + 4) });\n }\n return pts;\n });\n if (stroke.length > 0) out.push(stroke);\n }\n return out;\n}\n\n/**\n * Read the `/L` endpoints of a line annotation via `FPDFAnnot_GetLine`\n * (two `FS_POINTF` out-params). Returns `null` when the annotation is not\n * a line or has no `/L` entry.\n */\nexport function readLine(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n annotPtr: Ptr,\n): LinePoints | null {\n return withScratchN(mem, [POINTF_BYTES, POINTF_BYTES], ([start, end]) => {\n if (!fn.FPDFAnnot_GetLine(annotPtr, start, end)) return null;\n return {\n start: { x: readF32(mem, start, 0), y: readF32(mem, start, 4) },\n end: { x: readF32(mem, end, 0), y: readF32(mem, end, 4) },\n };\n });\n}\n\n/**\n * Read the `/LE` line endings of a line/polyline annotation via the\n * EmbedPDF `EPDFAnnot_GetLineEndings` extension (two int out-params).\n * Returns `{ start: 'none', end: 'none' }` when the annotation has no\n * `/LE` entry, so callers always get a well-formed pair.\n */\nexport function readLineEndings(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n annotPtr: Ptr,\n): LineEndings {\n return withScratchN(mem, [I32_BYTES, I32_BYTES], ([start, end]) => {\n if (!fn.EPDFAnnot_GetLineEndings(annotPtr, start, end)) {\n return { start: 'none', end: 'none' };\n }\n return {\n start: lineEndingFromCode(readI32(mem, start)),\n end: lineEndingFromCode(readI32(mem, end)),\n };\n });\n}\n\n/**\n * Read the `/DA` default appearance (font + size + colour) of a free-text\n * annotation via `EPDFAnnot_GetDefaultAppearance` (font int, size f32, and\n * r/g/b int out-params). `fontCode` is the raw `FPDF_STANDARD_FONT` enum\n * value. Returns `null` when the annotation has no `/DA`.\n */\nexport function readDefaultAppearance(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n annotPtr: Ptr,\n): { fontCode: number; fontSize: number; color: Color } | null {\n return withScratchN(\n mem,\n [I32_BYTES, F32_BYTES, I32_BYTES, I32_BYTES, I32_BYTES],\n ([font, size, r, g, b]) => {\n if (!fn.EPDFAnnot_GetDefaultAppearance(annotPtr, font, size, r, g, b)) return null;\n return {\n fontCode: readI32(mem, font),\n fontSize: readF32(mem, size),\n color: {\n r: readI32(mem, r) & 0xff,\n g: readI32(mem, g) & 0xff,\n b: readI32(mem, b) & 0xff,\n },\n };\n },\n );\n}\n\n/**\n * Read the `/Q` text alignment quadding code of a free-text annotation via\n * `EPDFAnnot_GetTextAlignment`. The code<->string mapping lives in\n * `textAlignment.ts`; an absent `/Q` reads back as `0` (left).\n */\nexport function readTextAlignment(fn: PdfFunctions, annotPtr: Ptr): number {\n return fn.EPDFAnnot_GetTextAlignment(annotPtr);\n}\n\n/**\n * Read `/OverlayText` of a redact annotation via `EPDFAnnot_GetOverlayText`\n * (standard UTF-16 byte-length ABI). Returns `null` when the key is absent\n * (the redaction has no label), otherwise the — possibly empty — label.\n */\nexport function readOverlayText(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n annotPtr: Ptr,\n): string | null {\n if (!fn.FPDFAnnot_HasKey(annotPtr, 'OverlayText')) return null;\n return readUtf16String(\n mem,\n (buf, capacity) => fn.EPDFAnnot_GetOverlayText(annotPtr, buf, capacity),\n '',\n );\n}\n\n/**\n * Read `/Repeat` of a redact annotation via `EPDFAnnot_GetOverlayTextRepeat`\n * (an absent key reads as `false`, the PDF default).\n */\nexport function readOverlayTextRepeat(fn: PdfFunctions, annotPtr: Ptr): boolean {\n return fn.EPDFAnnot_GetOverlayTextRepeat(annotPtr);\n}\n\n/**\n * Read the `/IT` intent name via `EPDFAnnot_GetIntent`. Unlike the standard\n * `FPDFAnnot_GetStringValue` ABI, this getter reports the count of UTF-16\n * code units (excluding the NUL), so we size the buffer as\n * `(count + 1) * 2` bytes. Returns `null` when no intent is present.\n */\nexport function readIntent(fn: PdfFunctions, mem: PdfRuntimeMemory, annotPtr: Ptr): string | null {\n const codeUnits = fn.EPDFAnnot_GetIntent(annotPtr, NULL_PTR, 0);\n if (codeUnits <= 0) return null;\n const bytes = (codeUnits + 1) * 2;\n return withScratch(mem, bytes, (buf) => {\n fn.EPDFAnnot_GetIntent(annotPtr, buf, bytes);\n return mem.readU16String(buf);\n });\n}\n\n/**\n * Read the `/CL` callout leader line of a free-text callout via\n * `EPDFAnnot_GetCalloutLineCount` + `EPDFAnnot_GetCalloutLine` (the points\n * are read into a `count * FS_POINTF` buffer, like {@link readVertices}).\n * Returns an empty array when there is no callout line.\n */\nexport function readCalloutLine(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n annotPtr: Ptr,\n): PdfPoint[] {\n const count = fn.EPDFAnnot_GetCalloutLineCount(annotPtr);\n if (count <= 0) return [];\n return withScratch(mem, count * POINTF_BYTES, (buf) => {\n const got = fn.EPDFAnnot_GetCalloutLine(annotPtr, buf, count);\n if (got <= 0) return [];\n const out: PdfPoint[] = [];\n for (let i = 0; i < got; i++) {\n const off = i * POINTF_BYTES;\n out.push({ x: readF32(mem, buf, off), y: readF32(mem, buf, off + 4) });\n }\n return out;\n });\n}\n\n/**\n * Read attachment points for a text-markup annotation.\n * Each `FS_QUADPOINTSF` is 8 floats = 32 bytes.\n */\nexport function readQuadPoints(fn: PdfFunctions, mem: PdfRuntimeMemory, annotPtr: Ptr): PdfQuad[] {\n const count = fn.FPDFAnnot_CountAttachmentPoints(annotPtr);\n if (count <= 0) return [];\n\n return withScratch(mem, QUADPOINTSF_BYTES, (buf) => {\n const out: PdfQuad[] = [];\n for (let i = 0; i < count; i++) {\n if (!fn.FPDFAnnot_GetAttachmentPoints(annotPtr, i, buf)) continue;\n const f = (off: number) => readF32(mem, buf, off);\n // Positional, in PDFium FS_QUADPOINTSF slot order (PDF 32000 12.5.6.10):\n // { x1,y1, x2,y2, x3,y3, x4,y4 } -> p1 p2 p3 p4. We do NOT relabel these\n // as named corners: PdfQuad asserts no corner semantics (see its docs).\n out.push({\n p1: { x: f(0), y: f(4) },\n p2: { x: f(8), y: f(12) },\n p3: { x: f(16), y: f(20) },\n p4: { x: f(24), y: f(28) },\n });\n }\n return out;\n });\n}\n","import type { CaretIntent, StrikeoutIntent } from '@embedpdf/engine-core/runtime';\n\n/** Adobe-compatible `/IT` names, normalized at the engine-core boundary. */\nconst IT_REPLACE = 'Replace';\nconst IT_STRIKEOUT_TEXT_EDIT = 'StrikeOutTextEdit';\n\nexport function caretIntentToName(intent: CaretIntent): string {\n switch (intent) {\n case 'replace':\n return IT_REPLACE;\n }\n}\n\nexport function caretIntentFromName(name: string | null): CaretIntent | null {\n return name === IT_REPLACE ? 'replace' : null;\n}\n\nexport function strikeoutIntentToName(intent: StrikeoutIntent): string {\n switch (intent) {\n case 'strikeout-text-edit':\n return IT_STRIKEOUT_TEXT_EDIT;\n }\n}\n\nexport function strikeoutIntentFromName(name: string | null): StrikeoutIntent | null {\n return name === IT_STRIKEOUT_TEXT_EDIT ? 'strikeout-text-edit' : null;\n}\n","import type { AnnotationBase, CaretAnnotationDTO, Color } from '@embedpdf/engine-core/runtime';\nimport type { PdfFunctions, PdfRuntimeMemory, Ptr } from '@embedpdf/engine-runtime';\n\nimport {\n readAnnotColor,\n readAnnotOpacity,\n readIntent,\n readRectangleDifferences,\n} from './annotationReadPrimitives';\nimport { caretIntentFromName } from '../textEditIntent';\n\n/** Default `/C` colour when a caret has none (matches the writer default). */\nconst DEFAULT_CARET_COLOR: Color = { r: 255, g: 0, b: 0 };\n\nexport function readCaret(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n annotPtr: Ptr,\n base: AnnotationBase,\n): CaretAnnotationDTO {\n const color = readAnnotColor(fn, mem, annotPtr) ?? { ...DEFAULT_CARET_COLOR };\n const ca = readAnnotOpacity(fn, mem, annotPtr);\n const opacity = ca == null ? 1 : Math.max(0, Math.min(1, ca));\n const rd = readRectangleDifferences(fn, mem, annotPtr);\n const intent = caretIntentFromName(readIntent(fn, mem, annotPtr));\n\n return {\n ...base,\n subtype: 'caret',\n intent,\n color,\n opacity,\n rectDifferences: rd,\n };\n}\n","import type {\n AttachmentFileInfo,\n EmbeddedFileRef,\n WireResource,\n} from '@embedpdf/engine-core/runtime';\nimport { EngineError, EngineErrorCode } from '@embedpdf/engine-core/runtime';\nimport { NULL_PTR } from '@embedpdf/engine-runtime';\nimport type {\n PdfFunctions,\n PdfRuntimeMemory,\n PdfRuntimeModule,\n Ptr,\n} from '@embedpdf/engine-runtime';\n\nimport { readUtf16String, writeUtf16String } from '../../../runtime/memory/strings';\n\n/**\n * Shared primitives over an `FPDF_ATTACHMENT` handle (an unretained\n * filespec pointer — no close call exists or is needed). Used by both\n * homes an embedded file can have: the document-level `/EmbeddedFiles`\n * name tree (`AttachmentReader`) and a FileAttachment annotation's `/FS`\n * (the annotation reader + `downloadFile`).\n */\n\n/** Read the name-tree KEY at |index| — the durable EmbeddedFileRef address. */\nexport function readAttachmentKey(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n docPtr: Ptr,\n index: number,\n): string | null {\n return readUtf16String(mem, (buf, cap) => fn.EPDFDoc_GetAttachmentKey(docPtr, index, buf, cap));\n}\n\n/** Resolve an EmbeddedFileRef to its CURRENT name-tree index, or -1. */\nexport function resolveAttachmentIndex(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n docPtr: Ptr,\n ref: EmbeddedFileRef,\n): number {\n const keyPtr = mem.writeU16String(ref.key);\n try {\n return fn.EPDFDoc_GetAttachmentIndexByKey(docPtr, keyPtr);\n } finally {\n mem.free(keyPtr);\n }\n}\n\n/**\n * Write an embedded file's payload onto an existing FPDF_ATTACHMENT:\n * bytes via FPDFAttachment_SetFile (which also writes /Params\n * Size/CheckSum/CreationDate), declared mime via EPDFAttachment_SetSubtype\n * (attachments accept any format — no sniffing), optional /Desc. Shared\n * by the file-attachment annotation writer and the document-level\n * `attachments.create` mutation — the write half of the one attachment\n * vocabulary.\n */\nexport function writeAttachmentFilePayload(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n attachmentPtr: Ptr,\n docPtr: Ptr,\n file: { mimeType?: string; description?: string },\n resource: WireResource,\n): void {\n const byteLength = resource.bytes.byteLength;\n if (byteLength === 0) {\n // Valid zero-byte attachment: PDFium accepts (NULL, 0).\n if (!fn.FPDFAttachment_SetFile(attachmentPtr, docPtr, NULL_PTR, 0)) {\n throw new EngineError(EngineErrorCode.Unknown, 'FPDFAttachment_SetFile returned false');\n }\n } else {\n const dataPtr = mem.alloc(byteLength);\n try {\n mem.writeBytes(dataPtr, new Uint8Array(resource.bytes));\n if (!fn.FPDFAttachment_SetFile(attachmentPtr, docPtr, dataPtr, byteLength)) {\n throw new EngineError(EngineErrorCode.Unknown, 'FPDFAttachment_SetFile returned false');\n }\n } finally {\n mem.free(dataPtr);\n }\n }\n\n if (!fn.EPDFAttachment_SetSubtype(attachmentPtr, file.mimeType ?? 'application/octet-stream')) {\n throw new EngineError(EngineErrorCode.Unknown, 'EPDFAttachment_SetSubtype returned false');\n }\n if (file.description !== undefined) {\n const ok = writeUtf16String(mem, file.description, (ptr) =>\n fn.EPDFAttachment_SetDescription(attachmentPtr, ptr),\n );\n if (!ok) {\n throw new EngineError(\n EngineErrorCode.Unknown,\n 'EPDFAttachment_SetDescription returned false',\n );\n }\n }\n}\n\n/** Read the metadata projection of an embedded file (never its bytes). */\nexport function readAttachmentFileInfo(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n attachmentPtr: Ptr,\n): AttachmentFileInfo {\n const name =\n readUtf16String(mem, (buf, cap) => fn.FPDFAttachment_GetName(attachmentPtr, buf, cap)) ?? '';\n const mimeType = readUtf16String(mem, (buf, cap) =>\n fn.FPDFAttachment_GetSubtype(attachmentPtr, buf, cap),\n );\n const description = readUtf16String(mem, (buf, cap) =>\n fn.EPDFAttachment_GetDescription(attachmentPtr, buf, cap),\n );\n const creationDate = readAttachmentString(fn, mem, attachmentPtr, 'CreationDate');\n const checksum = normalizeChecksum(readAttachmentString(fn, mem, attachmentPtr, 'CheckSum'));\n const size = readAttachmentSize(fn, mem, attachmentPtr);\n\n return {\n name,\n ...(mimeType ? { mimeType } : {}),\n ...(description ? { description } : {}),\n ...(size !== null ? { size } : {}),\n ...(checksum ? { checksum } : {}),\n ...(creationDate ? { creationDate } : {}),\n };\n}\n\n/**\n * Decode the embedded file into a standalone buffer via the fork's\n * single-decode `EPDFAttachment_ExtractFileToOwnedBuffer`. A zero-byte\n * embedded file is a valid `{ size: 0 }` result.\n */\nexport function extractAttachmentToBuffer(\n runtime: PdfRuntimeModule,\n attachmentPtr: Ptr,\n maxDecodedBytes: number | undefined,\n): { bytes: ArrayBuffer; size: number } {\n const { fn, mem } = runtime;\n const bufPtrSlot = mem.alloc(8); // void** — 8 bytes covers wasm32 and native\n const sizePtr = mem.alloc(4);\n const statusPtr = mem.alloc(4);\n let dataPtr: Ptr | null = null;\n try {\n // Plain 0 (not 0n): the wasm memory writes pointer slots via\n // Emscripten setValue, which rejects BigInt for 32-bit pointers.\n mem.poke(bufPtrSlot, 'ptr', 0);\n mem.poke(sizePtr, 'i32', 0);\n mem.poke(statusPtr, 'i32', -1);\n const ok = fn.EPDFAttachment_ExtractFileToOwnedBuffer(\n attachmentPtr,\n BigInt(maxDecodedBytes ?? 0),\n bufPtrSlot,\n sizePtr,\n statusPtr,\n );\n if (!ok) {\n throw extractStatusError(Number(mem.peek(statusPtr, 'i32')));\n }\n const size = Number(mem.peek(sizePtr, 'i32')) >>> 0;\n dataPtr = mem.peek(bufPtrSlot, 'ptr') as Ptr;\n if (size === 0 || !dataPtr) {\n return { bytes: new ArrayBuffer(0), size: 0 };\n }\n const view = mem.readBytes(dataPtr, size);\n const buffer = new ArrayBuffer(view.byteLength);\n new Uint8Array(buffer).set(view);\n return { bytes: buffer, size };\n } finally {\n if (dataPtr) fn.EPDF_FreeBuffer(dataPtr);\n mem.free(statusPtr);\n mem.free(sizePtr);\n mem.free(bufPtrSlot);\n }\n}\n\n/**\n * Decode the embedded file straight to `path` via the fork's streaming\n * `EPDFAttachment_ExtractFile` + `FPDF_FILEWRITE` — the server mode: the\n * decoded payload never crosses the thread boundary and HTTP streams it\n * from disk. On failure the destination may hold a partial file (the\n * caller owns temp-file cleanup, as with `document.saveFile`).\n */\nexport function extractAttachmentToFile(\n runtime: PdfRuntimeModule,\n attachmentPtr: Ptr,\n path: string,\n maxDecodedBytes: number | undefined,\n): { size: number } {\n const { fn, mem } = runtime;\n const sizePtr = mem.alloc(4);\n const statusPtr = mem.alloc(4);\n const writer = runtime.fileWrite.toNodeFile(path);\n try {\n mem.poke(sizePtr, 'i32', 0);\n mem.poke(statusPtr, 'i32', -1);\n const ok = fn.EPDFAttachment_ExtractFile(\n attachmentPtr,\n writer.ptr,\n BigInt(maxDecodedBytes ?? 0),\n sizePtr,\n statusPtr,\n );\n if (!ok) {\n throw extractStatusError(Number(mem.peek(statusPtr, 'i32')));\n }\n return { size: Number(mem.peek(sizePtr, 'i32')) >>> 0 };\n } finally {\n writer.close();\n mem.free(statusPtr);\n mem.free(sizePtr);\n }\n}\n\n/** `EPDFAttachmentExtractStatus` (public/fpdf_attachment.h) → EngineError. */\nfunction extractStatusError(status: number): EngineError {\n switch (status) {\n case 1: // kNoFileStream\n return new EngineError(\n EngineErrorCode.InvalidArg,\n 'attachment has no embedded file stream (missing /EF)',\n );\n case 2: // kDecodeFailed\n return new EngineError(EngineErrorCode.MalformedPdf, 'embedded file stream failed to decode');\n case 3: // kSizeLimitExceeded\n return new EngineError(\n EngineErrorCode.InvalidArg,\n 'embedded file exceeds the configured decoded-size limit',\n );\n case 4: // kWriteFailed\n return new EngineError(EngineErrorCode.Unknown, 'writing the extracted attachment failed');\n default:\n return new EngineError(\n EngineErrorCode.Unknown,\n `attachment extraction failed (status ${status})`,\n );\n }\n}\n\nfunction readAttachmentString(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n attachmentPtr: Ptr,\n key: string,\n): string | null {\n if (!fn.FPDFAttachment_HasKey(attachmentPtr, key)) return null;\n return readUtf16String(\n mem,\n (buf, cap) => fn.FPDFAttachment_GetStringValue(attachmentPtr, key, buf, cap),\n null,\n );\n}\n\nfunction readAttachmentSize(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n attachmentPtr: Ptr,\n): number | null {\n const out = mem.alloc(4);\n try {\n if (!fn.EPDFAttachment_GetIntegerValue(attachmentPtr, 'Size', out)) return null;\n const size = Number(mem.peek(out, 'i32'));\n return size >= 0 ? size : null;\n } finally {\n mem.free(out);\n }\n}\n\n/** PDFium reports `/CheckSum` hex strings as `<ABCD…>` — normalize to bare lowercase hex. */\nfunction normalizeChecksum(raw: string | null): string | null {\n if (!raw) return null;\n const inner = raw.startsWith('<') && raw.endsWith('>') ? raw.slice(1, -1) : raw;\n return /^[0-9a-fA-F]+$/.test(inner) ? inner.toLowerCase() : raw;\n}\n","import type { FileAttachmentIcon, NoteIcon } from '@embedpdf/engine-core/runtime';\n\n/**\n * `/Name` icon ↔ `FPDF_ANNOT_NAME` enum code mapping for text and\n * file-attachment annotations (`EPDFAnnot_SetName` / `EPDFAnnot_GetName`).\n * Codes mirror the `FPDF_ANNOT_NAME` enum in `public/fpdf_annot.h` —\n * same pattern as `stampName.ts` (whose stamp block starts at 13, right\n * after these) keeping engine-core PDFium-free.\n */\n\nexport const NOTE_ICON_TO_CODE: Readonly<Record<NoteIcon, number>> = Object.freeze({\n comment: 0,\n key: 1,\n note: 2,\n help: 3,\n 'new-paragraph': 4,\n paragraph: 5,\n insert: 6,\n});\n\nexport const NOTE_CODE_TO_ICON: Readonly<Record<number, NoteIcon>> = Object.freeze(\n Object.fromEntries(\n Object.entries(NOTE_ICON_TO_CODE).map(([icon, code]) => [code, icon as NoteIcon]),\n ),\n);\n\nexport const FILE_ICON_TO_CODE: Readonly<Record<FileAttachmentIcon, number>> = Object.freeze({\n graph: 7,\n 'push-pin': 8,\n paperclip: 9,\n tag: 10,\n});\n\nexport const FILE_CODE_TO_ICON: Readonly<Record<number, FileAttachmentIcon>> = Object.freeze(\n Object.fromEntries(\n Object.entries(FILE_ICON_TO_CODE).map(([icon, code]) => [code, icon as FileAttachmentIcon]),\n ),\n);\n","import type {\n AnnotationBase,\n AttachmentFileInfo,\n Color,\n FileAttachmentAnnotationDTO,\n FileAttachmentIcon,\n} from '@embedpdf/engine-core/runtime';\nimport type { PdfFunctions, PdfRuntimeMemory, Ptr } from '@embedpdf/engine-runtime';\n\nimport { readAttachmentFileInfo } from '../../../attachments/internal/attachmentPrimitives';\nimport { FILE_CODE_TO_ICON } from '../annotationIcon';\nimport { readAnnotColor, readAnnotOpacity } from './annotationReadPrimitives';\n\n/** Default `/C` — matches the generator's default icon fill and the writer default. */\nconst DEFAULT_FILE_ATTACHMENT_COLOR: Color = { r: 255, g: 255, b: 0 };\n\n/** An absent or foreign `/Name` reads as 'push-pin' (ISO 32000 §12.5.6.15 default). */\nconst DEFAULT_FILE_ATTACHMENT_ICON: FileAttachmentIcon = 'push-pin';\n\n/**\n * FileAttachment DTO: base + icon presentation + the attached file's\n * METADATA (bytes are downloaded explicitly via\n * `PageAnnotationsService.downloadFile`). A malformed annotation without\n * a readable `/FS` filespec still reads — `file.name` is `''` and the\n * download call reports the precise error.\n */\nexport function readFileAttachment(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n annotPtr: Ptr,\n base: AnnotationBase,\n): FileAttachmentAnnotationDTO {\n const color = readAnnotColor(fn, mem, annotPtr) ?? { ...DEFAULT_FILE_ATTACHMENT_COLOR };\n const ca = readAnnotOpacity(fn, mem, annotPtr);\n const opacity = ca == null ? 1 : Math.max(0, Math.min(1, ca));\n const icon = FILE_CODE_TO_ICON[fn.EPDFAnnot_GetName(annotPtr)] ?? DEFAULT_FILE_ATTACHMENT_ICON;\n\n const attachmentPtr = fn.FPDFAnnot_GetFileAttachment(annotPtr);\n const file: AttachmentFileInfo = attachmentPtr\n ? readAttachmentFileInfo(fn, mem, attachmentPtr)\n : { name: '' };\n\n return {\n ...base,\n subtype: 'file-attachment',\n icon,\n file,\n color,\n opacity,\n };\n}\n","/**\n * `FPDFANNOT_COLORTYPE` enum codes from `public/fpdf_annot.h`. Shared by\n * the annotation read/write primitives and the shape reader/writer so the\n * color-selector magic numbers live in exactly one place.\n *\n * Color=0 (the stroke/fill `/C`)\n * InteriorColor=1 (the `/IC` of square/circle/polygon)\n * OverlayColor=2 (the redaction overlay)\n * TextColor=3 (the free-text `/DA` color)\n */\nexport const FPDFANNOT_COLORTYPE = {\n Color: 0,\n InteriorColor: 1,\n OverlayColor: 2,\n TextColor: 3,\n} as const;\n\nexport type AnnotationColorType = (typeof FPDFANNOT_COLORTYPE)[keyof typeof FPDFANNOT_COLORTYPE];\n","import type { FreeTextIntent } from '@embedpdf/engine-core/runtime';\n\n/**\n * Free-text `/IT` intent names (ISO 32000 §12.5.6.6) mapped to the\n * wire-stable `FreeTextIntent` strings. Kept in engine-services so\n * engine-core stays PDFium-free.\n *\n * FreeText -> 'free-text' (plain text box)\n * FreeTextCallout -> 'free-text-callout' (with /CL leader line)\n *\n * `FreeTextTypeWriter` (a typewriter variant) round-trips as the plain\n * `'free-text'` intent — we don't author it.\n */\nconst IT_FREE_TEXT = 'FreeText';\nconst IT_FREE_TEXT_CALLOUT = 'FreeTextCallout';\n\nexport function freeTextIntentToName(intent: FreeTextIntent): string {\n return intent === 'free-text-callout' ? IT_FREE_TEXT_CALLOUT : IT_FREE_TEXT;\n}\n\nexport function freeTextIntentFromName(name: string | null): FreeTextIntent {\n return name === IT_FREE_TEXT_CALLOUT ? 'free-text-callout' : 'free-text';\n}\n","import type { FreeTextFont, StandardFont } from '@embedpdf/engine-core/runtime';\n\n/**\n * `FPDF_STANDARD_FONT` enum codes (the 14 standard PDF fonts) mapped to the\n * wire-stable kebab-case `StandardFont` strings. We keep this PDFium-specific\n * mapping in engine-services so engine-core stays free of any PDFium\n * dependency (mirrors `lineEnding.ts` / `shapeBorderStyle.ts`).\n *\n * Courier=0, Courier-Bold=1, Courier-BoldOblique=2, Courier-Oblique=3,\n * Helvetica=4, Helvetica-Bold=5, Helvetica-BoldOblique=6,\n * Helvetica-Oblique=7, Times-Roman=8, Times-Bold=9, Times-BoldItalic=10,\n * Times-Italic=11, Symbol=12, ZapfDingbats=13\n */\nconst FONT_TO_CODE: Record<StandardFont, number> = {\n courier: 0,\n 'courier-bold': 1,\n 'courier-bold-oblique': 2,\n 'courier-oblique': 3,\n helvetica: 4,\n 'helvetica-bold': 5,\n 'helvetica-bold-oblique': 6,\n 'helvetica-oblique': 7,\n 'times-roman': 8,\n 'times-bold': 9,\n 'times-bold-italic': 10,\n 'times-italic': 11,\n symbol: 12,\n 'zapf-dingbats': 13,\n};\n\nconst CODE_TO_FONT: Record<number, StandardFont> = Object.fromEntries(\n Object.entries(FONT_TO_CODE).map(([font, code]) => [code, font as StandardFont]),\n) as Record<number, StandardFont>;\n\n/** Default when a `/DA` font is missing or unrecognised. */\nexport const DEFAULT_STANDARD_FONT: StandardFont = 'helvetica';\n\nexport function standardFontToCode(font: StandardFont): number {\n return FONT_TO_CODE[font] ?? FONT_TO_CODE[DEFAULT_STANDARD_FONT];\n}\n\n/**\n * Narrow a FreeText `fontFamily` to one of the 14 standard fonts. A `false`\n * result means the value is a registered-font `key`. The standard names are\n * therefore reserved — a registered font keyed `'helvetica'` resolves as the\n * standard font.\n */\nexport function isStandardFont(font: FreeTextFont): font is StandardFont {\n return Object.prototype.hasOwnProperty.call(FONT_TO_CODE, font);\n}\n\nexport function standardFontFromCode(code: number): StandardFont {\n return CODE_TO_FONT[code] ?? DEFAULT_STANDARD_FONT;\n}\n","import type { TextAlignment } from '@embedpdf/engine-core/runtime';\n\n/**\n * `/Q` quadding codes (ISO 32000 §12.7.3.3) mapped to the wire-stable\n * `TextAlignment` strings. Kept in engine-services so engine-core stays\n * PDFium-free (mirrors `lineEnding.ts`).\n *\n * Left=0, Center=1, Right=2\n */\nconst Q_LEFT = 0;\nconst Q_CENTER = 1;\nconst Q_RIGHT = 2;\n\nexport function textAlignmentToCode(align: TextAlignment): number {\n switch (align) {\n case 'center':\n return Q_CENTER;\n case 'right':\n return Q_RIGHT;\n case 'left':\n default:\n return Q_LEFT;\n }\n}\n\nexport function textAlignmentFromCode(code: number): TextAlignment {\n switch (code) {\n case Q_CENTER:\n return 'center';\n case Q_RIGHT:\n return 'right';\n case Q_LEFT:\n default:\n return 'left';\n }\n}\n","import type { AnnotationBorderStyle } from '@embedpdf/engine-core/runtime';\n\n/**\n * `FPDF_ANNOT_BORDER_STYLE` enum codes from `public/fpdf_annot.h`. We keep\n * this PDFium-specific mapping in engine-services so engine-core stays free\n * of any PDFium dependency (mirrors `PDF_SUBTYPE_TO_CODE`).\n *\n * UNKNOWN=0, SOLID=1, DASHED=2, BEVELED=3, INSET=4, UNDERLINE=5, CLOUDY=6\n *\n * The wire-stable `AnnotationBorderStyle` union covers the four styles a\n * shape annotation realistically authors; cloudy borders are surfaced\n * separately via `cloudyIntensity` (the `/BE` border effect).\n */\nconst BS_SOLID = 1;\nconst BS_DASHED = 2;\nconst BS_BEVELED = 3;\nconst BS_INSET = 4;\n\nexport function borderStyleToCode(style: AnnotationBorderStyle): number {\n switch (style) {\n case 'dashed':\n return BS_DASHED;\n case 'beveled':\n return BS_BEVELED;\n case 'inset':\n return BS_INSET;\n case 'solid':\n default:\n return BS_SOLID;\n }\n}\n\nexport function borderStyleFromCode(code: number): AnnotationBorderStyle {\n switch (code) {\n case BS_DASHED:\n return 'dashed';\n case BS_BEVELED:\n return 'beveled';\n case BS_INSET:\n return 'inset';\n case BS_SOLID:\n default:\n return 'solid';\n }\n}\n","import type {\n AnnotationBorderStyle,\n Color,\n FilledStyleFields,\n GeometryStyleFields,\n} from '@embedpdf/engine-core/runtime';\nimport type { PdfFunctions, PdfRuntimeMemory, Ptr } from '@embedpdf/engine-runtime';\n\nimport { FPDFANNOT_COLORTYPE } from '../colorType';\nimport { borderStyleFromCode } from '../shapeBorderStyle';\nimport {\n readAnnotColor,\n readAnnotOpacity,\n readBorderDashPattern,\n readBorderStyle,\n} from './annotationReadPrimitives';\n\n/**\n * Default `/C` colour when an annotation has none. Matches the v2 engine\n * (circle/square/polygon/polyline/line/ink all default red).\n */\nconst DEFAULT_COLOR: Color = { r: 255, g: 0, b: 0 };\n\n/** Effective `/BS` or legacy `/Border` fields shared by bordered kinds. */\nexport interface BorderFields {\n strokeWidth: number;\n borderStyle: AnnotationBorderStyle;\n dashArray?: number[];\n}\n\n/**\n * Shared reader for the effective border (style + width + dash), resolving\n * `/BS`, legacy `/Border`, and the ISO defaults. The border-only slice of\n * {@link readGeometryStyleExtras}, reused by the free-text box border (which\n * reads `/C` and `/DA` itself).\n */\nexport function readBorderFields(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n annotPtr: Ptr,\n): BorderFields {\n const { styleCode, width } = readBorderStyle(fn, mem, annotPtr);\n const dashArray = readBorderDashPattern(fn, mem, annotPtr);\n return {\n strokeWidth: width,\n borderStyle: borderStyleFromCode(styleCode),\n ...(dashArray.length > 0 ? { dashArray } : {}),\n };\n}\n\n/**\n * Shared reader for the geometry styling (`/C`, `/CA`, border, dash) — the\n * no-fill layer shared by ink and the filled families. Family readers layer\n * their own geometry + extras on top; filled families add `/IC` via\n * {@link readFilledStyleExtras}.\n */\nexport function readGeometryStyleExtras(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n annotPtr: Ptr,\n): GeometryStyleFields {\n const color = readAnnotColor(fn, mem, annotPtr, FPDFANNOT_COLORTYPE.Color) ?? {\n ...DEFAULT_COLOR,\n };\n const ca = readAnnotOpacity(fn, mem, annotPtr);\n const opacity = ca == null ? 1 : Math.max(0, Math.min(1, ca));\n\n return {\n color,\n opacity,\n ...readBorderFields(fn, mem, annotPtr),\n };\n}\n\n/**\n * Shared reader for the full stroke/fill styling (geometry styling + `/IC`).\n * Reused by every filled family (shape/vertex/line); each layers its own\n * geometry + extras on top.\n */\nexport function readFilledStyleExtras(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n annotPtr: Ptr,\n): FilledStyleFields {\n const interiorColor = readAnnotColor(fn, mem, annotPtr, FPDFANNOT_COLORTYPE.InteriorColor);\n return {\n ...readGeometryStyleExtras(fn, mem, annotPtr),\n interiorColor: interiorColor ?? null,\n };\n}\n","import type { PdfRect } from '@embedpdf/engine-core/runtime';\nimport type { PdfFunctions, PdfRuntimeMemory, Ptr } from '@embedpdf/engine-runtime';\n\nimport { withScratch } from '../../../../runtime/memory/scratch';\nimport { F32_BYTES, RECTF_BYTES, readF32, readRectF } from '../../../../runtime/memory/structs';\n\n/**\n * Read-side twin of `writers/.../writeAnnotationTransformMetadata.ts`. Decodes\n * the EmbedPDF rotation keys from /EMBD_Metadata back onto the DTO:\n *\n * - `Rotation` — degrees, PDF convention. Returned for EVERY rotatable\n * kind (box AND vertex); the plugin converts it back to its CW-content\n * `rot` once at the repository seam.\n * - `UnrotatedRect` — the logical box. BOX kinds only (square/circle/\n * free-text); a vertex annotation never carries one (its points are the\n * visual), so vertex readers don't ask for it.\n *\n * Both are absent on un-rotated annotations (and on everything authored before\n * rotation shipped), so both reads return `undefined` and the DTO field stays\n * unset.\n */\n\nconst KEY_ROTATION = 'Rotation';\nconst KEY_UNROTATED_RECT = 'UnrotatedRect';\n\n/** The advisory/portable rotation scalar (degrees, PDF convention), or\n * `undefined` when absent or zero. */\nexport function readAnnotationRotation(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n annotPtr: Ptr,\n): number | undefined {\n if (!fn.EPDFAnnot_HasEmbedMetadata(annotPtr)) return undefined;\n return withScratch(mem, F32_BYTES, (buf) => {\n if (!fn.EPDFAnnot_GetEmbedMetadataNumber(annotPtr, KEY_ROTATION, buf)) return undefined;\n const v = readF32(mem, buf);\n return v ? v : undefined; // 0 ≡ \"no rotation\"\n });\n}\n\n/** The logical (unrotated) box of a rotated BOX annotation, or `undefined`. */\nexport function readAnnotationUnrotatedRect(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n annotPtr: Ptr,\n): PdfRect | undefined {\n if (!fn.EPDFAnnot_HasEmbedMetadata(annotPtr)) return undefined;\n return withScratch(mem, RECTF_BYTES, (buf) => {\n if (!fn.EPDFAnnot_GetEmbedMetadataRect(annotPtr, KEY_UNROTATED_RECT, buf)) return undefined;\n // FS_RECTF { left, top, right, bottom } → wire-stable PdfRect.\n const r = readRectF(mem, buf);\n return { left: r.left, bottom: r.bottom, right: r.right, top: r.top };\n });\n}\n","import type {\n AnnotationBase,\n CalloutLine,\n Color,\n FreeTextAnnotationDTO,\n} from '@embedpdf/engine-core/runtime';\nimport type { PdfFunctions, PdfRuntimeMemory, Ptr } from '@embedpdf/engine-runtime';\n\nimport { FPDFANNOT_COLORTYPE } from '../colorType';\nimport { freeTextIntentFromName } from '../freeTextIntent';\nimport { standardFontFromCode, DEFAULT_STANDARD_FONT } from '../standardFont';\nimport { textAlignmentFromCode } from '../textAlignment';\nimport {\n readAnnotColor,\n readAnnotOpacity,\n readCalloutLine,\n readDefaultAppearance,\n readIntent,\n readLineEndings,\n readRectangleDifferences,\n readTextAlignment,\n} from './annotationReadPrimitives';\nimport { readBorderFields } from './readStyle';\nimport {\n readAnnotationRotation,\n readAnnotationUnrotatedRect,\n} from './readAnnotationTransformMetadata';\n\n/** Default `/DA` colour (black) when an annotation has no default appearance. */\nconst DEFAULT_FREETEXT_COLOR: Color = { r: 0, g: 0, b: 0 };\n\n/** Default font size when `/DA` has none (or an unusable 0). */\nconst DEFAULT_FONT_SIZE = 12;\n\nfunction colorsEqual(a: Color, b: Color): boolean {\n return a.r === b.r && a.g === b.g && a.b === b.b;\n}\n\nexport function readFreeText(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n annotPtr: Ptr,\n base: AnnotationBase,\n): FreeTextAnnotationDTO {\n const da = readDefaultAppearance(fn, mem, annotPtr);\n const color = da?.color ?? { ...DEFAULT_FREETEXT_COLOR };\n const fontFamily = da ? standardFontFromCode(da.fontCode) : DEFAULT_STANDARD_FONT;\n const fontSize = da && da.fontSize > 0 ? da.fontSize : DEFAULT_FONT_SIZE;\n\n // `TextColor` overrides text only; surface it as `fontColor` solely when it\n // is present AND differs from the `/DA` colour (otherwise text follows `color`).\n const textColor = readAnnotColor(fn, mem, annotPtr, FPDFANNOT_COLORTYPE.TextColor);\n const fontColor = textColor && !colorsEqual(textColor, color) ? textColor : undefined;\n\n // For free text `/C` (color type 0) is the box background, not a stroke.\n const background = readAnnotColor(fn, mem, annotPtr, FPDFANNOT_COLORTYPE.Color);\n\n const ca = readAnnotOpacity(fn, mem, annotPtr);\n const opacity = ca == null ? 1 : Math.max(0, Math.min(1, ca));\n\n const textAlign = textAlignmentFromCode(readTextAlignment(fn, annotPtr));\n const intent = freeTextIntentFromName(readIntent(fn, mem, annotPtr));\n\n const points = readCalloutLine(fn, mem, annotPtr);\n const calloutLine: CalloutLine | undefined =\n points.length === 2\n ? [points[0]!, points[1]!]\n : points.length === 3\n ? [points[0]!, points[1]!, points[2]!]\n : undefined;\n const leaderEnd = readLineEndings(fn, mem, annotPtr).end;\n\n const rd = readRectangleDifferences(fn, mem, annotPtr);\n const rotation = readAnnotationRotation(fn, mem, annotPtr);\n const unrotatedRect = readAnnotationUnrotatedRect(fn, mem, annotPtr);\n\n return {\n ...base,\n subtype: 'free-text',\n intent,\n fontFamily,\n fontSize,\n textAlign,\n color,\n ...(fontColor !== undefined ? { fontColor } : {}),\n interiorColor: background ?? null,\n opacity,\n ...readBorderFields(fn, mem, annotPtr),\n rectDifferences: rd,\n ...(calloutLine !== undefined ? { calloutLine } : {}),\n ...(calloutLine !== undefined && leaderEnd !== 'none' ? { lineEnding: leaderEnd } : {}),\n ...(rotation != null ? { rotation } : {}),\n ...(unrotatedRect ? { unrotatedRect } : {}),\n };\n}\n","import type { InkIntent } from '@embedpdf/engine-core/runtime';\n\nexport function inkIntentToName(intent: InkIntent): string {\n switch (intent) {\n case 'ink-highlight':\n return 'InkHighlight';\n }\n}\n\nexport function inkIntentFromName(name: string | null): InkIntent | null {\n switch (name) {\n case 'InkHighlight':\n return 'ink-highlight';\n default:\n return null;\n }\n}\n","import type { AnnotationBase, InkAnnotationDTO } from '@embedpdf/engine-core/runtime';\nimport type { PdfFunctions, PdfRuntimeMemory, Ptr } from '@embedpdf/engine-runtime';\n\nimport { readInkList, readIntent } from './annotationReadPrimitives';\nimport { readGeometryStyleExtras } from './readStyle';\nimport { readAnnotationRotation } from './readAnnotationTransformMetadata';\nimport { inkIntentFromName } from '../inkIntent';\n\nexport function readInk(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n annotPtr: Ptr,\n base: AnnotationBase,\n): InkAnnotationDTO {\n const rotation = readAnnotationRotation(fn, mem, annotPtr);\n const intent = inkIntentFromName(readIntent(fn, mem, annotPtr));\n return {\n ...base,\n subtype: 'ink',\n ...readGeometryStyleExtras(fn, mem, annotPtr),\n intent,\n inkList: readInkList(fn, mem, annotPtr),\n ...(rotation != null ? { rotation } : {}),\n };\n}\n","import type { AnnotationBase, LineAnnotationDTO } from '@embedpdf/engine-core/runtime';\nimport type { PdfFunctions, PdfRuntimeMemory, Ptr } from '@embedpdf/engine-runtime';\n\nimport { readLine as readLinePoints, readLineEndings } from './annotationReadPrimitives';\nimport { readFilledStyleExtras } from './readStyle';\nimport { readAnnotationRotation } from './readAnnotationTransformMetadata';\n\n/** Fallback `/L` when the annotation has no line geometry. */\nconst ZERO_LINE = { start: { x: 0, y: 0 }, end: { x: 0, y: 0 } };\n\nexport function readLine(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n annotPtr: Ptr,\n base: AnnotationBase,\n): LineAnnotationDTO {\n const rotation = readAnnotationRotation(fn, mem, annotPtr);\n return {\n ...base,\n subtype: 'line',\n ...readFilledStyleExtras(fn, mem, annotPtr),\n linePoints: readLinePoints(fn, mem, annotPtr) ?? ZERO_LINE,\n lineEndings: readLineEndings(fn, mem, annotPtr),\n ...(rotation != null ? { rotation } : {}),\n };\n}\n","import type { PdfDestination } from '@embedpdf/engine-core/runtime';\n\n/**\n * `PDFDEST_VIEW_*` fit-type codes (public/fpdf_doc.h) — the shared\n * vocabulary of `FPDFDest_GetView` (read) and `EPDFDest_CreateView`\n * (write). XYZ is listed for completeness but never goes through\n * CreateView (it has its own null-aware constructor).\n */\nexport const DEST_VIEW = {\n unknown: 0,\n xyz: 1,\n fit: 2,\n fitH: 3,\n fitV: 4,\n fitR: 5,\n fitB: 6,\n fitBH: 7,\n fitBV: 8,\n} as const;\n\ntype NonXyzKind = Exclude<PdfDestination['kind'], 'xyz'>;\n\n/** Wire destination kind → PDFDEST_VIEW code, for the non-XYZ kinds. */\nexport const VIEW_CODE_BY_KIND: Record<NonXyzKind, number> = {\n fit: DEST_VIEW.fit,\n fitH: DEST_VIEW.fitH,\n fitV: DEST_VIEW.fitV,\n fitR: DEST_VIEW.fitR,\n fitB: DEST_VIEW.fitB,\n fitBH: DEST_VIEW.fitBH,\n fitBV: DEST_VIEW.fitBV,\n};\n","import type { PdfDestination } from '@embedpdf/engine-core/runtime';\nimport type { PdfFunctions, PdfRuntimeMemory, Ptr } from '@embedpdf/engine-runtime';\n\nimport { withScratchN } from '../../../../runtime/memory/scratch';\nimport { F32_BYTES, I32_BYTES, readF32, readI32 } from '../../../../runtime/memory/structs';\nimport { DEST_VIEW } from '../destinationViewCodes';\n\nconst MAX_VIEW_PARAMS = 4; // /FitR carries the most: left, bottom, right, top\n\n/**\n * Materialise one explicit `PdfDestination` from a live `destPtr`. PDFium\n * already resolved named destinations before handing us the pointer, so\n * only explicit arrays arrive here (the rule `PdfDestination` documents).\n *\n * Returns `null` when the destination is unreadable: no visible indirect page\n * in the document, or an unknown fit type. Coordinates stay raw PDF user\n * space — no conversion at this layer.\n *\n * Shared by the link reader today; the outline/bookmark port reuses it.\n */\nexport function readDestination(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n docPtr: Ptr,\n destPtr: Ptr,\n): PdfDestination | null {\n const pageObjectNumber = fn.EPDFDest_GetPageObjectNumber(docPtr, destPtr);\n if (pageObjectNumber === 0) return null;\n\n const view = withScratchN(\n mem,\n [I32_BYTES, MAX_VIEW_PARAMS * F32_BYTES],\n ([countPtr, paramsPtr]) => {\n const code = fn.FPDFDest_GetView(destPtr, countPtr, paramsPtr);\n const count = Math.min(readI32(mem, countPtr), MAX_VIEW_PARAMS);\n const params: number[] = [];\n for (let i = 0; i < count; i++) params.push(readF32(mem, paramsPtr, i * F32_BYTES));\n return { code, params };\n },\n );\n const at = (i: number): number | null => (i < view.params.length ? view.params[i]! : null);\n\n switch (view.code) {\n case DEST_VIEW.xyz:\n return { kind: 'xyz', pageObjectNumber, ...readXyzLocation(fn, mem, destPtr) };\n case DEST_VIEW.fit:\n return { kind: 'fit', pageObjectNumber };\n case DEST_VIEW.fitH:\n return { kind: 'fitH', pageObjectNumber, top: at(0) };\n case DEST_VIEW.fitV:\n return { kind: 'fitV', pageObjectNumber, left: at(0) };\n case DEST_VIEW.fitR: {\n // /FitR is only meaningful with the full rect; a malformed one\n // degrades to the whole page rather than inventing coordinates.\n if (view.params.length < 4) return { kind: 'fit', pageObjectNumber };\n return {\n kind: 'fitR',\n pageObjectNumber,\n left: view.params[0]!,\n bottom: view.params[1]!,\n right: view.params[2]!,\n top: view.params[3]!,\n };\n }\n case DEST_VIEW.fitB:\n return { kind: 'fitB', pageObjectNumber };\n case DEST_VIEW.fitBH:\n return { kind: 'fitBH', pageObjectNumber, top: at(0) };\n case DEST_VIEW.fitBV:\n return { kind: 'fitBV', pageObjectNumber, left: at(0) };\n default:\n return null;\n }\n}\n\n/** `/XYZ` null-aware axes via `FPDFDest_GetLocationInPage` (FPDF_BOOL is 4 bytes). */\nfunction readXyzLocation(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n destPtr: Ptr,\n): { left: number | null; top: number | null; zoom: number | null } {\n return withScratchN(\n mem,\n [I32_BYTES, I32_BYTES, I32_BYTES, F32_BYTES, F32_BYTES, F32_BYTES],\n ([hasLeft, hasTop, hasZoom, left, top, zoom]) => {\n if (!fn.FPDFDest_GetLocationInPage(destPtr, hasLeft, hasTop, hasZoom, left, top, zoom)) {\n // Unreadable location: every axis \"retains current\" — still a valid /XYZ.\n return { left: null, top: null, zoom: null };\n }\n return {\n left: readI32(mem, hasLeft) ? readF32(mem, left) : null,\n top: readI32(mem, hasTop) ? readF32(mem, top) : null,\n zoom: readI32(mem, hasZoom) ? readF32(mem, zoom) : null,\n };\n },\n );\n}\n","import type {\n AnnotationBase,\n LinkAnnotationDTO,\n PdfLinkTarget,\n} from '@embedpdf/engine-core/runtime';\nimport {\n NULL_PTR,\n type PdfFunctions,\n type PdfRuntimeMemory,\n type Ptr,\n} from '@embedpdf/engine-runtime';\n\nimport { readUtf8String } from '../../../../runtime/memory/strings';\nimport {\n ANNOT_ACTION_ACTIVATE,\n actionTypeFromCode,\n isValidActionNodeId,\n} from '../../../actions/ActionModelReader';\nimport type { AnnotationReadContext } from './annotationReadContext';\nimport { readDestination } from './readDestination';\n\n/**\n * Link reader: rect/flags/relationship ride the base (a link grouped to an\n * annotation is plain `inReplyTo` + `replyType: 'group'`); this module only\n * materialises the normalized target.\n *\n * ONE truth, two views: the target is projected off the SAME fork action\n * model the scripting plane reads (`base.actions`) — root classification\n * via the full `EPDF_ACTION_TYPE_*` vocabulary, payloads via the on-demand\n * node getters. The classic `FPDFAction_*` surface (5 types, JavaScript-\n * and Named-blind) is deliberately not consulted; `FPDFLink_GetDest`\n * remains only for the data-only direct `/Dest`, which is not an action.\n *\n * `/A` wins over `/Dest` — the spec forbids carrying both, and when a\n * malformed file has both, Acrobat gives the action precedence. (Our own\n * writes can't produce that state: `EPDFAnnot_SetAction` strips `/Dest`.)\n */\nexport function readLink(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n annotPtr: Ptr,\n base: AnnotationBase,\n _rawSubtypeCode: number,\n ctx: AnnotationReadContext,\n): LinkAnnotationDTO {\n return { ...base, subtype: 'link', target: readLinkTarget(fn, mem, annotPtr, ctx) };\n}\n\nfunction readLinkTarget(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n annotPtr: Ptr,\n ctx: AnnotationReadContext,\n): PdfLinkTarget | null {\n // The activate slot (/A). Root-only read: O(1) native calls, no tree\n // walk — the chain (/Next) rides base.actions for the orchestrator.\n const modelPtr = fn.EPDFAnnot_GetActionModel(annotPtr, ANNOT_ACTION_ACTIVATE);\n if (modelPtr !== NULL_PTR) {\n try {\n const root = fn.EPDFAction_GetRootNode(modelPtr);\n if (isValidActionNodeId(root)) {\n return readRootTarget(fn, mem, modelPtr, root, ctx);\n }\n } finally {\n fn.EPDFAction_CloseModel(modelPtr);\n }\n }\n\n // No usable /A → the direct `/Dest`, normalized onto `goto`.\n const linkPtr = fn.FPDFAnnot_GetLink(annotPtr);\n if (!linkPtr) return null;\n const destPtr = fn.FPDFLink_GetDest(ctx.docPtr, linkPtr);\n if (!destPtr) return null; // neither /A nor /Dest: a dead link, reported as-is\n const destination = readDestination(fn, mem, ctx.docPtr, destPtr);\n return destination ? { kind: 'goto', destination } : { kind: 'unsupported' };\n}\n\n/** Classify the root action node and fetch its payload — the projection. */\nfunction readRootTarget(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n modelPtr: Ptr,\n node: number,\n ctx: AnnotationReadContext,\n): PdfLinkTarget {\n switch (actionTypeFromCode(fn.EPDFAction_GetNodeType(modelPtr, node))) {\n case 'goto': {\n const destPtr = fn.EPDFAction_GetNodeDest(ctx.docPtr, modelPtr, node);\n const destination = destPtr ? readDestination(fn, mem, ctx.docPtr, destPtr) : null;\n return destination ? { kind: 'goto', destination } : { kind: 'unsupported' };\n }\n case 'uri': {\n const uri = readUtf8String(mem, (buf, capacity) =>\n fn.EPDFAction_GetNodeURI(ctx.docPtr, modelPtr, node, buf, capacity),\n );\n return uri == null ? { kind: 'unsupported' } : { kind: 'uri', uri };\n }\n // Reported, never followed/executed (and never writable — see the DTO).\n case 'goto-remote': {\n const file = readUtf8String(mem, (buf, capacity) =>\n fn.EPDFAction_GetNodeFilePath(modelPtr, node, buf, capacity),\n );\n return { kind: 'goto-remote', file: file ?? '' };\n }\n case 'launch': {\n const path = readUtf8String(mem, (buf, capacity) =>\n fn.EPDFAction_GetNodeFilePath(modelPtr, node, buf, capacity),\n );\n return { kind: 'launch', path: path ?? '' };\n }\n case 'javascript':\n // No script payload here by design: the text rides base.actions —\n // the scripting plane's single home.\n return { kind: 'javascript' };\n case 'named': {\n const name = readUtf8String(mem, (buf, capacity) =>\n fn.EPDFAction_GetNodeName(modelPtr, node, buf, capacity),\n );\n return name == null ? { kind: 'unsupported' } : { kind: 'named', name };\n }\n default:\n return { kind: 'unsupported' };\n }\n}\n","import type { AnnotationBase, Color, RedactAnnotationDTO } from '@embedpdf/engine-core/runtime';\nimport type { PdfFunctions, PdfRuntimeMemory, Ptr } from '@embedpdf/engine-runtime';\n\nimport { FPDFANNOT_COLORTYPE } from '../colorType';\nimport { DEFAULT_STANDARD_FONT, standardFontFromCode } from '../standardFont';\nimport { textAlignmentFromCode } from '../textAlignment';\nimport {\n readAnnotColor,\n readAnnotOpacity,\n readDefaultAppearance,\n readOverlayText,\n readOverlayTextRepeat,\n readQuadPoints,\n readTextAlignment,\n} from './annotationReadPrimitives';\n\n/** Default `/C` marking outline (red) — the redaction marking convention and\n * the AP generator's default. */\nconst DEFAULT_REDACT_COLOR: Color = { r: 255, g: 0, b: 0 };\n\n/** Default label colour (black) when a redaction carries no `/DA`. */\nconst DEFAULT_LABEL_COLOR: Color = { r: 0, g: 0, b: 0 };\n\n/** Default label size when there is no `/DA`. When a `/DA` IS present its\n * size is kept verbatim — including `0`, which means auto-fit for a\n * redaction label (unlike free text, which normalizes 0 away). */\nconst DEFAULT_FONT_SIZE = 12;\n\nexport function readRedact(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n annotPtr: Ptr,\n base: AnnotationBase,\n): RedactAnnotationDTO {\n const color = readAnnotColor(fn, mem, annotPtr, FPDFANNOT_COLORTYPE.Color) ?? {\n ...DEFAULT_REDACT_COLOR,\n };\n const ca = readAnnotOpacity(fn, mem, annotPtr);\n const opacity = ca == null ? 1 : Math.max(0, Math.min(1, ca));\n const interiorColor =\n readAnnotColor(fn, mem, annotPtr, FPDFANNOT_COLORTYPE.InteriorColor) ?? null;\n\n const da = readDefaultAppearance(fn, mem, annotPtr);\n const fontFamily = da ? standardFontFromCode(da.fontCode) : DEFAULT_STANDARD_FONT;\n const fontSize = da ? da.fontSize : DEFAULT_FONT_SIZE;\n const fontColor = da?.color ?? { ...DEFAULT_LABEL_COLOR };\n\n return {\n ...base,\n subtype: 'redact',\n quadPoints: readQuadPoints(fn, mem, annotPtr),\n color,\n opacity,\n interiorColor,\n overlayText: readOverlayText(fn, mem, annotPtr),\n repeat: readOverlayTextRepeat(fn, annotPtr),\n fontFamily,\n fontSize,\n fontColor,\n textAlign: textAlignmentFromCode(readTextAlignment(fn, annotPtr)),\n };\n}\n","import type {\n AnnotationBase,\n CircleAnnotationDTO,\n ShapeAnnotationFields,\n SquareAnnotationDTO,\n} from '@embedpdf/engine-core/runtime';\nimport type { PdfFunctions, PdfRuntimeMemory, Ptr } from '@embedpdf/engine-runtime';\n\nimport { readBorderEffect, readRectangleDifferences } from './annotationReadPrimitives';\nimport { readFilledStyleExtras } from './readStyle';\nimport {\n readAnnotationRotation,\n readAnnotationUnrotatedRect,\n} from './readAnnotationTransformMetadata';\n\n/**\n * Shared reader for the two shape subtypes. Materialises the common\n * stroke/fill styling plus the shape-only cloudy (`/BE`) and rect-diff\n * (`/RD`) fields; the caller fills in the `subtype` literal. Absent `/BE`\n * and `/RD` read as explicit `null` (never omission), so a read DTO\n * compares structurally against a clearing patch.\n */\nexport function readShapeExtras(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n annotPtr: Ptr,\n): ShapeAnnotationFields {\n const cloudyIntensity = readBorderEffect(fn, mem, annotPtr);\n const rectDifferences = readRectangleDifferences(fn, mem, annotPtr);\n const rotation = readAnnotationRotation(fn, mem, annotPtr);\n const unrotatedRect = readAnnotationUnrotatedRect(fn, mem, annotPtr);\n\n return {\n ...readFilledStyleExtras(fn, mem, annotPtr),\n cloudyIntensity,\n rectDifferences,\n ...(rotation != null ? { rotation } : {}),\n ...(unrotatedRect ? { unrotatedRect } : {}),\n };\n}\n\nexport function readCircle(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n annotPtr: Ptr,\n base: AnnotationBase,\n): CircleAnnotationDTO {\n return { ...base, subtype: 'circle', ...readShapeExtras(fn, mem, annotPtr) };\n}\n\nexport function readSquare(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n annotPtr: Ptr,\n base: AnnotationBase,\n): SquareAnnotationDTO {\n return { ...base, subtype: 'square', ...readShapeExtras(fn, mem, annotPtr) };\n}\n","/**\n * Stamp `/Name` label ↔ `FPDF_ANNOT_NAME` enum code mapping for the\n * `EPDFAnnot_SetName` / `EPDFAnnot_GetName` fork helpers. Labels are the\n * PDF spec / Adobe literal name values (ISO 32000 §12.5.6.12 table 181\n * plus the Adobe SB/SH extended set the fork supports). Codes mirror the\n * `FPDF_ANNOT_NAME` enum in `public/fpdf_annot.h` — same pattern as\n * `lineEnding.ts` keeping engine-core PDFium-free.\n */\n\nexport const STAMP_NAME_TO_CODE: Readonly<Record<string, number>> = Object.freeze({\n Approved: 13,\n Experimental: 14,\n NotApproved: 15,\n AsIs: 16,\n Expired: 17,\n NotForPublicRelease: 18,\n Confidential: 19,\n Final: 20,\n Sold: 21,\n Departmental: 22,\n ForComment: 23,\n TopSecret: 24,\n Draft: 25,\n ForPublicRelease: 26,\n Completed: 27,\n Void: 28,\n PreliminaryResults: 29,\n InformationOnly: 30,\n Rejected: 31,\n Witness: 32,\n InitialHere: 33,\n SignHere: 34,\n Accepted: 35,\n});\n\nexport const STAMP_CODE_TO_NAME: Readonly<Record<number, string>> = Object.freeze(\n Object.fromEntries(Object.entries(STAMP_NAME_TO_CODE).map(([name, code]) => [code, name])),\n);\n\nexport function isKnownStampName(name: string): boolean {\n return Object.prototype.hasOwnProperty.call(STAMP_NAME_TO_CODE, name);\n}\n","import type { AnnotationBase, StampAnnotationDTO } from '@embedpdf/engine-core/runtime';\nimport type { PdfFunctions, PdfRuntimeMemory, Ptr } from '@embedpdf/engine-runtime';\n\nimport { STAMP_CODE_TO_NAME } from '../stampName';\nimport { readAnnotString } from './annotationReadPrimitives';\nimport {\n readAnnotationRotation,\n readAnnotationUnrotatedRect,\n} from './readAnnotationTransformMetadata';\n\n/**\n * Stamp DTO: base + `/Name` label + transform metadata. The visual content\n * stays in the `/AP` stream — rendered via `renderAppearanceImages()`,\n * never surfaced as DTO data.\n */\nexport function readStamp(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n annotPtr: Ptr,\n base: AnnotationBase,\n): StampAnnotationDTO {\n const rotation = readAnnotationRotation(fn, mem, annotPtr);\n const unrotatedRect = readAnnotationUnrotatedRect(fn, mem, annotPtr);\n return {\n ...base,\n subtype: 'stamp',\n name: readStampName(fn, mem, annotPtr),\n ...(rotation != null ? { rotation } : {}),\n ...(unrotatedRect != null ? { unrotatedRect } : {}),\n };\n}\n\nfunction readStampName(fn: PdfFunctions, mem: PdfRuntimeMemory, annotPtr: Ptr): string | null {\n const code = fn.EPDFAnnot_GetName(annotPtr);\n const known = STAMP_CODE_TO_NAME[code];\n if (known !== undefined) return known;\n // Custom /Name values fall outside the fork's enum; try the raw entry.\n return readAnnotString(fn, mem, annotPtr, 'Name');\n}\n","import type {\n AnnotationBase,\n Color,\n NoteIcon,\n TextAnnotationDTO,\n} from '@embedpdf/engine-core/runtime';\nimport type { PdfFunctions, PdfRuntimeMemory, Ptr } from '@embedpdf/engine-runtime';\n\nimport { NOTE_CODE_TO_ICON } from '../annotationIcon';\nimport { readAnnotColor, readAnnotOpacity } from './annotationReadPrimitives';\n\n/** Default `/C` — matches the generator's yellow note fill and the writer default. */\nconst DEFAULT_NOTE_COLOR: Color = { r: 255, g: 255, b: 0 };\n\n/** An absent or foreign `/Name` reads as 'note' (ISO 32000 §12.5.6.4 default). */\nconst DEFAULT_NOTE_ICON: NoteIcon = 'note';\n\nexport function readText(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n annotPtr: Ptr,\n base: AnnotationBase,\n): TextAnnotationDTO {\n const color = readAnnotColor(fn, mem, annotPtr) ?? { ...DEFAULT_NOTE_COLOR };\n const ca = readAnnotOpacity(fn, mem, annotPtr);\n const opacity = ca == null ? 1 : Math.max(0, Math.min(1, ca));\n const icon = NOTE_CODE_TO_ICON[fn.EPDFAnnot_GetName(annotPtr)] ?? DEFAULT_NOTE_ICON;\n\n return {\n ...base,\n subtype: 'text',\n icon,\n color,\n opacity,\n };\n}\n","import type {\n AnnotationBase,\n Color,\n HighlightAnnotationDTO,\n PdfQuad,\n SquigglyAnnotationDTO,\n StrikeoutAnnotationDTO,\n UnderlineAnnotationDTO,\n} from '@embedpdf/engine-core/runtime';\nimport type { PdfFunctions, PdfRuntimeMemory, Ptr } from '@embedpdf/engine-runtime';\n\nimport {\n readAnnotColor,\n readAnnotOpacity,\n readIntent,\n readQuadPoints,\n} from './annotationReadPrimitives';\nimport { strikeoutIntentFromName } from '../textEditIntent';\n\nconst DEFAULT_HIGHLIGHT_COLOR: Color = { r: 255, g: 255, b: 0 };\nconst DEFAULT_TEXT_MARKUP_COLOR: Color = { r: 0, g: 0, b: 0 };\n\n/**\n * Shared reader for the four text-markup subtypes. Wires color, opacity,\n * and quadPoints; the caller fills in the `subtype` literal so the\n * result matches the requested DTO shape.\n */\nexport function readTextMarkupExtras(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n annotPtr: Ptr,\n fallbackColor: Color = DEFAULT_TEXT_MARKUP_COLOR,\n): {\n color: Color;\n opacity: number;\n quadPoints: PdfQuad[];\n} {\n const color = readAnnotColor(fn, mem, annotPtr) ?? { ...fallbackColor };\n const ca = readAnnotOpacity(fn, mem, annotPtr);\n const opacity = ca == null ? 1 : Math.max(0, Math.min(1, ca));\n const quadPoints = readQuadPoints(fn, mem, annotPtr);\n return { color, opacity, quadPoints };\n}\n\nexport function readHighlight(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n annotPtr: Ptr,\n base: AnnotationBase,\n): HighlightAnnotationDTO {\n const extras = readTextMarkupExtras(fn, mem, annotPtr, DEFAULT_HIGHLIGHT_COLOR);\n return { ...base, subtype: 'highlight', ...extras };\n}\n\nexport function readUnderline(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n annotPtr: Ptr,\n base: AnnotationBase,\n): UnderlineAnnotationDTO {\n const extras = readTextMarkupExtras(fn, mem, annotPtr);\n return { ...base, subtype: 'underline', ...extras };\n}\n\nexport function readSquiggly(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n annotPtr: Ptr,\n base: AnnotationBase,\n): SquigglyAnnotationDTO {\n const extras = readTextMarkupExtras(fn, mem, annotPtr);\n return { ...base, subtype: 'squiggly', ...extras };\n}\n\nexport function readStrikeout(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n annotPtr: Ptr,\n base: AnnotationBase,\n): StrikeoutAnnotationDTO {\n const extras = readTextMarkupExtras(fn, mem, annotPtr);\n const intent = strikeoutIntentFromName(readIntent(fn, mem, annotPtr));\n return { ...base, subtype: 'strikeout', intent, ...extras };\n}\n","import type { AnnotationBase, UnsupportedAnnotationDTO } from '@embedpdf/engine-core/runtime';\nimport type { PdfFunctions, PdfRuntimeMemory, Ptr } from '@embedpdf/engine-runtime';\n\nimport { readAnnotString } from './annotationReadPrimitives';\n\n/**\n * Forward-compat fallback. Captures the raw subtype code (and best-effort\n * subtype name from the dict) so debugging information survives across\n * the wire even when no per-subtype reader has been wired yet.\n */\nexport function readUnsupported(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n annotPtr: Ptr,\n base: AnnotationBase,\n rawSubtypeCode: number,\n): UnsupportedAnnotationDTO {\n const rawSubtypeName = readAnnotString(fn, mem, annotPtr, 'Subtype');\n return {\n ...base,\n subtype: 'unsupported',\n rawSubtypeCode,\n rawSubtypeName,\n };\n}\n","import type {\n AnnotationBase,\n PolygonAnnotationDTO,\n PolylineAnnotationDTO,\n VertexAnnotationFields,\n} from '@embedpdf/engine-core/runtime';\nimport type { PdfFunctions, PdfRuntimeMemory, Ptr } from '@embedpdf/engine-runtime';\n\nimport { readBorderEffect, readLineEndings, readVertices } from './annotationReadPrimitives';\nimport { readFilledStyleExtras } from './readStyle';\nimport { readAnnotationRotation } from './readAnnotationTransformMetadata';\n\n/**\n * Shared reader for the two vertex subtypes (polygon/polyline). Reads the\n * common stroke/fill styling plus the `/Vertices` point list; each caller\n * layers its own subtype-specific extras (polygon: cloudy border; polyline:\n * line endings) and the `subtype` literal.\n */\nexport function readVertexExtras(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n annotPtr: Ptr,\n): VertexAnnotationFields {\n const rotation = readAnnotationRotation(fn, mem, annotPtr);\n return {\n ...readFilledStyleExtras(fn, mem, annotPtr),\n vertices: readVertices(fn, mem, annotPtr),\n ...(rotation != null ? { rotation } : {}),\n };\n}\n\nexport function readPolygon(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n annotPtr: Ptr,\n base: AnnotationBase,\n): PolygonAnnotationDTO {\n return {\n ...base,\n subtype: 'polygon',\n ...readVertexExtras(fn, mem, annotPtr),\n // Absent /BE reads as explicit `null` (never omission), so a read DTO\n // compares structurally against a clearing patch.\n cloudyIntensity: readBorderEffect(fn, mem, annotPtr),\n };\n}\n\nexport function readPolyline(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n annotPtr: Ptr,\n base: AnnotationBase,\n): PolylineAnnotationDTO {\n return {\n ...base,\n subtype: 'polyline',\n ...readVertexExtras(fn, mem, annotPtr),\n lineEndings: readLineEndings(fn, mem, annotPtr),\n };\n}\n","import type { AnnotationBase, Color, WidgetAnnotationDTO } from '@embedpdf/engine-core/runtime';\nimport { type PdfFunctions, type PdfRuntimeMemory, type Ptr } from '@embedpdf/engine-runtime';\n\nimport { withScratchN } from '../../../../runtime/memory/scratch';\nimport { readI32 } from '../../../../runtime/memory/structs';\nimport { standardFontFromCode } from '../standardFont';\nimport { textAlignmentFromCode } from '../textAlignment';\nimport { readDefaultAppearance, readTextAlignment } from './annotationReadPrimitives';\nimport { readBorderFields } from './readStyle';\n\nconst MK_BORDER_COLOR = 0; // EPDF_MK_COLOR_BC\nconst MK_BACKGROUND_COLOR = 1; // EPDF_MK_COLOR_BG\nconst I32_BYTES = 4;\n\nfunction readMKColor(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n annotPtr: Ptr,\n which: number,\n): Color | null {\n return withScratchN(mem, [I32_BYTES, I32_BYTES, I32_BYTES], ([r, g, b]) => {\n if (!fn.EPDFAnnot_GetMKColor(annotPtr, which, r, g, b)) return null;\n return {\n r: readI32(mem, r) & 0xff,\n g: readI32(mem, g) & 0xff,\n b: readI32(mem, b) & 0xff,\n };\n });\n}\n\n/**\n * Widget-plane read: /MK colours, /BS border, /DA text defaults, /Q, and\n * the field join. Field-plane data (value, options, flags) lives on\n * `doc.forms` — join via `fieldObjectNumber`.\n */\nexport function readWidget(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n annotPtr: Ptr,\n base: AnnotationBase,\n): WidgetAnnotationDTO {\n const border = readBorderFields(fn, mem, annotPtr);\n const da = readDefaultAppearance(fn, mem, annotPtr);\n return {\n ...base,\n subtype: 'widget',\n color: readMKColor(fn, mem, annotPtr, MK_BORDER_COLOR),\n interiorColor: readMKColor(fn, mem, annotPtr, MK_BACKGROUND_COLOR),\n strokeWidth: border.strokeWidth,\n borderStyle: border.borderStyle,\n ...(da\n ? {\n fontFamily: standardFontFromCode(da.fontCode),\n fontSize: da.fontSize,\n fontColor: da.color,\n }\n : {}),\n textAlign: textAlignmentFromCode(readTextAlignment(fn, annotPtr)),\n // Joined by the caller (joinWidgetFieldNumbers): the /Parent target is\n // a FIELD dictionary, which annotation-plane primitives cannot follow.\n fieldObjectNumber: 0,\n fieldFamily: 'unknown',\n };\n}\n","import type {\n AnnotationBase,\n AnnotationDTO,\n AnnotationSubtype,\n} from '@embedpdf/engine-core/runtime';\nimport { subtypeFromCode } from '@embedpdf/engine-core/runtime';\nimport type { PdfFunctions, PdfRuntimeMemory, Ptr } from '@embedpdf/engine-runtime';\n\nimport type { AnnotationReadContext } from './annotationReadContext';\nimport { readCaret } from './readCaretAnnotation';\nimport { readFileAttachment } from './readFileAttachmentAnnotation';\nimport { readFreeText } from './readFreeTextAnnotation';\nimport { readInk } from './readInkAnnotation';\nimport { readLine } from './readLineAnnotation';\nimport { readLink } from './readLinkAnnotation';\nimport { readRedact } from './readRedactAnnotation';\nimport { readCircle, readSquare } from './readShapeAnnotation';\nimport { readStamp } from './readStampAnnotation';\nimport { readText } from './readTextAnnotation';\nimport {\n readHighlight,\n readSquiggly,\n readStrikeout,\n readUnderline,\n} from './readTextMarkupAnnotation';\nimport { readUnsupported } from './readUnsupportedAnnotation';\nimport { readPolygon, readPolyline } from './readVertexAnnotation';\nimport { readWidget } from './readWidgetAnnotation';\n\n/**\n * One reader per `AnnotationSubtype`. Each reader produces the DTO type\n * the registry promised: `kinds/<subtype>/dto.ts`. Readers receive the\n * pre-built `AnnotationBase` (identity + flags + rect + dates) so each\n * implementation only has to materialise its own fields, plus the\n * document-scoped `AnnotationReadContext` — most readers ignore it (they\n * work off the `annotPtr` alone); the link reader consumes it.\n *\n * The `unsupported` fallback preserves the raw subtype code so a future\n * reader landing for that subtype can replace it without a wire-format\n * version bump.\n */\nexport type AnnotationSubtypeReader = (\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n annotPtr: Ptr,\n base: AnnotationBase,\n rawSubtypeCode: number,\n ctx: AnnotationReadContext,\n) => AnnotationDTO;\n\nconst READER_BY_SUBTYPE: Partial<Record<AnnotationSubtype, AnnotationSubtypeReader>> = {\n highlight: readHighlight,\n underline: readUnderline,\n squiggly: readSquiggly,\n strikeout: readStrikeout,\n circle: readCircle,\n square: readSquare,\n polygon: readPolygon,\n polyline: readPolyline,\n line: readLine,\n link: readLink,\n ink: readInk,\n 'free-text': readFreeText,\n caret: readCaret,\n text: readText,\n stamp: readStamp,\n 'file-attachment': readFileAttachment,\n widget: readWidget,\n redact: readRedact,\n unsupported: readUnsupported,\n};\n\n/**\n * Maps a PDFium subtype code onto the reader that should handle it.\n * Returns the `unsupported` reader for any subtype that doesn't have a\n * dedicated reader yet.\n */\nexport function pickReader(rawSubtypeCode: number): {\n reader: AnnotationSubtypeReader;\n subtype: AnnotationSubtype;\n} {\n const subtype = subtypeFromCode(rawSubtypeCode);\n const reader = READER_BY_SUBTYPE[subtype];\n if (reader) return { reader, subtype };\n return { reader: READER_BY_SUBTYPE.unsupported!, subtype: 'unsupported' };\n}\n","import { EngineError, EngineErrorCode } from '@embedpdf/engine-core/runtime';\nimport { NULL_PTR, type PdfRuntimeModule, type Ptr } from '@embedpdf/engine-runtime';\n\nimport type { DocumentSession } from '../../../document-session/DocumentSession';\n\ninterface FormModelEntry {\n /** The session mutation sequence the model was built at. */\n seq: number;\n ptr: Ptr;\n}\n\n/**\n * Per-session cache of the native `EPDFForm_LoadModel` snapshot, keyed on\n * the session's mutation sequence.\n *\n * The native model is an immutable, detached snapshot: correct forever,\n * stale after any document mutation. Rebuilding it per call would walk the\n * field tree and sweep every page's /Annots on each read (widget lists on\n * multi-page documents read it constantly); keeping one forever would\n * serve stale values. Version-keying gives exact coherence for free:\n * `DocumentSession.noteMutation()` bumps the sequence on EVERY successful\n * mutation (annotations, pages, metadata, forms — widgets are annotations,\n * so all of them can affect the form model), and the next read rebuilds.\n *\n * The cache also owns the native handle's lifetime: exactly one live model\n * per session, closed before replacement and on session teardown via\n * {@link disposeFormModel}.\n */\nconst cache = new WeakMap<DocumentSession, FormModelEntry>();\n\nexport function acquireFormModel(runtime: PdfRuntimeModule, session: DocumentSession): Ptr {\n const seq = session.mutationSeq();\n const hit = cache.get(session);\n if (hit && hit.seq === seq) {\n return hit.ptr;\n }\n if (hit) {\n runtime.fn.EPDFForm_CloseModel(hit.ptr);\n cache.delete(session);\n }\n const ptr = runtime.fn.EPDFForm_LoadModel(session.requireDocPtr());\n if (ptr === NULL_PTR) {\n throw new EngineError(EngineErrorCode.Unknown, 'failed to build form model');\n }\n cache.set(session, { seq, ptr });\n return ptr;\n}\n\n/** Close and forget the session's cached model, if any. */\nexport function disposeFormModel(runtime: PdfRuntimeModule, session: DocumentSession): void {\n const hit = cache.get(session);\n if (!hit) {\n return;\n }\n runtime.fn.EPDFForm_CloseModel(hit.ptr);\n cache.delete(session);\n}\n","import type {\n FormFieldBase,\n FormFieldDTO,\n FormFieldFamily,\n FormFieldOption,\n FormKind,\n FormSnapshot,\n FormWidgetRef,\n ToggleFieldWidget,\n FormValueEntry,\n PdfFieldActions,\n} from '@embedpdf/engine-core/runtime';\nimport type { PdfRuntimeModule, Ptr } from '@embedpdf/engine-runtime';\n\nimport { readUtf16String, readUtf8String } from '../../../runtime/memory/strings';\nimport { ActionReadBudgetTracker, readActionModel } from '../../actions/ActionModelReader';\n\n// Mirrors EPDF_FORMFIELD_FAMILY_* in public/epdf_form.h.\nexport const FAMILY_BY_CODE: Record<number, FormFieldFamily> = {\n 0: 'unknown',\n 1: 'pushbutton',\n 2: 'checkbox',\n 3: 'radio',\n 4: 'text',\n 5: 'combobox',\n 6: 'listbox',\n 7: 'signature',\n};\n\n// Mirrors EPDF_FORMKIND_* in public/epdf_form.h.\nconst FORM_KIND_BY_CODE: Record<number, FormKind> = {\n 0: 'none',\n 1: 'acroform',\n 2: 'xfa',\n};\n\n// PDF /Ff bits (1-based bit numbers per ISO 32000 Table 226/228/230).\nconst FF_READ_ONLY = 1 << 0;\nconst FF_REQUIRED = 1 << 1;\nconst FF_NO_EXPORT = 1 << 2;\nconst FF_MULTILINE = 1 << 12;\nconst FF_PASSWORD = 1 << 13;\nconst FF_NO_TOGGLE_TO_OFF = 1 << 14;\nconst FF_EDIT = 1 << 18;\nconst FF_MULTI_SELECT = 1 << 21;\nconst FF_COMB = 1 << 24;\nconst FF_RADIOS_IN_UNISON = 1 << 25;\n\nfunction readWide(runtime: PdfRuntimeModule, call: (buf: Ptr, capacity: number) => number): string {\n return readUtf16String(runtime.mem, call) ?? '';\n}\n\nfunction readWideOrNull(\n runtime: PdfRuntimeModule,\n call: (buf: Ptr, capacity: number) => number,\n): string | null {\n return readUtf16String(runtime.mem, call, null);\n}\n\nfunction readToggleWidgets(\n runtime: PdfRuntimeModule,\n model: Ptr,\n fieldIndex: number,\n): ToggleFieldWidget[] {\n const { fn } = runtime;\n const count = fn.EPDFForm_CountFieldWidgets(model, fieldIndex);\n const widgets: ToggleFieldWidget[] = [];\n for (let w = 0; w < count; w++) {\n widgets.push({\n annotObjectNumber: fn.EPDFForm_GetFieldWidgetObjNum(model, fieldIndex, w),\n pageObjectNumber: fn.EPDFForm_GetFieldWidgetPageObjNum(model, fieldIndex, w),\n onState:\n readUtf8String(runtime.mem, (buf, cap) =>\n fn.EPDFForm_GetFieldWidgetOnState(model, fieldIndex, w, buf, cap),\n ) ?? '',\n exportValue: readWide(runtime, (buf, cap) =>\n fn.EPDFForm_GetFieldWidgetExportValue(model, fieldIndex, w, buf, cap),\n ),\n checked: fn.EPDFForm_IsFieldWidgetChecked(model, fieldIndex, w),\n });\n }\n return widgets;\n}\n\nfunction readPlainWidgets(\n runtime: PdfRuntimeModule,\n model: Ptr,\n fieldIndex: number,\n): FormWidgetRef[] {\n const { fn } = runtime;\n const count = fn.EPDFForm_CountFieldWidgets(model, fieldIndex);\n const widgets: FormWidgetRef[] = [];\n for (let w = 0; w < count; w++) {\n widgets.push({\n annotObjectNumber: fn.EPDFForm_GetFieldWidgetObjNum(model, fieldIndex, w),\n pageObjectNumber: fn.EPDFForm_GetFieldWidgetPageObjNum(model, fieldIndex, w),\n });\n }\n return widgets;\n}\n\nfunction readOptions(runtime: PdfRuntimeModule, model: Ptr, fieldIndex: number): FormFieldOption[] {\n const { fn } = runtime;\n const count = fn.EPDFForm_CountFieldOptions(model, fieldIndex);\n const options: FormFieldOption[] = [];\n for (let o = 0; o < count; o++) {\n options.push({\n label: readWide(runtime, (buf, cap) =>\n fn.EPDFForm_GetFieldOptionLabel(model, fieldIndex, o, buf, cap),\n ),\n value: readWide(runtime, (buf, cap) =>\n fn.EPDFForm_GetFieldOptionValue(model, fieldIndex, o, buf, cap),\n ),\n selected: fn.EPDFForm_IsFieldOptionSelected(model, fieldIndex, o),\n });\n }\n return options;\n}\n\n/** Read one field of the native model into its per-family DTO. */\nexport function readFieldAt(\n runtime: PdfRuntimeModule,\n model: Ptr,\n fieldIndex: number,\n actionBudget = new ActionReadBudgetTracker(),\n): FormFieldDTO {\n const { fn } = runtime;\n const fieldObjectNumber = fn.EPDFForm_GetFieldObjNum(model, fieldIndex);\n const name = readWide(runtime, (buf, cap) =>\n fn.EPDFForm_GetFieldName(model, fieldIndex, buf, cap),\n );\n const rawFlags = fn.EPDFForm_GetFieldFlags(model, fieldIndex);\n const family = FAMILY_BY_CODE[fn.EPDFForm_GetFieldFamily(model, fieldIndex)] ?? 'unknown';\n const valueEntry = readValueEntry(runtime, model, fieldIndex, false);\n const defaultValueEntry = readValueEntry(runtime, model, fieldIndex, true);\n const actions = readFieldActions(runtime, model, fieldIndex, actionBudget);\n\n const base: FormFieldBase = {\n ref:\n fieldObjectNumber > 0 ? { kind: 'objectNumber', fieldObjectNumber } : { kind: 'fqn', name },\n fieldObjectNumber,\n name,\n family,\n origin: fn.EPDFForm_GetFieldOrigin(model, fieldIndex) === 1 ? 'recovered' : 'acroform',\n flags: {\n readOnly: (rawFlags & FF_READ_ONLY) !== 0,\n required: (rawFlags & FF_REQUIRED) !== 0,\n noExport: (rawFlags & FF_NO_EXPORT) !== 0,\n raw: rawFlags,\n },\n alternateName: readWideOrNull(runtime, (buf, cap) =>\n fn.EPDFForm_GetFieldAlternateName(model, fieldIndex, buf, cap),\n ),\n mappingName: readWideOrNull(runtime, (buf, cap) =>\n fn.EPDFForm_GetFieldMappingName(model, fieldIndex, buf, cap),\n ),\n valueEntry,\n defaultValueEntry,\n ...(actions ? { actions } : {}),\n widgets: [],\n };\n const scalarValue = entryScalar(valueEntry);\n const scalarDefault = entryScalar(defaultValueEntry);\n\n switch (family) {\n case 'text': {\n const maxLen = fn.EPDFForm_GetFieldMaxLen(model, fieldIndex);\n return {\n ...base,\n family,\n value: scalarValue,\n defaultValue: scalarDefault,\n maxLength: maxLen > 0 ? maxLen : null,\n multiline: (rawFlags & FF_MULTILINE) !== 0,\n password: (rawFlags & FF_PASSWORD) !== 0,\n comb: (rawFlags & FF_COMB) !== 0,\n widgets: readPlainWidgets(runtime, model, fieldIndex),\n };\n }\n case 'checkbox': {\n const widgets = readToggleWidgets(runtime, model, fieldIndex);\n return {\n ...base,\n family,\n checked: widgets.some((w) => w.checked),\n exportValue: widgets[0]?.exportValue ?? 'Yes',\n widgets,\n };\n }\n case 'radio': {\n const widgets = readToggleWidgets(runtime, model, fieldIndex);\n return {\n ...base,\n family,\n value: widgets.find((widget) => widget.checked)?.exportValue ?? 'Off',\n radiosInUnison: (rawFlags & FF_RADIOS_IN_UNISON) !== 0,\n noToggleToOff: (rawFlags & FF_NO_TOGGLE_TO_OFF) !== 0,\n widgets,\n };\n }\n case 'combobox': {\n return {\n ...base,\n family,\n value: scalarValue,\n defaultValue: scalarDefault,\n edit: (rawFlags & FF_EDIT) !== 0,\n options: readOptions(runtime, model, fieldIndex),\n widgets: readPlainWidgets(runtime, model, fieldIndex),\n };\n }\n case 'listbox': {\n const options = readOptions(runtime, model, fieldIndex);\n return {\n ...base,\n family,\n selectedValues: options.filter((o) => o.selected).map((o) => o.value),\n multiSelect: (rawFlags & FF_MULTI_SELECT) !== 0,\n options,\n widgets: readPlainWidgets(runtime, model, fieldIndex),\n };\n }\n case 'pushbutton':\n case 'signature': {\n return { ...base, family, widgets: readPlainWidgets(runtime, model, fieldIndex) };\n }\n default: {\n return {\n ...base,\n family: 'unknown',\n rawValue:\n valueEntry.kind === 'array' ? valueEntry.values.join(',') : entryScalar(valueEntry),\n widgets: readPlainWidgets(runtime, model, fieldIndex),\n };\n }\n }\n}\n\n/** Read the whole native model into a detached {@link FormSnapshot}. */\nexport function readFormSnapshot(runtime: PdfRuntimeModule, model: Ptr): FormSnapshot {\n const { fn } = runtime;\n const count = fn.EPDFForm_CountFields(model);\n const fields: FormFieldDTO[] = [];\n const actionBudget = new ActionReadBudgetTracker();\n for (let i = 0; i < count; i++) {\n fields.push(readFieldAt(runtime, model, i, actionBudget));\n }\n const calculationOrder: FormSnapshot['calculationOrder'] = [];\n const calculationCount = fn.EPDFForm_CountCalculationOrder(model);\n for (let index = 0; index < calculationCount; index++) {\n const fieldIndex = fn.EPDFForm_GetCalculationOrderFieldIndex(model, index);\n calculationOrder.push(\n fieldIndex >= 0 && fieldIndex < fields.length ? fields[fieldIndex].ref : null,\n );\n }\n return {\n formKind: FORM_KIND_BY_CODE[fn.EPDFForm_GetFormKind(model)] ?? 'none',\n needsAppearances: fn.EPDFForm_GetNeedAppearances(model),\n fields,\n calculationOrder,\n };\n}\n\nfunction readValueEntry(\n runtime: PdfRuntimeModule,\n model: Ptr,\n fieldIndex: number,\n isDefault: boolean,\n): FormValueEntry {\n const { fn } = runtime;\n const kind = isDefault\n ? fn.EPDFForm_GetFieldDefaultValueKind(model, fieldIndex)\n : fn.EPDFForm_GetFieldValueKind(model, fieldIndex);\n if (kind === 0) return { kind: 'none' };\n if (kind === 3) return { kind: 'unsupported' };\n if (kind !== 1 && kind !== 2) return { kind: 'unsupported' };\n const count = isDefault\n ? fn.EPDFForm_CountFieldDefaultValues(model, fieldIndex)\n : fn.EPDFForm_CountFieldValues(model, fieldIndex);\n const values: string[] = [];\n for (let index = 0; index < count; index++) {\n values.push(\n readWide(runtime, (buf, capacity) =>\n isDefault\n ? fn.EPDFForm_GetFieldDefaultValueAt(model, fieldIndex, index, buf, capacity)\n : fn.EPDFForm_GetFieldValueAt(model, fieldIndex, index, buf, capacity),\n ),\n );\n }\n return kind === 1 ? { kind: 'scalar', value: values[0] ?? '' } : { kind: 'array', values };\n}\n\nfunction entryScalar(entry: FormValueEntry): string {\n if (entry.kind === 'scalar') return entry.value;\n if (entry.kind === 'array') return entry.values[0] ?? '';\n return '';\n}\n\nfunction readFieldActions(\n runtime: PdfRuntimeModule,\n model: Ptr,\n fieldIndex: number,\n budget: ActionReadBudgetTracker,\n): PdfFieldActions | undefined {\n const { fn, mem } = runtime;\n const entries = [\n ['keystroke', 0],\n ['format', 1],\n ['validate', 2],\n ['calculate', 3],\n ] as const;\n const actions: PdfFieldActions = {};\n for (const [key, event] of entries) {\n const action = readActionModel(\n fn,\n mem,\n fn.EPDFForm_GetFieldActionModel(model, fieldIndex, event),\n budget,\n );\n if (action) actions[key] = action;\n }\n return Object.keys(actions).length > 0 ? actions : undefined;\n}\n","import type { AnnotationDTO } from '@embedpdf/engine-core/runtime';\nimport type { PdfRuntimeModule } from '@embedpdf/engine-runtime';\n\nimport type { DocumentSession } from '../../../../document-session/DocumentSession';\n// Cross-feature read into the forms model cache: the widget<->field join is\n// form-tree knowledge, and the version-keyed cache makes it O(1) between\n// mutations. No module cycle: the cache imports nothing from annotations.\nimport { acquireFormModel } from '../../../forms/internal/formModelCache';\nimport { FAMILY_BY_CODE } from '../../../forms/internal/readFormSnapshot';\n\n/**\n * Resolve the owning field's object number for a widget annotation, or 0\n * when unattached. (The /Parent of a widget is a FIELD dictionary - not an\n * annotation - so FPDFAnnot_GetLinkedAnnot cannot follow it; the reconciled\n * form model is the authoritative join.)\n */\nexport function resolveWidgetFieldObjectNumber(\n runtime: PdfRuntimeModule,\n session: DocumentSession,\n annotObjectNumber: number,\n): number {\n if (annotObjectNumber <= 0) return 0;\n const model = acquireFormModel(runtime, session);\n const fieldIndex = runtime.fn.EPDFForm_GetFieldIndexForWidget(model, annotObjectNumber);\n if (fieldIndex < 0) return 0;\n return runtime.fn.EPDFForm_GetFieldObjNum(model, fieldIndex);\n}\n\n/** Stamp `fieldObjectNumber` onto every widget DTO in a freshly read list. */\nexport function joinWidgetFieldNumbers(\n runtime: PdfRuntimeModule,\n session: DocumentSession,\n annotations: AnnotationDTO[],\n): void {\n for (const annotation of annotations) {\n if (annotation.subtype !== 'widget') continue;\n if (annotation.ref.kind !== 'objectNumber') continue;\n const model = acquireFormModel(runtime, session);\n const fieldIndex = runtime.fn.EPDFForm_GetFieldIndexForWidget(\n model,\n annotation.ref.annotObjectNumber,\n );\n if (fieldIndex < 0) {\n annotation.fieldObjectNumber = 0;\n annotation.fieldFamily = 'unknown';\n continue;\n }\n annotation.fieldObjectNumber = runtime.fn.EPDFForm_GetFieldObjNum(model, fieldIndex);\n annotation.fieldFamily =\n FAMILY_BY_CODE[runtime.fn.EPDFForm_GetFieldFamily(model, fieldIndex)] ?? 'unknown';\n }\n}\n","import type {\n AnnotationIdentityQuality,\n AnnotationRef,\n PageObjectNumber,\n RevisionToken,\n} from '@embedpdf/engine-core/runtime';\nimport type { PdfFunctions, PdfRuntimeMemory, Ptr } from '@embedpdf/engine-runtime';\n\nimport { readAnnotString } from './annotationReadPrimitives';\n\nexport interface AnnotationIdentity {\n ref: AnnotationRef;\n identityQuality: AnnotationIdentityQuality;\n nm: string | null;\n}\n\n/**\n * Decides which `AnnotationRef` form to expose on the wire and the\n * `identityQuality` flag.\n *\n * Order:\n * 1. `EPDFAnnot_GetObjectNumber(annot)` - if `> 0`, use `objectNumber`.\n * Always durable.\n * 2. /NM - if present and non-empty, use `nm`. Always durable.\n * 3. Fallback: `index + revision`. Always weak. The revision must be\n * provided by the caller (sourced from the live `RevisionAuthority`).\n */\nexport function readAnnotationIdentity(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n annotPtr: Ptr,\n pageObjectNumber: PageObjectNumber,\n index: number,\n revision: RevisionToken,\n): AnnotationIdentity {\n const objectNumber = fn.EPDFAnnot_GetObjectNumber(annotPtr);\n const nm = readAnnotString(fn, mem, annotPtr, 'NM');\n\n if (objectNumber > 0) {\n return {\n ref: {\n kind: 'objectNumber',\n pageObjectNumber,\n annotObjectNumber: objectNumber,\n },\n identityQuality: 'durable',\n nm: nm ?? null,\n };\n }\n\n if (nm && nm.length > 0) {\n return {\n ref: { kind: 'nm', pageObjectNumber, nm },\n identityQuality: 'durable',\n nm,\n };\n }\n\n return {\n ref: { kind: 'index', pageObjectNumber, index, revision },\n identityQuality: 'weak',\n nm: nm ?? null,\n };\n}\n","import type { AnnotationReplyType } from '@embedpdf/engine-core/runtime';\n\n/**\n * `/RT` (reply type) codec between the wire-stable {@link AnnotationReplyType}\n * strings and PDFium's `FPDF_ANNOT_REPLY_TYPE` integer codes (see\n * `public/fpdf_annot.h`). Kept in engine-services so engine-core stays\n * PDFium-free.\n *\n * 0 FPDF_ANNOT_RT_UNKNOWN (RT absent / unrecognized)\n * 1 FPDF_ANNOT_RT_REPLY /R — the ISO default when /RT is missing\n * 2 FPDF_ANNOT_RT_GROUP /Group\n */\nexport const RT_UNKNOWN = 0;\nexport const RT_REPLY = 1;\nexport const RT_GROUP = 2;\n\n/**\n * Map a PDFium reply-type code to the wire string, GATED on the presence\n * of `/IRT`. PDFium's `EPDFAnnot_GetReplyType` returns `RT_REPLY` even\n * when there is no `/IRT` (it reports the `/RT` default in isolation), so\n * callers must only invoke this for annotations that actually carry an\n * `/IRT` link. `RT_GROUP` -> `'group'`; everything else -> `'reply'`.\n */\nexport function replyTypeFromCode(code: number): AnnotationReplyType {\n return code === RT_GROUP ? 'group' : 'reply';\n}\n\n/** Map the wire string to the PDFium code written via `EPDFAnnot_SetReplyType`. */\nexport function replyTypeToCode(replyType: AnnotationReplyType): number {\n return replyType === 'group' ? RT_GROUP : RT_REPLY;\n}\n","import type {\n AnnotationRef,\n AnnotationReplyType,\n PageObjectNumber,\n} from '@embedpdf/engine-core/runtime';\nimport type { PdfFunctions, PdfRuntimeMemory, Ptr } from '@embedpdf/engine-runtime';\n\nimport { readAnnotString } from './annotationReadPrimitives';\nimport { replyTypeFromCode } from '../replyType';\n\nexport interface AnnotationRelationship {\n inReplyTo: AnnotationRef | null;\n replyType: AnnotationReplyType | null;\n}\n\nconst NO_RELATIONSHIP: AnnotationRelationship = { inReplyTo: null, replyType: null };\n\n/**\n * Read the `/IRT` + `/RT` relationship edge of an annotation.\n *\n * `/IRT` is an indirect reference to the parent annotation, which (per ISO\n * 32000 §12.5.6.2) lives on the SAME page — so we surface the parent with\n * the same `pageObjectNumber` and the same identity precedence the rest of\n * the engine uses (objectNumber, then `/NM`). We do NOT fall back to an\n * index ref: an `/IRT` target is by construction an indirect object, so its\n * object number is always available. In the pathological case where neither\n * an object number nor an `/NM` can be read (a malformed direct-object\n * target), we report no relationship rather than an unaddressable parent —\n * keeping the invariant `replyType === null` iff `inReplyTo === null`.\n *\n * `/RT` is read via `EPDFAnnot_GetReplyType`, which returns the `/R` default\n * when `/RT` is absent; we only consult it when `/IRT` is present, so a\n * top-level annotation never spuriously reports `'reply'`.\n */\nexport function readAnnotationRelationship(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n annotPtr: Ptr,\n pageObjectNumber: PageObjectNumber,\n): AnnotationRelationship {\n const parentPtr = fn.FPDFAnnot_GetLinkedAnnot(annotPtr, 'IRT');\n if (!parentPtr) return NO_RELATIONSHIP;\n\n try {\n const inReplyTo = readParentRef(fn, mem, parentPtr, pageObjectNumber);\n if (!inReplyTo) return NO_RELATIONSHIP;\n return { inReplyTo, replyType: replyTypeFromCode(fn.EPDFAnnot_GetReplyType(annotPtr)) };\n } finally {\n fn.FPDFPage_CloseAnnot(parentPtr);\n }\n}\n\nfunction readParentRef(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n parentPtr: Ptr,\n pageObjectNumber: PageObjectNumber,\n): AnnotationRef | null {\n const objectNumber = fn.EPDFAnnot_GetObjectNumber(parentPtr);\n if (objectNumber > 0) {\n return { kind: 'objectNumber', pageObjectNumber, annotObjectNumber: objectNumber };\n }\n const nm = readAnnotString(fn, mem, parentPtr, 'NM');\n if (nm && nm.length > 0) {\n return { kind: 'nm', pageObjectNumber, nm };\n }\n return null;\n}\n","import type { PdfFunctions, PdfRuntimeMemory, Ptr } from '@embedpdf/engine-runtime';\nimport { NULL_PTR } from '@embedpdf/engine-runtime';\n\n/**\n * Decoded /EMBD_Metadata dictionary as seen from a single annotation.\n *\n * Mirrors the schema written by `writers/annotations/embed-metadata.ts`.\n * Each field is optional because:\n * - older annotations (pre-cloud, or imported from other tools) have no\n * /EMBD_Metadata at all,\n * - the dict may be partially populated (e.g. only UserID, no GroupID),\n * - future schema versions may add or drop fields.\n *\n * Readers tolerate missing fields by returning `undefined`; callers\n * decide how to render the absence (typically \"unknown author\" /\n * \"no group\").\n */\nexport interface EmbedMetadata {\n schemaVersion?: number;\n userId?: string;\n groupId?: string;\n createdBy?: string;\n updatedBy?: string;\n}\n\n/**\n * Read /EMBD_Metadata from an annotation, if present. Returns `null`\n * (not an empty object) when the annotation has no EMBD_Metadata\n * dictionary at all — the caller can distinguish \"no metadata\" from\n * \"metadata with only some fields set\".\n *\n * Uses the same UTF-16LE two-pass read pattern as `readAnnotString` in\n * `./util.ts` so a future change to the underlying memory helpers\n * propagates uniformly.\n */\nexport function readEmbedMetadata(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n annotPtr: Ptr,\n): EmbedMetadata | null {\n if (!fn.EPDFAnnot_HasEmbedMetadata(annotPtr)) return null;\n\n const schemaVersion = readMetaNumber(fn, mem, annotPtr, 'SchemaVersion');\n const userId = readMetaString(fn, mem, annotPtr, 'UserID');\n const groupId = readMetaString(fn, mem, annotPtr, 'GroupID');\n const createdBy = readMetaString(fn, mem, annotPtr, 'CreatedBy');\n const updatedBy = readMetaString(fn, mem, annotPtr, 'UpdatedBy');\n\n const out: EmbedMetadata = {};\n if (schemaVersion !== undefined) out.schemaVersion = schemaVersion;\n if (userId !== undefined) out.userId = userId;\n if (groupId !== undefined) out.groupId = groupId;\n if (createdBy !== undefined) out.createdBy = createdBy;\n if (updatedBy !== undefined) out.updatedBy = updatedBy;\n return out;\n}\n\nfunction readMetaString(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n annotPtr: Ptr,\n key: string,\n): string | undefined {\n // Two-pass UTF-16LE read mirroring readAnnotString:\n // pass 1: NULL_PTR + 0 → returns required byte count (incl. null\n // terminator, so an empty string returns 2)\n // pass 2: alloc buf, fill it, decode\n const len = fn.EPDFAnnot_GetEmbedMetadataString(annotPtr, key, NULL_PTR, 0);\n if (len <= 0) return undefined;\n if (len === 2) return '';\n\n const buf = mem.alloc(len);\n try {\n const written = fn.EPDFAnnot_GetEmbedMetadataString(annotPtr, key, buf, len);\n if (written <= 0) return undefined;\n return mem.readU16String(buf);\n } finally {\n mem.free(buf);\n }\n}\n\nfunction readMetaNumber(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n annotPtr: Ptr,\n key: string,\n): number | undefined {\n const buf = mem.alloc(4); // float\n try {\n const ok = fn.EPDFAnnot_GetEmbedMetadataNumber(annotPtr, key, buf);\n if (!ok) return undefined;\n return Number(mem.peek(buf, 'f32'));\n } finally {\n mem.free(buf);\n }\n}\n","import type { BlendMode } from '@embedpdf/engine-core/runtime';\n\n/** Explicit wire-domain ↔ PDFium `FPDF_BLENDMODE` mapping. */\nexport function blendModeToCode(mode: BlendMode): number {\n switch (mode) {\n case 'normal':\n return 0;\n case 'multiply':\n return 1;\n case 'screen':\n return 2;\n case 'overlay':\n return 3;\n case 'darken':\n return 4;\n case 'lighten':\n return 5;\n case 'color-dodge':\n return 6;\n case 'color-burn':\n return 7;\n case 'hard-light':\n return 8;\n case 'soft-light':\n return 9;\n case 'difference':\n return 10;\n case 'exclusion':\n return 11;\n case 'hue':\n return 12;\n case 'saturation':\n return 13;\n case 'color':\n return 14;\n case 'luminosity':\n return 15;\n }\n}\n\nexport function blendModeFromCode(code: number): BlendMode {\n switch (code) {\n case 1:\n return 'multiply';\n case 2:\n return 'screen';\n case 3:\n return 'overlay';\n case 4:\n return 'darken';\n case 5:\n return 'lighten';\n case 6:\n return 'color-dodge';\n case 7:\n return 'color-burn';\n case 8:\n return 'hard-light';\n case 9:\n return 'soft-light';\n case 10:\n return 'difference';\n case 11:\n return 'exclusion';\n case 12:\n return 'hue';\n case 13:\n return 'saturation';\n case 14:\n return 'color';\n case 15:\n return 'luminosity';\n default:\n return 'normal';\n }\n}\n","import type {\n AnnotationBase,\n PageObjectNumber,\n RevisionToken,\n PdfAnnotationActions,\n} from '@embedpdf/engine-core/runtime';\nimport type { PdfFunctions, PdfRuntimeMemory, Ptr } from '@embedpdf/engine-runtime';\n\nimport { readAnnotFlags, readAnnotRect, readAnnotString } from './annotationReadPrimitives';\nimport { readAnnotationIdentity } from './readAnnotationIdentity';\nimport { readAnnotationRelationship } from './readAnnotationRelationship';\nimport { readEmbedMetadata } from './readEmbedMetadata';\nimport { blendModeFromCode } from '../blendMode';\nimport { pdfDateToIso } from '../../../../shared/pdf-date';\nimport { ActionReadBudgetTracker, readActionModel } from '../../../actions/ActionModelReader';\n\n/**\n * Reads the wire shell every annotation DTO carries: identity, flags,\n * rect, contents, author, dates. No subtype-specific fields. The\n * per-subtype reader builds its DTO by extending this with its own\n * fields and `subtype: '...'` discriminator.\n */\nexport function readAnnotationBase(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n annotPtr: Ptr,\n pageObjectNumber: PageObjectNumber,\n index: number,\n revision: RevisionToken,\n actionBudget = new ActionReadBudgetTracker(),\n): AnnotationBase {\n const identity = readAnnotationIdentity(fn, mem, annotPtr, pageObjectNumber, index, revision);\n const rect = readAnnotRect(fn, mem, annotPtr);\n const flags = readAnnotFlags(fn, annotPtr);\n const contents = readAnnotString(fn, mem, annotPtr, 'Contents');\n const author = readAnnotString(fn, mem, annotPtr, 'T');\n const createdRaw = readAnnotString(fn, mem, annotPtr, 'CreationDate');\n const modifiedRaw = readAnnotString(fn, mem, annotPtr, 'M');\n const blendMode = blendModeFromCode(fn.EPDFAnnot_GetBlendMode(annotPtr));\n // EmbedPDF /EMBD_Metadata is optional; absent for legacy or anonymous\n // annotations. We spread the present fields into the DTO so the wire\n // never carries explicit `undefined` keys.\n const embd = readEmbedMetadata(fn, mem, annotPtr);\n const relationship = readAnnotationRelationship(fn, mem, annotPtr, pageObjectNumber);\n const actions = readAnnotationActions(fn, mem, annotPtr, actionBudget);\n\n return {\n ref: identity.ref,\n pageObjectNumber,\n index,\n identityQuality: identity.identityQuality,\n nm: identity.nm,\n flags,\n rect,\n contents,\n author,\n created: createdRaw ? pdfDateToIso(createdRaw) : null,\n modified: modifiedRaw ? pdfDateToIso(modifiedRaw) : null,\n blendMode,\n inReplyTo: relationship.inReplyTo,\n replyType: relationship.replyType,\n ...(embd?.userId !== undefined ? { userId: embd.userId } : {}),\n ...(embd?.groupId !== undefined ? { groupId: embd.groupId } : {}),\n ...(embd?.createdBy !== undefined ? { createdBy: embd.createdBy } : {}),\n ...(embd?.updatedBy !== undefined ? { updatedBy: embd.updatedBy } : {}),\n ...(actions ? { actions } : {}),\n };\n}\n\nfunction readAnnotationActions(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n annotPtr: Ptr,\n budget: ActionReadBudgetTracker,\n): PdfAnnotationActions | undefined {\n const events = [\n ['activate', 0],\n ['cursorEnter', 1],\n ['cursorExit', 2],\n ['mouseDown', 3],\n ['mouseUp', 4],\n ['focus', 5],\n ['blur', 6],\n ['pageOpen', 7],\n ['pageClose', 8],\n ['pageVisible', 9],\n ['pageInvisible', 10],\n ] as const;\n const actions: PdfAnnotationActions = {};\n for (const [key, event] of events) {\n const action = readActionModel(fn, mem, fn.EPDFAnnot_GetActionModel(annotPtr, event), budget);\n if (action) actions[key] = action;\n }\n return Object.keys(actions).length > 0 ? actions : undefined;\n}\n","import type {\n AnnotationDTO,\n AnnotationListPageSnapshot,\n PageObjectNumber,\n} from '@embedpdf/engine-core/runtime';\nimport type { PdfRuntimeModule, Ptr } from '@embedpdf/engine-runtime';\n\nimport { readContextFor } from './annotationReadContext';\nimport { pickReader } from './annotationReaderRegistry';\nimport { joinWidgetFieldNumbers } from './joinWidgetField';\nimport { readAnnotationBase } from './readAnnotationBase';\nimport type { DocumentSession } from '../../../../document-session/DocumentSession';\nimport { throwIfAborted } from '../../../../shared/abort';\nimport { ActionReadBudgetTracker } from '../../../actions/ActionModelReader';\n\n/**\n * Shared per-page annotation read loop, used by both read paths. The raw\n * path (off `docPtr`, no `pagePtr`) and the full path (off an acquired\n * `pagePtr`) differ only in how they obtain the annotation count and each\n * `annotPtr`; everything after that — per-subtype dispatch, weak-flag\n * accounting, `pageState` decoration — is identical, so it lives here once.\n *\n * `getAnnotPtrAt(i)` returns the annotation handle at index `i`; this loop\n * always closes it via `FPDFPage_CloseAnnot`. The caller owns acquiring and\n * releasing any enclosing `pagePtr`.\n */\nexport function collectPageAnnotations(input: {\n runtime: PdfRuntimeModule;\n session: DocumentSession;\n pageObjectNumber: PageObjectNumber;\n count: number;\n getAnnotPtrAt: (index: number) => Ptr;\n signal: AbortSignal;\n}): AnnotationListPageSnapshot {\n const { runtime, session, pageObjectNumber, count, getAnnotPtrAt, signal } = input;\n const { fn, mem } = runtime;\n\n const annotations: AnnotationDTO[] = [];\n let hasWeak = false;\n const revision = session.pageState(pageObjectNumber).revision;\n const actionBudget = new ActionReadBudgetTracker();\n const readCtx = readContextFor(session);\n\n for (let i = 0; i < count; i++) {\n throwIfAborted(signal);\n const annotPtr = getAnnotPtrAt(i);\n if (!annotPtr) continue;\n try {\n const base = readAnnotationBase(\n fn,\n mem,\n annotPtr,\n pageObjectNumber,\n i,\n revision,\n actionBudget,\n );\n const subtypeCode = fn.FPDFAnnot_GetSubtype(annotPtr);\n const { reader } = pickReader(subtypeCode);\n const dto = reader(fn, mem, annotPtr, base, subtypeCode, readCtx);\n annotations.push(dto);\n if (dto.identityQuality === 'weak') hasWeak = true;\n } finally {\n fn.FPDFPage_CloseAnnot(annotPtr);\n }\n }\n\n joinWidgetFieldNumbers(runtime, session, annotations);\n session.recordWeakFlag(pageObjectNumber, hasWeak);\n return { pageState: session.pageState(pageObjectNumber), annotations };\n}\n","import type { AnnotationListPageSnapshot, PageObjectNumber } from '@embedpdf/engine-core/runtime';\nimport type { PdfRuntimeModule } from '@embedpdf/engine-runtime';\n\nimport type { DocumentSession } from '../../document-session/DocumentSession';\nimport { throwIfAborted } from '../../shared/abort';\nimport { collectPageAnnotations } from './internal/read/collectPageAnnotations';\n\n/**\n * Per-page slow-path reader. Acquires a `pagePtr` from the\n * `PagePtrPool`, dispatches the same per-subtype catalog as the raw\n * reader (via `collectPageAnnotations`), and releases the page on exit.\n *\n * Currently the dispatched readers do not use the `pagePtr` parameter\n * (text-markup is fully readable from the dict). Subtype readers that\n * need form/widget access (e.g. widget) will plug into this code path\n * as they land - the public DTO surface stays the same.\n */\nexport class AnnotationReader {\n constructor(\n private readonly runtime: PdfRuntimeModule,\n private readonly session: DocumentSession,\n ) {}\n\n list(pageObjectNumber: PageObjectNumber, signal: AbortSignal): AnnotationListPageSnapshot {\n throwIfAborted(signal);\n const { fn } = this.runtime;\n const pool = this.session.pagePool();\n const pagePtr = pool.acquire(pageObjectNumber);\n\n try {\n const count = fn.FPDFPage_GetAnnotCount(pagePtr);\n return collectPageAnnotations({\n runtime: this.runtime,\n session: this.session,\n pageObjectNumber,\n count,\n getAnnotPtrAt: (i) => fn.FPDFPage_GetAnnot(pagePtr, i),\n signal,\n });\n } finally {\n pool.release(pageObjectNumber);\n }\n }\n}\n","import type {\n PageRaster,\n PageRenderBackground,\n PageRenderViewport,\n PdfRect,\n PdfRotation,\n} from '@embedpdf/engine-core/runtime';\nimport { EngineError, EngineErrorCode } from '@embedpdf/engine-core/runtime';\nimport type { PdfRuntimeModule, Ptr } from '@embedpdf/engine-runtime';\n\n/**\n * The ONE place a PDF user-space region becomes a device raster.\n *\n * Every PDFium rasterizer — `PageRenderReader`, `AnnotationAppearanceReader`,\n * and any future one (thumbnails, stamps, flatten) — composes these three\n * pieces and supplies only its own `draw` call. The geometry is a pure affine\n * (the engine twin of the viewer's `Mat2D`/`rotateScaleMatrix`); the bitmap\n * lifecycle (alloc → fill → draw → read back → free) lives in `rasterize`.\n */\n\nconst FPDF_BITMAP_BGRA = 4;\n/** Emit RGBA byte order (vs PDFium's native BGRA) so callers get `rgba8` directly. */\nexport const FPDF_REVERSE_BYTE_ORDER = 0x10;\n\n/** A 2D affine as the same six numbers as the viewer `Mat2D`, CSS `matrix()`, FS_MATRIX. */\nexport type Mat2D = readonly [a: number, b: number, c: number, d: number, e: number, f: number];\n\n/**\n * Map a normalized post-`GetDisplayMatrix()` display-space rect onto an\n * `outW × outH` device bitmap, baking in the caller's viewport rotation.\n *\n * PDFium's page and annotation renderers pre-apply `CPDF_Page::GetDisplayMatrix()`\n * before concatenating the caller matrix. That display matrix has already\n * converted PDF page coordinates (y-up) into bitmap/display coordinates\n * (y-down), so the caller matrix must target that post-display rect.\n */\nexport function displayRectToDeviceMatrix(\n rect: PdfRect,\n rotation: PdfRotation,\n outW: number,\n outH: number,\n): Mat2D {\n const left = rect.left;\n const bottom = rect.bottom;\n const width = rect.right - rect.left;\n const height = rect.top - rect.bottom;\n const sx0 = outW / width;\n const sy0 = outH / height;\n const sx90 = outW / height;\n const sy90 = outH / width;\n\n switch (rotation) {\n case 90:\n return [0, sy90, -sx90, 0, sx90 * (bottom + height), -sy90 * left];\n case 180:\n return [-sx0, 0, 0, -sy0, sx0 * (left + width), sy0 * (bottom + height)];\n case 270:\n return [0, -sy90, sx90, 0, -sx90 * bottom, sy90 * (left + width)];\n case 0:\n return [sx0, 0, 0, sy0, -sx0 * left, -sy0 * bottom];\n }\n}\n\n/**\n * Device pixel size for a region under a rotation + viewport. `width` swaps with\n * height on quarter-turns. Validates the viewport (the public-API contract).\n */\nexport function deviceSize(\n rect: PdfRect,\n rotation: PdfRotation,\n viewport: PageRenderViewport,\n): { width: number; height: number } {\n const rectWidth = rect.right - rect.left;\n const rectHeight = rect.top - rect.bottom;\n const swap = rotation === 90 || rotation === 270;\n const baseWidth = swap ? rectHeight : rectWidth;\n const baseHeight = swap ? rectWidth : rectHeight;\n\n if (viewport.kind === 'width') {\n if (!Number.isFinite(viewport.width) || viewport.width <= 0) {\n throw new EngineError(EngineErrorCode.InvalidArg, 'render viewport width must be positive');\n }\n const width = Math.max(1, Math.round(viewport.width));\n return { width, height: Math.max(1, Math.round((width * baseHeight) / baseWidth)) };\n }\n\n const scale = viewport.scale ?? 1;\n if (!Number.isFinite(scale) || scale <= 0) {\n throw new EngineError(EngineErrorCode.InvalidArg, 'render viewport scale must be positive');\n }\n return {\n width: Math.max(1, Math.round(baseWidth * scale)),\n height: Math.max(1, Math.round(baseHeight * scale)),\n };\n}\n\nexport interface RasterizeOptions {\n /** The region to render, in PDF user space — ALREADY normalized by the caller. */\n rect: PdfRect;\n /** Page dimensions in PDF user space, used to mirror PDFium's display matrix. */\n page: { width: number; height: number };\n rotation: PdfRotation;\n viewport: PageRenderViewport;\n background: PageRenderBackground;\n /**\n * Output-pixel budget: reject BEFORE allocating when the computed device\n * size exceeds it (the decode-bomb-guard pattern — the check lives where\n * the allocation happens). PDF page space is effectively unbounded, so a\n * width-bounded request can still explode vertically on degenerate\n * geometry. Optional: LOCAL renders omit it (exactness is the local\n * product promise); server renders carry the deployment policy's budget.\n */\n maxOutputPixels?: number;\n /**\n * Perform the PDFium draw into `bitmapPtr` with the prepared user `matrixPtr`\n * (and `clipPtr`, the full-bitmap clip — annotation renders ignore it). Return\n * false to abort the raster (e.g. the PDFium call failed).\n */\n draw: (bitmapPtr: Ptr, matrixPtr: Ptr, clipPtr: Ptr) => boolean;\n}\n\n/**\n * Owns the whole bitmap lifecycle: allocate the pixel buffer + bitmap + matrix\n * (+ clip), fill the background, run the caller's `draw`, read the pixels back\n * into a `PageRaster`, and free everything. Returns null on a degenerate rect or\n * a failed allocation/draw.\n */\nexport function rasterize(runtime: PdfRuntimeModule, opts: RasterizeOptions): PageRaster | null {\n const { fn, mem } = runtime;\n const { rect, page, rotation, viewport, background, draw } = opts;\n\n // Degenerate (zero/negative area) has no renderable output and would divide by\n // zero in the matrix.\n if (rect.right <= rect.left || rect.top <= rect.bottom) return null;\n\n const displayRect = pdfRectToDisplayRect(rect, page.height);\n const { width, height } = deviceSize(displayRect, rotation, viewport);\n if (opts.maxOutputPixels !== undefined && width * height > opts.maxOutputPixels) {\n throw new EngineError(\n EngineErrorCode.InvalidArg,\n `render output ${width}x${height} exceeds the ${opts.maxOutputPixels}-pixel budget — ` +\n 'request a smaller width (or tiles, once available)',\n );\n }\n const stride = width * 4;\n const bytes = stride * height;\n\n let pixelPtr: Ptr | null = null;\n let bitmapPtr: Ptr | null = null;\n let matrixPtr: Ptr | null = null;\n let clipPtr: Ptr | null = null;\n try {\n pixelPtr = mem.alloc(bytes);\n bitmapPtr = fn.FPDFBitmap_CreateEx(width, height, FPDF_BITMAP_BGRA, pixelPtr, stride);\n if (!bitmapPtr) return null;\n\n fn.FPDFBitmap_FillRect(\n bitmapPtr,\n 0,\n 0,\n width,\n height,\n background === 'transparent' ? 0x00000000 : 0xffffffff,\n );\n\n matrixPtr = mem.alloc(6 * 4);\n pokeMat2D(mem, matrixPtr, displayRectToDeviceMatrix(displayRect, rotation, width, height));\n\n clipPtr = mem.alloc(4 * 4);\n mem.poke(clipPtr, 'f32', 0, 0);\n mem.poke(clipPtr, 'f32', 0, 4);\n mem.poke(clipPtr, 'f32', width, 8);\n mem.poke(clipPtr, 'f32', height, 12);\n\n if (!draw(bitmapPtr, matrixPtr, clipPtr)) return null;\n\n const pixels = mem.readBytes(pixelPtr, bytes);\n return {\n width,\n height,\n stride,\n color: 'rgba8',\n premultipliedAlpha: false,\n data: toExactArrayBuffer(pixels),\n };\n } finally {\n if (bitmapPtr) fn.FPDFBitmap_Destroy(bitmapPtr);\n if (clipPtr) mem.free(clipPtr);\n if (matrixPtr) mem.free(matrixPtr);\n if (pixelPtr) mem.free(pixelPtr);\n }\n}\n\nfunction pdfRectToDisplayRect(rect: PdfRect, pageHeight: number): PdfRect {\n return {\n left: rect.left,\n right: rect.right,\n bottom: pageHeight - rect.top,\n top: pageHeight - rect.bottom,\n };\n}\n\nfunction pokeMat2D(mem: PdfRuntimeModule['mem'], ptr: Ptr, m: Mat2D): void {\n for (let i = 0; i < 6; i++) mem.poke(ptr, 'f32', m[i], i * 4);\n}\n\nfunction toExactArrayBuffer(bytes: Uint8Array): ArrayBuffer {\n const out = new Uint8Array(bytes.byteLength);\n out.set(bytes);\n return out.buffer;\n}\n","import type {\n AnnotationAppearanceMode,\n AnnotationAppearanceRaster,\n AnnotationAppearanceRenderOptions,\n AnnotationAppearancesResult,\n PageObjectNumber,\n PageRaster,\n PdfRect,\n PdfRotation,\n} from '@embedpdf/engine-core/runtime';\nimport { normalizePdfRect } from '@embedpdf/engine-core/runtime';\nimport type { PdfRuntimeModule, Ptr } from '@embedpdf/engine-runtime';\n\nimport type { DocumentSession } from '../../document-session/DocumentSession';\nimport { throwIfAborted } from '../../shared/abort';\nimport { FPDF_REVERSE_BYTE_ORDER, rasterize } from '../render/deviceRaster';\nimport { readAnnotRect, readIntent } from './internal/read/annotationReadPrimitives';\nimport { readAnnotationIdentity } from './internal/read/readAnnotationIdentity';\nimport {\n readAnnotationRotation,\n readAnnotationUnrotatedRect,\n} from './internal/read/readAnnotationTransformMetadata';\nimport { freeTextIntentFromName } from './internal/freeTextIntent';\n\n/** `FPDF_ANNOT_WIDGET` — form-field annotation subtype code. */\nconst ANNOT_SUBTYPE_WIDGET = 20;\n\n/** `FPDF_ANNOT_FREETEXT` — free-text annotation subtype code. */\nconst ANNOT_SUBTYPE_FREETEXT = 3;\n\n/**\n * BOX-family subtypes (free-text 3, square 5, circle 6, stamp 13): the kinds\n * whose v3 writers put rotation in the AP `/Matrix` + `/EMBD_Metadata`\n * `/UnrotatedRect`. Only these are eligible for rotation-stripped appearance\n * rendering — vertex kinds (line/polyline/polygon/ink) pre-rotate their\n * geometry, so their rasters must stay on the classic path.\n */\nconst BOX_FAMILY_SUBTYPES: ReadonlySet<number> = new Set([3, 5, 6, 13]);\n\n/**\n * Maps an `AnnotationAppearanceMode` onto the PDFium appearance-mode int and\n * the `EPDFAnnot_GetAvailableAppearanceModes` bit it occupies.\n * N -> mode 0 / bit 1, R -> mode 1 / bit 2, D -> mode 2 / bit 4.\n */\nconst APPEARANCE_MODES: ReadonlyArray<{\n name: AnnotationAppearanceMode;\n modeInt: number;\n bit: number;\n}> = [\n { name: 'normal', modeInt: 0, bit: 1 },\n { name: 'rollover', modeInt: 1, bit: 2 },\n { name: 'down', modeInt: 2, bit: 4 },\n];\n\n/**\n * Batch-renders the appearance streams (`/AP`) of every annotation on a page,\n * one bitmap per requested mode. Ported from the v2 PDFium engine's\n * `renderPageAnnotationsRaw` / `renderSingleAnnotAppearance`, but expressed in\n * PDF user space and against the `PdfRuntimeModule` (`fn` + `mem`).\n *\n * Each appearance bitmap is sized to its annotation's `/Rect` scaled by\n * `options.scale`. The shared raster helper handles PDFium's display matrix\n * convention, so this reader stays in normalized PDF page coordinates.\n */\nexport class AnnotationAppearanceReader {\n constructor(\n private readonly runtime: PdfRuntimeModule,\n private readonly session: DocumentSession,\n ) {}\n\n render(\n pageObjectNumber: PageObjectNumber,\n options: AnnotationAppearanceRenderOptions,\n signal: AbortSignal,\n ): AnnotationAppearancesResult {\n throwIfAborted(signal);\n const { fn, mem } = this.runtime;\n const pool = this.session.pagePool();\n const pagePtr = pool.acquire(pageObjectNumber);\n\n const scale = normalizeScale(options.scale);\n const rotation = (options.rotation ?? 0) as PdfRotation;\n const modes = resolveModes(options.modes);\n const revision = this.session.pageState(pageObjectNumber).revision;\n\n const appearances: AnnotationAppearanceRaster[] = [];\n\n try {\n const page = {\n width: fn.FPDF_GetPageWidthF(pagePtr),\n height: fn.FPDF_GetPageHeightF(pagePtr),\n };\n const count = fn.FPDFPage_GetAnnotCount(pagePtr);\n for (let i = 0; i < count; i++) {\n throwIfAborted(signal);\n const annotPtr = fn.FPDFPage_GetAnnot(pagePtr, i);\n if (!annotPtr) continue;\n\n try {\n const available = fn.EPDFAnnot_GetAvailableAppearanceModes(annotPtr);\n // Skip annotations without any /AP sub-dictionary. Mirrors v2.\n if (!available) continue;\n\n const identity = readAnnotationIdentity(fn, mem, annotPtr, pageObjectNumber, i, revision);\n // Rotation-stripped rendering (see AnnotationRender.ts) applies ONLY\n // where the rotation demonstrably lives in the AP Matrix: a BOX-family\n // kind carrying BOTH `/EMBD_Metadata` `/Rotation` and `/UnrotatedRect`.\n // There the raster renders flat, `rect` is the logical unrotated box,\n // and the DTO's `rotation` (same two fields, surfaced by the box\n // readers) is the consumer's view transform. Everything else — vertex\n // kinds (rotation pre-baked into their geometry), foreign PDFs with\n // arbitrary AP matrices — renders on the classic path, placed by\n // `/Rect`, bit-identical to before.\n // A free-text CALLOUT is excluded even with both fields present: only\n // its text box tilts, via an INLINE `cm` mid-stream (the leader stays\n // page-space), so the form `/Matrix` is identity — nothing to strip.\n const subtypeCode = fn.FPDFAnnot_GetSubtype(annotPtr);\n const isCallout =\n subtypeCode === ANNOT_SUBTYPE_FREETEXT &&\n freeTextIntentFromName(readIntent(fn, mem, annotPtr)) === 'free-text-callout';\n const stripRotation =\n BOX_FAMILY_SUBTYPES.has(subtypeCode) &&\n !isCallout &&\n readAnnotationRotation(fn, mem, annotPtr) !== undefined;\n const unrotatedRect = stripRotation\n ? readAnnotationUnrotatedRect(fn, mem, annotPtr)\n : undefined;\n // Normalize once at the read boundary — the wire `rect` and the render\n // matrix both rely on the normalized invariant.\n const rect = normalizePdfRect(unrotatedRect ?? readAnnotRect(fn, mem, annotPtr));\n\n for (const mode of modes) {\n if (!(available & mode.bit)) continue;\n const raster = this.renderOne(\n pagePtr,\n annotPtr,\n mode.modeInt,\n rect,\n page,\n rotation,\n scale,\n unrotatedRect !== undefined,\n options.maxOutputPixels,\n );\n if (!raster) continue;\n appearances.push({\n ref: identity.ref,\n mode: mode.name,\n rect,\n raster,\n });\n }\n } finally {\n fn.FPDFPage_CloseAnnot(annotPtr);\n }\n }\n\n return { pageState: this.session.pageState(pageObjectNumber), appearances };\n } finally {\n pool.release(pageObjectNumber);\n }\n }\n\n /**\n * Render a single annotation appearance into its own raster. Returns `null`\n * when the mode has no appearance stream (after an optional form-field AP\n * generation fallback) or the render fails.\n */\n private renderOne(\n pagePtr: Ptr,\n annotPtr: Ptr,\n modeInt: number,\n rect: PdfRect,\n page: { width: number; height: number },\n rotation: PdfRotation,\n scale: number,\n stripRotation: boolean,\n maxOutputPixels?: number,\n ): PageRaster | null {\n const { fn } = this.runtime;\n\n if (!fn.EPDFAnnot_HasAppearanceStream(annotPtr, modeInt)) {\n // Form widgets frequently ship without a baked /AP. Generate one on the\n // fly (same fallback as the v2 engine), then re-check.\n const subtype = fn.FPDFAnnot_GetSubtype(annotPtr);\n if (subtype === ANNOT_SUBTYPE_WIDGET && !fn.FPDFAnnot_HasKey(annotPtr, 'AP')) {\n fn.EPDFAnnot_GenerateFormFieldAP(annotPtr);\n if (!fn.EPDFAnnot_HasAppearanceStream(annotPtr, modeInt)) return null;\n } else {\n return null;\n }\n }\n\n // `rect` is already normalized at the read boundary; `rasterize` handles the\n // degenerate-rect / device-size / matrix / bitmap lifecycle. We supply only\n // the annotation draw (transparent background — appearances composite over\n // page content).\n return rasterize(this.runtime, {\n rect,\n page,\n rotation,\n viewport: { kind: 'scale', scale },\n ...(maxOutputPixels !== undefined ? { maxOutputPixels } : {}),\n background: 'transparent',\n // `stripRotation` (EmbedPDF box-kind rotation only): render the AP form\n // content WITHOUT its rotation Matrix, MatchRect-mapped to the unrotated\n // box — the consumer re-applies the DTO's `rotation` as a view transform.\n draw: (bitmapPtr, matrixPtr) =>\n (stripRotation ? fn.EPDF_RenderAnnotBitmapUnrotated : fn.EPDF_RenderAnnotBitmap)(\n bitmapPtr,\n pagePtr,\n annotPtr,\n modeInt,\n matrixPtr,\n FPDF_REVERSE_BYTE_ORDER,\n ),\n });\n }\n}\n\nfunction resolveModes(\n requested: AnnotationAppearanceMode[] | undefined,\n): ReadonlyArray<(typeof APPEARANCE_MODES)[number]> {\n if (!requested || requested.length === 0) {\n return APPEARANCE_MODES.filter((m) => m.name === 'normal');\n }\n const wanted = new Set(requested);\n return APPEARANCE_MODES.filter((m) => wanted.has(m.name));\n}\n\nfunction normalizeScale(scale: number | undefined): number {\n if (scale === undefined) return 1;\n if (!Number.isFinite(scale) || scale <= 0) return 1;\n return scale;\n}\n","import type {\n AnnotationListPageSnapshot,\n AnnotationListSnapshotAllPages,\n PageObjectNumber,\n} from '@embedpdf/engine-core/runtime';\nimport { EngineError, EngineErrorCode } from '@embedpdf/engine-core/runtime';\nimport type { PdfRuntimeModule } from '@embedpdf/engine-runtime';\n\nimport type { DocumentSession } from '../../document-session/DocumentSession';\nimport { throwIfAborted } from '../../shared/abort';\nimport { collectPageAnnotations } from './internal/read/collectPageAnnotations';\n\n/**\n * Whole-document and per-page raw read paths. Never acquires a pagePtr;\n * uses `EPDFPage_GetAnnotCountRaw` / `EPDFPage_GetAnnotRaw` /\n * `EPDFAnnot_GetObjectNumber` directly off the docPtr.\n *\n * Per-subtype dispatch is the same as the full reader (both share\n * `collectPageAnnotations`), so the wire shape `AnnotationDTO[]` is\n * identical between raw and full read paths for the subtypes that don't\n * actually need a pagePtr to materialise their fields.\n */\nexport class RawAnnotationReader {\n constructor(\n private readonly runtime: PdfRuntimeModule,\n private readonly session: DocumentSession,\n ) {}\n\n listAll(signal: AbortSignal): AnnotationListSnapshotAllPages {\n throwIfAborted(signal);\n this.session.ensureFullPageRegistry();\n const records = this.session.allRecords();\n const pages: AnnotationListPageSnapshot[] = [];\n for (const record of records) {\n throwIfAborted(signal);\n pages.push(this.listOne(record.pageObjectNumber, signal));\n }\n return { pages };\n }\n\n listOne(pageObjectNumber: PageObjectNumber, signal: AbortSignal): AnnotationListPageSnapshot {\n throwIfAborted(signal);\n const { fn } = this.runtime;\n const docPtr = this.session.requireDocPtr();\n const record = this.session.recordByObjectNumber(pageObjectNumber);\n\n const count = fn.EPDFPage_GetAnnotCountRaw(docPtr, record.pageIndex);\n if (count < 0) {\n throw new EngineError(\n EngineErrorCode.Unknown,\n `EPDFPage_GetAnnotCountRaw returned ${count} for page ${pageObjectNumber}`,\n );\n }\n\n return collectPageAnnotations({\n runtime: this.runtime,\n session: this.session,\n pageObjectNumber,\n count,\n getAnnotPtrAt: (i) => fn.EPDFPage_GetAnnotRaw(docPtr, record.pageIndex, i),\n signal,\n });\n }\n}\n","import {\n EngineError,\n EngineErrorCode,\n type AnnotationFlags,\n type Color,\n type InkList,\n type LineEndings,\n type LinePoints,\n type PdfPoint,\n type PdfRect,\n type PdfRectDifferences,\n} from '@embedpdf/engine-core/runtime';\nimport type { PdfFunctions, PdfRuntimeMemory, Ptr } from '@embedpdf/engine-runtime';\n\nimport { F32_BYTES, POINTF_BYTES, RECTF_BYTES } from '../../../../runtime/memory/structs';\nimport { flagsToBits } from '../annotationFlagBits';\nimport { FPDFANNOT_COLORTYPE } from '../colorType';\nimport { lineEndingToCode } from '../lineEnding';\n\n/**\n * Write-side twin of `annotationReadPrimitives.ts`. Every annotation\n * family (text-markup, shape, and upcoming polygon/polyline/line/free-text)\n * composes these low-level setters so the PDFium FFI surface lives in one\n * place. All colour/opacity/border writes go through the EmbedPDF\n * `EPDFAnnot_*` extensions — the same path v2 used and the read primitives\n * read back — so values survive native `EPDFAnnot_GenerateAppearance`.\n */\n\n/**\n * Set an annotation colour via the EmbedPDF `EPDFAnnot_SetColor`\n * extension. The `type` arg (FPDFANNOT_COLORTYPE) selects which colour to\n * write — `Color` is the stroke/fill `/C`, `InteriorColor` is the `/IC`\n * of square/circle/polygon. RGB only; annotation opacity lives in `/CA`\n * (see {@link setAnnotOpacity}), not a per-colour alpha. The stock\n * `FPDFAnnot_SetColor` cannot author interior colour, which is why we use\n * the extension uniformly.\n */\nexport function setAnnotColor(\n fn: PdfFunctions,\n annotPtr: Ptr,\n color: Color,\n type: number = FPDFANNOT_COLORTYPE.Color,\n): void {\n const ok = fn.EPDFAnnot_SetColor(annotPtr, type, color.r & 0xff, color.g & 0xff, color.b & 0xff);\n if (!ok) {\n throw new EngineError(EngineErrorCode.Unknown, 'EPDFAnnot_SetColor returned false');\n }\n}\n\n/**\n * Remove an annotation colour entry via `EPDFAnnot_ClearColor` (e.g. a\n * transparent fill clears `/IC`). A false return is benign — there was no\n * entry to clear — so we don't treat it as an error.\n */\nexport function clearAnnotColor(fn: PdfFunctions, annotPtr: Ptr, type: number): void {\n fn.EPDFAnnot_ClearColor(annotPtr, type);\n}\n\n/**\n * Set annotation opacity (`/CA`) via the dedicated `EPDFAnnot_SetOpacity`\n * extension. Input is 0..1; the native alpha is 0..255. This is the path\n * that stores `/CA` in the form native appearance generation expects, so\n * opacity survives the bake.\n */\nexport function setAnnotOpacity(fn: PdfFunctions, annotPtr: Ptr, opacity: number): void {\n const alpha = Math.max(0, Math.min(255, Math.round(opacity * 255)));\n if (!fn.EPDFAnnot_SetOpacity(annotPtr, alpha)) {\n throw new EngineError(EngineErrorCode.Unknown, 'EPDFAnnot_SetOpacity returned false');\n }\n}\n\n/**\n * Set the `/F` (Annotation Flags) entry via `FPDFAnnot_SetFlags`. Only the\n * keys present in `partial` are changed; the rest preserve their current\n * value (read back via `FPDFAnnot_GetFlags` first). On create the dict\n * starts at 0, so this is equivalently \"set exactly these\"; on update it\n * merges onto the live flags.\n */\nexport function setAnnotFlags(\n fn: PdfFunctions,\n annotPtr: Ptr,\n partial: Partial<AnnotationFlags>,\n): void {\n const next = flagsToBits(fn.FPDFAnnot_GetFlags(annotPtr), partial);\n if (!fn.FPDFAnnot_SetFlags(annotPtr, next)) {\n throw new EngineError(EngineErrorCode.Unknown, 'FPDFAnnot_SetFlags returned false');\n }\n}\n\n/**\n * Write `/Rect` via `FPDFAnnot_SetRect`. FS_RECTF layout is\n * `{ left, top, right, bottom }` (top > bottom in PDF coords).\n */\nexport function setAnnotRect(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n annotPtr: Ptr,\n rect: PdfRect,\n): void {\n const buf = mem.alloc(RECTF_BYTES);\n try {\n mem.poke(buf, 'f32', rect.left, 0);\n mem.poke(buf, 'f32', rect.top, 4);\n mem.poke(buf, 'f32', rect.right, 8);\n mem.poke(buf, 'f32', rect.bottom, 12);\n if (!fn.FPDFAnnot_SetRect(annotPtr, buf)) {\n throw new EngineError(EngineErrorCode.Unknown, 'FPDFAnnot_SetRect returned false');\n }\n } finally {\n mem.free(buf);\n }\n}\n\n/**\n * Set `/BS /S` (border style code) and `/BS /W` (width) in one call via\n * `EPDFAnnot_SetBorderStyle`. `styleCode` is a raw\n * `FPDF_ANNOT_BORDER_STYLE` enum value — the string<->code mapping lives\n * in `shapeBorderStyle.ts` so engine-core stays PDFium-free.\n */\nexport function setBorderStyle(\n fn: PdfFunctions,\n annotPtr: Ptr,\n styleCode: number,\n width: number,\n): void {\n if (!fn.EPDFAnnot_SetBorderStyle(annotPtr, styleCode, width)) {\n throw new EngineError(EngineErrorCode.Unknown, 'EPDFAnnot_SetBorderStyle returned false');\n }\n}\n\n/**\n * Write the dashed-border pattern (`/BS /D`) via\n * `EPDFAnnot_SetBorderDashPattern`. Each entry is clamped to >= 0.\n */\nexport function setBorderDashPattern(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n annotPtr: Ptr,\n dashArray: number[],\n): void {\n const buf = mem.alloc(dashArray.length * F32_BYTES);\n try {\n for (let i = 0; i < dashArray.length; i++) {\n mem.poke(buf, 'f32', Math.max(0, dashArray[i]!), i * F32_BYTES);\n }\n if (!fn.EPDFAnnot_SetBorderDashPattern(annotPtr, buf, dashArray.length)) {\n throw new EngineError(\n EngineErrorCode.Unknown,\n 'EPDFAnnot_SetBorderDashPattern returned false',\n );\n }\n } finally {\n mem.free(buf);\n }\n}\n\n/** Set the `/BE` cloudy border effect intensity. */\nexport function setBorderEffect(fn: PdfFunctions, annotPtr: Ptr, intensity: number): void {\n if (!fn.EPDFAnnot_SetBorderEffect(annotPtr, intensity)) {\n throw new EngineError(EngineErrorCode.Unknown, 'EPDFAnnot_SetBorderEffect returned false');\n }\n}\n\n/**\n * Remove the `/BE` cloudy border effect. A false return is benign (there\n * was no effect to clear), so we don't treat it as an error.\n */\nexport function clearBorderEffect(fn: PdfFunctions, annotPtr: Ptr): void {\n fn.EPDFAnnot_ClearBorderEffect(annotPtr);\n}\n\n/**\n * Write `/RD` rectangle differences via\n * `EPDFAnnot_SetRectangleDifferences`. PDFium core stores `/RD` as\n * `[left, bottom, right, top]`; we accept the wire-stable\n * `{ left, top, right, bottom }` shape and reorder at the boundary.\n */\nexport function setRectangleDifferences(\n fn: PdfFunctions,\n annotPtr: Ptr,\n rd: PdfRectDifferences,\n): void {\n if (!fn.EPDFAnnot_SetRectangleDifferences(annotPtr, rd.left, rd.bottom, rd.right, rd.top)) {\n throw new EngineError(\n EngineErrorCode.Unknown,\n 'EPDFAnnot_SetRectangleDifferences returned false',\n );\n }\n}\n\n/**\n * Remove the `/RD` rectangle-differences entry. A false return is benign\n * (there was no entry to clear), so we don't treat it as an error.\n */\nexport function clearRectangleDifferences(fn: PdfFunctions, annotPtr: Ptr): void {\n fn.EPDFAnnot_ClearRectangleDifferences(annotPtr);\n}\n\n/**\n * Replace the `/Vertices` point list of a polygon/polyline annotation via\n * the EmbedPDF `EPDFAnnot_SetVertices` extension. Writes the points into a\n * contiguous `count * FS_POINTF` buffer.\n */\nexport function setVertices(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n annotPtr: Ptr,\n vertices: PdfPoint[],\n): void {\n const buf = mem.alloc(vertices.length * POINTF_BYTES);\n try {\n for (let i = 0; i < vertices.length; i++) {\n const off = i * POINTF_BYTES;\n mem.poke(buf, 'f32', vertices[i]!.x, off);\n mem.poke(buf, 'f32', vertices[i]!.y, off + 4);\n }\n if (!fn.EPDFAnnot_SetVertices(annotPtr, buf, vertices.length)) {\n throw new EngineError(EngineErrorCode.Unknown, 'EPDFAnnot_SetVertices returned false');\n }\n } finally {\n mem.free(buf);\n }\n}\n\n/**\n * Write the `/L` endpoints of a line annotation via the EmbedPDF\n * `EPDFAnnot_SetLine` extension. Uses one 16-byte buffer holding two\n * `FS_POINTF` structs (start at offset 0, end at offset 8).\n */\nexport function setLine(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n annotPtr: Ptr,\n line: LinePoints,\n): void {\n const start = mem.alloc(POINTF_BYTES);\n const end = mem.alloc(POINTF_BYTES);\n try {\n mem.poke(start, 'f32', line.start.x, 0);\n mem.poke(start, 'f32', line.start.y, 4);\n mem.poke(end, 'f32', line.end.x, 0);\n mem.poke(end, 'f32', line.end.y, 4);\n if (!fn.EPDFAnnot_SetLine(annotPtr, start, end)) {\n throw new EngineError(EngineErrorCode.Unknown, 'EPDFAnnot_SetLine returned false');\n }\n } finally {\n mem.free(start);\n mem.free(end);\n }\n}\n\n/**\n * Replace the `/InkList` of an ink annotation. PDFium has no single\n * \"set ink list\" call, so we clear any existing list with\n * `FPDFAnnot_RemoveInkList` (a false return is benign on a freshly-created\n * annotation that has none) and re-add each non-empty stroke via\n * `FPDFAnnot_AddInkStroke`, which takes a contiguous `count * FS_POINTF`\n * buffer and returns the new stroke index (`< 0` on failure).\n */\nexport function setInkList(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n annotPtr: Ptr,\n inkList: InkList,\n): void {\n fn.FPDFAnnot_RemoveInkList(annotPtr);\n for (const stroke of inkList) {\n if (stroke.length === 0) continue;\n const buf = mem.alloc(stroke.length * POINTF_BYTES);\n try {\n for (let i = 0; i < stroke.length; i++) {\n const off = i * POINTF_BYTES;\n mem.poke(buf, 'f32', stroke[i]!.x, off);\n mem.poke(buf, 'f32', stroke[i]!.y, off + 4);\n }\n if (fn.FPDFAnnot_AddInkStroke(annotPtr, buf, stroke.length) < 0) {\n throw new EngineError(EngineErrorCode.Unknown, 'FPDFAnnot_AddInkStroke returned < 0');\n }\n } finally {\n mem.free(buf);\n }\n }\n}\n\n/**\n * Write the `/LE` line endings of a line/polyline annotation via the\n * EmbedPDF `EPDFAnnot_SetLineEndings` extension. The string<->code mapping\n * lives in `lineEnding.ts` so engine-core stays PDFium-free.\n */\nexport function setLineEndings(fn: PdfFunctions, annotPtr: Ptr, endings: LineEndings): void {\n if (\n !fn.EPDFAnnot_SetLineEndings(\n annotPtr,\n lineEndingToCode(endings.start),\n lineEndingToCode(endings.end),\n )\n ) {\n throw new EngineError(EngineErrorCode.Unknown, 'EPDFAnnot_SetLineEndings returned false');\n }\n}\n\n/**\n * Write the `/DA` default appearance (font + size + colour) of a free-text\n * annotation via `EPDFAnnot_SetDefaultAppearance`. The `/DA` colour paints\n * the border and the default text colour; a separate `TextColor` entry (see\n * {@link setAnnotColor}) overrides the text only. `fontCode` is the raw\n * `FPDF_STANDARD_FONT` enum value — the string<->code mapping lives in\n * `standardFont.ts` so engine-core stays PDFium-free.\n */\nexport function setDefaultAppearance(\n fn: PdfFunctions,\n annotPtr: Ptr,\n fontCode: number,\n fontSize: number,\n color: Color,\n): void {\n if (\n !fn.EPDFAnnot_SetDefaultAppearance(\n annotPtr,\n fontCode,\n fontSize,\n color.r & 0xff,\n color.g & 0xff,\n color.b & 0xff,\n )\n ) {\n throw new EngineError(EngineErrorCode.Unknown, 'EPDFAnnot_SetDefaultAppearance returned false');\n }\n}\n\n/**\n * Write the `/DA` default appearance using a runtime font registered through\n * `engine.fonts` (via `EPDFAnnot_SetDefaultAppearanceRegisteredFont`). `fontId`\n * is the thread-local `CFX_FontRegistry::FontId` resolved from the stable\n * `registeredFontKey` at authoring time. The font's glyph subset is embedded\n * into the annotation's appearance stream when the document/layer is saved.\n */\nexport function setDefaultAppearanceRegisteredFont(\n fn: PdfFunctions,\n annotPtr: Ptr,\n fontId: number,\n fontSize: number,\n color: Color,\n): void {\n if (\n !fn.EPDFAnnot_SetDefaultAppearanceRegisteredFont(\n annotPtr,\n fontId,\n fontSize,\n color.r & 0xff,\n color.g & 0xff,\n color.b & 0xff,\n )\n ) {\n throw new EngineError(\n EngineErrorCode.Unknown,\n 'EPDFAnnot_SetDefaultAppearanceRegisteredFont returned false',\n );\n }\n}\n\n/**\n * Write the `/Q` text alignment of a free-text annotation via\n * `EPDFAnnot_SetTextAlignment`. `code` is the raw quadding value — the\n * string<->code mapping lives in `textAlignment.ts`.\n */\nexport function setTextAlignment(fn: PdfFunctions, annotPtr: Ptr, code: number): void {\n if (!fn.EPDFAnnot_SetTextAlignment(annotPtr, code)) {\n throw new EngineError(EngineErrorCode.Unknown, 'EPDFAnnot_SetTextAlignment returned false');\n }\n}\n\n/**\n * Write the `/IT` intent name via `EPDFAnnot_SetIntent` (expects a UTF-8\n * bytestring without the leading slash, e.g. `'FreeTextCallout'`). The\n * string<->name mapping lives in `freeTextIntent.ts`.\n */\nexport function setIntent(fn: PdfFunctions, annotPtr: Ptr, name: string): void {\n if (!fn.EPDFAnnot_SetIntent(annotPtr, name)) {\n throw new EngineError(EngineErrorCode.Unknown, 'EPDFAnnot_SetIntent returned false');\n }\n}\n\n/**\n * Write the `/CL` callout leader line of a free-text callout via\n * `EPDFAnnot_SetCalloutLine`. Accepts 2 points (straight leader) or 3\n * (knee-jointed); writes them into a contiguous `count * FS_POINTF` buffer\n * (like {@link setVertices}).\n */\n/**\n * Write `/OverlayText` of a redact annotation via `EPDFAnnot_SetOverlayText`.\n * The native setter removes the key for an empty string, so passing `''`\n * clears the label.\n */\nexport function setOverlayText(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n annotPtr: Ptr,\n text: string,\n): void {\n const ptr = mem.writeU16String(text);\n try {\n if (!fn.EPDFAnnot_SetOverlayText(annotPtr, ptr)) {\n throw new EngineError(EngineErrorCode.Unknown, 'EPDFAnnot_SetOverlayText returned false');\n }\n } finally {\n mem.free(ptr);\n }\n}\n\n/**\n * Write `/Repeat` of a redact annotation via `EPDFAnnot_SetOverlayTextRepeat`\n * (`false` removes the key — absent is the PDF default).\n */\nexport function setOverlayTextRepeat(fn: PdfFunctions, annotPtr: Ptr, repeat: boolean): void {\n if (!fn.EPDFAnnot_SetOverlayTextRepeat(annotPtr, repeat)) {\n throw new EngineError(EngineErrorCode.Unknown, 'EPDFAnnot_SetOverlayTextRepeat returned false');\n }\n}\n\nexport function setCalloutLine(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n annotPtr: Ptr,\n points: readonly PdfPoint[],\n): void {\n const buf = mem.alloc(points.length * POINTF_BYTES);\n try {\n for (let i = 0; i < points.length; i++) {\n const off = i * POINTF_BYTES;\n mem.poke(buf, 'f32', points[i]!.x, off);\n mem.poke(buf, 'f32', points[i]!.y, off + 4);\n }\n if (!fn.EPDFAnnot_SetCalloutLine(annotPtr, buf, points.length)) {\n throw new EngineError(EngineErrorCode.Unknown, 'EPDFAnnot_SetCalloutLine returned false');\n }\n } finally {\n mem.free(buf);\n }\n}\n","import type { AnnotationDraftBase, AnnotationPatchBase } from '@embedpdf/engine-core/runtime';\nimport type { PdfFunctions, PdfRuntimeMemory, Ptr } from '@embedpdf/engine-runtime';\nimport { NULL_PTR } from '@embedpdf/engine-runtime';\n\nimport { setAnnotFlags } from './annotationWritePrimitives';\nimport { formatPdfDate } from '../../../../shared/pdf-date';\n\n/**\n * Write the annotation-wide base fields shared by every Draft\n * (contents/nm). The kind-specific writer calls this BEFORE its own\n * field writes; order doesn't actually matter at the PDF level, but\n * keeping the base first makes the writers symmetric with the readers.\n *\n * `/T` (author display) is stamped by the mutator from\n * `AnnotationActor.displayName` via {@link writeAnnotationAuthor}.\n *\n * `nm` is written verbatim if the caller supplied one. The mutator\n * decides whether to opportunistically stamp a UUID v4 on a weak\n * annotation; the writer does not.\n */\nexport function applyAnnotationBaseDraft(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n annotPtr: Ptr,\n draft: AnnotationDraftBase,\n): void {\n if (draft.contents !== undefined) {\n writeStringOrClear(fn, mem, annotPtr, 'Contents', draft.contents);\n }\n if (draft.nm !== undefined && draft.nm.length > 0) {\n writeString(fn, mem, annotPtr, 'NM', draft.nm);\n }\n if (draft.flags !== undefined) {\n setAnnotFlags(fn, annotPtr, draft.flags);\n }\n}\n\n/**\n * Write the annotation-wide base fields shared by every Patch\n * (contents). /T is bound at creation and not patchable — see\n * `AnnotationPatchBase`. /NM is monotonic per annotation; the mutator\n * may stamp /NM opportunistically on a weak annotation via\n * `writeAnnotationNm`.\n *\n * Three-state semantics on string|null fields:\n * undefined -> don't touch the dict\n * null -> remove the entry\n * \"...\" -> set the entry to that value\n */\nexport function applyAnnotationBasePatch(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n annotPtr: Ptr,\n patch: AnnotationPatchBase,\n): void {\n if (patch.contents !== undefined) {\n writeStringOrClear(fn, mem, annotPtr, 'Contents', patch.contents);\n }\n if (patch.flags !== undefined) {\n setAnnotFlags(fn, annotPtr, patch.flags);\n }\n}\n\n/**\n * Stamp /T (the standard PDF \"author\" display field) on an annotation.\n * Called by the mutator on CREATE — /T is bound to the caller's\n * `display_name` at creation. No-op when `displayName` is empty so\n * callers don't need to gate it.\n */\nexport function writeAnnotationAuthor(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n annotPtr: Ptr,\n displayName: string,\n): void {\n if (displayName.length === 0) return;\n writeString(fn, mem, annotPtr, 'T', displayName);\n}\n\n/**\n * Stamp /NM on an annotation that didn't have one. Used by the mutator\n * (not by the writers proper) to upgrade a weak annotation to durable\n * identity during update. Idempotent and silent if the value is empty.\n */\nexport function writeAnnotationNm(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n annotPtr: Ptr,\n nm: string,\n): void {\n if (nm.length === 0) return;\n writeString(fn, mem, annotPtr, 'NM', nm);\n}\n\n/**\n * Stamp /M (modification date) on an annotation. /M is a standard\n * ISO 32000 base annotation field — the moment of the last edit — so\n * it lives here alongside /T / /NM / /Contents rather than in any\n * vendor-namespaced extension.\n *\n * Called by the mutator on every annotation create AND every update;\n * the existing base draft/patch writers leave /M alone because the\n * value is derived from the moment of the write, not from the\n * draft/patch payload. The base reader already extracts /M and\n * surfaces it on `AnnotationBase.modified`.\n *\n * Format: `D:YYYYMMDDHHmmSSOHH'mm'` (see formatPdfDate).\n */\nexport function writeAnnotationModified(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n annotPtr: Ptr,\n now: Date = new Date(),\n): void {\n writeString(fn, mem, annotPtr, 'M', formatPdfDate(now));\n}\n\nfunction writeString(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n annotPtr: Ptr,\n key: string,\n value: string,\n): void {\n const ptr = mem.writeU16String(value);\n try {\n fn.FPDFAnnot_SetStringValue(annotPtr, key, ptr);\n } finally {\n mem.free(ptr);\n }\n}\n\nfunction writeStringOrClear(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n annotPtr: Ptr,\n key: string,\n value: string | null,\n): void {\n if (value === null) {\n // PDFium accepts a NULL string-value pointer as \"clear the entry\".\n fn.FPDFAnnot_SetStringValue(annotPtr, key, NULL_PTR);\n return;\n }\n writeString(fn, mem, annotPtr, key, value);\n}\n","import type { AnnotationStableId } from '@embedpdf/engine-core/runtime';\nimport type { PdfRuntimeModule, Ptr } from '@embedpdf/engine-runtime';\n\nimport { generateUuid } from '../../../../shared/uuid';\nimport { readAnnotString } from '../read/annotationReadPrimitives';\nimport { writeAnnotationNm } from '../write/writeAnnotationBase';\n\n/**\n * Read an annotation's stable id, opportunistically stamping a fresh\n * engine-generated UUID v4 as `/NM` if it is currently weak (no object\n * number, no `/NM`). Monotonic `/NM` rule: an already-durable annotation\n * is NEVER touched. Caller owns the lifecycle of `annotPtr`.\n *\n * Shared by the create/update/move mutator paths and the `/IRT`\n * relationship writer (which strengthens a weak parent before linking to\n * it, so the strengthened id can be reported in `meta.changed`).\n */\nexport function captureOrStampStableId(\n runtime: PdfRuntimeModule,\n annotPtr: Ptr,\n): AnnotationStableId {\n const { fn, mem } = runtime;\n const objNum = fn.EPDFAnnot_GetObjectNumber(annotPtr);\n if (objNum > 0) return { kind: 'objectNumber', value: objNum };\n const nm = readAnnotString(fn, mem, annotPtr, 'NM');\n if (nm !== null && nm.length > 0) return { kind: 'nm', value: nm };\n const minted = generateUuid();\n writeAnnotationNm(fn, mem, annotPtr, minted);\n return { kind: 'nm', value: minted };\n}\n","import type { AnnotationRef } from '@embedpdf/engine-core/runtime';\nimport { EngineError, EngineErrorCode } from '@embedpdf/engine-core/runtime';\nimport type { PdfRuntimeModule, Ptr } from '@embedpdf/engine-runtime';\n\nimport type { DocumentSession } from '../../../../document-session/DocumentSession';\n\n/**\n * Resolve an `AnnotationRef` to a live `annotPtr` on an ALREADY-acquired\n * `pagePtr`. This does NOT acquire/release the page and does NOT close the\n * returned annot — the caller owns both lifetimes.\n *\n * Resolution order matches the wire spec:\n * 1. `objectNumber` -> `EPDFPage_GetAnnotByObjectNumber`\n * 2. `nm` -> `EPDFPage_GetAnnotByName`\n * 3. `index` -> revision validation, then `FPDFPage_GetAnnot`\n *\n * Surfaces `InvalidReference` deterministically when the ref doesn't\n * resolve, so mutation paths can fail fast before doing any work.\n */\nexport function resolveAnnotPtr(\n runtime: PdfRuntimeModule,\n session: DocumentSession,\n pagePtr: Ptr,\n ref: AnnotationRef,\n): Ptr {\n const { fn, mem } = runtime;\n switch (ref.kind) {\n case 'objectNumber': {\n const annotPtr = fn.EPDFPage_GetAnnotByObjectNumber(pagePtr, ref.annotObjectNumber);\n if (!annotPtr) {\n throw new EngineError(\n EngineErrorCode.InvalidReference,\n `no annotation with object number ${ref.annotObjectNumber} on page ${ref.pageObjectNumber}`,\n );\n }\n return annotPtr;\n }\n case 'nm': {\n const namePtr = mem.writeU16String(ref.nm);\n try {\n const annotPtr = fn.EPDFPage_GetAnnotByName(pagePtr, namePtr);\n if (!annotPtr) {\n throw new EngineError(\n EngineErrorCode.InvalidReference,\n `no annotation with /NM '${ref.nm}' on page ${ref.pageObjectNumber}`,\n );\n }\n return annotPtr;\n } finally {\n mem.free(namePtr);\n }\n }\n case 'index': {\n session.validateRevision(ref.revision);\n const annotPtr = fn.FPDFPage_GetAnnot(pagePtr, ref.index);\n if (!annotPtr) {\n throw new EngineError(\n EngineErrorCode.InvalidReference,\n `index ${ref.index} out of range on page ${ref.pageObjectNumber}`,\n );\n }\n return annotPtr;\n }\n }\n throw new EngineError(EngineErrorCode.InvalidArg, `unsupported annotation ref kind`);\n}\n","import type {\n AnnotationListMutationMeta,\n AnnotationStableId,\n PageState,\n} from '@embedpdf/engine-core/runtime';\nimport {\n invalidatesWeakIndexRefs,\n shiftsExistingAnnotationIndices,\n type AnnotationMutationKind,\n} from '@embedpdf/engine-core/runtime';\n\n/**\n * The kind of mutation that just happened on a page.\n *\n * Index-space behaviour drives whether weak (`kind: 'index'`) refs\n * the client may be holding stay valid:\n *\n * - `update` does not touch the /Annots array at all.\n * - `create` is append-only — the new annotation lands at\n * `index = previousCount`, so no existing index ever shifts.\n * The array grows, but every pre-existing weak ref still points\n * at the same physical annotation.\n * - `delete` removes an entry and shifts every later index down by\n * one. Pre-existing weak refs at or after the removed index are\n * now off-by-one and stale.\n * - `move` detaches a contiguous block and re-inserts it, rewriting\n * indices on both ends of the gap. Existing weak refs across that\n * range are stale.\n *\n * So the doctrine for `MutationKind` is: only `delete` and `move`\n * actually invalidate weak refs. `update` and `create` leave them\n * alone. (A future explicit-position `createAt(index)` API would\n * shift indices >= toIndex and would join the structural cohort —\n * see `MutationKind` extension note in `compute()` below.)\n */\nexport type MutationKind = AnnotationMutationKind;\n\n/**\n * Inputs that decide whether a mutation should make a client refetch.\n *\n * `pageStateBefore` is captured BEFORE the mutation. Its known\n * `weakAnnotationState` drives the locked rule:\n * index-shifting mutation × any weak annotation on the page ⇒ refetch.\n *\n * `pageStateAfter` is captured AFTER the mutation. It carries the\n * bumped revision token (for index-shifting ops) and the recomputed\n * weak-annotation state (for any op that might have changed it, e.g.\n * opportunistic /NM stamping during update).\n *\n * `changed` is the list of stable ids the mutation actually touched.\n * Empty for a weak delete (we have no durable id to report).\n */\nexport interface ImpactInputs {\n mutation: MutationKind;\n pageStateBefore: PageState;\n pageStateAfter: PageState;\n changed: AnnotationStableId[];\n}\n\n/**\n * Pure helper: turn a mutation outcome into the side-effect envelope\n * every result type carries on its `meta` field.\n *\n * The rules — locked with the user, do not change without re-reading\n * the doc comment on `AnnotationListMutationMeta` and the\n * `MutationKind` definition above:\n *\n * 1. `update` and `create` are non-invalidating.\n *\n * - `update` doesn't touch the /Annots array; indices on the page\n * do not move, so weak refs the client may be holding stay\n * valid. Opportunistic /NM stamping during an update is also\n * non-structural — it changes the annotation's identity quality\n * but not its position.\n *\n * - `create` is append-only. The new annotation goes at\n * `index = previousCount`, so no existing index shifts and no\n * pre-existing weak ref ever becomes stale. We treat `create`\n * the same as `update` for impact purposes: no revision bump,\n * `weakRefsInvalidated = false`, `shouldRefetch = null`.\n *\n * The \"revisions exist solely for weak-ref authentication\"\n * doctrine (see `pages.move()`'s identical reasoning) means we\n * deliberately do NOT bump on `create` — bumping a revision\n * that nobody's weak ref depends on would erode the invariant\n * and turn revisions into a generic \"something changed\" signal.\n *\n * 2. `delete` and `move` ARE index-shifting. They genuinely move\n * pre-existing indices:\n * - `delete` removes an annotation, shifting every later index\n * down by one.\n * - `move` detaches a contiguous block and re-inserts it\n * elsewhere, rewriting indices on both ends of the gap.\n * They invalidate weak refs iff the page actually had any weak\n * refs *before* the mutation — if every annotation already had a\n * durable identity, no client could possibly be holding a stale\n * index, and we keep `shouldRefetch = null`.\n *\n * (`move` opportunistically stamps /NM on weak refs in the batch\n * BEFORE the move, so the annotations actually being moved end up\n * durable on the way out; but other weak annotations on the page\n * still need a refetch.)\n *\n * 3. When rule (2) fires, the reason is always `'weakRefsInvalidated'`.\n * `'pageRebuilt'` and `'externalChange'` are reserved for higher-\n * level signals the engine doesn't emit yet (insert/delete-page\n * that rebuilds /Annots, watch-based refresh). Page **reorder**\n * explicitly does NOT bump per-page revisions and does NOT emit\n * `pageRebuilt` — see `PagesMutator`.\n *\n * Future note: when an explicit-position `createAt(index)` API\n * ships, add `'createAt'` to `MutationKind` and slot it into rule\n * (2) — it shifts every index >= toIndex and is structural in the\n * same way `delete` and `move` are.\n */\nexport function computeMutationImpact(inputs: ImpactInputs): AnnotationListMutationMeta {\n const { mutation, pageStateBefore, pageStateAfter, changed } = inputs;\n\n if (!shiftsExistingAnnotationIndices(mutation)) {\n return {\n affectedPages: [pageStateAfter],\n cacheDelta: null,\n changed,\n weakRefsInvalidated: false,\n shouldRefetch: null,\n };\n }\n\n // delete / move: index-shifting.\n const weakRefsInvalidated = invalidatesWeakIndexRefs(\n mutation,\n pageStateBefore.weakAnnotationState,\n );\n return {\n affectedPages: [pageStateAfter],\n cacheDelta: null,\n changed,\n weakRefsInvalidated,\n shouldRefetch: weakRefsInvalidated ? { reason: 'weakRefsInvalidated' } : null,\n };\n}\n","import type { AnnotationDTO, PageObjectNumber, RevisionToken } from '@embedpdf/engine-core/runtime';\nimport type { PdfFunctions, PdfRuntimeMemory, Ptr } from '@embedpdf/engine-runtime';\n\nimport type { AnnotationReadContext } from './annotationReadContext';\nimport { pickReader } from './annotationReaderRegistry';\nimport { readAnnotationBase } from './readAnnotationBase';\n\n/**\n * Materialise a single annotation DTO from a live `annotPtr`, reusing the\n * exact same code paths the list readers use. Caller owns the lifecycle of\n * `annotPtr` (this function does NOT close it) so the mutator can keep it\n * for follow-up writes.\n *\n * Used by:\n * - `AnnotationMutator.create()` after `EPDFPage_CreateAnnot` to\n * produce `AnnotationCreateResult.created`.\n * - `AnnotationMutator.update()` after writes complete to produce\n * `AnnotationUpdateResult.updated`.\n */\nexport function readAnnotationFromPtr(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n annotPtr: Ptr,\n pageObjectNumber: PageObjectNumber,\n index: number,\n revision: RevisionToken,\n ctx: AnnotationReadContext,\n): AnnotationDTO {\n const base = readAnnotationBase(fn, mem, annotPtr, pageObjectNumber, index, revision);\n const subtypeCode = fn.FPDFAnnot_GetSubtype(annotPtr);\n const { reader } = pickReader(subtypeCode);\n return reader(fn, mem, annotPtr, base, subtypeCode, ctx);\n}\n","import type { CaretDraft, CaretPatch, Color } from '@embedpdf/engine-core/runtime';\nimport type { PdfFunctions, PdfRuntimeMemory, Ptr } from '@embedpdf/engine-runtime';\n\nimport {\n clearRectangleDifferences,\n setAnnotColor,\n setAnnotOpacity,\n setAnnotRect,\n setIntent,\n setRectangleDifferences,\n} from './annotationWritePrimitives';\nimport { applyAnnotationBaseDraft, applyAnnotationBasePatch } from './writeAnnotationBase';\nimport { caretIntentToName } from '../textEditIntent';\n\n/** Default `/C` colour when a caret draft omits it (engine-wide default mark). */\nconst DEFAULT_CARET_COLOR: Color = { r: 255, g: 0, b: 0 };\n\n/** Default opacity, set explicitly so reads always round-trip the same value. */\nconst DEFAULT_OPACITY = 1;\n\n/**\n * Apply a caret draft to a freshly-created annotation. Caret carries no\n * geometry of its own beyond `/Rect`. Order:\n * 1. base author-metadata (contents/nm/flags)\n * 2. `/Rect` (required — supplied by the caller; never derived)\n * 3. `/C` color + `/CA` opacity\n * 4. `/RD` rectangle differences (optional)\n */\nexport function applyCaretDraft(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n annotPtr: Ptr,\n draft: CaretDraft,\n): void {\n applyAnnotationBaseDraft(fn, mem, annotPtr, draft);\n setAnnotRect(fn, mem, annotPtr, draft.rect);\n setAnnotColor(fn, annotPtr, draft.color ?? DEFAULT_CARET_COLOR);\n setAnnotOpacity(fn, annotPtr, draft.opacity ?? DEFAULT_OPACITY);\n if (draft.intent !== undefined) setIntent(fn, annotPtr, caretIntentToName(draft.intent));\n if (draft.rectDifferences != null) {\n setRectangleDifferences(fn, annotPtr, draft.rectDifferences);\n }\n}\n\n/**\n * Apply a caret patch to an existing annotation. Only present fields are\n * touched.\n */\nexport function applyCaretPatch(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n annotPtr: Ptr,\n patch: CaretPatch,\n): void {\n applyAnnotationBasePatch(fn, mem, annotPtr, patch);\n if (patch.rect !== undefined) {\n setAnnotRect(fn, mem, annotPtr, patch.rect);\n }\n if (patch.color !== undefined) {\n setAnnotColor(fn, annotPtr, patch.color);\n }\n if (patch.opacity !== undefined) {\n setAnnotOpacity(fn, annotPtr, patch.opacity);\n }\n if (patch.intent !== undefined) {\n setIntent(fn, annotPtr, caretIntentToName(patch.intent));\n }\n if (patch.rectDifferences === null) {\n clearRectangleDifferences(fn, annotPtr);\n } else if (patch.rectDifferences !== undefined) {\n setRectangleDifferences(fn, annotPtr, patch.rectDifferences);\n }\n}\n\n/**\n * Type-narrowing predicate used by the writer registry to pick the caret\n * writer for a draft/patch's `subtype`.\n */\nexport function isCaretSubtype(subtype: string): subtype is 'caret' {\n return subtype === 'caret';\n}\n","import type {\n Color,\n FileAttachmentPatch,\n FileAttachmentWireDraft,\n WireAttachmentFile,\n WireResource,\n} from '@embedpdf/engine-core/runtime';\nimport { EngineError, EngineErrorCode } from '@embedpdf/engine-core/runtime';\nimport type { PdfFunctions, PdfRuntimeMemory, Ptr } from '@embedpdf/engine-runtime';\n\nimport { writeAttachmentFilePayload } from '../../../attachments/internal/attachmentPrimitives';\nimport { FILE_ICON_TO_CODE } from '../annotationIcon';\nimport type { AnnotationWriteContext } from './annotationWriteContext';\nimport { setAnnotColor, setAnnotOpacity, setAnnotRect } from './annotationWritePrimitives';\nimport { applyAnnotationBaseDraft, applyAnnotationBasePatch } from './writeAnnotationBase';\n\n/** Default `/C` — the generator's default icon fill, set explicitly so reads round-trip. */\nconst DEFAULT_FILE_ATTACHMENT_COLOR: Color = { r: 255, g: 255, b: 0 };\n\nconst DEFAULT_OPACITY = 1;\n\n/**\n * Validate a file-attachment draft before any native write: the wire\n * `file.resource` ref must have arrived with the mutation. No format\n * sniffing — unlike stamps, ANY bytes are a valid attachment.\n */\nexport function preflightFileAttachmentDraft(\n draft: FileAttachmentWireDraft,\n ctx: AnnotationWriteContext | undefined,\n): void {\n requireFileResource(draft.file, ctx);\n if (ctx?.docPtr === undefined) {\n throw new EngineError(\n EngineErrorCode.Unknown,\n 'file-attachment writer requires docPtr on the write context',\n );\n }\n}\n\n/**\n * Apply a file-attachment draft. Order:\n * 1. base author-metadata (contents/nm/flags)\n * 2. `/Rect` + `/C` + `/CA` + `/Name` icon\n * 3. the embedded file: `/FS` filespec via `FPDFAnnot_AddFileAttachment`,\n * bytes via `FPDFAttachment_SetFile` (which also writes `/Params`\n * Size/CheckSum/CreationDate), declared mime via\n * `EPDFAttachment_SetSubtype`, optional `/Desc`.\n *\n * The icon appearance itself is generator-owned: the mutator's closing\n * `regenerateAppearance` bakes it from `/C` + `/Name`\n * (GenerateFileAttachmentAP), exactly like the text note.\n */\nexport function applyFileAttachmentDraft(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n annotPtr: Ptr,\n draft: FileAttachmentWireDraft,\n ctx: AnnotationWriteContext | undefined,\n): void {\n applyAnnotationBaseDraft(fn, mem, annotPtr, draft);\n setAnnotRect(fn, mem, annotPtr, draft.rect);\n setAnnotColor(fn, annotPtr, draft.color ?? DEFAULT_FILE_ATTACHMENT_COLOR);\n setAnnotOpacity(fn, annotPtr, draft.opacity ?? DEFAULT_OPACITY);\n setFileAttachmentIcon(fn, annotPtr, draft.icon ?? 'paperclip');\n attachFile(fn, mem, annotPtr, draft.file, requireFileResource(draft.file, ctx), ctx!.docPtr!);\n}\n\n/** Patch: presentation only — the attached file is create-only by design. */\nexport function applyFileAttachmentPatch(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n annotPtr: Ptr,\n patch: FileAttachmentPatch,\n): void {\n applyAnnotationBasePatch(fn, mem, annotPtr, patch);\n if (patch.rect !== undefined) {\n setAnnotRect(fn, mem, annotPtr, patch.rect);\n }\n if (patch.color !== undefined) {\n setAnnotColor(fn, annotPtr, patch.color);\n }\n if (patch.opacity !== undefined) {\n setAnnotOpacity(fn, annotPtr, patch.opacity);\n }\n if (patch.icon !== undefined) {\n setFileAttachmentIcon(fn, annotPtr, patch.icon);\n }\n}\n\nexport function isFileAttachmentSubtype(subtype: string): subtype is 'file-attachment' {\n return subtype === 'file-attachment';\n}\n\nfunction setFileAttachmentIcon(\n fn: PdfFunctions,\n annotPtr: Ptr,\n icon: keyof typeof FILE_ICON_TO_CODE,\n): void {\n if (!fn.EPDFAnnot_SetName(annotPtr, FILE_ICON_TO_CODE[icon])) {\n throw new EngineError(EngineErrorCode.Unknown, 'EPDFAnnot_SetName returned false');\n }\n}\n\nfunction requireFileResource(\n file: WireAttachmentFile,\n ctx: AnnotationWriteContext | undefined,\n): WireResource {\n const resource = ctx?.resources?.[file.resource];\n if (!resource) {\n throw new EngineError(\n EngineErrorCode.InvalidArg,\n `attachment file references resource '${file.resource}' but no such binary payload accompanied the mutation`,\n );\n }\n return resource;\n}\n\nfunction attachFile(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n annotPtr: Ptr,\n file: WireAttachmentFile,\n resource: WireResource,\n docPtr: Ptr,\n): void {\n const namePtr = mem.writeU16String(file.name);\n let attachmentPtr: Ptr;\n try {\n attachmentPtr = fn.FPDFAnnot_AddFileAttachment(annotPtr, namePtr);\n } finally {\n mem.free(namePtr);\n }\n if (!attachmentPtr) {\n throw new EngineError(EngineErrorCode.Unknown, 'FPDFAnnot_AddFileAttachment returned NULL');\n }\n\n writeAttachmentFilePayload(fn, mem, attachmentPtr, docPtr, file, resource);\n}\n","import {\n EngineError,\n EngineErrorCode,\n type Color,\n type FreeTextFont,\n} from '@embedpdf/engine-core/runtime';\nimport type { PdfFunctions, Ptr } from '@embedpdf/engine-runtime';\n\nimport { isStandardFont, standardFontToCode } from '../standardFont';\nimport type { AnnotationWriteContext } from './annotationWriteContext';\nimport {\n setDefaultAppearance,\n setDefaultAppearanceRegisteredFont,\n} from './annotationWritePrimitives';\n\n/**\n * Write `/DA`. A standard font name goes through the native standard-font\n * path; anything else is treated as a registered-font `key` and resolved to\n * this thread's FontId. A key with no resolver wired (e.g. a host without a\n * font registry) is a programming error — fail loud rather than silently\n * downgrade to Helvetica and embed the wrong glyphs.\n *\n * Shared by the free-text and redact writers: `/DA` styles a free-text body\n * and a redaction `/OverlayText` label through the exact same triple.\n */\nexport function applyDefaultAppearance(\n fn: PdfFunctions,\n annotPtr: Ptr,\n fontFamily: FreeTextFont,\n fontSize: number,\n color: Color,\n ctx: AnnotationWriteContext | undefined,\n): void {\n if (isStandardFont(fontFamily)) {\n setDefaultAppearance(fn, annotPtr, standardFontToCode(fontFamily), fontSize, color);\n return;\n }\n if (!ctx?.resolveRegisteredFontId) {\n throw new EngineError(\n EngineErrorCode.InvalidArg,\n `fontFamily '${fontFamily}' is not a standard font and no font registry is available on this host`,\n );\n }\n setDefaultAppearanceRegisteredFont(\n fn,\n annotPtr,\n ctx.resolveRegisteredFontId(fontFamily),\n fontSize,\n color,\n );\n}\n","import {\n type Color,\n type FilledStyleDraftFields,\n type GeometryStyleDraftFields,\n} from '@embedpdf/engine-core/runtime';\nimport type { PdfFunctions, PdfRuntimeMemory, Ptr } from '@embedpdf/engine-runtime';\n\nimport { FPDFANNOT_COLORTYPE } from '../colorType';\nimport { readBorderStyle } from '../read/annotationReadPrimitives';\nimport { borderStyleFromCode, borderStyleToCode } from '../shapeBorderStyle';\nimport {\n clearAnnotColor,\n setAnnotColor,\n setAnnotOpacity,\n setBorderDashPattern,\n setBorderStyle,\n} from './annotationWritePrimitives';\n\n/** The `/BS` (border) subset shared by every kind that draws a border. */\nexport type BorderDraftFields = Pick<\n GeometryStyleDraftFields,\n 'strokeWidth' | 'borderStyle' | 'dashArray'\n>;\n\n/**\n * Defaults applied when a draft omits a styling field. Shared by every\n * geometric family (shape/vertex/line/ink) so circle, square, polygon,\n * polyline, line, and ink all default to a 1pt solid red stroke.\n */\nexport const DEFAULT_OPACITY = 1;\nexport const DEFAULT_STROKE_WIDTH = 1;\nexport const DEFAULT_COLOR: Color = { r: 255, g: 0, b: 0 };\n\n/**\n * Apply the geometry styling (`/C`, `/CA`, `/BS`, dash) from a draft to a\n * freshly-created annotation. This is the no-fill layer shared by ink and\n * the filled families; `interiorColor` (`/IC`) is layered on by\n * {@link applyFilledStyleDraft}. Geometry (`/Rect`, `/Vertices`, `/L`,\n * `/InkList`), cloudy borders, rect-differences, and line endings are\n * layered on by the family-specific writer around this call.\n */\nexport function applyGeometryStyleDraft(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n annotPtr: Ptr,\n draft: GeometryStyleDraftFields,\n): void {\n setAnnotColor(fn, annotPtr, draft.color ?? DEFAULT_COLOR);\n setAnnotOpacity(fn, annotPtr, draft.opacity ?? DEFAULT_OPACITY);\n applyBorderDraft(fn, mem, annotPtr, draft);\n}\n\n/**\n * Write the `/BS` border (style + width, then dash) from a draft. This is\n * the border-only slice of {@link applyGeometryStyleDraft}, shared with the\n * free-text box border (which manages `/C` and `/DA` itself). A missing\n * `borderStyle`/`strokeWidth` falls back to a 1pt solid border.\n */\nexport function applyBorderDraft(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n annotPtr: Ptr,\n draft: BorderDraftFields,\n): void {\n setBorderStyle(\n fn,\n annotPtr,\n borderStyleToCode(draft.borderStyle ?? 'solid'),\n draft.strokeWidth ?? DEFAULT_STROKE_WIDTH,\n );\n if (draft.dashArray !== undefined && draft.dashArray.length > 0) {\n setBorderDashPattern(fn, mem, annotPtr, draft.dashArray);\n }\n}\n\n/**\n * Apply the geometry styling from a patch to an existing annotation. Only\n * present fields are touched. Border style + width share the single\n * `EPDFAnnot_SetBorderStyle` call, so when only one is patched we read the\n * current pair first and preserve the other.\n */\nexport function applyGeometryStylePatch(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n annotPtr: Ptr,\n patch: GeometryStyleDraftFields,\n): void {\n if (patch.color !== undefined) {\n setAnnotColor(fn, annotPtr, patch.color);\n }\n if (patch.opacity !== undefined) {\n setAnnotOpacity(fn, annotPtr, patch.opacity);\n }\n applyBorderPatch(fn, mem, annotPtr, patch);\n}\n\n/**\n * Write the `/BS` border from a patch, touching only present fields. Border\n * style + width share the single `EPDFAnnot_SetBorderStyle` call, so when\n * only one is patched we read the current pair first and preserve the other.\n * The border-only slice of {@link applyGeometryStylePatch}, shared with the\n * free-text box border.\n */\nexport function applyBorderPatch(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n annotPtr: Ptr,\n patch: BorderDraftFields,\n): void {\n if (patch.borderStyle !== undefined || patch.strokeWidth !== undefined) {\n const current = readBorderStyle(fn, mem, annotPtr);\n const style = patch.borderStyle ?? borderStyleFromCode(current.styleCode);\n const width = patch.strokeWidth ?? current.width;\n setBorderStyle(fn, annotPtr, borderStyleToCode(style), width);\n }\n if (patch.dashArray !== undefined && patch.dashArray.length > 0) {\n setBorderDashPattern(fn, mem, annotPtr, patch.dashArray);\n }\n}\n\n/**\n * Apply the full stroke/fill styling (geometry styling + `/IC`) from a\n * draft. A `null`/omitted fill clears `/IC` so the shape renders unfilled.\n * Used by the filled families (circle/square/polygon/polyline/line).\n */\nexport function applyFilledStyleDraft(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n annotPtr: Ptr,\n draft: FilledStyleDraftFields,\n): void {\n const interior = draft.interiorColor ?? null;\n if (interior === null) {\n clearAnnotColor(fn, annotPtr, FPDFANNOT_COLORTYPE.InteriorColor);\n } else {\n setAnnotColor(fn, annotPtr, interior, FPDFANNOT_COLORTYPE.InteriorColor);\n }\n applyGeometryStyleDraft(fn, mem, annotPtr, draft);\n}\n\n/**\n * Apply the full stroke/fill styling from a patch. Only present fields are\n * touched; `interiorColor: null` clears `/IC`.\n */\nexport function applyFilledStylePatch(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n annotPtr: Ptr,\n patch: FilledStyleDraftFields,\n): void {\n if (patch.interiorColor !== undefined) {\n if (patch.interiorColor === null) {\n clearAnnotColor(fn, annotPtr, FPDFANNOT_COLORTYPE.InteriorColor);\n } else {\n setAnnotColor(fn, annotPtr, patch.interiorColor, FPDFANNOT_COLORTYPE.InteriorColor);\n }\n }\n applyGeometryStylePatch(fn, mem, annotPtr, patch);\n}\n","import type { AnnotationActor } from '@embedpdf/engine-core/runtime';\nimport type { PdfFunctions, PdfRuntimeMemory, Ptr } from '@embedpdf/engine-runtime';\n\n/**\n * Write the EmbedPDF-namespaced /EMBD_Metadata annotation dictionary.\n *\n * This module owns ONLY the vendor-extension dictionary. Standard PDF\n * base fields (/T, /M, /NM, /Contents) are handled by\n * `writers/annotations/base.ts` — /EMBD_Metadata is a separate\n * dictionary nested under the annotation that carries cloud-side\n * identity bookkeeping which has no PDF-spec equivalent.\n *\n * Schema (v1):\n * /EMBD_Metadata <<\n * /SchemaVersion 1 % EmbedPDF metadata schema version\n * /UserID (acme/alice) % identity that created the annotation\n * /GroupID (engineering) % group the annotation belongs to\n * /CreatedBy (acme/alice) % same as UserID on create\n * /UpdatedBy (acme/alice) % last editor; refreshed on every update\n * >>\n *\n * Read side: see `readers/annotations/embed-metadata.ts` (commit 12).\n *\n * PDFium bindings used: the `EPDFAnnot_*EmbedMetadata*` extension API\n * shipped in the EmbedPDF PDFium fork. Values are written as UTF-16LE\n * strings via the same `mem.writeU16String` pattern the base writer\n * uses for /T.\n */\n\nconst KEY_SCHEMA_VERSION = 'SchemaVersion';\nconst KEY_USER_ID = 'UserID';\nconst KEY_GROUP_ID = 'GroupID';\nconst KEY_CREATED_BY = 'CreatedBy';\nconst KEY_UPDATED_BY = 'UpdatedBy';\n\n/**\n * Current EmbedPDF metadata schema version. Bump if/when the field set\n * or semantics change; readers tolerate older versions by falling back\n * to the fields they recognise.\n */\nexport const EMBD_METADATA_SCHEMA_VERSION = 1;\n\n/**\n * Stamp /EMBD_Metadata on a freshly created annotation. No-op if the\n * actor has no identity fields — the worker still emits the standard\n * /M timestamp via the base writer; only the vendor dictionary is\n * skipped.\n *\n * actor.userId → /UserID, /CreatedBy, /UpdatedBy\n * actor.groupId → /GroupID\n *\n * /SchemaVersion is written whenever any field is written.\n */\nexport function applyEmbedMetadataOnCreate(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n annotPtr: Ptr,\n actor: AnnotationActor | undefined,\n): void {\n if (!actor || (!actor.userId && !actor.groupId)) return;\n\n fn.EPDFAnnot_SetEmbedMetadataNumber(annotPtr, KEY_SCHEMA_VERSION, EMBD_METADATA_SCHEMA_VERSION);\n\n if (actor.userId) {\n setMetadataString(fn, mem, annotPtr, KEY_USER_ID, actor.userId);\n setMetadataString(fn, mem, annotPtr, KEY_CREATED_BY, actor.userId);\n setMetadataString(fn, mem, annotPtr, KEY_UPDATED_BY, actor.userId);\n }\n if (actor.groupId) {\n setMetadataString(fn, mem, annotPtr, KEY_GROUP_ID, actor.groupId);\n }\n}\n\n/**\n * Apply /EMBD_Metadata refreshes on update. Two fields can change on\n * update; everything else (UserID, CreatedBy) is immutable.\n *\n * actor.userId → /UpdatedBy (refreshed every update where the\n * caller has an identity)\n * actor.groupId → /GroupID (reassigned only when the patch\n * explicitly contains a new groupId; route runs\n * `checkSetGroup` first)\n *\n * If the target annotation has no EMBD_Metadata yet (created before\n * the cloud started stamping, or by a non-cloud writer), we seed\n * /SchemaVersion so subsequent readers can find the marker.\n *\n * No-op when the actor has neither userId nor groupId.\n */\nexport function applyEmbedMetadataOnUpdate(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n annotPtr: Ptr,\n actor: AnnotationActor | undefined,\n): void {\n if (!actor || (!actor.userId && !actor.groupId)) return;\n\n if (!fn.EPDFAnnot_HasEmbedMetadata(annotPtr)) {\n fn.EPDFAnnot_SetEmbedMetadataNumber(annotPtr, KEY_SCHEMA_VERSION, EMBD_METADATA_SCHEMA_VERSION);\n }\n if (actor.userId) {\n setMetadataString(fn, mem, annotPtr, KEY_UPDATED_BY, actor.userId);\n }\n if (actor.groupId) {\n setMetadataString(fn, mem, annotPtr, KEY_GROUP_ID, actor.groupId);\n }\n}\n\nfunction setMetadataString(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n annotPtr: Ptr,\n key: string,\n value: string,\n): void {\n // Mirror the UTF-16LE pattern from writers/annotations/base.ts:\n // FPDFAnnot_SetStringValue and EPDFAnnot_SetEmbedMetadataString share\n // the same FPDF_WIDESTRING value shape, so we use the same helper.\n const ptr = mem.writeU16String(value);\n try {\n fn.EPDFAnnot_SetEmbedMetadataString(annotPtr, key, ptr);\n } finally {\n mem.free(ptr);\n }\n}\n","import { EngineError, EngineErrorCode, type PdfRect } from '@embedpdf/engine-core/runtime';\nimport type { PdfFunctions, PdfRuntimeMemory, Ptr } from '@embedpdf/engine-runtime';\n\nimport { RECTF_BYTES } from '../../../../runtime/memory/structs';\nimport { readAnnotationUnrotatedRect } from '../read/readAnnotationTransformMetadata';\nimport { EMBD_METADATA_SCHEMA_VERSION } from './writeEmbedMetadata';\n\n/**\n * Write the EmbedPDF transform keys under /EMBD_Metadata. This is the seam\n * PDFium's native AP generator reads to bake a ROTATED appearance:\n *\n * /EMBD_Metadata <<\n * /Rotation 45 % degrees, PDF convention (CCW)\n * /UnrotatedRect [x0 y0 x1 y1] % BOX kinds only — the logical box\n * >>\n *\n * The family split (see the v3 plan):\n * - BOX kinds (square/circle/free-text): `/Rotation` + `/UnrotatedRect`.\n * With BOTH present the AP generator emits an `/AP /Matrix` that rotates a\n * box-sized appearance about the box centre, and `/Rect` is the enclosing\n * AABB. This is the portable, externally-correct rotation.\n * - VERTEX kinds (line/polyline/polygon/ink): `/Rotation` ONLY (advisory).\n * The points are already rotated (they are the visual), so a lone\n * `/Rotation` is INERT for the AP generator (it ignores `/Rotation` with no\n * `/UnrotatedRect`) — it just records the applied angle so EmbedPDF can\n * reconstruct an oriented selection box + offer reset.\n *\n * Both fields follow the engine-wide tri-state law (\"a patch touches what it\n * states, preserves what it omits\"):\n * - `undefined` → the key is UNTOUCHED (a rect-only move keeps its rotation).\n * - `null` or `0` → CLEAR just that key via `EPDFAnnot_ClearEmbedMetadataKey`\n * (0 ≡ no rotation is the canonical identity, not a sentinel; never clear\n * the whole dict — identity fields UserID/GroupID/CreatedBy/UpdatedBy must\n * survive).\n * - a value → SET the key. Setting a nonzero rotation with no\n * `/UnrotatedRect` (neither in the patch nor already on the annotation)\n * is an unsatisfiable state for the AP generator and throws `InvalidArg`.\n *\n * MUST run BEFORE `EPDFAnnot_GenerateAppearance` so the bake sees the rotation.\n * `/SchemaVersion` is seeded (stays 1) if this is the first key in the dict.\n */\n\nconst KEY_ROTATION = 'Rotation';\nconst KEY_UNROTATED_RECT = 'UnrotatedRect';\n\n/** Transform fields a rotatable draft/patch can carry (off the engine DTO).\n * Tri-state: `undefined` preserves, `null` clears, a value sets. */\nexport interface AnnotationTransform {\n /** `/EMBD_Metadata/Rotation` — degrees, PDF convention. 0 ≡ none. */\n rotation?: number | null;\n /** `/EMBD_Metadata/UnrotatedRect` — the logical box (BOX kinds only). */\n unrotatedRect?: PdfRect | null;\n}\n\n/** Seed `/SchemaVersion` when we are about to create the dict by writing the\n * first transform key, so the marker readers look for is always present. */\nfunction ensureSchemaVersion(fn: PdfFunctions, annotPtr: Ptr): void {\n if (!fn.EPDFAnnot_HasEmbedMetadata(annotPtr)) {\n fn.EPDFAnnot_SetEmbedMetadataNumber(annotPtr, 'SchemaVersion', EMBD_METADATA_SCHEMA_VERSION);\n }\n}\n\nfunction setRotation(fn: PdfFunctions, annotPtr: Ptr, rotation: number): void {\n ensureSchemaVersion(fn, annotPtr);\n fn.EPDFAnnot_SetEmbedMetadataNumber(annotPtr, KEY_ROTATION, rotation);\n}\n\nfunction setUnrotatedRect(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n annotPtr: Ptr,\n rect: PdfRect,\n): void {\n ensureSchemaVersion(fn, annotPtr);\n const buf = mem.alloc(RECTF_BYTES);\n try {\n // FS_RECTF { left, top, right, bottom } — same layout as setAnnotRect.\n mem.poke(buf, 'f32', rect.left, 0);\n mem.poke(buf, 'f32', rect.top, 4);\n mem.poke(buf, 'f32', rect.right, 8);\n mem.poke(buf, 'f32', rect.bottom, 12);\n fn.EPDFAnnot_SetEmbedMetadataRect(annotPtr, KEY_UNROTATED_RECT, buf);\n } finally {\n mem.free(buf);\n }\n}\n\n/**\n * Write transform metadata for a BOX kind (square/circle/free-text/stamp),\n * tri-state per field: `undefined` never touches the document (safe to call on\n * every patch), `null`/`0` clears, a value sets. A nonzero rotation with no\n * unrotated box anywhere (patch or annotation) is unsatisfiable — the AP\n * generator needs the pair — and throws instead of writing a broken state.\n */\nexport function writeBoxTransformMetadata(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n annotPtr: Ptr,\n t: AnnotationTransform,\n): void {\n if (t.rotation !== undefined) {\n if (t.rotation !== null && t.rotation !== 0) {\n const hasBox =\n t.unrotatedRect != null ||\n (t.unrotatedRect === undefined && readAnnotationUnrotatedRect(fn, mem, annotPtr) != null);\n if (!hasBox) {\n throw new EngineError(\n EngineErrorCode.InvalidArg,\n 'rotation requires unrotatedRect: supply the pair together (or rely on an existing /EMBD_Metadata/UnrotatedRect)',\n );\n }\n setRotation(fn, annotPtr, t.rotation);\n } else {\n fn.EPDFAnnot_ClearEmbedMetadataKey(annotPtr, KEY_ROTATION);\n }\n }\n if (t.unrotatedRect !== undefined) {\n if (t.unrotatedRect !== null) setUnrotatedRect(fn, mem, annotPtr, t.unrotatedRect);\n else fn.EPDFAnnot_ClearEmbedMetadataKey(annotPtr, KEY_UNROTATED_RECT);\n }\n}\n\n/**\n * Write the advisory `/Rotation` scalar for a VERTEX kind\n * (line/polyline/polygon/ink), tri-state: `undefined` never touches the\n * document, `null`/`0` clears, a value sets. Whenever it does write, any\n * `/UnrotatedRect` is defensively cleared — that key is an impossible state on\n * a vertex kind and must never accidentally drive the AP generator.\n */\nexport function writeVertexTransformMetadata(\n fn: PdfFunctions,\n annotPtr: Ptr,\n t: AnnotationTransform,\n): void {\n if (t.rotation === undefined) return;\n if (t.rotation !== null && t.rotation !== 0) setRotation(fn, annotPtr, t.rotation);\n else fn.EPDFAnnot_ClearEmbedMetadataKey(annotPtr, KEY_ROTATION);\n fn.EPDFAnnot_ClearEmbedMetadataKey(annotPtr, KEY_UNROTATED_RECT);\n}\n","import { type Color, type FreeTextDraft, type FreeTextPatch } from '@embedpdf/engine-core/runtime';\nimport type { PdfFunctions, PdfRuntimeMemory, Ptr } from '@embedpdf/engine-runtime';\n\nimport { FPDFANNOT_COLORTYPE } from '../colorType';\nimport { freeTextIntentToName } from '../freeTextIntent';\nimport { readDefaultAppearance } from '../read/annotationReadPrimitives';\nimport { DEFAULT_STANDARD_FONT, standardFontFromCode } from '../standardFont';\nimport { textAlignmentToCode } from '../textAlignment';\nimport type { AnnotationWriteContext } from './annotationWriteContext';\nimport {\n clearAnnotColor,\n clearRectangleDifferences,\n setAnnotColor,\n setAnnotOpacity,\n setAnnotRect,\n setCalloutLine,\n setIntent,\n setLineEndings,\n setRectangleDifferences,\n setTextAlignment,\n} from './annotationWritePrimitives';\nimport { applyAnnotationBaseDraft, applyAnnotationBasePatch } from './writeAnnotationBase';\nimport { applyDefaultAppearance } from './writeDefaultAppearance';\nimport { applyBorderDraft, applyBorderPatch, DEFAULT_OPACITY } from './writeStyle';\nimport { writeBoxTransformMetadata } from './writeAnnotationTransformMetadata';\n\n/**\n * Default `/DA` colour for free text: black (border + default text). Unlike\n * the geometric families (which default to red `/C`), a text box reads best\n * with a black mark.\n */\nconst DEFAULT_FREETEXT_COLOR: Color = { r: 0, g: 0, b: 0 };\n\n/**\n * Apply a free-text draft to a freshly-created annotation. Colour model:\n * - `color` -> `/DA` colour = border + default text colour.\n * - `fontColor` (optional) -> `TextColor` channel, overriding text only;\n * written AFTER `/DA` so the override wins.\n * - `interiorColor` -> `/C` box background (`null`/omitted clears it).\n *\n * Order:\n * 1. base author-metadata (contents/nm/flags)\n * 2. `/Rect` (required — supplied by the caller; never derived)\n * 3. `/C` background (set or clear) + `/CA` opacity\n * 4. `/BS` border (style + width + dash)\n * 5. `/DA` default appearance (font + size + `color`)\n * 6. `TextColor` override (only when `fontColor` is given)\n * 7. `/Q` text alignment\n * 8. `/IT` intent\n * 9. `/RD` rectangle differences (optional)\n * 10. callout `/CL` + leader `/LE` ending (only for callouts with geometry)\n */\nexport function applyFreeTextDraft(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n annotPtr: Ptr,\n draft: FreeTextDraft,\n ctx?: AnnotationWriteContext,\n): void {\n applyAnnotationBaseDraft(fn, mem, annotPtr, draft);\n setAnnotRect(fn, mem, annotPtr, draft.rect);\n\n const background = draft.interiorColor ?? null;\n if (background === null) {\n clearAnnotColor(fn, annotPtr, FPDFANNOT_COLORTYPE.Color);\n } else {\n setAnnotColor(fn, annotPtr, background, FPDFANNOT_COLORTYPE.Color);\n }\n setAnnotOpacity(fn, annotPtr, draft.opacity ?? DEFAULT_OPACITY);\n\n applyBorderDraft(fn, mem, annotPtr, draft);\n\n const daColor = draft.color ?? DEFAULT_FREETEXT_COLOR;\n applyDefaultAppearance(fn, annotPtr, draft.fontFamily, draft.fontSize, daColor, ctx);\n if (draft.fontColor !== undefined) {\n setAnnotColor(fn, annotPtr, draft.fontColor, FPDFANNOT_COLORTYPE.TextColor);\n }\n\n setTextAlignment(fn, annotPtr, textAlignmentToCode(draft.textAlign));\n setIntent(fn, annotPtr, freeTextIntentToName(draft.intent));\n\n if (draft.rectDifferences != null) {\n setRectangleDifferences(fn, annotPtr, draft.rectDifferences);\n }\n\n if (draft.calloutLine !== undefined) {\n setCalloutLine(fn, mem, annotPtr, draft.calloutLine);\n }\n if (draft.lineEnding !== undefined) {\n setLineEndings(fn, annotPtr, { start: 'none', end: draft.lineEnding });\n }\n // A plain text box rotates like square/circle (box model). A callout's\n // rotation applies to its text BOX only (`unrotatedRect` = the logical text\n // box; the /CL leader stays page-space) — the AP generator bakes it as an\n // inline matrix, not the form /Matrix. Absent fields simply clear the keys.\n writeBoxTransformMetadata(fn, mem, annotPtr, {\n rotation: draft.rotation,\n unrotatedRect: draft.unrotatedRect,\n });\n}\n\n/**\n * Apply a free-text patch to an existing annotation. Only present fields are\n * touched. `/DA` packs the font, size, and `color` into ONE string, so a\n * partial patch preserves the unpatched members by READING the current triple\n * first (the same read-modify-write as {@link applyBorderPatch}'s shared\n * `/BS` call) — a `{fontSize}` patch must never reset the font or colour.\n * Registered (embedded) fonts are the one caveat: the current `/DA` reads\n * back as a font CODE, so preserving a registered family requires the patch\n * to restate `fontFamily` (an unknown code falls back to the standard-font\n * default).\n *\n * `fontColor` here only sets an override; clearing it back to \"follow\n * `color`\" is out of scope this iteration.\n */\nexport function applyFreeTextPatch(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n annotPtr: Ptr,\n patch: FreeTextPatch,\n ctx?: AnnotationWriteContext,\n): void {\n applyAnnotationBasePatch(fn, mem, annotPtr, patch);\n\n if (patch.rect !== undefined) {\n setAnnotRect(fn, mem, annotPtr, patch.rect);\n }\n // Transform metadata is tri-state per field (undefined preserves, null\n // clears, value sets) — independent of whether /Rect was rewritten. A\n // rect-only patch on a rotated box keeps its rotation.\n writeBoxTransformMetadata(fn, mem, annotPtr, {\n rotation: patch.rotation,\n unrotatedRect: patch.unrotatedRect,\n });\n\n if (patch.interiorColor !== undefined) {\n if (patch.interiorColor === null) {\n clearAnnotColor(fn, annotPtr, FPDFANNOT_COLORTYPE.Color);\n } else {\n setAnnotColor(fn, annotPtr, patch.interiorColor, FPDFANNOT_COLORTYPE.Color);\n }\n }\n if (patch.opacity !== undefined) {\n setAnnotOpacity(fn, annotPtr, patch.opacity);\n }\n\n applyBorderPatch(fn, mem, annotPtr, patch);\n\n if (patch.fontFamily !== undefined || patch.fontSize !== undefined || patch.color !== undefined) {\n const cur = readDefaultAppearance(fn, mem, annotPtr);\n applyDefaultAppearance(\n fn,\n annotPtr,\n patch.fontFamily ?? (cur ? standardFontFromCode(cur.fontCode) : DEFAULT_STANDARD_FONT),\n patch.fontSize ?? (cur && cur.fontSize > 0 ? cur.fontSize : 12),\n patch.color ?? cur?.color ?? DEFAULT_FREETEXT_COLOR,\n ctx,\n );\n }\n if (patch.fontColor !== undefined) {\n setAnnotColor(fn, annotPtr, patch.fontColor, FPDFANNOT_COLORTYPE.TextColor);\n }\n\n if (patch.textAlign !== undefined) {\n setTextAlignment(fn, annotPtr, textAlignmentToCode(patch.textAlign));\n }\n if (patch.intent !== undefined) {\n setIntent(fn, annotPtr, freeTextIntentToName(patch.intent));\n }\n\n if (patch.rectDifferences === null) {\n clearRectangleDifferences(fn, annotPtr);\n } else if (patch.rectDifferences !== undefined) {\n setRectangleDifferences(fn, annotPtr, patch.rectDifferences);\n }\n\n if (patch.calloutLine !== undefined) {\n setCalloutLine(fn, mem, annotPtr, patch.calloutLine);\n }\n if (patch.lineEnding !== undefined) {\n setLineEndings(fn, annotPtr, { start: 'none', end: patch.lineEnding });\n }\n}\n\n/**\n * Type-narrowing predicate used by the writer registry to pick the\n * free-text writer for a draft/patch's `subtype`.\n */\nexport function isFreeTextSubtype(subtype: string): subtype is 'free-text' {\n return subtype === 'free-text';\n}\n","import type { InkDraft, InkPatch } from '@embedpdf/engine-core/runtime';\nimport type { PdfFunctions, PdfRuntimeMemory, Ptr } from '@embedpdf/engine-runtime';\n\nimport { setAnnotRect, setInkList, setIntent } from './annotationWritePrimitives';\nimport { applyAnnotationBaseDraft, applyAnnotationBasePatch } from './writeAnnotationBase';\nimport { applyGeometryStyleDraft, applyGeometryStylePatch } from './writeStyle';\nimport { writeVertexTransformMetadata } from './writeAnnotationTransformMetadata';\nimport { inkIntentToName } from '../inkIntent';\n\n/**\n * Apply an ink draft to a freshly-created annotation. Ink has a stroke but\n * no `/IC`, so it uses the geometry styling layer (not the filled one).\n * Order:\n * 1. base author-metadata (contents/nm)\n * 2. /Rect (required — supplied by the plugin; the engine never derives it)\n * 3. geometry styling (/C, /CA, /BS, dash)\n * 4. /InkList freehand strokes\n */\nexport function applyInkDraft(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n annotPtr: Ptr,\n draft: InkDraft,\n): void {\n applyAnnotationBaseDraft(fn, mem, annotPtr, draft);\n if (draft.intent !== undefined) setIntent(fn, annotPtr, inkIntentToName(draft.intent));\n setAnnotRect(fn, mem, annotPtr, draft.rect);\n applyGeometryStyleDraft(fn, mem, annotPtr, draft);\n setInkList(fn, mem, annotPtr, draft.inkList);\n // Advisory rotation: the strokes are already rotated; this just records θ.\n writeVertexTransformMetadata(fn, annotPtr, { rotation: draft.rotation });\n}\n\nexport function applyInkPatch(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n annotPtr: Ptr,\n patch: InkPatch,\n): void {\n applyAnnotationBasePatch(fn, mem, annotPtr, patch);\n if (patch.intent !== undefined) setIntent(fn, annotPtr, inkIntentToName(patch.intent));\n if (patch.rect !== undefined) {\n setAnnotRect(fn, mem, annotPtr, patch.rect);\n }\n applyGeometryStylePatch(fn, mem, annotPtr, patch);\n if (patch.inkList !== undefined) {\n setInkList(fn, mem, annotPtr, patch.inkList);\n }\n // Advisory rotation is tri-state (undefined preserves, null/0 clears).\n writeVertexTransformMetadata(fn, annotPtr, { rotation: patch.rotation });\n}\n\n/**\n * Type-narrowing predicate used by the writer registry to pick the ink\n * writer for a draft/patch's `subtype`.\n */\nexport function isInkSubtype(subtype: string): subtype is 'ink' {\n return subtype === 'ink';\n}\n","import type { LineDraft, LinePatch } from '@embedpdf/engine-core/runtime';\nimport type { PdfFunctions, PdfRuntimeMemory, Ptr } from '@embedpdf/engine-runtime';\n\nimport { setAnnotRect, setLine, setLineEndings } from './annotationWritePrimitives';\nimport { applyAnnotationBaseDraft, applyAnnotationBasePatch } from './writeAnnotationBase';\nimport { applyFilledStyleDraft, applyFilledStylePatch } from './writeStyle';\nimport { writeVertexTransformMetadata } from './writeAnnotationTransformMetadata';\n\n/** Default line endings when a line draft omits them. */\nconst DEFAULT_LINE_ENDINGS = { start: 'none', end: 'none' } as const;\n\n/**\n * Apply a line draft to a freshly-created annotation. Order:\n * 1. base author-metadata (contents/nm)\n * 2. /Rect (required — supplied by the plugin; the engine never derives it)\n * 3. shared stroke/fill styling (/C, /CA, /BS, dash)\n * 4. /L line geometry\n * 5. /LE line endings (default none/none)\n */\nexport function applyLineDraft(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n annotPtr: Ptr,\n draft: LineDraft,\n): void {\n applyAnnotationBaseDraft(fn, mem, annotPtr, draft);\n setAnnotRect(fn, mem, annotPtr, draft.rect);\n applyFilledStyleDraft(fn, mem, annotPtr, draft);\n setLine(fn, mem, annotPtr, draft.linePoints);\n setLineEndings(fn, annotPtr, draft.lineEndings ?? DEFAULT_LINE_ENDINGS);\n // Advisory rotation: the endpoints are already rotated; this just records θ.\n writeVertexTransformMetadata(fn, annotPtr, { rotation: draft.rotation });\n}\n\nexport function applyLinePatch(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n annotPtr: Ptr,\n patch: LinePatch,\n): void {\n applyAnnotationBasePatch(fn, mem, annotPtr, patch);\n if (patch.rect !== undefined) {\n setAnnotRect(fn, mem, annotPtr, patch.rect);\n }\n applyFilledStylePatch(fn, mem, annotPtr, patch);\n if (patch.linePoints !== undefined) {\n setLine(fn, mem, annotPtr, patch.linePoints);\n }\n // Advisory rotation is tri-state (undefined preserves, null/0 clears).\n writeVertexTransformMetadata(fn, annotPtr, { rotation: patch.rotation });\n if (patch.lineEndings !== undefined) {\n setLineEndings(fn, annotPtr, patch.lineEndings);\n }\n}\n\n/**\n * Type-narrowing predicate used by the writer registry to pick the line\n * writer for a draft/patch's `subtype`.\n */\nexport function isLineSubtype(subtype: string): subtype is 'line' {\n return subtype === 'line';\n}\n","import {\n EngineError,\n EngineErrorCode,\n type LinkDraft,\n type LinkPatch,\n type PdfDestination,\n type PdfLinkTargetWritable,\n} from '@embedpdf/engine-core/runtime';\nimport type { PdfFunctions, PdfRuntimeMemory, Ptr } from '@embedpdf/engine-runtime';\nimport { NULL_PTR } from '@embedpdf/engine-runtime';\n\nimport { withScratch } from '../../../../runtime/memory/scratch';\nimport { F32_BYTES } from '../../../../runtime/memory/structs';\nimport { VIEW_CODE_BY_KIND } from '../destinationViewCodes';\nimport { setAnnotRect } from './annotationWritePrimitives';\nimport type { AnnotationWriteContext } from './annotationWriteContext';\nimport { applyAnnotationBaseDraft, applyAnnotationBasePatch } from './writeAnnotationBase';\n\n/**\n * Link writer: rect + the `/A` action. Only `goto`/`uri` targets are\n * writable (the draft/patch types enforce it; `goto-remote`/`launch` are\n * read-only by design). Relationship (`/IRT` + `/RT` — v2's grouped links)\n * is written by the mutator's kind-agnostic relationship pass, never here.\n *\n * A retarget REPLACES `/A`; it cannot remove a pre-existing direct `/Dest`\n * (no dict-entry removal primitive in the runtime), which is why the link\n * READER gives `/A` precedence — see readLinkAnnotation.ts.\n */\nexport function applyLinkDraft(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n annotPtr: Ptr,\n draft: LinkDraft,\n ctx?: AnnotationWriteContext,\n): void {\n applyAnnotationBaseDraft(fn, mem, annotPtr, draft);\n setAnnotRect(fn, mem, annotPtr, draft.rect);\n // `target: null` is the create-then-edit flow: the rect exists first, a\n // later patch supplies the destination/URI. Nothing to write yet.\n if (draft.target) applyLinkTarget(fn, mem, annotPtr, draft.target, ctx);\n}\n\nexport function applyLinkPatch(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n annotPtr: Ptr,\n patch: LinkPatch,\n ctx?: AnnotationWriteContext,\n): void {\n applyAnnotationBasePatch(fn, mem, annotPtr, patch);\n if (patch.rect !== undefined) setAnnotRect(fn, mem, annotPtr, patch.rect);\n if (patch.target === null) clearLinkTarget(fn, annotPtr);\n else if (patch.target !== undefined) applyLinkTarget(fn, mem, annotPtr, patch.target, ctx);\n}\n\n/**\n * `target: null` → a dead link. The model treats the target as ONE concept\n * with two spellings, so THIS layer composes the two single-purpose\n * removal primitives — removing only `/A` would resurrect a stale direct\n * `/Dest` as the live target.\n */\nfunction clearLinkTarget(fn: PdfFunctions, annotPtr: Ptr): void {\n if (!fn.EPDFAnnot_RemoveAction(annotPtr) || !fn.EPDFAnnot_RemoveDest(annotPtr)) {\n throw new EngineError(EngineErrorCode.Unknown, 'failed to clear link target');\n }\n}\n\nexport function isLinkSubtype(subtype: string): subtype is 'link' {\n return subtype === 'link';\n}\n\nfunction applyLinkTarget(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n annotPtr: Ptr,\n target: PdfLinkTargetWritable,\n ctx?: AnnotationWriteContext,\n): void {\n const docPtr = ctx?.docPtr;\n if (!docPtr) {\n throw new EngineError(\n EngineErrorCode.InvalidArg,\n 'writing a link target requires a document pointer on the write context',\n );\n }\n\n const actionPtr =\n target.kind === 'uri'\n ? fn.EPDFAction_CreateURI(docPtr, target.uri)\n : fn.EPDFAction_CreateGoTo(docPtr, createDestination(fn, mem, docPtr, target.destination));\n if (!actionPtr) {\n throw new EngineError(EngineErrorCode.Unknown, `failed to create '${target.kind}' action`);\n }\n if (!fn.EPDFAnnot_SetAction(annotPtr, actionPtr)) {\n throw new EngineError(EngineErrorCode.Unknown, 'EPDFAnnot_SetAction failed for link');\n }\n}\n\n/**\n * Build an INDIRECT explicit-destination array for `dest`. The target page\n * is loaded just to reference its dictionary and closed immediately —\n * destinations routinely point at pages the mutator's pool never touches.\n */\nfunction createDestination(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n docPtr: Ptr,\n dest: PdfDestination,\n): Ptr {\n const pagePtr = fn.EPDFDoc_LoadPageByObjectNumber(docPtr, dest.pageObjectNumber);\n if (!pagePtr) {\n throw new EngineError(\n EngineErrorCode.NotFound,\n `link destination page not found: pageObjectNumber=${dest.pageObjectNumber}`,\n );\n }\n try {\n const destPtr =\n dest.kind === 'xyz'\n ? // Absent axes write PDF nulls (spec: \"retain current value\").\n fn.EPDFDest_CreateXYZ(\n pagePtr,\n dest.left != null,\n dest.left ?? 0,\n dest.top != null,\n dest.top ?? 0,\n dest.zoom != null,\n dest.zoom ?? 0,\n )\n : createViewDestination(fn, mem, pagePtr, dest);\n if (!destPtr) {\n throw new EngineError(EngineErrorCode.Unknown, `failed to create '${dest.kind}' destination`);\n }\n return destPtr;\n } finally {\n fn.FPDF_ClosePage(pagePtr);\n }\n}\n\nfunction createViewDestination(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n pagePtr: Ptr,\n dest: Exclude<PdfDestination, { kind: 'xyz' }>,\n): Ptr {\n // The runtime pads missing params with 0 up to the fit type's arity —\n // a null top/left therefore writes as 0 (v2 parity; the array form has\n // no per-param null encoding through this API).\n const params: number[] = (() => {\n switch (dest.kind) {\n case 'fitH':\n case 'fitBH':\n return dest.top != null ? [dest.top] : [];\n case 'fitV':\n case 'fitBV':\n return dest.left != null ? [dest.left] : [];\n case 'fitR':\n return [dest.left, dest.bottom, dest.right, dest.top];\n default:\n return [];\n }\n })();\n\n const view = VIEW_CODE_BY_KIND[dest.kind];\n if (!params.length) return fn.EPDFDest_CreateView(pagePtr, view, NULL_PTR, 0);\n return withScratch(mem, params.length * F32_BYTES, (buf) => {\n for (let i = 0; i < params.length; i++) mem.poke(buf, 'f32', params[i]!, i * F32_BYTES);\n return fn.EPDFDest_CreateView(pagePtr, view, buf, params.length);\n });\n}\n","import {\n EngineError,\n EngineErrorCode,\n type Color,\n type HighlightDraft,\n type HighlightPatch,\n type PdfQuad,\n type SquigglyDraft,\n type SquigglyPatch,\n type StrikeoutDraft,\n type StrikeoutPatch,\n type UnderlineDraft,\n type UnderlinePatch,\n} from '@embedpdf/engine-core/runtime';\nimport type { PdfFunctions, PdfRuntimeMemory, Ptr } from '@embedpdf/engine-runtime';\n\nimport {\n setAnnotColor,\n setAnnotOpacity,\n setAnnotRect,\n setIntent,\n} from './annotationWritePrimitives';\nimport { applyAnnotationBaseDraft, applyAnnotationBasePatch } from './writeAnnotationBase';\nimport { strikeoutIntentToName } from '../textEditIntent';\n\n/**\n * Default opacity when a draft omits `opacity`. PDFium's /CA defaults to\n * 1.0 if absent from the dict, but we set it explicitly so reads always\n * round-trip the same value.\n */\nconst DEFAULT_OPACITY = 1;\n\n/**\n * Default fill colour per text-markup subtype. Matches the read-side\n * fallback in `readers/annotations/text-markup.ts`.\n */\nconst DEFAULT_HIGHLIGHT_COLOR: Color = { r: 255, g: 255, b: 0 };\nconst DEFAULT_TEXT_MARKUP_COLOR: Color = { r: 0, g: 0, b: 0 };\n\nexport type TextMarkupDraft = HighlightDraft | UnderlineDraft | SquigglyDraft | StrikeoutDraft;\nexport type TextMarkupPatch = HighlightPatch | UnderlinePatch | SquigglyPatch | StrikeoutPatch;\n\n/**\n * Apply a text-markup draft to a freshly-created annotation. Caller is\n * responsible for `EPDFPage_CreateAnnot`; this function only writes\n * fields. Order:\n * 1. base author-metadata (contents/author/nm)\n * 2. quadPoints (required for text-markup; 0-length is a typed error)\n * 3. rect (computed from quadPoints when not supplied — text-markup\n * annotations require /Rect to be the smallest enclosing box)\n * 4. color (with subtype-aware fallback)\n * 5. opacity (/CA)\n */\nexport function applyTextMarkupDraft(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n annotPtr: Ptr,\n draft: TextMarkupDraft,\n): void {\n applyAnnotationBaseDraft(fn, mem, annotPtr, draft);\n\n const quadPoints = draft.quadPoints;\n if (!Array.isArray(quadPoints) || quadPoints.length === 0) {\n throw new EngineError(\n EngineErrorCode.InvalidArg,\n `text-markup draft (${draft.subtype}) requires at least one quadPoint`,\n );\n }\n appendQuadPoints(fn, mem, annotPtr, quadPoints);\n setRectFromQuadPoints(fn, mem, annotPtr, quadPoints);\n\n const fallback =\n draft.subtype === 'highlight' ? DEFAULT_HIGHLIGHT_COLOR : DEFAULT_TEXT_MARKUP_COLOR;\n setAnnotColor(fn, annotPtr, draft.color ?? fallback);\n setAnnotOpacity(fn, annotPtr, draft.opacity ?? DEFAULT_OPACITY);\n if (draft.subtype === 'strikeout' && draft.intent !== undefined) {\n setIntent(fn, annotPtr, strikeoutIntentToName(draft.intent));\n }\n}\n\n/**\n * Apply a text-markup patch to an existing annotation. Order:\n * 1. base author-metadata (contents/author; never /NM)\n * 2. color (only if present)\n * 3. opacity (only if present)\n * 4. quadPoints (only if present, AND non-empty — the schema accepts an\n * empty array but PDFium would treat it as a deletion of the\n * attachment-point list, which is never the user's intent. We\n * explicitly reject the empty-array case).\n *\n * `rect` is recomputed only when quadPoints change, to keep /Rect in sync\n * with the smallest enclosing box.\n */\nexport function applyTextMarkupPatch(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n annotPtr: Ptr,\n patch: TextMarkupPatch,\n): void {\n applyAnnotationBasePatch(fn, mem, annotPtr, patch);\n\n if (patch.color !== undefined) {\n setAnnotColor(fn, annotPtr, patch.color);\n }\n if (patch.opacity !== undefined) {\n setAnnotOpacity(fn, annotPtr, patch.opacity);\n }\n if (patch.subtype === 'strikeout' && patch.intent !== undefined) {\n setIntent(fn, annotPtr, strikeoutIntentToName(patch.intent));\n }\n if (patch.quadPoints !== undefined) {\n if (patch.quadPoints.length === 0) {\n throw new EngineError(\n EngineErrorCode.InvalidArg,\n `text-markup patch quadPoints, when present, must be non-empty`,\n );\n }\n replaceQuadPoints(fn, mem, annotPtr, patch.quadPoints);\n setRectFromQuadPoints(fn, mem, annotPtr, patch.quadPoints);\n }\n}\n\n/**\n * Type-narrowing predicate. Mirrors the reader-side dispatch. Used by\n * the writer registry to pick the right writer for a draft/patch's\n * `subtype` discriminator.\n */\nexport function isTextMarkupSubtype(\n subtype: string,\n): subtype is 'highlight' | 'underline' | 'squiggly' | 'strikeout' {\n return (\n subtype === 'highlight' ||\n subtype === 'underline' ||\n subtype === 'squiggly' ||\n subtype === 'strikeout'\n );\n}\n\nexport function appendQuadPoints(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n annotPtr: Ptr,\n quadPoints: PdfQuad[],\n): void {\n const buf = mem.alloc(32);\n try {\n for (const qp of quadPoints) {\n writeQuadPointStruct(mem, buf, qp);\n const ok = fn.FPDFAnnot_AppendAttachmentPoints(annotPtr, buf);\n if (!ok) {\n throw new EngineError(\n EngineErrorCode.Unknown,\n 'FPDFAnnot_AppendAttachmentPoints returned false',\n );\n }\n }\n } finally {\n mem.free(buf);\n }\n}\n\n/**\n * Replace the existing quadPoints with the supplied list. PDFium has\n * `FPDFAnnot_SetAttachmentPoints` which writes at index, but no truncate\n * helper, so we overwrite as many existing slots as we can and append\n * the rest. PDFium will GROW the list via append, but it cannot SHRINK\n * it; for that reason `applyTextMarkupPatch` rejects an empty patch and\n * the conformance suite covers the \"patch must not shrink quadPoints\"\n * rule (`patch.quadPoints.length >= existingCount`).\n */\nexport function replaceQuadPoints(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n annotPtr: Ptr,\n quadPoints: PdfQuad[],\n): void {\n const existing = fn.FPDFAnnot_CountAttachmentPoints(annotPtr);\n if (quadPoints.length < existing) {\n throw new EngineError(\n EngineErrorCode.InvalidArg,\n `text-markup patch cannot shrink quadPoints (have ${existing}, patch supplies ${quadPoints.length})`,\n );\n }\n\n const buf = mem.alloc(32);\n try {\n for (let i = 0; i < existing; i++) {\n writeQuadPointStruct(mem, buf, quadPoints[i]!);\n const ok = fn.FPDFAnnot_SetAttachmentPoints(annotPtr, i, buf);\n if (!ok) {\n throw new EngineError(\n EngineErrorCode.Unknown,\n `FPDFAnnot_SetAttachmentPoints failed at index ${i}`,\n );\n }\n }\n for (let i = existing; i < quadPoints.length; i++) {\n writeQuadPointStruct(mem, buf, quadPoints[i]!);\n const ok = fn.FPDFAnnot_AppendAttachmentPoints(annotPtr, buf);\n if (!ok) {\n throw new EngineError(\n EngineErrorCode.Unknown,\n `FPDFAnnot_AppendAttachmentPoints failed at index ${i}`,\n );\n }\n }\n } finally {\n mem.free(buf);\n }\n}\n\nfunction writeQuadPointStruct(mem: PdfRuntimeMemory, buf: Ptr, qp: PdfQuad): void {\n // FS_QUADPOINTSF layout per public/fpdf_annot.h: { x1,y1, x2,y2, x3,y3, x4,y4 }\n // = p1 p2 p3 p4 — same positional slot order as readQuadPoints.\n mem.poke(buf, 'f32', qp.p1.x, 0);\n mem.poke(buf, 'f32', qp.p1.y, 4);\n mem.poke(buf, 'f32', qp.p2.x, 8);\n mem.poke(buf, 'f32', qp.p2.y, 12);\n mem.poke(buf, 'f32', qp.p3.x, 16);\n mem.poke(buf, 'f32', qp.p3.y, 20);\n mem.poke(buf, 'f32', qp.p4.x, 24);\n mem.poke(buf, 'f32', qp.p4.y, 28);\n}\n\nexport function setRectFromQuadPoints(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n annotPtr: Ptr,\n quadPoints: PdfQuad[],\n): void {\n let minX = Number.POSITIVE_INFINITY;\n let minY = Number.POSITIVE_INFINITY;\n let maxX = Number.NEGATIVE_INFINITY;\n let maxY = Number.NEGATIVE_INFINITY;\n for (const qp of quadPoints) {\n for (const p of [qp.p1, qp.p2, qp.p3, qp.p4]) {\n if (p.x < minX) minX = p.x;\n if (p.x > maxX) maxX = p.x;\n if (p.y < minY) minY = p.y;\n if (p.y > maxY) maxY = p.y;\n }\n }\n\n // /Rect must be the smallest box enclosing every quad.\n setAnnotRect(fn, mem, annotPtr, { left: minX, top: maxY, right: maxX, bottom: minY });\n}\n","import type { Color, RedactDraft, RedactPatch } from '@embedpdf/engine-core/runtime';\nimport type { PdfFunctions, PdfRuntimeMemory, Ptr } from '@embedpdf/engine-runtime';\n\nimport { FPDFANNOT_COLORTYPE } from '../colorType';\nimport { DEFAULT_STANDARD_FONT } from '../standardFont';\nimport { textAlignmentToCode } from '../textAlignment';\nimport type { AnnotationWriteContext } from './annotationWriteContext';\nimport {\n clearAnnotColor,\n setAnnotColor,\n setAnnotOpacity,\n setAnnotRect,\n setOverlayText,\n setOverlayTextRepeat,\n setTextAlignment,\n} from './annotationWritePrimitives';\nimport { applyAnnotationBaseDraft, applyAnnotationBasePatch } from './writeAnnotationBase';\nimport { applyDefaultAppearance } from './writeDefaultAppearance';\nimport { DEFAULT_OPACITY } from './writeStyle';\nimport {\n appendQuadPoints,\n replaceQuadPoints,\n setRectFromQuadPoints,\n} from './writeTextMarkupAnnotation';\n\n/** Default `/C` marking outline: red — the redaction marking convention (and\n * the AP generator's default). */\nconst DEFAULT_REDACT_COLOR: Color = { r: 255, g: 0, b: 0 };\n\n/** Default `/DA` label colour: black, mirroring free text. Tools that pair a\n * label with a dark `interiorColor` should set a light `fontColor`\n * explicitly. */\nconst DEFAULT_LABEL_COLOR: Color = { r: 0, g: 0, b: 0 };\n\nconst DEFAULT_FONT_SIZE = 12;\n\n/**\n * True when the draft/patch carries the label or any `/DA` member — i.e. the\n * `/DA` must be (re)written. ISO 32000-2 requires a `/DA` alongside\n * `/OverlayText`, so setting a label always emits one (defaults filling any\n * omitted triple member). Clearing the label (`overlayText: null`) does not.\n */\nfunction touchesLabelStyle(p: {\n overlayText?: string | null;\n fontFamily?: unknown;\n fontSize?: number;\n fontColor?: Color;\n}): boolean {\n return (\n (p.overlayText !== undefined && p.overlayText !== null) ||\n p.fontFamily !== undefined ||\n p.fontSize !== undefined ||\n p.fontColor !== undefined\n );\n}\n\n/**\n * Apply a redact draft to a freshly-created annotation. Colour model:\n * - `color` -> `/C` marking-stage outline.\n * - `interiorColor` -> `/IC` post-apply fill (`null`/omitted = the key is\n * never written; ISO leaves the region transparent).\n * - `fontColor` -> the `/DA` colour (label text).\n *\n * Order:\n * 1. base author-metadata (contents/nm/flags)\n * 2. `/Rect` (required — supplied by the caller; never derived)\n * 3. `/QuadPoints` (text redactions only)\n * 4. `/C` outline + `/CA` opacity + `/IC` fill\n * 5. `/OverlayText` + `/Repeat`\n * 6. `/DA` (only when a label field is present)\n * 7. `/Q` label alignment\n */\nexport function applyRedactDraft(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n annotPtr: Ptr,\n draft: RedactDraft,\n ctx?: AnnotationWriteContext,\n): void {\n applyAnnotationBaseDraft(fn, mem, annotPtr, draft);\n setAnnotRect(fn, mem, annotPtr, draft.rect);\n if (draft.quadPoints && draft.quadPoints.length > 0) {\n appendQuadPoints(fn, mem, annotPtr, draft.quadPoints);\n }\n\n setAnnotColor(fn, annotPtr, draft.color ?? DEFAULT_REDACT_COLOR, FPDFANNOT_COLORTYPE.Color);\n setAnnotOpacity(fn, annotPtr, draft.opacity ?? DEFAULT_OPACITY);\n const fill = draft.interiorColor ?? null;\n if (fill !== null) {\n setAnnotColor(fn, annotPtr, fill, FPDFANNOT_COLORTYPE.InteriorColor);\n }\n\n if (draft.overlayText !== undefined && draft.overlayText.length > 0) {\n setOverlayText(fn, mem, annotPtr, draft.overlayText);\n }\n if (draft.repeat) {\n setOverlayTextRepeat(fn, annotPtr, true);\n }\n if (touchesLabelStyle(draft)) {\n applyDefaultAppearance(\n fn,\n annotPtr,\n draft.fontFamily ?? DEFAULT_STANDARD_FONT,\n draft.fontSize ?? DEFAULT_FONT_SIZE,\n draft.fontColor ?? DEFAULT_LABEL_COLOR,\n ctx,\n );\n }\n if (draft.textAlign !== undefined) {\n setTextAlignment(fn, annotPtr, textAlignmentToCode(draft.textAlign));\n }\n}\n\n/**\n * Apply a redact patch to an existing annotation. Only present fields are\n * touched. `/DA` follows the free-text triple rule: send `fontFamily` +\n * `fontSize` + `fontColor` together when changing any of them. `quadPoints`\n * shares the text-markup no-shrink constraint (PDFium can grow but not\n * shrink the attachment-points list); patching quads re-derives `/Rect` from\n * their bounds unless the patch also carries an explicit `rect`.\n */\nexport function applyRedactPatch(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n annotPtr: Ptr,\n patch: RedactPatch,\n ctx?: AnnotationWriteContext,\n): void {\n applyAnnotationBasePatch(fn, mem, annotPtr, patch);\n\n if (patch.rect !== undefined) {\n setAnnotRect(fn, mem, annotPtr, patch.rect);\n }\n if (patch.quadPoints !== undefined) {\n replaceQuadPoints(fn, mem, annotPtr, patch.quadPoints);\n if (patch.rect === undefined) {\n setRectFromQuadPoints(fn, mem, annotPtr, patch.quadPoints);\n }\n }\n\n if (patch.color !== undefined) {\n setAnnotColor(fn, annotPtr, patch.color, FPDFANNOT_COLORTYPE.Color);\n }\n if (patch.opacity !== undefined) {\n setAnnotOpacity(fn, annotPtr, patch.opacity);\n }\n if (patch.interiorColor !== undefined) {\n if (patch.interiorColor === null) {\n clearAnnotColor(fn, annotPtr, FPDFANNOT_COLORTYPE.InteriorColor);\n } else {\n setAnnotColor(fn, annotPtr, patch.interiorColor, FPDFANNOT_COLORTYPE.InteriorColor);\n }\n }\n\n if (patch.overlayText !== undefined) {\n // The native setter removes the key for an empty string, so `null`\n // (clear the label) maps to ''.\n setOverlayText(fn, mem, annotPtr, patch.overlayText ?? '');\n }\n if (patch.repeat !== undefined) {\n setOverlayTextRepeat(fn, annotPtr, patch.repeat);\n }\n if (touchesLabelStyle(patch)) {\n applyDefaultAppearance(\n fn,\n annotPtr,\n patch.fontFamily ?? DEFAULT_STANDARD_FONT,\n patch.fontSize ?? DEFAULT_FONT_SIZE,\n patch.fontColor ?? DEFAULT_LABEL_COLOR,\n ctx,\n );\n }\n if (patch.textAlign !== undefined) {\n setTextAlignment(fn, annotPtr, textAlignmentToCode(patch.textAlign));\n }\n}\n\n/**\n * Type-narrowing predicate used by the writer registry to pick the redact\n * writer for a draft/patch's `subtype`.\n */\nexport function isRedactSubtype(subtype: string): subtype is 'redact' {\n return subtype === 'redact';\n}\n","import {\n type CircleDraft,\n type CirclePatch,\n type SquareDraft,\n type SquarePatch,\n} from '@embedpdf/engine-core/runtime';\nimport type { PdfFunctions, PdfRuntimeMemory, Ptr } from '@embedpdf/engine-runtime';\n\nimport {\n clearBorderEffect,\n clearRectangleDifferences,\n setAnnotRect,\n setBorderEffect,\n setRectangleDifferences,\n} from './annotationWritePrimitives';\nimport { applyAnnotationBaseDraft, applyAnnotationBasePatch } from './writeAnnotationBase';\nimport { applyFilledStyleDraft, applyFilledStylePatch } from './writeStyle';\nimport { writeBoxTransformMetadata } from './writeAnnotationTransformMetadata';\n\nexport type ShapeDraft = CircleDraft | SquareDraft;\nexport type ShapePatch = CirclePatch | SquarePatch;\n\n/**\n * Apply a shape draft to a freshly-created annotation. Caller is\n * responsible for `EPDFPage_CreateAnnot`; this function only writes\n * fields. Order:\n * 1. base author-metadata (contents/nm)\n * 2. /Rect (required — shapes carry their geometry as /Rect, not quads)\n * 3. shared stroke/fill styling (/IC, /C, /CA, /BS, dash)\n * 4. optional cloudy (/BE), rect-diff (/RD)\n */\nexport function applyShapeDraft(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n annotPtr: Ptr,\n draft: ShapeDraft,\n): void {\n applyAnnotationBaseDraft(fn, mem, annotPtr, draft);\n\n setAnnotRect(fn, mem, annotPtr, draft.rect);\n applyFilledStyleDraft(fn, mem, annotPtr, draft);\n\n if (draft.cloudyIntensity != null && draft.cloudyIntensity > 0) {\n setBorderEffect(fn, annotPtr, draft.cloudyIntensity);\n }\n if (draft.rectDifferences != null) {\n setRectangleDifferences(fn, annotPtr, draft.rectDifferences);\n }\n // /Rect above is the rotated visual AABB; the rotation metadata tells the AP\n // generator to bake a /Matrix from the unrotated box.\n writeBoxTransformMetadata(fn, mem, annotPtr, {\n rotation: draft.rotation,\n unrotatedRect: draft.unrotatedRect,\n });\n}\n\n/**\n * Apply a shape patch to an existing annotation. Only fields present on\n * the patch are touched; `cloudyIntensity` and `rectDifferences` are\n * tri-state (as `interiorColor`): a value sets the entry, `null` removes it.\n */\nexport function applyShapePatch(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n annotPtr: Ptr,\n patch: ShapePatch,\n): void {\n applyAnnotationBasePatch(fn, mem, annotPtr, patch);\n\n if (patch.rect !== undefined) {\n setAnnotRect(fn, mem, annotPtr, patch.rect);\n }\n // Transform metadata is tri-state per field (undefined preserves, null\n // clears, value sets) — independent of whether /Rect was rewritten. A\n // rect-only patch on a rotated box keeps its rotation.\n writeBoxTransformMetadata(fn, mem, annotPtr, {\n rotation: patch.rotation,\n unrotatedRect: patch.unrotatedRect,\n });\n applyFilledStylePatch(fn, mem, annotPtr, patch);\n\n if (patch.cloudyIntensity !== undefined) {\n if (patch.cloudyIntensity !== null && patch.cloudyIntensity > 0) {\n setBorderEffect(fn, annotPtr, patch.cloudyIntensity);\n } else {\n // `null` removes /BE (tri-state). The schema forbids 0, but treat any\n // non-positive value defensively as a clear — never write a degenerate\n // /BE the read side would normalize away.\n clearBorderEffect(fn, annotPtr);\n }\n }\n if (patch.rectDifferences === null) {\n clearRectangleDifferences(fn, annotPtr);\n } else if (patch.rectDifferences !== undefined) {\n setRectangleDifferences(fn, annotPtr, patch.rectDifferences);\n }\n}\n\n/**\n * Type-narrowing predicate. Mirrors the reader-side dispatch. Used by the\n * writer registry to pick the shape writer for a draft/patch's `subtype`.\n */\nexport function isShapeSubtype(subtype: string): subtype is 'circle' | 'square' {\n return subtype === 'circle' || subtype === 'square';\n}\n","import {\n EngineError,\n EngineErrorCode,\n sniffBinaryMetadata,\n type BinaryMetadata,\n type PdfRect,\n type ResourceRef,\n type StampFit,\n type StampWireDraft,\n type StampWirePatch,\n type WireResource,\n} from '@embedpdf/engine-core/runtime';\nimport type { PdfFunctions, PdfRuntimeMemory, Ptr } from '@embedpdf/engine-runtime';\n\nimport { F32_BYTES } from '../../../../runtime/memory/structs';\nimport { readAnnotRect } from '../read/annotationReadPrimitives';\nimport { STAMP_NAME_TO_CODE } from '../stampName';\nimport type { AnnotationWriteContext } from './annotationWriteContext';\nimport { setAnnotRect } from './annotationWritePrimitives';\nimport { applyAnnotationBaseDraft, applyAnnotationBasePatch } from './writeAnnotationBase';\nimport { writeBoxTransformMetadata } from './writeAnnotationTransformMetadata';\n\n/** `EPDF_STAMP_FIT` codes from `public/fpdf_annot.h` (CSS `object-fit` naming on the wire). */\nconst STAMP_FIT_TO_CODE: Record<StampFit, number> = {\n contain: 0, // EPDF_STAMP_FIT_CONTAIN\n cover: 1, // EPDF_STAMP_FIT_COVER\n fill: 2, // EPDF_STAMP_FIT_STRETCH\n};\n\n/**\n * Validate every caller-controlled stamp input before the mutation owner\n * performs its first native write. AnnotationMutator invokes these before\n * creating an annotation or strengthening a weak annotation id.\n */\nexport function preflightStampDraft(draft: StampWireDraft, ctx?: AnnotationWriteContext): void {\n if (draft.name !== undefined) requireStampNameCode(draft.name);\n requireStampFit(draft.fit ?? 'contain');\n requireStampContent(draft.source, ctx);\n}\n\nexport function preflightStampPatch(patch: StampWirePatch, ctx?: AnnotationWriteContext): void {\n if (patch.name !== undefined) requireStampNameCode(patch.name);\n requireStampFit(patch.fit ?? 'contain');\n if (patch.source !== undefined) requireStampContent(patch.source, ctx);\n}\n\n/**\n * Apply a stamp draft. Order mirrors the other writers (base → subtype\n * fields), then the appearance pipeline via {@link authorStampAppearance}:\n * 1. resolve the `{ resource }` ref against the mutation's binary payloads\n * 2. sniff the bytes (PNG/JPEG → image object, PDF → cloned form XObject)\n * 3. `EPDFAnnot_UpdateAppearanceToRect` fits the appearance into the box\n * honouring `fit` and any `/EMBD_Metadata` rotation.\n * The mutator's `EPDFAnnot_GenerateAppearance` pass afterwards is a no-op\n * for stamps (CPDF_GenerateAP has no stamp arm), so the appearance built\n * here is what ships.\n */\nexport function applyStampDraft(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n annotPtr: Ptr,\n draft: StampWireDraft,\n ctx?: AnnotationWriteContext,\n): void {\n applyAnnotationBaseDraft(fn, mem, annotPtr, draft);\n if (draft.name !== undefined) {\n setStampName(fn, annotPtr, draft.name);\n }\n authorStampAppearance(\n fn,\n mem,\n annotPtr,\n draft.source,\n draft.fit ?? 'contain',\n {\n rect: draft.rect,\n // The appearance author wants values-or-absent; a tri-state `null`\n // (no rotation) authors the same as an omitted field.\n unrotatedRect: draft.unrotatedRect ?? undefined,\n rotation: draft.rotation ?? undefined,\n },\n ctx,\n );\n}\n\nexport function applyStampPatch(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n annotPtr: Ptr,\n patch: StampWirePatch,\n ctx?: AnnotationWriteContext,\n): void {\n applyAnnotationBasePatch(fn, mem, annotPtr, patch);\n if (patch.name !== undefined) {\n setStampName(fn, annotPtr, patch.name);\n }\n if (patch.source !== undefined) {\n // Content replacement: rebuild the appearance from the new bytes, authored\n // in the unrotated frame (see authorStampAppearance) so a rotated stamp\n // never double-fits into its padded AABB.\n const rect = patch.rect ?? readAnnotRect(fn, mem, annotPtr);\n authorStampAppearance(\n fn,\n mem,\n annotPtr,\n patch.source,\n patch.fit ?? 'contain',\n {\n rect,\n unrotatedRect: patch.unrotatedRect ?? undefined,\n rotation: patch.rotation ?? undefined,\n },\n ctx,\n );\n return;\n }\n // No new bytes: geometry / rotation / fit only.\n if (patch.rect !== undefined) {\n setAnnotRect(fn, mem, annotPtr, patch.rect);\n }\n // Transform metadata is tri-state per field (undefined preserves, null/0\n // clears, value sets) — a rect-only re-position keeps the rotation, and\n // rotate-back-to-0 is stated explicitly (`rotation: null`/`0`) by the\n // emitter rather than implied by omission.\n writeBoxTransformMetadata(fn, mem, annotPtr, {\n rotation: patch.rotation,\n unrotatedRect: patch.unrotatedRect,\n });\n if (\n patch.rect !== undefined ||\n patch.fit !== undefined ||\n patch.rotation !== undefined ||\n patch.unrotatedRect !== undefined\n ) {\n // Geometry-only patch: re-fit the existing appearance into the new /Rect.\n refitAppearance(fn, annotPtr, patch.fit ?? 'contain');\n }\n}\n\nexport function isStampSubtype(subtype: string): subtype is 'stamp' {\n return subtype === 'stamp';\n}\n\nfunction setStampName(fn: PdfFunctions, annotPtr: Ptr, name: string): void {\n const code = STAMP_NAME_TO_CODE[name];\n if (code === undefined) {\n throw new EngineError(EngineErrorCode.Unknown, 'stamp name preflight invariant broken');\n }\n if (!fn.EPDFAnnot_SetName(annotPtr, code)) {\n throw new EngineError(EngineErrorCode.Unknown, 'EPDFAnnot_SetName returned false');\n }\n}\n\nfunction requireStampNameCode(name: string): number {\n const code = STAMP_NAME_TO_CODE[name];\n if (code === undefined) {\n throw new EngineError(\n EngineErrorCode.InvalidArg,\n `unknown stamp name '${name}'; supported names: ${Object.keys(STAMP_NAME_TO_CODE).join(', ')}`,\n );\n }\n return code;\n}\n\nfunction requireStampFit(fit: StampFit): void {\n if (STAMP_FIT_TO_CODE[fit] === undefined) {\n throw new EngineError(\n EngineErrorCode.InvalidArg,\n `unknown stamp fit '${String(fit)}'; expected contain, cover, or fill`,\n );\n }\n}\n\nfunction requireStampResource(\n ref: ResourceRef,\n ctx: AnnotationWriteContext | undefined,\n): WireResource {\n const resource = ctx?.resources?.[ref.resource];\n if (!resource) {\n throw new EngineError(\n EngineErrorCode.InvalidArg,\n `stamp source references resource '${ref.resource}' but no such binary payload accompanied the mutation`,\n );\n }\n return resource;\n}\n\nfunction requireStampContent(ref: ResourceRef, ctx: AnnotationWriteContext | undefined): void {\n const resource = requireStampResource(ref, ctx);\n if (!(resource.bytes instanceof ArrayBuffer) || !sniffBinaryMetadata(resource.bytes)) {\n throw new EngineError(\n EngineErrorCode.InvalidArg,\n 'stamp source must be PNG, JPEG, or single-page PDF bytes',\n );\n }\n if (ctx?.docPtr === undefined || ctx.pagePtr === undefined) {\n throw new EngineError(\n EngineErrorCode.Unknown,\n 'stamp writer requires docPtr/pagePtr on the write context',\n );\n }\n}\n\n/** The box transform a stamp draft/patch carries (the box-kind rotation split). */\ninterface StampBox {\n /** `/Rect` — the rotated visual AABB when rotated; the box itself otherwise. */\n rect: PdfRect;\n /** The logical (pre-rotation) box; present only alongside a non-zero rotation. */\n unrotatedRect?: PdfRect;\n /** `/EMBD_Metadata/Rotation` (deg, PDF convention). */\n rotation?: number;\n}\n\n/**\n * Author a stamp's appearance from `source`, correct under rotation.\n *\n * The appearance MUST be built in the UNROTATED frame and rotated by an\n * `/AP /Matrix` afterwards — the \"FreeText pattern\" the stamp draft documents.\n * If instead the image is fit into the rotated AABB `/Rect` (a portrait box for\n * a landscape image, say), the letterboxed bands get baked into the appearance,\n * and the closing native re-fit — which records `EPDFOrigContentRect` from that\n * padded box and then fits it into the unrotated box — shrinks the image by the\n * aspect ratio a SECOND time. The result is a small image adrift in white\n * padding, and only when rotated (at 0° the two frames coincide, so it fills).\n *\n * So for a rotated stamp we: author the image into the UNROTATED box with no\n * rotation metadata active (its recorded `EPDFOrigContentRect` is the\n * image-filled logical box), then write the rotation metadata, set the real\n * AABB `/Rect`, and re-fit once — which bakes the `/Matrix` and leaves the\n * appearance filling the box exactly as the 0° case does. The unrotated path is\n * unchanged: author straight into `/Rect`.\n */\nfunction authorStampAppearance(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n annotPtr: Ptr,\n source: ResourceRef,\n fit: StampFit,\n box: StampBox,\n ctx: AnnotationWriteContext | undefined,\n): void {\n const rotated = !!box.rotation && box.unrotatedRect !== undefined;\n if (!rotated) {\n setAnnotRect(fn, mem, annotPtr, box.rect);\n setStampContent(fn, mem, annotPtr, source, fit, box.rect, ctx);\n return;\n }\n const unrotated = box.unrotatedRect!;\n // 1. Author in the unrotated frame — clear any rotation metadata first so the\n // internal re-fit records an image-shaped EPDFOrigContentRect, not the AABB.\n writeBoxTransformMetadata(fn, mem, annotPtr, {});\n setAnnotRect(fn, mem, annotPtr, unrotated);\n setStampContent(fn, mem, annotPtr, source, fit, unrotated, ctx);\n // 2. Apply the transform: metadata bakes the /Matrix, /Rect becomes the AABB,\n // and one re-fit reconciles BBox + Matrix from the now-recorded content.\n writeBoxTransformMetadata(fn, mem, annotPtr, {\n rotation: box.rotation,\n unrotatedRect: unrotated,\n });\n setAnnotRect(fn, mem, annotPtr, box.rect);\n refitAppearance(fn, annotPtr, fit);\n}\n\nfunction setStampContent(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n annotPtr: Ptr,\n ref: ResourceRef,\n fit: StampFit,\n rect: PdfRect,\n ctx: AnnotationWriteContext | undefined,\n): void {\n const resource = ctx?.resources?.[ref.resource];\n const meta = resource ? sniffBinaryMetadata(resource.bytes) : null;\n if (!resource || !meta || ctx?.docPtr === undefined || ctx.pagePtr === undefined) {\n throw new EngineError(EngineErrorCode.Unknown, 'stamp content preflight invariant broken');\n }\n\n // Replace, not merge: drop any existing appearance objects (no-op on create).\n for (let i = fn.FPDFAnnot_GetObjectCount(annotPtr) - 1; i >= 0; i--) {\n fn.FPDFAnnot_RemoveObject(annotPtr, i);\n }\n\n if (meta.mimeType === 'application/pdf') {\n setAppearanceFromPdfBytes(fn, mem, annotPtr, resource.bytes);\n } else {\n appendImageObject(fn, mem, annotPtr, ctx.docPtr, ctx.pagePtr, resource.bytes, meta, rect, fit);\n }\n\n // Normalises the AP (BBox, EPDFOrigContentRect for future re-fits) and\n // applies any /EMBD_Metadata rotation — same closing step as v2.\n refitAppearance(fn, annotPtr, fit);\n}\n\nfunction refitAppearance(fn: PdfFunctions, annotPtr: Ptr, fit: StampFit): void {\n if (!fn.EPDFAnnot_UpdateAppearanceToRect(annotPtr, STAMP_FIT_TO_CODE[fit])) {\n throw new EngineError(\n EngineErrorCode.Unknown,\n 'EPDFAnnot_UpdateAppearanceToRect returned false',\n );\n }\n}\n\n/**\n * PNG/JPEG → image object appended to the appearance.\n *\n * The AP's coordinate space aligns with page space (its BBox is the annot\n * `/Rect`, same as v2), so the image must be painted INSIDE `/Rect` or it\n * falls outside the form's clip and renders blank. The `fit` placement is\n * computed here from the sniffed intrinsic dimensions; the closing\n * `EPDFAnnot_UpdateAppearanceToRect` pass then normalises the BBox and\n * records `EPDFOrigContentRect` so later geometry-only patches can re-fit\n * natively.\n */\nfunction appendImageObject(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n annotPtr: Ptr,\n docPtr: Ptr,\n pagePtr: Ptr,\n bytes: ArrayBuffer,\n meta: Extract<BinaryMetadata, { width: number }>,\n rect: PdfRect,\n fit: StampFit,\n): void {\n const imageObjPtr = fn.FPDFPageObj_NewImageObj(docPtr);\n if (!imageObjPtr) {\n throw new EngineError(EngineErrorCode.Unknown, 'FPDFPageObj_NewImageObj returned NULL');\n }\n\n let appended = false;\n try {\n const dataPtr = mem.alloc(bytes.byteLength);\n try {\n mem.writeBytes(dataPtr, new Uint8Array(bytes));\n const ok =\n meta.mimeType === 'image/png'\n ? fn.EPDFImageObj_SetPng(pagePtr, 0, imageObjPtr, dataPtr, bytes.byteLength)\n : fn.EPDFImageObj_SetJpeg(pagePtr, 0, imageObjPtr, dataPtr, bytes.byteLength);\n if (!ok) {\n throw new EngineError(\n EngineErrorCode.InvalidArg,\n `${meta.mimeType === 'image/png' ? 'EPDFImageObj_SetPng' : 'EPDFImageObj_SetJpeg'} rejected the image data`,\n );\n }\n } finally {\n mem.free(dataPtr);\n }\n\n const placement = fitIntoRect(meta.width, meta.height, rect, fit);\n setImageMatrix(fn, mem, imageObjPtr, placement.width, placement.height);\n fn.FPDFPageObj_Transform(imageObjPtr, 1, 0, 0, 1, placement.left, placement.bottom);\n\n if (!fn.FPDFAnnot_AppendObject(annotPtr, imageObjPtr)) {\n throw new EngineError(EngineErrorCode.Unknown, 'FPDFAnnot_AppendObject returned false');\n }\n appended = true;\n } finally {\n // The annotation owns the object once appended; on failure we own it.\n if (!appended) {\n fn.FPDFPageObj_Destroy(imageObjPtr);\n }\n }\n}\n\n/** Fit-policy placement of `w×h` content inside `rect` (centered for the aspect-preserving fits). */\nfunction fitIntoRect(\n w: number,\n h: number,\n rect: PdfRect,\n fit: StampFit,\n): { left: number; bottom: number; width: number; height: number } {\n const boxW = Math.max(0, rect.right - rect.left);\n const boxH = Math.max(0, rect.top - rect.bottom);\n if (fit === 'fill' || w <= 0 || h <= 0) {\n return { left: rect.left, bottom: rect.bottom, width: boxW, height: boxH };\n }\n const scale = fit === 'contain' ? Math.min(boxW / w, boxH / h) : Math.max(boxW / w, boxH / h);\n const width = w * scale;\n const height = h * scale;\n return {\n left: rect.left + (boxW - width) / 2,\n bottom: rect.bottom + (boxH - height) / 2,\n width,\n height,\n };\n}\n\n/** FS_MATRIX { a, b, c, d, e, f } — six f32s. */\nfunction setImageMatrix(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n imageObjPtr: Ptr,\n width: number,\n height: number,\n): void {\n const buf = mem.alloc(6 * F32_BYTES);\n try {\n mem.poke(buf, 'f32', width, 0);\n mem.poke(buf, 'f32', 0, 4);\n mem.poke(buf, 'f32', 0, 8);\n mem.poke(buf, 'f32', height, 12);\n mem.poke(buf, 'f32', 0, 16);\n mem.poke(buf, 'f32', 0, 20);\n if (!fn.FPDFPageObj_SetMatrix(imageObjPtr, buf)) {\n throw new EngineError(EngineErrorCode.Unknown, 'FPDFPageObj_SetMatrix returned false');\n }\n } finally {\n mem.free(buf);\n }\n}\n\n/**\n * Single-page PDF → deep-cloned Form XObject as AP/N (the v2 rubber-stamp\n * path). The source buffer must stay alive until the temp document closes.\n */\nfunction setAppearanceFromPdfBytes(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n annotPtr: Ptr,\n bytes: ArrayBuffer,\n): void {\n const dataPtr = mem.alloc(bytes.byteLength);\n try {\n mem.writeBytes(dataPtr, new Uint8Array(bytes));\n const tempDocPtr = fn.FPDF_LoadMemDocument(dataPtr, bytes.byteLength, '');\n if (!tempDocPtr) {\n throw new EngineError(EngineErrorCode.MalformedPdf, 'stamp source PDF could not be opened');\n }\n try {\n if (!fn.EPDFAnnot_SetAppearanceFromPage(annotPtr, tempDocPtr, 0)) {\n throw new EngineError(\n EngineErrorCode.Unknown,\n 'EPDFAnnot_SetAppearanceFromPage returned false',\n );\n }\n } finally {\n fn.FPDF_CloseDocument(tempDocPtr);\n }\n } finally {\n mem.free(dataPtr);\n }\n}\n","import type { Color, TextDraft, TextPatch } from '@embedpdf/engine-core/runtime';\nimport { EngineError, EngineErrorCode } from '@embedpdf/engine-core/runtime';\nimport type { PdfFunctions, PdfRuntimeMemory, Ptr } from '@embedpdf/engine-runtime';\n\nimport { NOTE_ICON_TO_CODE } from '../annotationIcon';\nimport { setAnnotColor, setAnnotOpacity, setAnnotRect } from './annotationWritePrimitives';\nimport { applyAnnotationBaseDraft, applyAnnotationBasePatch } from './writeAnnotationBase';\n\n/** Default `/C` — the generator's yellow note fill, set explicitly so reads round-trip. */\nconst DEFAULT_NOTE_COLOR: Color = { r: 255, g: 255, b: 0 };\n\nconst DEFAULT_OPACITY = 1;\n\n/**\n * Apply a text (sticky-note) draft. The visual is entirely generator-owned:\n * the mutator's closing `regenerateAppearance` bakes the 20×20 note icon\n * from `/C` + `/Name` (GenerateTextAP), so this writer only records state.\n */\nexport function applyTextDraft(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n annotPtr: Ptr,\n draft: TextDraft,\n): void {\n applyAnnotationBaseDraft(fn, mem, annotPtr, draft);\n setAnnotRect(fn, mem, annotPtr, draft.rect);\n setAnnotColor(fn, annotPtr, draft.color ?? DEFAULT_NOTE_COLOR);\n setAnnotOpacity(fn, annotPtr, draft.opacity ?? DEFAULT_OPACITY);\n setNoteIcon(fn, annotPtr, draft.icon ?? 'note');\n}\n\nexport function applyTextPatch(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n annotPtr: Ptr,\n patch: TextPatch,\n): void {\n applyAnnotationBasePatch(fn, mem, annotPtr, patch);\n if (patch.rect !== undefined) {\n setAnnotRect(fn, mem, annotPtr, patch.rect);\n }\n if (patch.color !== undefined) {\n setAnnotColor(fn, annotPtr, patch.color);\n }\n if (patch.opacity !== undefined) {\n setAnnotOpacity(fn, annotPtr, patch.opacity);\n }\n if (patch.icon !== undefined) {\n setNoteIcon(fn, annotPtr, patch.icon);\n }\n}\n\nexport function isTextSubtype(subtype: string): subtype is 'text' {\n return subtype === 'text';\n}\n\nfunction setNoteIcon(fn: PdfFunctions, annotPtr: Ptr, icon: keyof typeof NOTE_ICON_TO_CODE): void {\n if (!fn.EPDFAnnot_SetName(annotPtr, NOTE_ICON_TO_CODE[icon])) {\n throw new EngineError(EngineErrorCode.Unknown, 'EPDFAnnot_SetName returned false');\n }\n}\n","import type {\n PolygonDraft,\n PolygonPatch,\n PolylineDraft,\n PolylinePatch,\n} from '@embedpdf/engine-core/runtime';\nimport type { PdfFunctions, PdfRuntimeMemory, Ptr } from '@embedpdf/engine-runtime';\n\nimport {\n clearBorderEffect,\n setAnnotRect,\n setBorderEffect,\n setLineEndings,\n setVertices,\n} from './annotationWritePrimitives';\nimport { applyAnnotationBaseDraft, applyAnnotationBasePatch } from './writeAnnotationBase';\nimport { applyFilledStyleDraft, applyFilledStylePatch } from './writeStyle';\nimport { writeVertexTransformMetadata } from './writeAnnotationTransformMetadata';\n\nexport type VertexDraft = PolygonDraft | PolylineDraft;\nexport type VertexPatch = PolygonPatch | PolylinePatch;\n\n/** Default line endings when a polyline draft omits them. */\nconst DEFAULT_LINE_ENDINGS = { start: 'none', end: 'none' } as const;\n\n/**\n * Apply a polygon draft to a freshly-created annotation. Order:\n * 1. base author-metadata (contents/nm)\n * 2. /Rect (required — supplied by the plugin; the engine never derives it)\n * 3. shared stroke/fill styling (/IC, /C, /CA, /BS, dash)\n * 4. /Vertices geometry\n * 5. optional cloudy (/BE)\n *\n * Note: polygon does NOT use /RD (rectangle differences) — its geometry is\n * fully described by /Vertices + /Rect, so /RD is redundant. Per ISO 32000\n * /RD applies to Square/Circle (and FreeText/Caret), not Polygon.\n */\nexport function applyPolygonDraft(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n annotPtr: Ptr,\n draft: PolygonDraft,\n): void {\n applyAnnotationBaseDraft(fn, mem, annotPtr, draft);\n setAnnotRect(fn, mem, annotPtr, draft.rect);\n applyFilledStyleDraft(fn, mem, annotPtr, draft);\n setVertices(fn, mem, annotPtr, draft.vertices);\n\n if (draft.cloudyIntensity != null && draft.cloudyIntensity > 0) {\n setBorderEffect(fn, annotPtr, draft.cloudyIntensity);\n }\n // Advisory rotation: the vertices are already rotated; this just records θ.\n writeVertexTransformMetadata(fn, annotPtr, { rotation: draft.rotation });\n}\n\nexport function applyPolygonPatch(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n annotPtr: Ptr,\n patch: PolygonPatch,\n): void {\n applyAnnotationBasePatch(fn, mem, annotPtr, patch);\n if (patch.rect !== undefined) {\n setAnnotRect(fn, mem, annotPtr, patch.rect);\n }\n applyFilledStylePatch(fn, mem, annotPtr, patch);\n if (patch.vertices !== undefined) {\n setVertices(fn, mem, annotPtr, patch.vertices);\n }\n // Advisory rotation is tri-state (undefined preserves, null/0 clears).\n writeVertexTransformMetadata(fn, annotPtr, { rotation: patch.rotation });\n if (patch.cloudyIntensity !== undefined) {\n if (patch.cloudyIntensity !== null && patch.cloudyIntensity > 0) {\n setBorderEffect(fn, annotPtr, patch.cloudyIntensity);\n } else {\n // `null` removes /BE (tri-state). The schema forbids 0, but treat any\n // non-positive value defensively as a clear — never write a degenerate\n // /BE the read side would normalize away.\n clearBorderEffect(fn, annotPtr);\n }\n }\n}\n\n/**\n * Apply a polyline draft to a freshly-created annotation. Order:\n * 1. base author-metadata (contents/nm)\n * 2. /Rect (required — supplied by the plugin)\n * 3. shared stroke/fill styling (/IC, /C, /CA, /BS, dash)\n * 4. /Vertices geometry\n * 5. /LE line endings (default none/none)\n */\nexport function applyPolylineDraft(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n annotPtr: Ptr,\n draft: PolylineDraft,\n): void {\n applyAnnotationBaseDraft(fn, mem, annotPtr, draft);\n setAnnotRect(fn, mem, annotPtr, draft.rect);\n applyFilledStyleDraft(fn, mem, annotPtr, draft);\n setVertices(fn, mem, annotPtr, draft.vertices);\n setLineEndings(fn, annotPtr, draft.lineEndings ?? DEFAULT_LINE_ENDINGS);\n // Advisory rotation: the vertices are already rotated; this just records θ.\n writeVertexTransformMetadata(fn, annotPtr, { rotation: draft.rotation });\n}\n\nexport function applyPolylinePatch(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n annotPtr: Ptr,\n patch: PolylinePatch,\n): void {\n applyAnnotationBasePatch(fn, mem, annotPtr, patch);\n if (patch.rect !== undefined) {\n setAnnotRect(fn, mem, annotPtr, patch.rect);\n }\n applyFilledStylePatch(fn, mem, annotPtr, patch);\n if (patch.vertices !== undefined) {\n setVertices(fn, mem, annotPtr, patch.vertices);\n }\n // Advisory rotation is tri-state (undefined preserves, null/0 clears).\n writeVertexTransformMetadata(fn, annotPtr, { rotation: patch.rotation });\n if (patch.lineEndings !== undefined) {\n setLineEndings(fn, annotPtr, patch.lineEndings);\n }\n}\n\n/**\n * Type-narrowing predicate used by the writer registry to pick the vertex\n * writer for a draft/patch's `subtype`.\n */\nexport function isVertexSubtype(subtype: string): subtype is 'polygon' | 'polyline' {\n return subtype === 'polygon' || subtype === 'polyline';\n}\n","import type {\n AnnotationSubtype,\n WidgetDraft,\n WidgetPatch,\n WidgetStyleDraftFields,\n} from '@embedpdf/engine-core/runtime';\nimport type { PdfFunctions, PdfRuntimeMemory, Ptr } from '@embedpdf/engine-runtime';\n\nimport { borderStyleToCode } from '../shapeBorderStyle';\nimport { standardFontToCode } from '../standardFont';\nimport { textAlignmentToCode } from '../textAlignment';\nimport { setAnnotRect } from './annotationWritePrimitives';\n\nconst MK_BORDER_COLOR = 0; // EPDF_MK_COLOR_BC\nconst MK_BACKGROUND_COLOR = 1; // EPDF_MK_COLOR_BG\n\nexport function isWidgetSubtype(subtype: AnnotationSubtype): subtype is 'widget' {\n return subtype === 'widget';\n}\n\n/**\n * THE widget-plane style writer: /MK colours, /BS, /DA, /Q. Both entry\n * points funnel here — the widget annotation kind (create/patch) and\n * `doc.forms.createField`'s inline placements — so creation-time and\n * edit-time styling can never drift apart.\n */\nexport function applyWidgetStyle(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n annotPtr: Ptr,\n style: WidgetStyleDraftFields,\n): void {\n if (style.color === null) {\n fn.EPDFAnnot_ClearMKColor(annotPtr, MK_BORDER_COLOR);\n } else if (style.color) {\n fn.EPDFAnnot_SetMKColor(annotPtr, MK_BORDER_COLOR, style.color.r, style.color.g, style.color.b);\n }\n if (style.interiorColor === null) {\n fn.EPDFAnnot_ClearMKColor(annotPtr, MK_BACKGROUND_COLOR);\n } else if (style.interiorColor) {\n fn.EPDFAnnot_SetMKColor(\n annotPtr,\n MK_BACKGROUND_COLOR,\n style.interiorColor.r,\n style.interiorColor.g,\n style.interiorColor.b,\n );\n }\n\n if (style.strokeWidth !== undefined || style.borderStyle !== undefined) {\n fn.EPDFAnnot_SetBorderStyle(\n annotPtr,\n borderStyleToCode(style.borderStyle ?? 'solid'),\n style.strokeWidth ?? 1,\n );\n }\n\n if (\n style.fontFamily !== undefined ||\n style.fontSize !== undefined ||\n style.fontColor !== undefined\n ) {\n const color = style.fontColor ?? { r: 0, g: 0, b: 0 };\n fn.EPDFAnnot_SetDefaultAppearance(\n annotPtr,\n standardFontToCode(style.fontFamily ?? 'helvetica'),\n style.fontSize ?? 12,\n color.r,\n color.g,\n color.b,\n );\n }\n\n if (style.textAlign !== undefined) {\n fn.EPDFAnnot_SetTextAlignment(annotPtr, textAlignmentToCode(style.textAlign));\n }\n}\n\n/** Create an INERT widget: placement + style. Adoption is a forms concern. */\nexport function applyWidgetDraft(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n annotPtr: Ptr,\n draft: WidgetDraft,\n): void {\n setAnnotRect(fn, mem, annotPtr, draft.rect);\n applyWidgetStyle(fn, mem, annotPtr, draft);\n}\n\n/**\n * Move/restyle a widget. When the widget is attached to a field the\n * family-correct appearance is re-baked afterwards; on inert widgets the\n * regenerator is a no-op (no /FT context) and that is fine.\n */\nexport function applyWidgetPatch(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n annotPtr: Ptr,\n patch: WidgetPatch,\n): void {\n if (patch.rect) {\n setAnnotRect(fn, mem, annotPtr, patch.rect);\n }\n applyWidgetStyle(fn, mem, annotPtr, patch);\n fn.EPDFAnnot_GenerateFormFieldAP(annotPtr);\n}\n","import {\n EngineError,\n EngineErrorCode,\n type WireAnnotationDraft,\n type WireAnnotationPatch,\n} from '@embedpdf/engine-core/runtime';\nimport type {\n CaretDraft,\n CaretPatch,\n WidgetDraft,\n WidgetPatch,\n FreeTextDraft,\n FreeTextPatch,\n InkDraft,\n InkPatch,\n LineDraft,\n LinePatch,\n LinkDraft,\n LinkPatch,\n PolygonDraft,\n PolygonPatch,\n PolylineDraft,\n PolylinePatch,\n RedactDraft,\n RedactPatch,\n StampWireDraft,\n StampWirePatch,\n TextDraft,\n TextPatch,\n FileAttachmentWireDraft,\n FileAttachmentPatch,\n} from '@embedpdf/engine-core/runtime';\nimport type { PdfFunctions, PdfRuntimeMemory, Ptr } from '@embedpdf/engine-runtime';\n\nimport type { AnnotationWriteContext } from './annotationWriteContext';\nimport { applyCaretDraft, applyCaretPatch, isCaretSubtype } from './writeCaretAnnotation';\nimport {\n applyFileAttachmentDraft,\n applyFileAttachmentPatch,\n isFileAttachmentSubtype,\n preflightFileAttachmentDraft,\n} from './writeFileAttachmentAnnotation';\nimport {\n applyFreeTextDraft,\n applyFreeTextPatch,\n isFreeTextSubtype,\n} from './writeFreeTextAnnotation';\nimport { applyInkDraft, applyInkPatch, isInkSubtype } from './writeInkAnnotation';\nimport { applyLineDraft, applyLinePatch, isLineSubtype } from './writeLineAnnotation';\nimport { applyLinkDraft, applyLinkPatch, isLinkSubtype } from './writeLinkAnnotation';\nimport { applyRedactDraft, applyRedactPatch, isRedactSubtype } from './writeRedactAnnotation';\nimport {\n applyShapeDraft,\n applyShapePatch,\n isShapeSubtype,\n type ShapeDraft,\n type ShapePatch,\n} from './writeShapeAnnotation';\nimport {\n applyStampDraft,\n applyStampPatch,\n isStampSubtype,\n preflightStampDraft,\n preflightStampPatch,\n} from './writeStampAnnotation';\nimport { applyTextDraft, applyTextPatch, isTextSubtype } from './writeTextAnnotation';\nimport {\n applyTextMarkupDraft,\n applyTextMarkupPatch,\n isTextMarkupSubtype,\n type TextMarkupDraft,\n type TextMarkupPatch,\n} from './writeTextMarkupAnnotation';\nimport {\n applyPolygonDraft,\n applyPolygonPatch,\n applyPolylineDraft,\n applyPolylinePatch,\n isVertexSubtype,\n} from './writeVertexAnnotation';\nimport { applyWidgetDraft, applyWidgetPatch, isWidgetSubtype } from './writeWidgetAnnotation';\n\n/** Validate subtype inputs before AnnotationMutator performs any native write. */\nexport function preflightDraft(draft: WireAnnotationDraft, ctx?: AnnotationWriteContext): void {\n if (isStampSubtype(draft.subtype)) {\n preflightStampDraft(draft as StampWireDraft, ctx);\n }\n if (isFileAttachmentSubtype(draft.subtype)) {\n preflightFileAttachmentDraft(draft as FileAttachmentWireDraft, ctx);\n }\n}\n\n/** Validate subtype inputs before AnnotationMutator performs any native write. */\nexport function preflightPatch(patch: WireAnnotationPatch, ctx?: AnnotationWriteContext): void {\n if (isStampSubtype(patch.subtype)) {\n preflightStampPatch(patch as StampWirePatch, ctx);\n }\n}\n\n/**\n * Per-subtype write dispatch, mirroring the read-side registry. Adding a\n * new subtype is one extra arm here plus its writer module — no other\n * file in this package needs to change.\n *\n * The mutator calls `applyDraft` or `applyPatch` once per mutation; the\n * actual `EPDFPage_CreateAnnot` / identity resolution happens around\n * these calls in `AnnotationMutator`.\n */\nexport function applyDraft(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n annotPtr: Ptr,\n draft: WireAnnotationDraft,\n ctx?: AnnotationWriteContext,\n): void {\n if (isTextMarkupSubtype(draft.subtype)) {\n applyTextMarkupDraft(fn, mem, annotPtr, draft as TextMarkupDraft);\n return;\n }\n if (isShapeSubtype(draft.subtype)) {\n applyShapeDraft(fn, mem, annotPtr, draft as ShapeDraft);\n return;\n }\n if (isVertexSubtype(draft.subtype)) {\n if (draft.subtype === 'polygon') {\n applyPolygonDraft(fn, mem, annotPtr, draft as PolygonDraft);\n } else {\n applyPolylineDraft(fn, mem, annotPtr, draft as PolylineDraft);\n }\n return;\n }\n if (isLineSubtype(draft.subtype)) {\n applyLineDraft(fn, mem, annotPtr, draft as LineDraft);\n return;\n }\n if (isLinkSubtype(draft.subtype)) {\n applyLinkDraft(fn, mem, annotPtr, draft as LinkDraft, ctx);\n return;\n }\n if (isInkSubtype(draft.subtype)) {\n applyInkDraft(fn, mem, annotPtr, draft as InkDraft);\n return;\n }\n if (isFreeTextSubtype(draft.subtype)) {\n applyFreeTextDraft(fn, mem, annotPtr, draft as FreeTextDraft, ctx);\n return;\n }\n if (isCaretSubtype(draft.subtype)) {\n applyCaretDraft(fn, mem, annotPtr, draft as CaretDraft);\n return;\n }\n if (isTextSubtype(draft.subtype)) {\n applyTextDraft(fn, mem, annotPtr, draft as TextDraft);\n return;\n }\n if (isStampSubtype(draft.subtype)) {\n applyStampDraft(fn, mem, annotPtr, draft as StampWireDraft, ctx);\n return;\n }\n if (isFileAttachmentSubtype(draft.subtype)) {\n applyFileAttachmentDraft(fn, mem, annotPtr, draft as FileAttachmentWireDraft, ctx);\n return;\n }\n if (isWidgetSubtype(draft.subtype)) {\n applyWidgetDraft(fn, mem, annotPtr, draft as WidgetDraft);\n return;\n }\n if (isRedactSubtype(draft.subtype)) {\n applyRedactDraft(fn, mem, annotPtr, draft as RedactDraft, ctx);\n return;\n }\n // Should be unreachable: AnnotationDraft is the closed union of writable\n // subtypes (which today is exactly the four text-markup kinds — the\n // unsupported kind has Draft = never). The check is here so a future\n // subtype that lands in `AnnotationDraft` without a writer entry fails\n // loud at runtime instead of silently no-op-ing.\n throw new EngineError(\n EngineErrorCode.NotImplemented,\n `no writer registered for draft.subtype='${(draft as { subtype: string }).subtype}'`,\n );\n}\n\nexport function applyPatch(\n fn: PdfFunctions,\n mem: PdfRuntimeMemory,\n annotPtr: Ptr,\n patch: WireAnnotationPatch,\n ctx?: AnnotationWriteContext,\n): void {\n if (isTextMarkupSubtype(patch.subtype)) {\n applyTextMarkupPatch(fn, mem, annotPtr, patch as TextMarkupPatch);\n return;\n }\n if (isShapeSubtype(patch.subtype)) {\n applyShapePatch(fn, mem, annotPtr, patch as ShapePatch);\n return;\n }\n if (isVertexSubtype(patch.subtype)) {\n if (patch.subtype === 'polygon') {\n applyPolygonPatch(fn, mem, annotPtr, patch as PolygonPatch);\n } else {\n applyPolylinePatch(fn, mem, annotPtr, patch as PolylinePatch);\n }\n return;\n }\n if (isLineSubtype(patch.subtype)) {\n applyLinePatch(fn, mem, annotPtr, patch as LinePatch);\n return;\n }\n if (isLinkSubtype(patch.subtype)) {\n applyLinkPatch(fn, mem, annotPtr, patch as LinkPatch, ctx);\n return;\n }\n if (isInkSubtype(patch.subtype)) {\n applyInkPatch(fn, mem, annotPtr, patch as InkPatch);\n return;\n }\n if (isFreeTextSubtype(patch.subtype)) {\n applyFreeTextPatch(fn, mem, annotPtr, patch as FreeTextPatch, ctx);\n return;\n }\n if (isCaretSubtype(patch.subtype)) {\n applyCaretPatch(fn, mem, annotPtr, patch as CaretPatch);\n return;\n }\n if (isTextSubtype(patch.subtype)) {\n applyTextPatch(fn, mem, annotPtr, patch as TextPatch);\n return;\n }\n if (isStampSubtype(patch.subtype)) {\n applyStampPatch(fn, mem, annotPtr, patch as StampWirePatch, ctx);\n return;\n }\n if (isFileAttachmentSubtype(patch.subtype)) {\n applyFileAttachmentPatch(fn, mem, annotPtr, patch as FileAttachmentPatch);\n return;\n }\n if (isWidgetSubtype(patch.subtype)) {\n applyWidgetPatch(fn, mem, annotPtr, patch as WidgetPatch);\n return;\n }\n if (isRedactSubtype(patch.subtype)) {\n applyRedactPatch(fn, mem, annotPtr, patch as RedactPatch, ctx);\n return;\n }\n throw new EngineError(\n EngineErrorCode.NotImplemented,\n `no writer registered for patch.subtype='${(patch as { subtype: string }).subtype}'`,\n );\n}\n","import type {\n AnnotationRef,\n AnnotationReplyType,\n AnnotationStableId,\n PageObjectNumber,\n} from '@embedpdf/engine-core/runtime';\nimport { EngineError, EngineErrorCode } from '@embedpdf/engine-core/runtime';\nimport { NULL_PTR, type PdfRuntimeModule, type Ptr } from '@embedpdf/engine-runtime';\n\nimport type { DocumentSession } from '../../../../document-session/DocumentSession';\nimport { captureOrStampStableId } from '../identity/captureOrStampStableId';\nimport { resolveAnnotPtr } from '../identity/resolveAnnotationPointer';\nimport { RT_UNKNOWN, replyTypeToCode } from '../replyType';\n\n/**\n * The `/IRT` + `/RT` slice of a draft or patch, normalized to the three\n * cases the writer handles.\n */\nexport interface RelationshipWrite {\n /**\n * undefined -> leave `/IRT` untouched\n * null -> clear `/IRT` (+ `/RT`)\n * ref -> set/relink `/IRT` to this parent\n */\n inReplyTo?: AnnotationRef | null;\n /** `/RT` to write; defaults to `'reply'` when a link is set without it. */\n replyType?: AnnotationReplyType;\n}\n\n/**\n * Apply the `/IRT` + `/RT` relationship to `annotPtr` on an\n * already-acquired `pagePtr`. Returns the parent's (possibly newly\n * strengthened) {@link AnnotationStableId} when a link was SET, so the\n * mutator can report the side-effecting promotion in `meta.changed`;\n * `null` for the clear / RT-only / no-op cases.\n *\n * Linking to a parent that is a weak/direct object promotes it to an\n * indirect object (`/IRT` must be an indirect reference). This is\n * non-structural — it assigns the parent an object number in place\n * without shifting any `/Annots` index — so it does not invalidate weak\n * refs or warrant a revision bump. We strengthen the parent with a\n * durable `/NM` BEFORE linking (via {@link captureOrStampStableId}) so its\n * identity survives a full save/reload, and report that id upstream.\n *\n * ISO 32000 §12.5.6.2 requires the reply and its parent to share a page;\n * we enforce that here with a fast `InvalidArg` (PDFium itself only checks\n * same-document).\n */\nexport function writeAnnotationRelationship(\n runtime: PdfRuntimeModule,\n session: DocumentSession,\n pagePtr: Ptr,\n annotPtr: Ptr,\n pageObjectNumber: PageObjectNumber,\n rel: RelationshipWrite,\n): AnnotationStableId | null {\n const { fn } = runtime;\n\n // Clear: remove /IRT and /RT; the annotation becomes top-level.\n if (rel.inReplyTo === null) {\n fn.EPDFAnnot_SetLinkedAnnot(annotPtr, 'IRT', NULL_PTR);\n fn.EPDFAnnot_SetReplyType(annotPtr, RT_UNKNOWN);\n return null;\n }\n\n // Set / relink.\n if (rel.inReplyTo) {\n if (rel.inReplyTo.pageObjectNumber !== pageObjectNumber) {\n throw new EngineError(\n EngineErrorCode.InvalidArg,\n `/IRT parent must be on the same page as the reply (parent page ${rel.inReplyTo.pageObjectNumber}, reply page ${pageObjectNumber})`,\n );\n }\n const parentPtr = resolveAnnotPtr(runtime, session, pagePtr, rel.inReplyTo);\n try {\n // Strengthen BEFORE the link promotes the parent to indirect, so the\n // reported id is the save-stable /NM rather than a renumberable objNum.\n const parentStableId = captureOrStampStableId(runtime, parentPtr);\n if (!fn.EPDFAnnot_SetLinkedAnnot(annotPtr, 'IRT', parentPtr)) {\n throw new EngineError(EngineErrorCode.Unknown, 'failed to set /IRT linked annotation');\n }\n fn.EPDFAnnot_SetReplyType(annotPtr, replyTypeToCode(rel.replyType ?? 'reply'));\n return parentStableId;\n } finally {\n fn.FPDFPage_CloseAnnot(parentPtr);\n }\n }\n\n // inReplyTo undefined: a standalone /RT change only applies if the\n // annotation already has an /IRT link (RT without IRT is meaningless per\n // ISO 32000 §12.5.6.2). Silently skip otherwise.\n if (rel.replyType !== undefined) {\n const linkedPtr = fn.FPDFAnnot_GetLinkedAnnot(annotPtr, 'IRT');\n if (linkedPtr) {\n try {\n fn.EPDFAnnot_SetReplyType(annotPtr, replyTypeToCode(rel.replyType));\n } finally {\n fn.FPDFPage_CloseAnnot(linkedPtr);\n }\n }\n }\n return null;\n}\n","import {\n appearanceImpactOf,\n EngineError,\n EngineErrorCode,\n PDF_SUBTYPE_TO_CODE,\n type AnnotationActor,\n type AppearanceOutcome,\n type BlendMode,\n type AnnotationCreateResult,\n type AnnotationDeleteResult,\n type AnnotationDTO,\n type WireAnnotationDraft,\n type AnnotationListMutationMeta,\n type AnnotationMoveResult,\n type WireAnnotationPatch,\n type WireResourceMap,\n type AnnotationRef,\n type AnnotationStableId,\n type AnnotationUpdateResult,\n type PageObjectNumber,\n PdfAnnotationSubtypeCode,\n} from '@embedpdf/engine-core/runtime';\nimport type { PdfRuntimeModule, Ptr } from '@embedpdf/engine-runtime';\n\nimport { blendModeFromCode, blendModeToCode } from './internal/blendMode';\nimport type { DocumentSession } from '../../document-session/DocumentSession';\nimport { throwIfAborted } from '../../shared/abort';\nimport type { FontRegistrar } from '../fonts';\nimport { captureOrStampStableId } from './internal/identity/captureOrStampStableId';\nimport { resolveAnnotPtr } from './internal/identity/resolveAnnotationPointer';\nimport { computeMutationImpact } from './internal/mutations/computeMutationImpact';\nimport { readContextFor } from './internal/read/annotationReadContext';\nimport { readAnnotString } from './internal/read/annotationReadPrimitives';\nimport {\n joinWidgetFieldNumbers,\n resolveWidgetFieldObjectNumber,\n} from './internal/read/joinWidgetField';\nimport { readAnnotationFromPtr } from './internal/read/readAnnotationFromPtr';\nimport type { AnnotationWriteContext } from './internal/write/annotationWriteContext';\nimport {\n applyDraft,\n applyPatch,\n preflightDraft,\n preflightPatch,\n} from './internal/write/annotationWriterRegistry';\nimport {\n writeAnnotationAuthor,\n writeAnnotationModified,\n} from './internal/write/writeAnnotationBase';\nimport { writeAnnotationRelationship } from './internal/write/writeAnnotationRelationship';\nimport {\n applyEmbedMetadataOnCreate,\n applyEmbedMetadataOnUpdate,\n} from './internal/write/writeEmbedMetadata';\n\n/** `FPDF_ANNOT_APPEARANCEMODE_NORMAL` — the `/AP /N` stream. */\nconst APPEARANCE_MODE_NORMAL = 0;\n\n/**\n * Synchronous orchestrator for `create` / `update` / `delete` annotation\n * mutations. Owns the dance between PDFium calls, identity bookkeeping,\n * revision bumping (only for structural ops), and the\n * `AnnotationListMutationMeta` envelope every result type carries.\n *\n * Lives in `engine-services` (not the worker hosts) so the local Web\n * Worker, the Node `worker_thread` server, and any future direct-thread\n * embedding share the exact same code path. The only difference between\n * them is the underlying `PdfRuntimeModule` (WASM vs native).\n *\n * Identity rules enforced here, locked with the user:\n * - `create` always uses `EPDFPage_CreateAnnot` (the fork helper that\n * creates an INDIRECT object) so new annotations are born durable.\n * If the fork helper ever returns a direct object, we throw — never\n * silently produce a weak annotation.\n * - `update` is non-structural. /NM is monotonic per annotation:\n * * already durable (objectNumber > 0 OR /NM present) -> NEVER touched.\n * * weak (no objectNumber, no /NM) -> stamp engine-generated UUID v4.\n * The patch type has no `nm` field, so the writer surface enforces\n * \"callers cannot rename a stable id\" at the type level. Updates do\n * not bump the revision.\n * - `delete` is subtype-agnostic. Three native fork helpers handle the\n * three ref kinds without round-tripping through index. For weak\n * deletes (`AnnotationStableId | null`-shaped result), we set\n * `deleted: null` so callers can detect that no durable id was\n * reportable.\n */\nexport class AnnotationMutator {\n constructor(\n private readonly runtime: PdfRuntimeModule,\n private readonly session: DocumentSession,\n /**\n * Registered-font registry for this thread. Optional: when absent, the\n * registered-font authoring path is unavailable and a draft/patch carrying\n * a `registeredFontKey` fails loud (rather than silently using a standard\n * font). Standard-font FreeText and all other subtypes are unaffected.\n */\n private readonly fonts?: FontRegistrar,\n ) {}\n\n /** Build the per-write context handed to subtype writers: font resolver\n * (FreeText `/DA`), doc/page pointers and binary resources (stamp). */\n private writeContext(pagePtr: Ptr, resources?: WireResourceMap): AnnotationWriteContext {\n const fonts = this.fonts;\n return {\n ...(fonts ? { resolveRegisteredFontId: (key: string) => fonts.idFor(key) } : {}),\n docPtr: this.session.requireDocPtr(),\n pagePtr,\n ...(resources ? { resources } : {}),\n };\n }\n\n create(\n pageObjectNumber: PageObjectNumber,\n draft: WireAnnotationDraft,\n signal: AbortSignal,\n actor?: AnnotationActor,\n resources?: WireResourceMap,\n ): AnnotationCreateResult {\n throwIfAborted(signal);\n const { fn, mem } = this.runtime;\n const subtypeCode = PDF_SUBTYPE_TO_CODE[draft.subtype];\n\n const pool = this.session.pagePool();\n const pagePtr = pool.acquire(pageObjectNumber);\n try {\n this.ensureKnownWeakStateFromPage(pageObjectNumber, pagePtr);\n const writeCtx = this.writeContext(pagePtr, resources);\n preflightDraft(draft, writeCtx);\n // `create` is append-only: PDFium drops the new annotation at\n // `index = previousCount`, so no existing index ever shifts. Per\n // the locked rule in `computeMutationImpact`, that means create is\n // non-invalidating — no per-page revision bump, no weak-ref\n // staleness signal. The DTO is read against the page's current\n // revision (which both pre-existing and freshly-created\n // annotations share, since nothing bumped it).\n const pageStateBefore = this.session.pageState(pageObjectNumber);\n throwIfAborted(signal);\n\n const annotPtr = fn.EPDFPage_CreateAnnot(pagePtr, subtypeCode);\n if (!annotPtr) {\n throw new EngineError(\n EngineErrorCode.Unknown,\n `EPDFPage_CreateAnnot returned NULL for subtype '${draft.subtype}'`,\n );\n }\n\n let dto;\n let newObjNum: number;\n let newIndex: number;\n let linkedParentId: AnnotationStableId | null = null;\n try {\n applyDraft(fn, mem, annotPtr, draft, writeCtx);\n // Link to an /IRT parent when the draft asks for one. This may\n // promote a weak/direct parent to an indirect object (non-structural,\n // no index shift); the strengthened parent id is folded into\n // `meta.changed` below so the client can reconcile its cached ref.\n if (draft.inReplyTo !== undefined || draft.replyType !== undefined) {\n linkedParentId = writeAnnotationRelationship(\n this.runtime,\n this.session,\n pagePtr,\n annotPtr,\n pageObjectNumber,\n { inReplyTo: draft.inReplyTo, replyType: draft.replyType },\n );\n }\n // Stamp identity + modification metadata AFTER the per-subtype\n // writer so a buggy subtype writer can't clobber them:\n // /T ← actor.displayName (when present)\n // /M ← now (always)\n // /EMBD_Metadata ← actor.userId/groupId (when present)\n if (actor?.displayName) {\n writeAnnotationAuthor(fn, mem, annotPtr, actor.displayName);\n }\n writeAnnotationModified(fn, mem, annotPtr);\n applyEmbedMetadataOnCreate(fn, mem, annotPtr, actor);\n // Bake the /AP appearance stream now that every visual field is\n // written, so the new annotation ships with a standard-compliant\n // appearance (matches the v2 engine).\n this.regenerateAppearance(annotPtr, pagePtr, draft.blendMode);\n\n newObjNum = fn.EPDFAnnot_GetObjectNumber(annotPtr);\n if (newObjNum <= 0) {\n // Defensive: the fork helper guarantees an indirect object.\n throw new EngineError(\n EngineErrorCode.Unknown,\n `EPDFPage_CreateAnnot produced a direct object (no objectNumber); fork helper invariant broken`,\n );\n }\n newIndex = fn.FPDFPage_GetAnnotIndex(pagePtr, annotPtr);\n if (newIndex < 0) {\n throw new EngineError(\n EngineErrorCode.Unknown,\n `FPDFPage_GetAnnotIndex returned ${newIndex} for freshly created annotation`,\n );\n }\n\n dto = readAnnotationFromPtr(\n fn,\n mem,\n annotPtr,\n pageObjectNumber,\n newIndex,\n pageStateBefore.revision,\n readContextFor(this.session),\n );\n joinWidgetFieldNumbers(this.runtime, this.session, [dto]);\n } finally {\n fn.FPDFPage_CloseAnnot(annotPtr);\n }\n\n const createdId: AnnotationStableId = { kind: 'objectNumber', value: newObjNum };\n // Linking promoted the parent in place, so the page may now have one\n // fewer weak annotation — refresh the flag that future delete/move\n // refetch decisions read. (A plain create touches no existing annot.)\n if (linkedParentId) this.recordWeakStateFromPage(pageObjectNumber, pagePtr);\n const pageStateAfter = this.session.pageState(pageObjectNumber);\n const meta: AnnotationListMutationMeta = computeMutationImpact({\n mutation: 'create',\n pageStateBefore,\n pageStateAfter,\n changed: linkedParentId ? [createdId, linkedParentId] : [createdId],\n });\n\n return { created: dto, meta };\n } finally {\n pool.release(pageObjectNumber);\n }\n }\n\n update(\n ref: AnnotationRef,\n patch: WireAnnotationPatch,\n signal: AbortSignal,\n actor?: AnnotationActor,\n resources?: WireResourceMap,\n ): AnnotationUpdateResult {\n throwIfAborted(signal);\n const { fn, mem } = this.runtime;\n const pool = this.session.pagePool();\n const pagePtr = pool.acquire(ref.pageObjectNumber);\n let annotPtr: Ptr | null = null;\n try {\n annotPtr = resolveAnnotPtr(this.runtime, this.session, pagePtr, ref);\n throwIfAborted(signal);\n\n const writeCtx = this.writeContext(pagePtr, resources);\n preflightPatch(patch, writeCtx);\n\n this.ensureKnownWeakStateFromPage(ref.pageObjectNumber, pagePtr);\n const pageStateBefore = this.session.pageState(ref.pageObjectNumber);\n\n // Apply boundary: validation and cancellation are complete before the\n // first possible document write (weak-id strengthening below).\n throwIfAborted(signal);\n\n // Opportunistic /NM stamp for weak annotations + capture the\n // resulting stable id for `meta.changed`. Same monotonic /NM\n // rule that `move()` uses; sharing the helper guarantees the\n // two paths cannot drift in their identity bookkeeping.\n const stableId = this.captureOrStampStableId(annotPtr);\n\n // Blend mode lives inside the existing /AP graphics state rather than in\n // the annotation dictionary. Capture it before re-baking so an unrelated\n // patch (colour, geometry, contents...) cannot silently reset it.\n const previousBlendMode = blendModeFromCode(fn.EPDFAnnot_GetBlendMode(annotPtr));\n\n // Pre-patch DTO for the appearance classifier: it value-diffs the patch\n // against this, so no-op keys (full-projection clients) drop away and a\n // pure move is recognized no matter how verbose the patch is.\n const preIndex = fn.FPDFPage_GetAnnotIndex(pagePtr, annotPtr);\n if (preIndex < 0) {\n throw new EngineError(\n EngineErrorCode.Unknown,\n `FPDFPage_GetAnnotIndex returned ${preIndex} before update`,\n );\n }\n const currentDto = readAnnotationFromPtr(\n fn,\n mem,\n annotPtr,\n ref.pageObjectNumber,\n preIndex,\n pageStateBefore.revision,\n readContextFor(this.session),\n );\n\n // Apply caller-supplied subtype-specific writes.\n applyPatch(fn, mem, annotPtr, patch, writeCtx);\n // Apply /IRT + /RT changes (set/relink/clear, or RT-only). Setting a\n // link may promote a weak parent to indirect (non-structural); the\n // strengthened parent id is folded into `meta.changed` below.\n let linkedParentId: AnnotationStableId | null = null;\n if (patch.inReplyTo !== undefined || patch.replyType !== undefined) {\n linkedParentId = writeAnnotationRelationship(\n this.runtime,\n this.session,\n pagePtr,\n annotPtr,\n ref.pageObjectNumber,\n { inReplyTo: patch.inReplyTo, replyType: patch.replyType },\n );\n }\n // Refresh standard /M (modified date) on every update — independent\n // of whether the patch touched any subtype-specific field. Then\n // refresh /EMBD_Metadata/UpdatedBy if an actor was supplied;\n // UserID/GroupID/CreatedBy are preserved across updates.\n writeAnnotationModified(fn, mem, annotPtr);\n applyEmbedMetadataOnUpdate(fn, mem, annotPtr, actor);\n // The appearance decision (engine-core `appearanceImpactOf`): an /AP is\n // content, not cache — a foreign-authored stream (Acrobat's rich /AP, an\n // image stamp) is destroyed only as the explicit consequence of a\n // semantic edit, never as a side effect of writing back values nobody\n // changed. `inert` patches (metadata-only, or all values no-ops) never\n // touch /AP; a VERIFIED rigid translation preserves an existing /AP\n // byte-for-byte (ISO 32000: BBox→/Rect fitting translates the pixels);\n // everything else re-bakes. With no existing normal /AP there is\n // nothing to preserve, so any appearance-relevant write bakes one (v2\n // parity — otherwise the annotation renders as nothing). The verdict is\n // echoed on the result: clients drive raster invalidation off\n // `appearance.changed` instead of guessing from the patch they sent.\n const impact = appearanceImpactOf(currentDto, patch);\n let appearance: AppearanceOutcome;\n if (\n impact === 'inert' ||\n (impact === 'translation' &&\n fn.EPDFAnnot_HasAppearanceStream(annotPtr, APPEARANCE_MODE_NORMAL))\n ) {\n appearance = { action: 'preserved', changed: false };\n } else {\n const ok = this.regenerateAppearance(\n annotPtr,\n pagePtr,\n patch.blendMode ?? previousBlendMode,\n );\n appearance = ok\n ? { action: 'regenerated', changed: true }\n : // No generic generator for this subtype (e.g. widgets). The\n // dictionary still changed when the patch was appearance-relevant,\n // so `changed` stays true in that case — form-layer renderers may\n // paint differently even though no /AP was written.\n { action: 'generation-unavailable', changed: impact === 'regenerate' };\n }\n\n // PDFium caches the parsed appearance form on an annotation context. A\n // regenerated /AP is persisted immediately, but reading blend mode through\n // the same handle can still observe that old form. Reopen the non-structural\n // target before read-back so the returned DTO reflects the new stream.\n fn.FPDFPage_CloseAnnot(annotPtr);\n annotPtr = null;\n annotPtr = resolveAnnotPtr(this.runtime, this.session, pagePtr, ref);\n\n // Read back. Update is non-structural, so the index does NOT move\n // and the revision does NOT bump.\n const newIndex = fn.FPDFPage_GetAnnotIndex(pagePtr, annotPtr);\n if (newIndex < 0) {\n throw new EngineError(\n EngineErrorCode.Unknown,\n `FPDFPage_GetAnnotIndex returned ${newIndex} after update`,\n );\n }\n const dto = readAnnotationFromPtr(\n fn,\n mem,\n annotPtr,\n ref.pageObjectNumber,\n newIndex,\n pageStateBefore.revision,\n readContextFor(this.session),\n );\n joinWidgetFieldNumbers(this.runtime, this.session, [dto]);\n\n this.recordWeakStateFromPage(ref.pageObjectNumber, pagePtr);\n const pageStateAfter = this.session.pageState(ref.pageObjectNumber);\n const meta = computeMutationImpact({\n mutation: 'update',\n pageStateBefore,\n pageStateAfter,\n changed: linkedParentId ? [stableId, linkedParentId] : [stableId],\n });\n return { updated: dto, appearance, meta };\n } finally {\n if (annotPtr !== null) fn.FPDFPage_CloseAnnot(annotPtr);\n pool.release(ref.pageObjectNumber);\n }\n }\n\n /**\n * Attached widgets are views of a form field: deleting one here would\n * orphan the field's /Kids (the corruption class doc.forms.repair\n * exists to fix). Detach first, or use the forms-plane cascade.\n */\n private assertNotAttachedWidget(annotPtr: Ptr): void {\n const { fn } = this.runtime;\n if (fn.FPDFAnnot_GetSubtype(annotPtr) !== PdfAnnotationSubtypeCode.WIDGET) return;\n const annotObjectNumber = fn.EPDFAnnot_GetObjectNumber(annotPtr);\n if (resolveWidgetFieldObjectNumber(this.runtime, this.session, annotObjectNumber) === 0) {\n return; // inert widget: an ordinary annotation, ordinary delete\n }\n throw new EngineError(\n EngineErrorCode.InvalidArg,\n 'widget is attached to a form field - use doc.forms.detachWidget or doc.forms.deleteField',\n );\n }\n\n delete(ref: AnnotationRef, signal: AbortSignal): AnnotationDeleteResult {\n throwIfAborted(signal);\n const { fn, mem } = this.runtime;\n const pool = this.session.pagePool();\n const pagePtr = pool.acquire(ref.pageObjectNumber);\n let bumpRequested = false;\n try {\n this.ensureKnownWeakStateFromPage(ref.pageObjectNumber, pagePtr);\n const pageStateBefore = this.session.pageState(ref.pageObjectNumber);\n throwIfAborted(signal);\n\n let deleted: AnnotationStableId | null;\n let ok = false;\n switch (ref.kind) {\n case 'objectNumber': {\n // Probe so we 404 honestly before mutating. The fork helper\n // does its own existence check too, but we want a clean\n // InvalidReference up front rather than a \"false\" return code\n // we'd have to translate.\n const probe = fn.EPDFPage_GetAnnotByObjectNumber(pagePtr, ref.annotObjectNumber);\n if (!probe) {\n throw new EngineError(\n EngineErrorCode.InvalidReference,\n `no annotation with object number ${ref.annotObjectNumber} on page ${ref.pageObjectNumber}`,\n );\n }\n try {\n this.assertNotAttachedWidget(probe);\n } finally {\n fn.FPDFPage_CloseAnnot(probe);\n }\n bumpRequested = true;\n ok = fn.EPDFPage_RemoveAnnotByObjectNumber(pagePtr, ref.annotObjectNumber);\n deleted = { kind: 'objectNumber', value: ref.annotObjectNumber };\n break;\n }\n case 'nm': {\n const namePtr = mem.writeU16String(ref.nm);\n try {\n const probe = fn.EPDFPage_GetAnnotByName(pagePtr, namePtr);\n if (!probe) {\n throw new EngineError(\n EngineErrorCode.InvalidReference,\n `no annotation with /NM '${ref.nm}' on page ${ref.pageObjectNumber}`,\n );\n }\n try {\n this.assertNotAttachedWidget(probe);\n } finally {\n fn.FPDFPage_CloseAnnot(probe);\n }\n bumpRequested = true;\n ok = fn.EPDFPage_RemoveAnnotByName(pagePtr, namePtr);\n } finally {\n mem.free(namePtr);\n }\n deleted = { kind: 'nm', value: ref.nm };\n break;\n }\n case 'index': {\n this.session.validateRevision(ref.revision);\n const annotPtr = fn.FPDFPage_GetAnnot(pagePtr, ref.index);\n if (!annotPtr) {\n throw new EngineError(\n EngineErrorCode.InvalidReference,\n `index ${ref.index} out of range on page ${ref.pageObjectNumber}`,\n );\n }\n let probedObjNum: number;\n let probedNm: string | null;\n try {\n probedObjNum = fn.EPDFAnnot_GetObjectNumber(annotPtr);\n probedNm = readAnnotString(fn, mem, annotPtr, 'NM');\n } finally {\n fn.FPDFPage_CloseAnnot(annotPtr);\n }\n deleted =\n probedObjNum > 0\n ? { kind: 'objectNumber', value: probedObjNum }\n : probedNm !== null && probedNm.length > 0\n ? { kind: 'nm', value: probedNm }\n : null;\n bumpRequested = true;\n // EPDFPage_RemoveAnnot is the fork helper that ALSO cleans up\n // the indirect object if the annotation has one. The vanilla\n // FPDFPage_RemoveAnnot would leak the indirect object.\n ok = fn.EPDFPage_RemoveAnnot(pagePtr, ref.index);\n break;\n }\n }\n if (!ok) {\n throw new EngineError(EngineErrorCode.Unknown, `failed to remove annotation: ${ref.kind}`);\n }\n\n // Structural change; bump the local index-space epoch now and stop\n // the finally-bump. Do not gate this on the page's current weak state:\n // old snapshots can still hold index refs from before annotations were\n // strengthened, and delete/move can make those refs point elsewhere.\n this.session.bumpRevision(ref.pageObjectNumber);\n bumpRequested = false;\n this.recordWeakStateFromPage(ref.pageObjectNumber, pagePtr);\n const pageStateAfter = this.session.pageState(ref.pageObjectNumber);\n\n const meta = computeMutationImpact({\n mutation: 'delete',\n pageStateBefore,\n pageStateAfter,\n changed: deleted ? [deleted] : [],\n });\n return { deleted, meta };\n } finally {\n if (bumpRequested) this.session.bumpRevision(ref.pageObjectNumber);\n pool.release(ref.pageObjectNumber);\n }\n }\n\n /**\n * Batch reorder of a contiguous block of annotations within a single\n * page's /Annots array. Symmetric with `pages.move()` for pages.\n *\n * Semantics (locked with the user, mirrors `EPDFPage_MoveAnnots`):\n * - Each ref in `refs` is resolved to its current /Annots index.\n * The block is detached, then re-inserted at `toIndex` in the\n * post-removal index space, preserving caller-supplied order.\n * - Single-annotation case is `move([ref], toIndex)`. There is no\n * separate single-move path; one batch primitive serves both.\n * - Atomic from the caller's perspective:\n * * one revision bump per batch, regardless of `refs.length`.\n * * one `AnnotationListMutationMeta` envelope.\n * * if `EPDFPage_MoveAnnots` rejects (returns false) the page is\n * untouched and we throw `InvalidArg` without bumping.\n * - Identity strengthening: each weak ref in the batch (no\n * `objectNumber`, no `/NM`) is opportunistically stamped with a\n * fresh engine-generated UUID v4 BEFORE the move. So\n * `meta.changed` always lists durable stable ids, and the moved\n * DTOs come out durable. Same monotonic `/NM` rule as `update()`.\n *\n * Validation rules applied here BEFORE calling the helper, so callers\n * get clean errors instead of an opaque `false` return code:\n * - `refs.length >= 1`.\n * - All refs target the page identified by `pageObjectNumber`.\n * - `toIndex >= 0` and `toIndex <= count - refs.length` (count is\n * captured AFTER ref resolution, so the helper sees the same view).\n * - Resolved indices have no duplicates.\n *\n * The `EPDFPage_MoveAnnots` helper itself enforces the same rules; the\n * up-front validation is purely for a usable error surface.\n */\n move(\n pageObjectNumber: PageObjectNumber,\n refs: AnnotationRef[],\n toIndex: number,\n signal: AbortSignal,\n ): AnnotationMoveResult {\n throwIfAborted(signal);\n if (refs.length === 0) {\n throw new EngineError(EngineErrorCode.InvalidArg, 'move requires at least one ref');\n }\n if (toIndex < 0 || !Number.isInteger(toIndex)) {\n throw new EngineError(\n EngineErrorCode.InvalidArg,\n `move toIndex must be a non-negative integer (got ${toIndex})`,\n );\n }\n for (const r of refs) {\n if (r.pageObjectNumber !== pageObjectNumber) {\n throw new EngineError(\n EngineErrorCode.InvalidArg,\n `move refs must all target page ${pageObjectNumber}; got ref on page ${r.pageObjectNumber}`,\n );\n }\n }\n\n const { fn, mem } = this.runtime;\n const pool = this.session.pagePool();\n const pagePtr = pool.acquire(pageObjectNumber);\n let bumpRequested = false;\n\n try {\n this.ensureKnownWeakStateFromPage(pageObjectNumber, pagePtr);\n const pageStateBefore = this.session.pageState(pageObjectNumber);\n throwIfAborted(signal);\n\n // 1. Resolve every ref in caller order. For each: capture its\n // current /Annots index and its (possibly newly-stamped)\n // stable id. We close each annotPtr right after probing — the\n // move helper takes the page-level pointer, and we'll re-open\n // annotPtrs later by *new* index for the readback.\n const fromIndices: number[] = new Array(refs.length);\n const stableIds: AnnotationStableId[] = new Array(refs.length);\n for (let i = 0; i < refs.length; i++) {\n throwIfAborted(signal);\n const annotPtr = resolveAnnotPtr(this.runtime, this.session, pagePtr, refs[i]);\n try {\n const idx = fn.FPDFPage_GetAnnotIndex(pagePtr, annotPtr);\n if (idx < 0) {\n throw new EngineError(\n EngineErrorCode.Unknown,\n `FPDFPage_GetAnnotIndex returned ${idx} during move resolution`,\n );\n }\n fromIndices[i] = idx;\n stableIds[i] = this.captureOrStampStableId(annotPtr);\n } finally {\n fn.FPDFPage_CloseAnnot(annotPtr);\n }\n }\n\n // 2. Reject duplicate source indices up front. Two refs that\n // resolve to the same index would violate the helper's\n // invariant (and would also be a confused caller).\n const seen = new Set<number>();\n for (const idx of fromIndices) {\n if (seen.has(idx)) {\n throw new EngineError(\n EngineErrorCode.InvalidArg,\n `move refs resolve to duplicate /Annots index ${idx}`,\n );\n }\n seen.add(idx);\n }\n\n // 3. Range-check toIndex against the post-removal count, matching\n // the helper's contract.\n const count = fn.FPDFPage_GetAnnotCount(pagePtr);\n const postRemovalCount = count - fromIndices.length;\n if (toIndex > postRemovalCount) {\n throw new EngineError(\n EngineErrorCode.InvalidArg,\n `move toIndex ${toIndex} out of range; post-removal count is ${postRemovalCount}`,\n );\n }\n\n // 4. Marshal fromIndices into an i32 array in runtime memory and\n // invoke the helper. From this call onward a structural change\n // may have happened; finally-bump on any failure.\n const arrBytes = 4 * fromIndices.length;\n const arrPtr = mem.alloc(arrBytes);\n let ok: boolean;\n try {\n for (let i = 0; i < fromIndices.length; i++) {\n mem.poke(arrPtr, 'i32', fromIndices[i], 4 * i);\n }\n bumpRequested = true;\n ok = fn.EPDFPage_MoveAnnots(pagePtr, arrPtr, fromIndices.length, toIndex);\n } finally {\n mem.free(arrPtr);\n }\n\n if (!ok) {\n // The helper validates atomically: a `false` return means it\n // rejected the request and made no changes. Cancel the pending\n // bump and surface a clean error.\n bumpRequested = false;\n throw new EngineError(\n EngineErrorCode.InvalidArg,\n `EPDFPage_MoveAnnots rejected the request (toIndex=${toIndex}, fromIndices=[${fromIndices.join(\n ',',\n )}])`,\n );\n }\n\n // 5. Single revision bump for the whole batch. This is the local\n // index-space epoch, so it advances for every successful move even\n // if the page is currently strong. Read back DTOs against the\n // bumped revision so they are internally consistent.\n const bumpedRev = this.session.bumpRevision(pageObjectNumber);\n bumpRequested = false;\n\n const moved: AnnotationDTO[] = new Array(fromIndices.length);\n for (let i = 0; i < fromIndices.length; i++) {\n throwIfAborted(signal);\n const newIdx = toIndex + i;\n const annotPtr = fn.FPDFPage_GetAnnot(pagePtr, newIdx);\n if (!annotPtr) {\n throw new EngineError(\n EngineErrorCode.Unknown,\n `failed to re-read moved annotation at index ${newIdx}`,\n );\n }\n try {\n moved[i] = readAnnotationFromPtr(\n fn,\n mem,\n annotPtr,\n pageObjectNumber,\n newIdx,\n bumpedRev,\n readContextFor(this.session),\n );\n } finally {\n fn.FPDFPage_CloseAnnot(annotPtr);\n }\n }\n\n this.recordWeakStateFromPage(pageObjectNumber, pagePtr);\n const pageStateAfter = this.session.pageState(pageObjectNumber);\n const meta: AnnotationListMutationMeta = computeMutationImpact({\n mutation: 'move',\n pageStateBefore,\n pageStateAfter,\n changed: stableIds,\n });\n return { moved, meta };\n } finally {\n if (bumpRequested) this.session.bumpRevision(pageObjectNumber);\n pool.release(pageObjectNumber);\n }\n }\n\n /**\n * Bake (or re-bake) an annotation's `/AP` normal appearance stream from\n * its current dictionary properties using PDFium's native AP generator,\n * then flush the page content so the result is persisted into the\n * page/object tree. Same path the v2 engine used after every\n * create/update; runs for every writable subtype (shapes + text-markup).\n *\n * Best-effort: `EPDFAnnot_GenerateAppearance` returns false for subtypes\n * PDFium has no generator for (e.g. widgets), in which case the\n * annotation simply ships without a baked `/AP` and viewers synthesize\n * one — so a false return is not a hard error; it is surfaced to `update`\n * callers as the `generation-unavailable` appearance outcome. This step is\n * non-structural: it never shifts annotation indices or bumps revisions.\n */\n private regenerateAppearance(annotPtr: Ptr, pagePtr: Ptr, blendMode?: BlendMode): boolean {\n const { fn } = this.runtime;\n const ok =\n blendMode === undefined\n ? fn.EPDFAnnot_GenerateAppearance(annotPtr)\n : fn.EPDFAnnot_GenerateAppearanceWithBlend(annotPtr, blendModeToCode(blendMode));\n fn.FPDFPage_GenerateContent(pagePtr);\n return ok;\n }\n\n private captureOrStampStableId(annotPtr: Ptr): AnnotationStableId {\n return captureOrStampStableId(this.runtime, annotPtr);\n }\n\n private ensureKnownWeakStateFromPage(pageObjectNumber: PageObjectNumber, pagePtr: Ptr): void {\n if (this.session.weakAnnotationState(pageObjectNumber).kind === 'known') {\n return;\n }\n this.recordWeakStateFromPage(pageObjectNumber, pagePtr);\n }\n\n private recordWeakStateFromPage(pageObjectNumber: PageObjectNumber, pagePtr: Ptr): void {\n this.session.recordWeakFlag(pageObjectNumber, this.computeHasWeakAnnotations(pagePtr));\n }\n\n private computeHasWeakAnnotations(pagePtr: Ptr): boolean {\n const { fn, mem } = this.runtime;\n const count = fn.FPDFPage_GetAnnotCount(pagePtr);\n if (count < 0) {\n throw new EngineError(\n EngineErrorCode.Unknown,\n `FPDFPage_GetAnnotCount returned ${count} while computing weak annotations`,\n );\n }\n for (let i = 0; i < count; i++) {\n const annotPtr = fn.FPDFPage_GetAnnot(pagePtr, i);\n if (!annotPtr) {\n continue;\n }\n try {\n const objNum = fn.EPDFAnnot_GetObjectNumber(annotPtr);\n if (objNum > 0) {\n continue;\n }\n const nm = readAnnotString(fn, mem, annotPtr, 'NM');\n if (nm === null || nm.length === 0) {\n return true;\n }\n } finally {\n fn.FPDFPage_CloseAnnot(annotPtr);\n }\n }\n return false;\n }\n}\n","import type {\n MutationMeta,\n PageFlattenResult,\n PageFlattenUsage,\n PageObjectNumber,\n} from '@embedpdf/engine-core/runtime';\nimport { EngineError, EngineErrorCode, serializeError } from '@embedpdf/engine-core/runtime';\nimport type { PdfRuntimeModule } from '@embedpdf/engine-runtime';\n\nimport type { DocumentSession } from '../../document-session/DocumentSession';\nimport { throwIfAborted } from '../../shared/abort';\nimport { AnnotationReader } from '../annotations';\n\nconst FLATTEN_FAIL = 0;\nconst FLATTEN_SUCCESS = 1;\nconst FLATTEN_NOTHING_TO_DO = 2;\n\n/** Layer-safe page flattening. Content and annotation liveness change together. */\nexport class PagesFlattener {\n constructor(\n private readonly runtime: PdfRuntimeModule,\n private readonly session: DocumentSession,\n ) {}\n\n flatten(\n pageObjectNumbers: PageObjectNumber[],\n usage: PageFlattenUsage,\n signal: AbortSignal,\n ): PageFlattenResult {\n throwIfAborted(signal);\n requireUniquePages(pageObjectNumbers);\n for (const pageObjectNumber of pageObjectNumbers) {\n this.session.recordByObjectNumber(pageObjectNumber);\n }\n\n const results: PageFlattenResult['results'] = [];\n const affected = new Set<PageObjectNumber>();\n let stop = false;\n for (const pageObjectNumber of pageObjectNumbers) {\n if (stop || (signal.aborted && affected.size > 0)) {\n stop = true;\n results.push({ pageObjectNumber, status: 'skipped' });\n continue;\n }\n if (signal.aborted) throwIfAborted(signal);\n\n const pool = this.session.pagePool();\n const pagePtr = pool.acquire(pageObjectNumber);\n let code: number;\n try {\n code = this.runtime.fn.EPDFPage_Flatten(pagePtr, usage === 'print' ? 1 : 0);\n } catch (error) {\n affected.add(pageObjectNumber);\n results.push({ pageObjectNumber, status: 'failed', error: serializeError(error) });\n stop = true;\n continue;\n } finally {\n pool.release(pageObjectNumber);\n }\n\n if (code === FLATTEN_NOTHING_TO_DO) {\n results.push({ pageObjectNumber, status: 'unchanged' });\n } else if (code === FLATTEN_SUCCESS) {\n affected.add(pageObjectNumber);\n results.push({ pageObjectNumber, status: 'applied' });\n } else {\n affected.add(pageObjectNumber);\n results.push({\n pageObjectNumber,\n status: 'failed',\n error: serializeError(\n new EngineError(\n EngineErrorCode.Unknown,\n code === FLATTEN_FAIL\n ? 'native page flatten failed after preflight'\n : `native page flatten returned unexpected code ${code}`,\n ),\n ),\n });\n stop = true;\n }\n }\n\n if (affected.size === 0) return { pageObjectNumbers, usage, results, meta: null };\n\n this.session.noteMutation();\n for (const pageObjectNumber of affected) {\n this.session.bumpRevision(pageObjectNumber);\n try {\n // Recompute the weak-annotation flag from the annotations that remain.\n new AnnotationReader(this.runtime, this.session).list(pageObjectNumber, signal);\n } catch {\n // The page state remains conservatively unknown. Never lose the layer\n // artifact because a post-flatten diagnostic read failed.\n }\n }\n const meta: MutationMeta = {\n affectedPages: [...affected].map((pageObjectNumber) =>\n this.session.pageState(pageObjectNumber),\n ),\n cacheDelta: null,\n };\n return { pageObjectNumbers, usage, results, meta };\n }\n}\n\nfunction requireUniquePages(pageObjectNumbers: PageObjectNumber[]): void {\n if (pageObjectNumbers.length === 0) {\n throw new EngineError(EngineErrorCode.InvalidArg, 'pages.flatten requires at least one page');\n }\n const seen = new Set<PageObjectNumber>();\n for (const pageObjectNumber of pageObjectNumbers) {\n if (seen.has(pageObjectNumber)) {\n throw new EngineError(\n EngineErrorCode.InvalidArg,\n `pages.flatten was given duplicate page object number ${pageObjectNumber}`,\n );\n }\n seen.add(pageObjectNumber);\n }\n}\n","import type {\n AnnotationRef,\n MutationMeta,\n PageObjectNumber,\n RedactionApplyResult,\n RedactionApplyScope,\n} from '@embedpdf/engine-core/runtime';\nimport {\n EngineError,\n EngineErrorCode,\n serializeError,\n subtypeFromCode,\n} from '@embedpdf/engine-core/runtime';\nimport type { PdfRuntimeModule, Ptr } from '@embedpdf/engine-runtime';\n\nimport type { DocumentSession } from '../../document-session/DocumentSession';\nimport { I32_BYTES, readI32 } from '../../runtime/memory/structs';\nimport { withScratch } from '../../runtime/memory/scratch';\nimport { throwIfAborted } from '../../shared/abort';\nimport { AnnotationReader } from '../annotations';\nimport { resolveAnnotPtr } from '../annotations/internal/identity/resolveAnnotationPointer';\n\n/**\n * The destructive half of redaction (see `DocumentRedactionService` for the\n * model and the layer trust boundary). Content and annotation liveness\n * change together, exactly like {@link PagesFlattener} — this class mirrors\n * its validate-then-apply boundary and ordered-batch semantics.\n *\n * Scope semantics:\n * - `pages`: every REDACT annotation on each listed page is applied; a\n * page with none is `unchanged`.\n * - `annotations`: exactly the referenced REDACT annotations are applied.\n * Every ref is resolved and subtype-checked BEFORE the first native\n * write; a non-REDACT ref rejects the whole call with `InvalidArg`.\n *\n * The per-page `removedAnnotationCount` is the native collateral count:\n * annotations other than REDACT ones removed alongside the apply (popup\n * cascades and detached widgets included).\n */\nexport class RedactionApplier {\n constructor(\n private readonly runtime: PdfRuntimeModule,\n private readonly session: DocumentSession,\n ) {}\n\n apply(scope: RedactionApplyScope, signal: AbortSignal): RedactionApplyResult {\n throwIfAborted(signal);\n\n const plan = this.buildPlan(scope);\n for (const pageObjectNumber of plan.keys()) {\n this.session.recordByObjectNumber(pageObjectNumber);\n }\n this.preflight(plan, signal);\n\n const { fn } = this.runtime;\n const results: RedactionApplyResult['results'] = [];\n const affected = new Set<PageObjectNumber>();\n let totalRemoved = 0;\n let stop = false;\n\n for (const [pageObjectNumber, refs] of plan) {\n if (stop || (signal.aborted && affected.size > 0)) {\n stop = true;\n results.push({ pageObjectNumber, status: 'skipped', removedAnnotationCount: 0 });\n continue;\n }\n if (signal.aborted) throwIfAborted(signal);\n\n const pool = this.session.pagePool();\n const pagePtr = pool.acquire(pageObjectNumber);\n try {\n const outcome =\n refs === null ? this.applyAllOnPage(pagePtr) : this.applyRefsOnPage(pagePtr, refs);\n if (outcome.status === 'applied') {\n fn.FPDFPage_GenerateContent(pagePtr);\n affected.add(pageObjectNumber);\n totalRemoved += outcome.removed;\n }\n results.push({\n pageObjectNumber,\n status: outcome.status,\n removedAnnotationCount: outcome.removed,\n });\n } catch (error) {\n affected.add(pageObjectNumber);\n results.push({\n pageObjectNumber,\n status: 'failed',\n removedAnnotationCount: 0,\n error: serializeError(error),\n });\n stop = true;\n } finally {\n pool.release(pageObjectNumber);\n }\n }\n\n if (affected.size === 0) {\n return { scope, results, removedAnnotationCount: totalRemoved, meta: null };\n }\n\n this.session.noteMutation();\n for (const pageObjectNumber of affected) {\n this.session.bumpRevision(pageObjectNumber);\n try {\n // Recompute the weak-annotation flag from the annotations that remain.\n new AnnotationReader(this.runtime, this.session).list(pageObjectNumber, signal);\n } catch {\n // The page state remains conservatively unknown. Never lose the layer\n // artifact because a post-apply diagnostic read failed.\n }\n }\n const meta: MutationMeta = {\n affectedPages: [...affected].map((pageObjectNumber) =>\n this.session.pageState(pageObjectNumber),\n ),\n cacheDelta: null,\n };\n return { scope, results, removedAnnotationCount: totalRemoved, meta };\n }\n\n /**\n * Normalize the scope into an ordered per-page plan. `null` refs means\n * \"every REDACT annotation on the page\" (the `pages` scope).\n */\n private buildPlan(scope: RedactionApplyScope): Map<PageObjectNumber, AnnotationRef[] | null> {\n const plan = new Map<PageObjectNumber, AnnotationRef[] | null>();\n if (scope.kind === 'pages') {\n if (scope.pageObjectNumbers.length === 0) {\n throw new EngineError(\n EngineErrorCode.InvalidArg,\n 'redaction.apply requires at least one page',\n );\n }\n for (const pageObjectNumber of scope.pageObjectNumbers) {\n if (plan.has(pageObjectNumber)) {\n throw new EngineError(\n EngineErrorCode.InvalidArg,\n `redaction.apply was given duplicate page object number ${pageObjectNumber}`,\n );\n }\n plan.set(pageObjectNumber, null);\n }\n return plan;\n }\n\n if (scope.refs.length === 0) {\n throw new EngineError(\n EngineErrorCode.InvalidArg,\n 'redaction.apply requires at least one annotation ref',\n );\n }\n for (const ref of scope.refs) {\n const existing = plan.get(ref.pageObjectNumber);\n if (existing === null) {\n throw new EngineError(EngineErrorCode.InvalidArg, 'mixed redaction scopes on one page');\n }\n if (existing) existing.push(ref);\n else plan.set(ref.pageObjectNumber, [ref]);\n }\n // Applying removes annotations, which shifts positional indices — a\n // batch of multiple refs on one page can only address the survivors\n // stably through durable ref kinds.\n for (const [pageObjectNumber, refs] of plan) {\n if (refs !== null && refs.length > 1 && refs.some((r) => r.kind === 'index')) {\n throw new EngineError(\n EngineErrorCode.InvalidArg,\n `multiple redactions on page ${pageObjectNumber} cannot be addressed by positional 'index' refs — use objectNumber/nm refs, or one apply call per index ref`,\n );\n }\n }\n return plan;\n }\n\n /**\n * Validate every ref BEFORE the first native write: it must resolve and\n * it must be a REDACT annotation. After this returns, the apply loop's\n * writes begin and per-page failures are recorded, not thrown.\n */\n private preflight(\n plan: Map<PageObjectNumber, AnnotationRef[] | null>,\n signal: AbortSignal,\n ): void {\n const { fn } = this.runtime;\n for (const [pageObjectNumber, refs] of plan) {\n if (refs === null) continue;\n throwIfAborted(signal);\n const pool = this.session.pagePool();\n const pagePtr = pool.acquire(pageObjectNumber);\n try {\n for (const ref of refs) {\n const annotPtr = resolveAnnotPtr(this.runtime, this.session, pagePtr, ref);\n try {\n const subtype = subtypeFromCode(fn.FPDFAnnot_GetSubtype(annotPtr));\n if (subtype !== 'redact') {\n throw new EngineError(\n EngineErrorCode.InvalidArg,\n `redaction.apply ref on page ${pageObjectNumber} resolves to a '${subtype}' annotation, not a redact annotation`,\n );\n }\n } finally {\n fn.FPDFPage_CloseAnnot(annotPtr);\n }\n }\n } finally {\n pool.release(pageObjectNumber);\n }\n }\n }\n\n private applyAllOnPage(pagePtr: Ptr): { status: 'applied' | 'unchanged'; removed: number } {\n const { fn, mem } = this.runtime;\n return withScratch(mem, I32_BYTES, (countPtr) => {\n // FALSE here means \"no REDACT annotations on the page\" — nothing was\n // written, so the page is unchanged, not failed.\n const ok = fn.EPDFPage_ApplyRedactions(pagePtr, countPtr);\n if (!ok) return { status: 'unchanged' as const, removed: 0 };\n return { status: 'applied' as const, removed: readI32(mem, countPtr) >>> 0 };\n });\n }\n\n private applyRefsOnPage(\n pagePtr: Ptr,\n refs: AnnotationRef[],\n ): { status: 'applied'; removed: number } {\n const { fn, mem } = this.runtime;\n let removed = 0;\n for (const ref of refs) {\n // Re-resolve at apply time: an earlier apply on this page may have\n // removed collateral annotations, and durable refs stay valid across\n // that (preflight rejected fragile batched index refs).\n const annotPtr = resolveAnnotPtr(this.runtime, this.session, pagePtr, ref);\n try {\n const ok = withScratch(mem, I32_BYTES, (countPtr) => {\n const applied = fn.EPDFAnnot_ApplyRedaction(pagePtr, annotPtr, countPtr);\n if (applied) removed += readI32(mem, countPtr) >>> 0;\n return applied;\n });\n if (!ok) {\n throw new EngineError(\n EngineErrorCode.Unknown,\n 'native redaction apply failed after preflight',\n );\n }\n } finally {\n fn.FPDFPage_CloseAnnot(annotPtr);\n }\n }\n return { status: 'applied', removed };\n }\n}\n","import type { PageObjectNumber, PageTextSnapshot } from '@embedpdf/engine-core/runtime';\nimport { EngineError, EngineErrorCode } from '@embedpdf/engine-core/runtime';\nimport type { PdfRuntimeModule, Ptr } from '@embedpdf/engine-runtime';\n\nimport type { DocumentSession } from '../../document-session/DocumentSession';\nimport { withScratch } from '../../runtime/memory/scratch';\nimport { throwIfAborted } from '../../shared/abort';\n\n/**\n * Per-page slow-path text reader. Acquires a `pagePtr` from the\n * `PagePtrPool`, opens a PDFium text page (`FPDFText_LoadPage`),\n * extracts the full UTF-16 buffer with `FPDFText_GetText`, decodes,\n * and releases everything in reverse order.\n *\n * Memory model:\n * - `count` is in UTF-16 code units (FPDFText's \"char\").\n * - The buffer needs `(count + 1) * 2` bytes (PDFium writes a\n * trailing NUL terminator).\n * - `mem.readU16String` walks the buffer up to the NUL and decodes\n * to a JS string, faithfully preserving surrogate pairs.\n *\n * Errors:\n * - `EPDFDoc_LoadPageByObjectNumber` returning 0 is `NotFound`\n * (raised by `PagePtrPool.acquire`).\n * - `FPDFText_LoadPage` returning 0 is `RuntimeUnavailable` — should\n * not happen on a healthy page; treat it as a runtime bug rather\n * than user error.\n */\nexport class PageTextReader {\n constructor(\n private readonly runtime: PdfRuntimeModule,\n private readonly session: DocumentSession,\n ) {}\n\n read(pageObjectNumber: PageObjectNumber, signal: AbortSignal): PageTextSnapshot {\n throwIfAborted(signal);\n const { fn, mem } = this.runtime;\n const pool = this.session.pagePool();\n const pagePtr = pool.acquire(pageObjectNumber);\n\n try {\n throwIfAborted(signal);\n const textPagePtr = fn.FPDFText_LoadPage(pagePtr);\n if (!textPagePtr) {\n throw new EngineError(\n EngineErrorCode.RuntimeUnavailable,\n `FPDFText_LoadPage returned null for page object ${pageObjectNumber}`,\n );\n }\n try {\n throwIfAborted(signal);\n const charCount = fn.FPDFText_CountChars(textPagePtr);\n const text = readPageText(fn, mem, textPagePtr, charCount);\n return {\n text,\n charCount: Math.max(charCount, 0),\n };\n } finally {\n fn.FPDFText_ClosePage(textPagePtr);\n }\n } finally {\n pool.release(pageObjectNumber);\n }\n }\n}\n\nfunction readPageText(\n fn: PdfRuntimeModule['fn'],\n mem: PdfRuntimeModule['mem'],\n textPagePtr: Ptr,\n charCount: number,\n): string {\n if (charCount <= 0) return '';\n // FPDFText_GetText writes UTF-16 code units, NUL-terminated. The\n // documented sizing rule is `(count + 1) * 2` bytes for `count`\n // requested chars; PDFium writes `count + 1` UTF-16 units including\n // the terminator and returns the number of UTF-16 units it wrote\n // (terminator included).\n const bufBytes = (charCount + 1) * 2;\n return withScratch(mem, bufBytes, (buf) => {\n const written = fn.FPDFText_GetText(textPagePtr, 0, charCount, buf);\n if (written <= 0) return '';\n return mem.readU16String(buf);\n });\n}\n","import type {\n PageGeometryGlyph,\n PageGeometryRun,\n PageGeometrySnapshot,\n PageObjectNumber,\n PdfRect,\n} from '@embedpdf/engine-core/runtime';\nimport { EngineError, EngineErrorCode, normalizePdfRect } from '@embedpdf/engine-core/runtime';\nimport type { PdfRuntimeModule, Ptr } from '@embedpdf/engine-runtime';\n\nimport type { DocumentSession } from '../../document-session/DocumentSession';\nimport { throwIfAborted } from '../../shared/abort';\n\ninterface GlyphInfo {\n /** Loose char box in PDF user space (y-up edges). */\n looseBox: PdfRect;\n /** Tight glyph box in PDF user space (y-up edges), when available. */\n tightBox?: PdfRect;\n isSpace?: boolean;\n isEmpty?: boolean;\n}\n\n/**\n * Geometry-only text layout reader.\n *\n * Emits geometry in PDF user space (y-up edges) — the canonical engine\n * geometry. The viewer converts to content/view space via the page geometry\n * matrix; this reader applies NO Y-flip or device transform.\n */\nexport class PageGeometryReader {\n constructor(\n private readonly runtime: PdfRuntimeModule,\n private readonly session: DocumentSession,\n ) {}\n\n read(pageObjectNumber: PageObjectNumber, signal: AbortSignal): PageGeometrySnapshot {\n throwIfAborted(signal);\n const { fn } = this.runtime;\n const pool = this.session.pagePool();\n const pagePtr = pool.acquire(pageObjectNumber);\n\n try {\n throwIfAborted(signal);\n const textPagePtr = fn.FPDFText_LoadPage(pagePtr);\n if (!textPagePtr) {\n throw new EngineError(\n EngineErrorCode.RuntimeUnavailable,\n `FPDFText_LoadPage returned null for page object ${pageObjectNumber}`,\n );\n }\n try {\n throwIfAborted(signal);\n const glyphCount = Math.max(fn.FPDFText_CountChars(textPagePtr), 0);\n const glyphs: GlyphInfo[] = [];\n\n for (let i = 0; i < glyphCount; i++) {\n throwIfAborted(signal);\n glyphs.push(this.readGlyphInfo(textPagePtr, i));\n }\n\n return {\n runs: this.buildRunsFromGlyphs(glyphs, textPagePtr),\n };\n } finally {\n fn.FPDFText_ClosePage(textPagePtr);\n }\n } finally {\n pool.release(pageObjectNumber);\n }\n }\n\n private buildRunsFromGlyphs(glyphs: GlyphInfo[], textPagePtr: Ptr): PageGeometryRun[] {\n const { fn } = this.runtime;\n const runs: PageGeometryRun[] = [];\n let current: PageGeometryRun | null = null;\n let curObjPtr: Ptr | null = null;\n let bounds: { left: number; bottom: number; right: number; top: number } | null = null;\n\n for (let i = 0; i < glyphs.length; i++) {\n const glyph = glyphs[i];\n const objPtr = fn.FPDFText_GetTextObject(textPagePtr, i);\n\n if (objPtr !== curObjPtr) {\n curObjPtr = objPtr;\n current = {\n rect: { ...glyph.looseBox },\n charStart: i,\n glyphs: [],\n fontSize: fn.FPDFText_GetFontSize(textPagePtr, i),\n };\n bounds = { ...glyph.looseBox };\n runs.push(current);\n }\n\n current!.glyphs.push(toSlimGlyph(glyph));\n\n if (glyph.isEmpty) {\n continue;\n }\n\n bounds!.left = Math.min(bounds!.left, glyph.looseBox.left);\n bounds!.bottom = Math.min(bounds!.bottom, glyph.looseBox.bottom);\n bounds!.right = Math.max(bounds!.right, glyph.looseBox.right);\n bounds!.top = Math.max(bounds!.top, glyph.looseBox.top);\n\n current!.rect = { ...bounds! };\n }\n\n return runs;\n }\n\n private readGlyphInfo(textPagePtr: Ptr, charIndex: number): GlyphInfo {\n const { fn, mem } = this.runtime;\n const rectPtr = mem.alloc(16);\n const tLeftPtr = mem.alloc(8);\n const tRightPtr = mem.alloc(8);\n const tBottomPtr = mem.alloc(8);\n const tTopPtr = mem.alloc(8);\n const ptrs = [rectPtr, tLeftPtr, tRightPtr, tBottomPtr, tTopPtr];\n\n try {\n if (!fn.FPDFText_GetLooseCharBox(textPagePtr, charIndex, rectPtr)) {\n return emptyGlyph();\n }\n\n const left = Number(mem.peek(rectPtr, 'f32', 0));\n const top = Number(mem.peek(rectPtr, 'f32', 4));\n const right = Number(mem.peek(rectPtr, 'f32', 8));\n const bottom = Number(mem.peek(rectPtr, 'f32', 12));\n if (left === right || top === bottom) {\n return emptyGlyph();\n }\n\n // Loose box is already PDF user space (y-up). Normalize edges only.\n const glyph: GlyphInfo = {\n looseBox: normalizePdfRect({ left, bottom, right, top }),\n };\n\n if (\n fn.FPDFText_GetCharBox(textPagePtr, charIndex, tLeftPtr, tRightPtr, tBottomPtr, tTopPtr)\n ) {\n const tLeft = Number(mem.peek(tLeftPtr, 'f64'));\n const tRight = Number(mem.peek(tRightPtr, 'f64'));\n const tBottom = Number(mem.peek(tBottomPtr, 'f64'));\n const tTop = Number(mem.peek(tTopPtr, 'f64'));\n glyph.tightBox = normalizePdfRect({\n left: tLeft,\n bottom: tBottom,\n right: tRight,\n top: tTop,\n });\n }\n\n glyph.isSpace = fn.FPDFText_GetUnicode(textPagePtr, charIndex) === 32;\n return glyph;\n } finally {\n for (const ptr of ptrs) mem.free(ptr);\n }\n }\n}\n\nfunction emptyGlyph(): GlyphInfo {\n return {\n looseBox: { left: 0, bottom: 0, right: 0, top: 0 },\n isEmpty: true,\n };\n}\n\nfunction toSlimGlyph(glyph: GlyphInfo): PageGeometryGlyph {\n return {\n looseBox: glyph.looseBox,\n flags: glyph.isEmpty ? 2 : glyph.isSpace ? 1 : 0,\n ...(glyph.tightBox ? { tightBox: glyph.tightBox } : {}),\n };\n}\n","import type {\n PageObjectNumber,\n PageRenderOptions,\n PageRenderTarget,\n PdfRect,\n} from '@embedpdf/engine-core/runtime';\nimport { EngineError, EngineErrorCode, normalizePdfRect } from '@embedpdf/engine-core/runtime';\nimport type { PdfRuntimeModule } from '@embedpdf/engine-runtime';\n\nimport { FPDF_REVERSE_BYTE_ORDER, rasterize } from './deviceRaster';\nimport type { DocumentSession } from '../../document-session/DocumentSession';\nimport { throwIfAborted } from '../../shared/abort';\n\nconst FPDF_RENDER_ANNOT = 0x01;\n\nexport class PageRenderReader {\n constructor(\n private readonly runtime: PdfRuntimeModule,\n private readonly session: DocumentSession,\n ) {}\n\n render(pageObjectNumber: PageObjectNumber, options: PageRenderOptions, signal: AbortSignal) {\n throwIfAborted(signal);\n const { fn } = this.runtime;\n const pool = this.session.pagePool();\n const pagePtr = pool.acquire(pageObjectNumber);\n\n try {\n throwIfAborted(signal);\n\n const pageWidth = fn.FPDF_GetPageWidthF(pagePtr);\n const pageHeight = fn.FPDF_GetPageHeightF(pagePtr);\n const target = resolveTarget(options.target, pageWidth, pageHeight);\n const rotation = options.rotation ?? 0;\n const viewport = options.viewport ?? { kind: 'scale', scale: 1 };\n\n let flags = FPDF_REVERSE_BYTE_ORDER;\n if (options.includeAnnotations ?? true) flags |= FPDF_RENDER_ANNOT;\n\n const raster = rasterize(this.runtime, {\n rect: target,\n page: { width: pageWidth, height: pageHeight },\n rotation,\n viewport,\n ...(options.maxOutputPixels !== undefined\n ? { maxOutputPixels: options.maxOutputPixels }\n : {}),\n background: options.background === 'transparent' ? 'transparent' : 'white',\n draw: (bitmapPtr, matrixPtr, clipPtr) => {\n throwIfAborted(signal);\n fn.FPDF_RenderPageBitmapWithMatrix(bitmapPtr, pagePtr, matrixPtr, clipPtr, flags);\n throwIfAborted(signal);\n return true;\n },\n });\n if (!raster) {\n throw new EngineError(\n EngineErrorCode.RuntimeUnavailable,\n `failed to render page object ${pageObjectNumber}`,\n );\n }\n return raster;\n } finally {\n pool.release(pageObjectNumber);\n }\n }\n}\n\n/** Resolve the render target to a normalized PDF-space rect (page box, or a sub-rect). */\nfunction resolveTarget(\n target: PageRenderTarget | undefined,\n pageWidth: number,\n pageHeight: number,\n): PdfRect {\n if (!target || target.kind === 'page') {\n return { left: 0, bottom: 0, right: pageWidth, top: pageHeight };\n }\n const rect = normalizePdfRect(target.rect);\n if (rect.right <= rect.left || rect.top <= rect.bottom) {\n throw new EngineError(EngineErrorCode.InvalidArg, 'render rect must have positive area');\n }\n return rect;\n}\n","import type {\n AnnotationRef,\n AttachmentFileWorkerPayload,\n EmbeddedFileItem,\n EmbeddedFileRef,\n PageObjectNumber,\n} from '@embedpdf/engine-core/runtime';\nimport { EngineError, EngineErrorCode } from '@embedpdf/engine-core/runtime';\nimport type { PdfRuntimeModule, Ptr } from '@embedpdf/engine-runtime';\n\nimport {\n extractAttachmentToBuffer,\n extractAttachmentToFile,\n readAttachmentFileInfo,\n readAttachmentKey,\n resolveAttachmentIndex,\n} from './internal/attachmentPrimitives';\nimport type { DocumentSession } from '../../document-session/DocumentSession';\nimport { throwIfAborted } from '../../shared/abort';\nimport { resolveAnnotPtr } from '../annotations/internal/identity/resolveAnnotationPointer';\n\n/**\n * Read-only access to embedded files, at both of their homes: the\n * document catalog's `/EmbeddedFiles` name tree (list / readFile by\n * index) and a FileAttachment annotation's `/FS` (readAnnotationFile by\n * ref). Pure READS over the session — no revision bumps, no layer\n * artifacts (the `PagesExtractor` shape).\n *\n * Byte delivery mirrors the request's `path?`: absent → a standalone\n * buffer for the transfer list (browser); present → the decoded file is\n * streamed to `path` via `FPDF_FILEWRITE` (server), and only metadata\n * rides the response.\n */\nexport class AttachmentReader {\n constructor(\n private readonly runtime: PdfRuntimeModule,\n private readonly session: DocumentSession,\n ) {}\n\n /** Snapshot of the `/EmbeddedFiles` name tree, in tree (key-sorted) order. */\n list(signal: AbortSignal): EmbeddedFileItem[] {\n throwIfAborted(signal);\n const { fn, mem } = this.runtime;\n const docPtr = this.session.requireDocPtr();\n const count = fn.FPDFDoc_GetAttachmentCount(docPtr);\n const items: EmbeddedFileItem[] = [];\n for (let index = 0; index < count; index++) {\n const attachmentPtr = fn.FPDFDoc_GetAttachment(docPtr, index);\n if (!attachmentPtr) continue;\n const key = readAttachmentKey(fn, mem, docPtr, index) ?? '';\n items.push({ ...readAttachmentFileInfo(fn, mem, attachmentPtr), key, index });\n }\n return items;\n }\n\n /** Decode one document-level embedded file, addressed by key. */\n readFile(\n ref: EmbeddedFileRef,\n path: string | undefined,\n maxDecodedBytes: number | undefined,\n signal: AbortSignal,\n ): AttachmentFileWorkerPayload {\n throwIfAborted(signal);\n const { fn, mem } = this.runtime;\n const docPtr = this.session.requireDocPtr();\n const index = resolveAttachmentIndex(fn, mem, docPtr, ref);\n if (index < 0) {\n throw new EngineError(\n EngineErrorCode.NotFound,\n `no embedded file with key '${ref.key}' in the document`,\n );\n }\n const attachmentPtr = fn.FPDFDoc_GetAttachment(docPtr, index);\n if (!attachmentPtr) {\n throw new EngineError(\n EngineErrorCode.Unknown,\n `embedded file with key '${ref.key}' resolved to index ${index} but could not be opened`,\n );\n }\n const info = readAttachmentFileInfo(fn, mem, attachmentPtr);\n return this.extract(attachmentPtr, info.name, info.mimeType, path, maxDecodedBytes);\n }\n\n /** Decode the file embedded in a FileAttachment annotation's `/FS`. */\n readAnnotationFile(\n pageObjectNumber: PageObjectNumber,\n ref: AnnotationRef,\n path: string | undefined,\n maxDecodedBytes: number | undefined,\n signal: AbortSignal,\n ): AttachmentFileWorkerPayload {\n throwIfAborted(signal);\n const { fn, mem } = this.runtime;\n const pool = this.session.pagePool();\n const pagePtr = pool.acquire(pageObjectNumber);\n let annotPtr: Ptr | null = null;\n try {\n annotPtr = resolveAnnotPtr(this.runtime, this.session, pagePtr, ref);\n const attachmentPtr = fn.FPDFAnnot_GetFileAttachment(annotPtr);\n if (!attachmentPtr) {\n throw new EngineError(\n EngineErrorCode.InvalidArg,\n 'annotation is not a file attachment or carries no embedded file (/FS)',\n );\n }\n const info = readAttachmentFileInfo(fn, mem, attachmentPtr);\n return this.extract(attachmentPtr, info.name, info.mimeType, path, maxDecodedBytes);\n } finally {\n if (annotPtr !== null) fn.FPDFPage_CloseAnnot(annotPtr);\n pool.release(pageObjectNumber);\n }\n }\n\n private extract(\n attachmentPtr: Ptr,\n name: string,\n mimeType: string | undefined,\n path: string | undefined,\n maxDecodedBytes: number | undefined,\n ): AttachmentFileWorkerPayload {\n if (path !== undefined) {\n const { size } = extractAttachmentToFile(this.runtime, attachmentPtr, path, maxDecodedBytes);\n return { name, ...(mimeType ? { mimeType } : {}), size, path };\n }\n const { bytes, size } = extractAttachmentToBuffer(this.runtime, attachmentPtr, maxDecodedBytes);\n return { name, ...(mimeType ? { mimeType } : {}), size, bytes };\n }\n}\n","import type {\n AttachmentCreateResult,\n AttachmentDeleteResult,\n EmbeddedFileRef,\n WireAttachmentFile,\n WireResourceMap,\n} from '@embedpdf/engine-core/runtime';\nimport { EngineError, EngineErrorCode } from '@embedpdf/engine-core/runtime';\nimport type { PdfRuntimeModule, Ptr } from '@embedpdf/engine-runtime';\n\nimport {\n readAttachmentFileInfo,\n resolveAttachmentIndex,\n writeAttachmentFilePayload,\n} from './internal/attachmentPrimitives';\nimport type { DocumentSession } from '../../document-session/DocumentSession';\nimport { throwIfAborted } from '../../shared/abort';\n\n/**\n * Create/delete mutations over the document catalog's `/EmbeddedFiles`\n * name tree — the doc-level sibling of `AnnotationMutator`, sharing the\n * write path (`writeAttachmentFilePayload`) with the file-attachment\n * annotation writer.\n *\n * Identity is the name-tree KEY (unique by construction), so unlike\n * annotations there is no weak-ref/revision bookkeeping here. Note the\n * tree is key-sorted: both mutations shift OTHER entries' indices; keys\n * never move. Layer persistence (`finishMutation`) and event publication\n * happen in the callers, exactly like every other mutation family.\n */\nexport class AttachmentMutator {\n constructor(\n private readonly runtime: PdfRuntimeModule,\n private readonly session: DocumentSession,\n ) {}\n\n /**\n * Create an embedded file. `file.name` becomes the tree key (PDFium\n * writes key = /UF = /F); a duplicate key rejects with `InvalidArg`.\n * The result carries the read-back entry, `checksum`/`size`/dates\n * included.\n */\n create(\n file: WireAttachmentFile,\n resources: WireResourceMap | undefined,\n signal: AbortSignal,\n ): AttachmentCreateResult {\n throwIfAborted(signal);\n const { fn, mem } = this.runtime;\n const docPtr = this.session.requireDocPtr();\n\n const resource = resources?.[file.resource];\n if (!resource) {\n throw new EngineError(\n EngineErrorCode.InvalidArg,\n `attachment file references resource '${file.resource}' but no such binary payload accompanied the mutation`,\n );\n }\n if (file.name.length === 0) {\n throw new EngineError(EngineErrorCode.InvalidArg, 'attachment file requires a name');\n }\n\n // Duplicate keys are an identity violation, not a replace.\n // (FPDFDoc_AddAttachment would also refuse, but a probe first gives\n // the caller a precise error instead of a generic native failure.)\n if (resolveAttachmentIndex(fn, mem, docPtr, { kind: 'key', key: file.name }) !== -1) {\n throw new EngineError(\n EngineErrorCode.InvalidArg,\n `an embedded file with key '${file.name}' already exists — keys are unique; rename and retry`,\n );\n }\n\n throwIfAborted(signal);\n const namePtr = mem.writeU16String(file.name);\n let attachmentPtr: Ptr;\n try {\n attachmentPtr = fn.FPDFDoc_AddAttachment(docPtr, namePtr);\n } finally {\n mem.free(namePtr);\n }\n if (!attachmentPtr) {\n throw new EngineError(EngineErrorCode.Unknown, 'FPDFDoc_AddAttachment returned NULL');\n }\n\n writeAttachmentFilePayload(fn, mem, attachmentPtr, docPtr, file, resource);\n\n // Read back the materialised entry at its (name-sorted) position.\n const index = resolveAttachmentIndex(fn, mem, docPtr, { kind: 'key', key: file.name });\n if (index < 0) {\n throw new EngineError(\n EngineErrorCode.Unknown,\n 'created attachment did not resolve by key after the write',\n );\n }\n return {\n created: { ...readAttachmentFileInfo(fn, mem, attachmentPtr), key: file.name, index },\n // Cloud coherence pins are a server concern; the worker reports none.\n cache: null,\n };\n }\n\n /** Delete an embedded file by key. Unlinks the tree entry only. */\n delete(ref: EmbeddedFileRef, signal: AbortSignal): AttachmentDeleteResult {\n throwIfAborted(signal);\n const { fn, mem } = this.runtime;\n const docPtr = this.session.requireDocPtr();\n\n const index = resolveAttachmentIndex(fn, mem, docPtr, ref);\n if (index < 0) {\n throw new EngineError(\n EngineErrorCode.NotFound,\n `no embedded file with key '${ref.key}' in the document`,\n );\n }\n if (!fn.FPDFDoc_DeleteAttachment(docPtr, index)) {\n throw new EngineError(EngineErrorCode.Unknown, 'FPDFDoc_DeleteAttachment returned false');\n }\n return { deleted: ref, cache: null };\n }\n}\n","import type { DocumentSecurityProbeInfo } from '@embedpdf/engine-core/runtime';\n\nimport { hasAllStandardSecurityPermissions } from '../../../shared/securityPermissions';\n\nexport type OpenedAs = 'none' | 'user' | 'owner';\n\n/**\n * Single constructor for the \"successfully inspected\" shape of\n * `DocumentSecurityProbeInfo`. Every path that actually resolves a\n * permission word — the cold file probe, the live-session snapshot, and\n * the password-permission check — funnels through here so the encrypted/\n * none distinction, the revision-nulling rule, and the\n * `pdfPermissionsAllAllowed` derivation stay defined in exactly one place.\n *\n * The password-blocked / unsupported / unknown shapes are NOT built here:\n * those carry null permission words and only the cold probe can produce\n * them, so they stay local to `SecurityReader.probeFile`.\n */\nexport function buildSecurityInfo(input: {\n openedAs: OpenedAs;\n permissionsBits: number;\n securityHandlerRevision: number | null;\n probedAt: number;\n}): DocumentSecurityProbeInfo {\n const encrypted = input.openedAs !== 'none';\n return {\n encryptionState: encrypted ? 'encrypted' : 'none',\n encryptionRequiresPassword: false,\n securityHandlerRevision: encrypted ? input.securityHandlerRevision : null,\n pdfPermissionsBits: input.permissionsBits,\n pdfPermissionsAllAllowed: hasAllStandardSecurityPermissions(input.permissionsBits),\n pdfOpenedAs: input.openedAs,\n securityProbedAt: input.probedAt,\n };\n}\n\n/**\n * Mirrors `EPDF_PASSWORD_PERMISSION_*` in public/fpdfview.h:\n * invalid=0, none=1, user=2, owner=3.\n */\nexport function openedAsFromCode(code: number): OpenedAs {\n if (code === 3) return 'owner';\n if (code === 2) return 'user';\n return 'none';\n}\n","import type { DocumentSecurityProbeInfo } from '@embedpdf/engine-core/runtime';\nimport { EngineError, EngineErrorCode } from '@embedpdf/engine-core/runtime';\nimport type { PdfRuntimeModule, Ptr } from '@embedpdf/engine-runtime';\n\nimport { buildSecurityInfo, openedAsFromCode } from './internal/buildSecurityInfo';\nimport type { DocumentSession } from '../../document-session/DocumentSession';\nimport { ensureInitialized } from '../../runtime/lifecycle/bootstrap';\nimport { normalizeU32 } from '../../shared/securityPermissions';\n\nconst FPDF_ERR_PASSWORD = 4;\nconst FPDF_ERR_SECURITY = 5;\n\n/**\n * Reads document security/permission state. Three entry points:\n *\n * - `probeFile` is the only doc-less path: it opens, inspects, and\n * closes its own document straight off a file. It is the intentional\n * exception to the package's `(runtime, session)` reader shape — it\n * answers \"what is this file's security?\" before any session exists.\n * - `readLiveSecurityInfo` / `checkPasswordPermissions` inspect an\n * already-open `DocumentSession`.\n */\nexport class SecurityReader {\n constructor(private readonly runtime: PdfRuntimeModule) {\n // WorkerHost initializes the runtime before dispatching jobs, but\n // this reader is intentionally usable as a one-shot probe too.\n // `ensureInitialized()` is idempotent per runtime instance.\n ensureInitialized(this.runtime);\n }\n\n probeFile(path: string, password: string | null = null): DocumentSecurityProbeInfo {\n const now = Date.now();\n let access: ReturnType<PdfRuntimeModule['fileAccess']['fromNodeFile']> | null = null;\n let docPtr: Ptr | null = null;\n try {\n access = this.runtime.fileAccess.fromNodeFile(path);\n docPtr = this.runtime.fn.FPDF_LoadCustomDocument(access.ptr, password ?? '');\n if (!docPtr) {\n const err = this.runtime.fn.FPDF_GetLastError();\n if (err === FPDF_ERR_PASSWORD) {\n return {\n encryptionState: 'encrypted',\n encryptionRequiresPassword: true,\n securityHandlerRevision: null,\n pdfPermissionsBits: null,\n pdfPermissionsAllAllowed: null,\n pdfOpenedAs: null,\n securityProbedAt: now,\n };\n }\n if (err === FPDF_ERR_SECURITY) {\n return {\n encryptionState: 'unsupported',\n encryptionRequiresPassword: null,\n securityHandlerRevision: null,\n pdfPermissionsBits: null,\n pdfPermissionsAllAllowed: null,\n pdfOpenedAs: null,\n securityProbedAt: now,\n };\n }\n return unknownSecurity(now);\n }\n\n const encrypted = this.runtime.fn.EPDF_IsEncrypted(docPtr);\n // Cold probe (no password session): `FPDF_GetDocPermissions` reports\n // the document's declared permission word. Contrast with the live\n // session, which reads `FPDF_GetDocUserPermissions` (the effective\n // word after any owner unlock). See `readLiveSecurityInfo`.\n const bits = normalizeU32(this.runtime.fn.FPDF_GetDocPermissions(docPtr));\n const openedAs = !encrypted\n ? 'none'\n : this.runtime.fn.EPDF_IsOwnerUnlocked(docPtr)\n ? 'owner'\n : 'user';\n return buildSecurityInfo({\n openedAs,\n permissionsBits: bits,\n securityHandlerRevision: encrypted\n ? this.runtime.fn.FPDF_GetSecurityHandlerRevision(docPtr)\n : null,\n probedAt: now,\n });\n } finally {\n if (docPtr) this.runtime.fn.FPDF_CloseDocument(docPtr);\n access?.close();\n }\n }\n\n /**\n * Snapshot of the live session's EFFECTIVE security state.\n * `FPDF_GetDocUserPermissions` reports the permission word in force\n * right now (e.g. after an owner unlock), as opposed to the declared\n * word the cold `probeFile` path reads.\n */\n readLiveSecurityInfo(session: DocumentSession): DocumentSecurityProbeInfo {\n const { fn } = this.runtime;\n const docPtr = session.requireDocPtr();\n const encrypted = fn.EPDF_IsEncrypted(docPtr);\n const bits = normalizeU32(fn.FPDF_GetDocUserPermissions(docPtr));\n const openedAs = !encrypted ? 'none' : fn.EPDF_IsOwnerUnlocked(docPtr) ? 'owner' : 'user';\n return buildSecurityInfo({\n openedAs,\n permissionsBits: bits,\n securityHandlerRevision: encrypted ? fn.FPDF_GetSecurityHandlerRevision(docPtr) : null,\n probedAt: Date.now(),\n });\n }\n\n /**\n * Verify a password against the live session and report the resulting\n * effective permissions. Throws `DocPasswordIncorrect` when the\n * password is rejected, or (in `'owner'` mode) when it unlocks only as\n * a user.\n */\n checkPasswordPermissions(\n session: DocumentSession,\n password: string,\n mode: 'any' | 'owner' = 'any',\n ): DocumentSecurityProbeInfo {\n const docPtr = session.requireDocPtr();\n const { mem, fn } = this.runtime;\n const kindPtr = mem.alloc(4);\n const userPermissionsPtr = mem.alloc(4);\n const effectivePermissionsPtr = mem.alloc(4);\n const revisionPtr = mem.alloc(4);\n try {\n mem.poke(kindPtr, 'i32', 0);\n mem.poke(userPermissionsPtr, 'i32', 0);\n mem.poke(effectivePermissionsPtr, 'i32', 0);\n mem.poke(revisionPtr, 'i32', 0);\n const ok = fn.EPDF_CheckPasswordPermissions(\n docPtr,\n password,\n kindPtr,\n userPermissionsPtr,\n effectivePermissionsPtr,\n revisionPtr,\n );\n if (!ok) {\n throw new EngineError(EngineErrorCode.DocPasswordIncorrect, 'incorrect document password');\n }\n const openedAs = openedAsFromCode(Number(mem.peek(kindPtr, 'i32')));\n if (mode === 'owner' && openedAs !== 'owner') {\n throw new EngineError(EngineErrorCode.DocPasswordIncorrect, 'owner password required');\n }\n return buildSecurityInfo({\n openedAs,\n permissionsBits: normalizeU32(Number(mem.peek(effectivePermissionsPtr, 'i32'))),\n securityHandlerRevision: Number(mem.peek(revisionPtr, 'i32')),\n probedAt: Date.now(),\n });\n } finally {\n mem.free(revisionPtr);\n mem.free(effectivePermissionsPtr);\n mem.free(userPermissionsPtr);\n mem.free(kindPtr);\n }\n }\n}\n\nfunction unknownSecurity(now: number): DocumentSecurityProbeInfo {\n return {\n encryptionState: 'unknown',\n encryptionRequiresPassword: null,\n securityHandlerRevision: null,\n pdfPermissionsBits: null,\n pdfPermissionsAllAllowed: null,\n pdfOpenedAs: null,\n securityProbedAt: now,\n };\n}\n","import { EngineError, EngineErrorCode, type PdfSaveMode } from '@embedpdf/engine-core/runtime';\n\nconst FPDF_INCREMENTAL = 1 << 0;\nconst FPDF_NO_INCREMENTAL = 1 << 1;\n\nexport function pdfSaveModeFlags(mode: PdfSaveMode): number {\n return mode === 'incremental' ? FPDF_INCREMENTAL : FPDF_NO_INCREMENTAL;\n}\n\nexport function layerSaveError(status: number): EngineError {\n if (status === 1) {\n return new EngineError(\n EngineErrorCode.DocOpenFailed,\n 'layer artifact cannot be saved because append-only offsets exceed the supported range',\n );\n }\n return new EngineError(EngineErrorCode.DocOpenFailed, 'failed to save layer artifact');\n}\n","import { EngineError, EngineErrorCode, type PdfSaveMode } from '@embedpdf/engine-core/runtime';\nimport type { PdfRuntimeModule, Ptr } from '@embedpdf/engine-runtime';\n\nimport { layerSaveError, pdfSaveModeFlags } from './internal/pdfSaveMode';\nimport type { DocumentSession } from '../../document-session/DocumentSession';\n\n/**\n * Owns every \"serialize the open document\" path for a `DocumentSession`.\n * Two distinct outputs:\n *\n * - Layer artifacts (`saveLayerArtifact*`) are the storage-optimized\n * `.layer` delta used by server-side persistence. Only valid for a\n * `layer` session.\n * - Standalone saves (`saveStandalone*`) export a self-contained PDF\n * view (base + applied delta) via `FPDF_SaveAsCopy` /\n * `EPDF_SaveDocumentToOwnedBuffer`, valid for any session kind.\n *\n * Lives in `engine-services` so the browser Worker and the Node\n * `worker_thread` server share the exact same save code path.\n */\nexport class DocumentSaver {\n constructor(\n private readonly runtime: PdfRuntimeModule,\n private readonly session: DocumentSession,\n ) {}\n\n saveLayerArtifact(): { bytes: ArrayBuffer; size: number } {\n this.requireLayer();\n\n const { mem, fn } = this.runtime;\n const sizePtr = mem.alloc(4);\n const statusPtr = mem.alloc(4);\n let artifactPtr: Ptr | null = null;\n try {\n mem.poke(sizePtr, 'i32', 0);\n mem.poke(statusPtr, 'i32', -1);\n artifactPtr = fn.EPDFLayer_SaveLayerArtifactToOwnedBuffer(\n this.session.requireDocPtr(),\n sizePtr,\n statusPtr,\n );\n const status = Number(mem.peek(statusPtr, 'i32'));\n const size = Number(mem.peek(sizePtr, 'i32'));\n if (!artifactPtr || status !== 0 || size <= 0) {\n throw layerSaveError(status);\n }\n\n const bytes = mem.readBytes(artifactPtr, size);\n const buffer = new ArrayBuffer(bytes.byteLength);\n new Uint8Array(buffer).set(bytes);\n return { bytes: buffer, size };\n } finally {\n if (artifactPtr) fn.EPDF_FreeBuffer(artifactPtr);\n mem.free(statusPtr);\n mem.free(sizePtr);\n }\n }\n\n saveLayerArtifactToFile(path: string): { path: string } {\n this.requireLayer();\n\n const { mem, fn } = this.runtime;\n const statusPtr = mem.alloc(4);\n const writer = this.runtime.fileWrite.toNodeFile(path);\n try {\n mem.poke(statusPtr, 'i32', -1);\n const ok = fn.EPDFLayer_SaveLayerArtifact(\n this.session.requireDocPtr(),\n writer.ptr,\n statusPtr,\n );\n const status = Number(mem.peek(statusPtr, 'i32'));\n if (!ok || status !== 0) {\n throw layerSaveError(status);\n }\n return { path };\n } finally {\n writer.close();\n mem.free(statusPtr);\n }\n }\n\n saveStandaloneToBuffer(mode: PdfSaveMode): { bytes: ArrayBuffer; size: number } {\n const { mem, fn } = this.runtime;\n const sizePtr = mem.alloc(4);\n let pdfPtr: Ptr | null = null;\n try {\n mem.poke(sizePtr, 'i32', 0);\n // Standalone saves are not layer artifacts. For a CPDF_LayerDocument,\n // FPDF_INCREMENTAL copies the base bytes through and appends the layer\n // delta as a normal PDF revision. The EPDFLayer_* artifact APIs are only\n // for internal server storage.\n pdfPtr = fn.EPDF_SaveDocumentToOwnedBuffer(\n this.session.requireDocPtr(),\n pdfSaveModeFlags(mode),\n sizePtr,\n );\n const size = Number(mem.peek(sizePtr, 'i32'));\n if (!pdfPtr || size <= 0) {\n throw new EngineError(EngineErrorCode.DocOpenFailed, 'failed to save document');\n }\n\n const bytes = mem.readBytes(pdfPtr, size);\n const buffer = new ArrayBuffer(bytes.byteLength);\n new Uint8Array(buffer).set(bytes);\n return { bytes: buffer, size };\n } finally {\n if (pdfPtr) fn.EPDF_FreeBuffer(pdfPtr);\n mem.free(sizePtr);\n }\n }\n\n saveStandaloneToFile(path: string, mode: PdfSaveMode): { path: string } {\n const writer = this.runtime.fileWrite.toNodeFile(path);\n try {\n // See saveStandaloneToBuffer(): this exports a standalone PDF view,\n // not the storage-optimized `.layer` artifact.\n const ok = this.runtime.fn.FPDF_SaveAsCopy(\n this.session.requireDocPtr(),\n writer.ptr,\n pdfSaveModeFlags(mode),\n );\n if (!ok) {\n throw new EngineError(EngineErrorCode.DocOpenFailed, 'failed to save document');\n }\n return { path };\n } finally {\n writer.close();\n }\n }\n\n private requireLayer(): void {\n if (this.session.kind !== 'layer') {\n throw new EngineError(EngineErrorCode.InvalidArg, 'document session is not a layer');\n }\n }\n}\n","import { EngineError, EngineErrorCode } from '@embedpdf/engine-core/runtime';\nimport type { PdfFileAccessHandle, PdfRuntimeModule } from '@embedpdf/engine-runtime';\n\n/**\n * A font to register at thread startup from a local file. Used by hosts that\n * own their font policy (the cloud server's fallback fonts), as opposed to the\n * per-request `fonts.register` wire path the browser engine drives.\n *\n * Registration is by path, mirroring how the server opens base documents\n * (`fileAccess.fromNodeFile`): the bytes are range-read on demand and never\n * held resident in the JS heap, so a deployment can configure many large\n * fallback fonts (CJK families) without paying RAM per font.\n */\nexport interface StartupFontSpec {\n key: string;\n /** Absolute path to a TTF/OTF file (native/node runtimes only). */\n path: string;\n familyName?: string;\n weight?: number;\n /** `undefined` → infer from the file. */\n italic?: boolean;\n /** Also add to the glyph-fallback chain (automatic missing-glyph fill). */\n fallback?: boolean;\n}\n\n/**\n * Thread-confined runtime font registry binding.\n *\n * Wraps the `EPDFFont_*` C API on a single PDFium thread. PDFium's font\n * registry is thread-local: a font registered here is visible only to this\n * thread's page rendering and annotation-authoring calls, and the numeric\n * `CFX_FontRegistry::FontId` it returns is a per-thread `next_font_id++`.\n *\n * That id is volatile, so we never let it cross the worker boundary. The host\n * owns the `fontKey → id` map (passed in by reference) and every wire message\n * references the stable `fontKey`. The FreeText writer resolves a key to the\n * current thread's id through {@link idFor} at authoring time.\n *\n * Lives in `engine-services` (not a worker host) so the browser Web Worker,\n * the Node `worker_thread` server, and any future direct-thread embedding\n * share the exact same binding — only the `PdfRuntimeModule` (WASM vs native)\n * differs.\n */\nexport class FontRegistrar {\n /**\n * File-access handles retained for path-registered fonts. PDFium range-reads\n * the file lazily (on each face creation), so the FPDF_FILEACCESS must stay\n * alive until the registry is cleared — same lifetime rule as a file-backed\n * base document. Closed in {@link clear}.\n */\n private readonly fileHandles: PdfFileAccessHandle[] = [];\n\n constructor(\n private readonly runtime: PdfRuntimeModule,\n /** Host-owned `fontKey → native FontId` map for this thread. */\n private readonly ids: Map<string, number>,\n ) {}\n\n /**\n * Register a font from its bytes. Copies into the WASM heap, hands the\n * pointer to `EPDFFont_RegisterMemFont64` (which copies the bytes into the\n * native registry), then frees the scratch — so the heap holds exactly one\n * retained copy per registered font.\n *\n * Throws `InvalidArg` when the runtime rejects the font (corrupt, no glyphs).\n */\n register(\n fontKey: string,\n familyName: string,\n weight: number,\n italic: number,\n bytes: Uint8Array,\n ): void {\n if (bytes.byteLength === 0) {\n throw new EngineError(EngineErrorCode.InvalidArg, `empty font data: ${fontKey}`);\n }\n const { mem, fn } = this.runtime;\n const ptr = mem.alloc(bytes.byteLength);\n try {\n mem.writeBytes(ptr, bytes);\n const id = fn.EPDFFont_RegisterMemFont64(familyName, weight, italic, ptr, bytes.byteLength);\n if (id === 0) {\n throw new EngineError(\n EngineErrorCode.InvalidArg,\n `font registration failed (unloadable or no glyphs): ${fontKey}`,\n );\n }\n this.ids.set(fontKey, id);\n } finally {\n mem.free(ptr);\n }\n }\n\n /**\n * Register a font from a local file via `EPDFFont_RegisterFont`. The runtime\n * range-reads the file on demand (it is not loaded into the JS heap), and the\n * file-access handle is retained until {@link clear}. Native/node only.\n *\n * Throws `InvalidArg` when the runtime rejects the font (corrupt, no glyphs).\n */\n registerFromNodeFile(\n fontKey: string,\n familyName: string,\n weight: number,\n italic: number,\n path: string,\n ): void {\n const access = this.runtime.fileAccess.fromNodeFile(path);\n let id = 0;\n try {\n id = this.runtime.fn.EPDFFont_RegisterFont(familyName, weight, italic, access.ptr);\n } catch (error) {\n access.close();\n throw error;\n }\n if (id === 0) {\n access.close();\n throw new EngineError(\n EngineErrorCode.InvalidArg,\n `font registration failed (unloadable or no glyphs): ${fontKey} (${path})`,\n );\n }\n this.ids.set(fontKey, id);\n this.fileHandles.push(access);\n }\n\n /**\n * Register host-owned startup fonts on this thread, in order, optionally\n * adding each to the fallback chain. Order matters: it fixes both the native\n * FontIds and the fallback precedence, so every worker thread that runs the\n * same list ends up identical.\n */\n registerStartup(specs: readonly StartupFontSpec[]): void {\n for (const spec of specs) {\n const italic = spec.italic === undefined ? -1 : spec.italic ? 1 : 0;\n this.registerFromNodeFile(\n spec.key,\n spec.familyName ?? '',\n spec.weight ?? 0,\n italic,\n spec.path,\n );\n if (spec.fallback) {\n this.addFallback(spec.key);\n }\n }\n }\n\n /** Append a registered font to the ordered glyph-fallback chain. */\n addFallback(fontKey: string): void {\n const id = this.requireId(fontKey);\n if (!this.runtime.fn.EPDFFont_AddFallbackFont(id)) {\n throw new EngineError(EngineErrorCode.InvalidArg, `addFallback failed: ${fontKey}`);\n }\n }\n\n clearFallbacks(): void {\n this.runtime.fn.EPDFFont_ClearFallbackFonts();\n }\n\n /** Unregister every font and reset the fallback chain (clears the map too). */\n clear(): void {\n this.runtime.fn.EPDFFont_ClearRegisteredFonts();\n this.ids.clear();\n // Native registry no longer reads through these — release the file handles.\n for (const access of this.fileHandles) {\n access.close();\n }\n this.fileHandles.length = 0;\n }\n\n /** Resolve a stable key to this thread's native FontId. Throws if unknown. */\n idFor(fontKey: string): number {\n return this.requireId(fontKey);\n }\n\n private requireId(fontKey: string): number {\n const id = this.ids.get(fontKey);\n if (id === undefined) {\n throw new EngineError(\n EngineErrorCode.InvalidArg,\n `font not registered on this thread: ${fontKey}`,\n );\n }\n return id;\n }\n}\n","import type { FormFieldRef } from '@embedpdf/engine-core/runtime';\nimport { EngineError, EngineErrorCode } from '@embedpdf/engine-core/runtime';\nimport type { PdfRuntimeModule, Ptr } from '@embedpdf/engine-runtime';\n\nimport { readUtf16String } from '../../../runtime/memory/strings';\n\nexport interface ResolvedField {\n /** Index of the field in the native model. */\n fieldIndex: number;\n /** Indirect object number of the field dictionary; `0` for direct dicts. */\n fieldObjectNumber: number;\n}\n\n/**\n * Resolve a caller ref against the native model. `objectNumber` refs use\n * the model's reverse index; `fqn` refs compare fully qualified names.\n * Throws `NotFound` when nothing matches.\n */\nexport function resolveFieldRef(\n runtime: PdfRuntimeModule,\n model: Ptr,\n ref: FormFieldRef,\n): ResolvedField {\n const { fn } = runtime;\n if (ref.kind === 'objectNumber') {\n const fieldIndex = fn.EPDFForm_GetFieldIndexByObjNum(model, ref.fieldObjectNumber);\n if (fieldIndex < 0) {\n throw new EngineError(\n EngineErrorCode.NotFound,\n `form field not found: object ${ref.fieldObjectNumber}`,\n );\n }\n return { fieldIndex, fieldObjectNumber: ref.fieldObjectNumber };\n }\n\n const count = fn.EPDFForm_CountFields(model);\n for (let i = 0; i < count; i++) {\n const name =\n readUtf16String(runtime.mem, (buf, cap) => fn.EPDFForm_GetFieldName(model, i, buf, cap)) ??\n '';\n if (name === ref.name) {\n return { fieldIndex: i, fieldObjectNumber: fn.EPDFForm_GetFieldObjNum(model, i) };\n }\n }\n throw new EngineError(EngineErrorCode.NotFound, `form field not found: \"${ref.name}\"`);\n}\n","import type {\n FormDataFormat,\n FormFieldDTO,\n FormFieldRef,\n FormSnapshot,\n} from '@embedpdf/engine-core/runtime';\nimport { EngineError, EngineErrorCode } from '@embedpdf/engine-core/runtime';\nimport { NULL_PTR, type PdfRuntimeModule } from '@embedpdf/engine-runtime';\n\nimport type { DocumentSession } from '../../document-session/DocumentSession';\nimport { throwIfAborted } from '../../shared/abort';\nimport { withScratch } from '../../runtime/memory/scratch';\nimport { acquireFormModel } from './internal/formModelCache';\nimport { readFieldAt, readFormSnapshot } from './internal/readFormSnapshot';\nimport { resolveFieldRef } from './internal/resolveFieldRef';\n\n/**\n * Read side of the forms feature. All reads go through the session's\n * version-keyed model cache, so repeated reads between mutations reuse\n * one native snapshot build.\n */\nexport class FormReader {\n constructor(\n private readonly runtime: PdfRuntimeModule,\n private readonly session: DocumentSession,\n ) {}\n\n snapshot(signal: AbortSignal): FormSnapshot {\n throwIfAborted(signal);\n const model = acquireFormModel(this.runtime, this.session);\n return readFormSnapshot(this.runtime, model);\n }\n\n field(ref: FormFieldRef, signal: AbortSignal): FormFieldDTO {\n throwIfAborted(signal);\n const model = acquireFormModel(this.runtime, this.session);\n const { fieldIndex } = resolveFieldRef(this.runtime, model, ref);\n return readFieldAt(this.runtime, model, fieldIndex);\n }\n\n /**\n * Serialize form data. Exports read the reconciled view (recovered\n * fields included; on layers, promoted values win) straight from the\n * document — the model cache is not involved.\n */\n exportData(\n format: FormDataFormat,\n signal: AbortSignal,\n ): { format: FormDataFormat; bytes: ArrayBuffer } {\n throwIfAborted(signal);\n const { fn, mem } = this.runtime;\n const docPtr = this.session.requireDocPtr();\n const call = format === 'fdf' ? fn.EPDFForm_ExportFDF : fn.EPDFForm_ExportXFDF;\n\n const length = call(docPtr, NULL_PTR, 0, NULL_PTR, 0);\n if (length <= 0) {\n throw new EngineError(EngineErrorCode.Unknown, `form ${format} export failed`);\n }\n return withScratch(mem, length, (buf) => {\n const written = call(docPtr, NULL_PTR, 0, buf, length);\n if (written !== length) {\n throw new EngineError(EngineErrorCode.Unknown, `form ${format} export failed`);\n }\n const view = mem.readBytes(buf, length);\n const bytes = new ArrayBuffer(view.byteLength);\n new Uint8Array(bytes).set(view);\n return { format, bytes };\n });\n }\n}\n","import type { WidgetPlacement } from '@embedpdf/engine-core/runtime';\nimport { EngineError, EngineErrorCode } from '@embedpdf/engine-core/runtime';\nimport { NULL_PTR, type PdfRuntimeModule } from '@embedpdf/engine-runtime';\n\nimport type { DocumentSession } from '../../../document-session/DocumentSession';\nimport { setAnnotRect } from '../../annotations/internal/write/annotationWritePrimitives';\nimport { applyWidgetStyle } from '../../annotations/internal/write/writeWidgetAnnotation';\n\nconst WIDGET_SUBTYPE_CODE = 20; // FPDF_ANNOT_WIDGET\n\n/**\n * Birth a widget through the annotation plane (EPDFPage_CreateAnnot -\n * indirect, durable object number), place it, and style it with THE\n * widget-plane writer (`applyWidgetStyle` - the same code the widget\n * annotation kind uses for create/patch). Returns the widget's object\n * number, ready for EPDFForm_AttachWidget adoption.\n */\nexport function createUnattachedWidget(\n runtime: PdfRuntimeModule,\n session: DocumentSession,\n placement: WidgetPlacement,\n): number {\n const { fn, mem } = runtime;\n const pool = session.pagePool();\n const pagePtr = pool.acquire(placement.pageObjectNumber);\n try {\n const annotPtr = fn.EPDFPage_CreateAnnot(pagePtr, WIDGET_SUBTYPE_CODE);\n if (annotPtr === NULL_PTR) {\n throw new EngineError(EngineErrorCode.Unknown, 'failed to create widget annotation');\n }\n try {\n setAnnotRect(fn, mem, annotPtr, placement.rect);\n if (placement.appearance) {\n applyWidgetStyle(fn, mem, annotPtr, placement.appearance);\n }\n const widgetObjectNumber = fn.EPDFAnnot_GetObjectNumber(annotPtr);\n if (widgetObjectNumber <= 0) {\n throw new EngineError(EngineErrorCode.Unknown, 'widget annotation has no object number');\n }\n return widgetObjectNumber;\n } finally {\n fn.FPDFPage_CloseAnnot(annotPtr);\n }\n } finally {\n pool.release(placement.pageObjectNumber);\n }\n}\n","/**\n * /Ff bits writable through drafts and patches (1-based spec bit numbers).\n * Family-DEFINING bits (Radio 1<<15, Pushbutton 1<<16, Combo 1<<17) are set\n * once by EPDFForm_CreateField and immutable afterwards - the native\n * setter rejects them.\n */\nexport const FIELD_FLAG_BITS = {\n readOnly: 1 << 0,\n required: 1 << 1,\n noExport: 1 << 2,\n multiline: 1 << 12,\n password: 1 << 13,\n noToggleToOff: 1 << 14,\n edit: 1 << 18,\n multiSelect: 1 << 21,\n comb: 1 << 24,\n radiosInUnison: 1 << 25,\n} as const;\n\nexport type FieldFlagName = keyof typeof FIELD_FLAG_BITS;\n\n/**\n * Fold optional booleans into set/clear masks: `true` sets the bit,\n * `false` clears it, `undefined` leaves it alone.\n */\nexport function flagMasks(flags: Partial<Record<FieldFlagName, boolean | undefined>>): {\n setBits: number;\n clearBits: number;\n} {\n let setBits = 0;\n let clearBits = 0;\n for (const [name, bit] of Object.entries(FIELD_FLAG_BITS)) {\n const value = flags[name as FieldFlagName];\n if (value === true) setBits |= bit;\n else if (value === false) clearBits |= bit;\n }\n return { setBits, clearBits };\n}\n","import type { PdfRuntimeModule, Ptr } from '@embedpdf/engine-runtime';\n\nimport { withScratch } from '../../../runtime/memory/scratch';\n\n/**\n * Marshal a `const FPDF_WIDESTRING*` array: encode every string into the\n * runtime heap, write the pointer table with the runtime's pointer width\n * (bigint pointers cannot be poked into the wasm 32-bit heap), run |body|,\n * free everything.\n */\nexport function withWideStringArray<T>(\n runtime: PdfRuntimeModule,\n values: readonly string[],\n body: (arrayPtr: Ptr, count: number) => T,\n): T {\n const { mem } = runtime;\n const stringPtrs = values.map((value) => mem.writeU16String(value));\n const isWasm = runtime.kind === 'wasm';\n const ptrSize = isWasm ? 4 : 8;\n try {\n return withScratch(mem, Math.max(1, stringPtrs.length * ptrSize), (arrayPtr) => {\n stringPtrs.forEach((ptr, i) =>\n isWasm\n ? mem.poke(arrayPtr, 'i32', Number(ptr), i * 4)\n : mem.poke(arrayPtr, 'i64', ptr, i * 8),\n );\n return body(arrayPtr, stringPtrs.length);\n });\n } finally {\n for (let i = stringPtrs.length - 1; i >= 0; i--) {\n mem.free(stringPtrs[i]);\n }\n }\n}\n","import type {\n FormDataFormat,\n FormFieldDraft,\n FormFieldDTO,\n FormFieldPatch,\n FormFieldRef,\n FormFieldValue,\n FormImportResult,\n FormRepairResult,\n FormSetValueResult,\n FormWidgetRef,\n MutationMeta,\n WidgetPlacement,\n} from '@embedpdf/engine-core/runtime';\nimport { EngineError, EngineErrorCode } from '@embedpdf/engine-core/runtime';\nimport type { PdfRuntimeModule, Ptr } from '@embedpdf/engine-runtime';\n\nimport type { DocumentSession } from '../../document-session/DocumentSession';\nimport { throwIfAborted } from '../../shared/abort';\nimport { withScratch, withScratchN } from '../../runtime/memory/scratch';\nimport { createUnattachedWidget } from './internal/authorWidget';\nimport { flagMasks } from './internal/fieldFlagBits';\nimport { acquireFormModel } from './internal/formModelCache';\nimport { withWideStringArray } from './internal/wideStringArray';\nimport { readFieldAt, readFormSnapshot } from './internal/readFormSnapshot';\nimport { resolveFieldRef } from './internal/resolveFieldRef';\n\n// Mirrors EPDF_FORMFIELD_FAMILY_* in public/epdf_form.h.\nconst FAMILY_CODE = {\n checkbox: 2,\n radio: 3,\n text: 4,\n combobox: 5,\n listbox: 6,\n} as const;\n\n/** Widgets a single value write can touch; far above any real form. */\nconst CHANGED_WIDGETS_CAPACITY = 256;\n\n// Mirrors EPDF_FORM_REPAIR_* in public/epdf_form.h.\nconst REPAIR_BAKE_APPEARANCES = 0x1;\n\n/**\n * Value writes are non-structural: no page-list revision bumps, and the\n * cloud layer computes its own cache delta server-side.\n */\nconst EMPTY_META: MutationMeta = { affectedPages: [], cacheDelta: null };\n\nconst FAMILY_BY_VALUE_TYPE: Record<FormFieldValue['type'], readonly string[]> = {\n text: ['text'],\n toggle: ['checkbox', 'radio'],\n choice: ['combobox', 'listbox'],\n};\n\n/**\n * Write side of the forms feature. Every method is a validate-then-apply\n * transaction over the native EPDFForm_* write API: a failed call leaves\n * the document untouched (on layers: nothing promoted), and each success\n * bumps the session's mutation sequence so version-keyed caches rebuild.\n */\nexport class FormMutator {\n constructor(\n private readonly runtime: PdfRuntimeModule,\n private readonly session: DocumentSession,\n ) {}\n\n setValue(ref: FormFieldRef, value: FormFieldValue, signal: AbortSignal): FormSetValueResult {\n throwIfAborted(signal);\n const model = acquireFormModel(this.runtime, this.session);\n const resolved = resolveFieldRef(this.runtime, model, ref);\n this.assertWritable(resolved.fieldObjectNumber);\n\n const before = readFieldAt(this.runtime, model, resolved.fieldIndex);\n const allowed = FAMILY_BY_VALUE_TYPE[value.type];\n if (!allowed.includes(before.family)) {\n throw new EngineError(\n EngineErrorCode.InvalidArg,\n `value type '${value.type}' does not apply to a '${before.family}' field`,\n );\n }\n\n const changed = this.applyWrite(resolved.fieldObjectNumber, value);\n return this.readBack(resolved.fieldObjectNumber, changed);\n }\n\n reset(ref: FormFieldRef, signal: AbortSignal): FormSetValueResult {\n throwIfAborted(signal);\n const model = acquireFormModel(this.runtime, this.session);\n const resolved = resolveFieldRef(this.runtime, model, ref);\n this.assertWritable(resolved.fieldObjectNumber);\n\n const changed = this.withChangedWidgets((buf, cap, countPtr) =>\n this.runtime.fn.EPDFForm_ResetField(\n this.session.requireDocPtr(),\n resolved.fieldObjectNumber,\n buf,\n cap,\n countPtr,\n ),\n );\n if (changed === null) {\n throw new EngineError(EngineErrorCode.InvalidArg, 'form field cannot be reset');\n }\n return this.readBack(resolved.fieldObjectNumber, changed);\n }\n\n importData(\n data: ArrayBuffer,\n format: FormDataFormat | undefined,\n signal: AbortSignal,\n ): FormImportResult {\n throwIfAborted(signal);\n const { fn, mem } = this.runtime;\n const bytes = new Uint8Array(data);\n if (bytes.byteLength === 0) {\n throw new EngineError(EngineErrorCode.InvalidArg, 'empty form data payload');\n }\n const resolvedFormat = format ?? sniffFormat(bytes);\n const call = resolvedFormat === 'fdf' ? fn.EPDFForm_ImportFDF : fn.EPDFForm_ImportXFDF;\n const docPtr = this.session.requireDocPtr();\n\n const counters = withScratchN(mem, [bytes.byteLength, 16], ([dataPtr, resultPtr]) => {\n mem.writeBytes(dataPtr, bytes);\n const ok = call(docPtr, dataPtr, bytes.byteLength, resultPtr);\n if (!ok) {\n throw new EngineError(\n EngineErrorCode.InvalidArg,\n `payload is not valid ${resolvedFormat.toUpperCase()}`,\n );\n }\n return {\n fieldsTotal: Number(mem.peek(resultPtr, 'i32', 0)),\n fieldsApplied: Number(mem.peek(resultPtr, 'i32', 4)),\n fieldsSkipped: Number(mem.peek(resultPtr, 'i32', 8)),\n widgetsChanged: Number(mem.peek(resultPtr, 'i32', 12)),\n };\n });\n\n this.session.noteMutation();\n const fresh = acquireFormModel(this.runtime, this.session);\n return {\n ...counters,\n snapshot: readFormSnapshot(this.runtime, fresh),\n meta: EMPTY_META,\n };\n }\n\n repair(bakeAppearances: boolean, signal: AbortSignal): FormRepairResult {\n throwIfAborted(signal);\n const { fn, mem } = this.runtime;\n const flags = bakeAppearances ? REPAIR_BAKE_APPEARANCES : 0;\n\n const report = withScratch(mem, 24, (reportPtr) => {\n const ok = fn.EPDFForm_Repair(this.session.requireDocPtr(), flags, reportPtr);\n if (!ok) {\n throw new EngineError(EngineErrorCode.Unknown, 'form repair failed');\n }\n return {\n acroformCreated: Number(mem.peek(reportPtr, 'i32', 0)) !== 0,\n fieldsLinked: Number(mem.peek(reportPtr, 'i32', 4)),\n widgetsLinked: Number(mem.peek(reportPtr, 'i32', 8)),\n fieldsUnrepairable: Number(mem.peek(reportPtr, 'i32', 12)),\n appearancesBaked: Number(mem.peek(reportPtr, 'i32', 16)),\n needAppearancesCleared: Number(mem.peek(reportPtr, 'i32', 20)) !== 0,\n };\n });\n\n this.session.noteMutation();\n return { ...report, meta: EMPTY_META };\n }\n\n /**\n * Create a field and (optionally) its widgets in one composed\n * transaction: native field creation, widget birth through the\n * annotation plane, adoption, then field-plane setters. A failure\n * mid-composition throws; earlier steps stay applied (the document is\n * never inconsistent - at worst a partially configured field exists).\n */\n createField(draft: FormFieldDraft, signal: AbortSignal): { field: FormFieldDTO } {\n throwIfAborted(signal);\n const { fn, mem } = this.runtime;\n const docPtr = this.session.requireDocPtr();\n\n const placements = this.placementsOf(draft);\n if (draft.family === 'radio') {\n for (const placement of placements) {\n if (!placement.onState || placement.onState === 'Off') {\n throw new EngineError(\n EngineErrorCode.InvalidArg,\n 'every radio widget needs a non-\"Off\" onState',\n );\n }\n }\n }\n\n const familyCode = FAMILY_CODE[draft.family];\n const namePtr = mem.writeU16String(draft.name);\n let fieldObjectNumber: number;\n try {\n fieldObjectNumber = fn.EPDFForm_CreateField(docPtr, familyCode, namePtr);\n } finally {\n mem.free(namePtr);\n }\n if (fieldObjectNumber <= 0) {\n throw new EngineError(\n EngineErrorCode.InvalidArg,\n `cannot create field \"${draft.name}\" (name conflict or invalid)`,\n );\n }\n\n const { setBits, clearBits } = flagMasks(\n draft as unknown as Record<string, boolean | undefined>,\n );\n if (setBits !== 0 || clearBits !== 0) {\n fn.EPDFForm_SetFieldFlags(docPtr, fieldObjectNumber, setBits, clearBits);\n }\n if ('options' in draft && draft.options) {\n this.applyOptions(fieldObjectNumber, draft.options);\n }\n if ('defaultValue' in draft && draft.defaultValue !== undefined) {\n this.applyDefaultValues(fieldObjectNumber, [draft.defaultValue]);\n }\n if ('maxLength' in draft && draft.maxLength !== undefined) {\n if (!fn.EPDFForm_SetFieldMaxLen(docPtr, fieldObjectNumber, draft.maxLength)) {\n throw new EngineError(EngineErrorCode.InvalidArg, 'maxLength rejected');\n }\n }\n if (draft.alternateName !== undefined) {\n this.applyWideSetter(\n fn.EPDFForm_SetFieldAlternateName,\n fieldObjectNumber,\n draft.alternateName,\n 'alternate name rejected',\n );\n }\n if (draft.mappingName !== undefined) {\n this.applyWideSetter(\n fn.EPDFForm_SetFieldMappingName,\n fieldObjectNumber,\n draft.mappingName,\n 'mapping name rejected',\n );\n }\n\n for (const placement of placements) {\n const widgetObjectNumber = createUnattachedWidget(this.runtime, this.session, placement);\n const onState =\n draft.family === 'radio'\n ? placement.onState!\n : draft.family === 'checkbox'\n ? (placement.onState ?? 'Yes')\n : '';\n if (!fn.EPDFForm_AttachWidget(docPtr, fieldObjectNumber, widgetObjectNumber, onState)) {\n throw new EngineError(EngineErrorCode.Unknown, 'widget adoption failed');\n }\n }\n\n this.session.noteMutation();\n return { field: this.readBackField(fieldObjectNumber) };\n }\n\n updateField(\n ref: FormFieldRef,\n patch: FormFieldPatch,\n signal: AbortSignal,\n ): { field: FormFieldDTO } {\n throwIfAborted(signal);\n const { fn } = this.runtime;\n const docPtr = this.session.requireDocPtr();\n const model = acquireFormModel(this.runtime, this.session);\n const resolved = resolveFieldRef(this.runtime, model, ref);\n this.assertWritable(resolved.fieldObjectNumber);\n const before = readFieldAt(this.runtime, model, resolved.fieldIndex);\n if (before.family !== patch.family) {\n throw new EngineError(\n EngineErrorCode.InvalidArg,\n `patch family '${patch.family}' does not match field family '${before.family}'`,\n );\n }\n const fieldObjectNumber = resolved.fieldObjectNumber;\n\n if (patch.name !== undefined) {\n this.applyWideSetter(\n fn.EPDFForm_SetFieldName,\n fieldObjectNumber,\n patch.name,\n `cannot rename to \"${patch.name}\" (sibling conflict or invalid)`,\n );\n }\n const { setBits, clearBits } = flagMasks(\n patch as unknown as Record<string, boolean | undefined>,\n );\n if (setBits !== 0 || clearBits !== 0) {\n if (!fn.EPDFForm_SetFieldFlags(docPtr, fieldObjectNumber, setBits, clearBits)) {\n throw new EngineError(EngineErrorCode.InvalidArg, 'flag update rejected');\n }\n }\n if ('maxLength' in patch && patch.maxLength !== undefined) {\n if (!fn.EPDFForm_SetFieldMaxLen(docPtr, fieldObjectNumber, patch.maxLength ?? 0)) {\n throw new EngineError(\n EngineErrorCode.InvalidArg,\n 'maxLength rejected (current value exceeds it)',\n );\n }\n }\n if ('defaultValue' in patch && patch.defaultValue !== undefined) {\n if (patch.defaultValue === null) {\n if (!fn.EPDFForm_RemoveFieldDefaultValue(docPtr, fieldObjectNumber)) {\n throw new EngineError(EngineErrorCode.InvalidArg, 'default value removal rejected');\n }\n } else {\n this.applyDefaultValues(fieldObjectNumber, [patch.defaultValue]);\n }\n }\n if (patch.alternateName !== undefined) {\n this.applyWideSetter(\n fn.EPDFForm_SetFieldAlternateName,\n fieldObjectNumber,\n patch.alternateName ?? '',\n 'alternate name rejected',\n );\n }\n if (patch.mappingName !== undefined) {\n this.applyWideSetter(\n fn.EPDFForm_SetFieldMappingName,\n fieldObjectNumber,\n patch.mappingName ?? '',\n 'mapping name rejected',\n );\n }\n if ('options' in patch && patch.options) {\n this.applyOptions(fieldObjectNumber, patch.options);\n }\n\n this.session.noteMutation();\n return { field: this.readBackField(fieldObjectNumber) };\n }\n\n /**\n * Delete a terminal field. Widgets are DETACHED here (they become inert\n * annotations); the worker host cascades their annotation deletion so\n * page /Annots bookkeeping flows through the annotation feature.\n */\n deleteField(\n ref: FormFieldRef,\n signal: AbortSignal,\n ): { deletedFieldObjectNumber: number; detachedWidgets: FormWidgetRef[] } {\n throwIfAborted(signal);\n const { fn, mem } = this.runtime;\n const model = acquireFormModel(this.runtime, this.session);\n const resolved = resolveFieldRef(this.runtime, model, ref);\n this.assertWritable(resolved.fieldObjectNumber);\n const before = readFieldAt(this.runtime, model, resolved.fieldIndex);\n\n const ok = withScratchN(mem, [256 * 4, 4], ([buf, countPtr]) => {\n mem.poke(countPtr, 'i32', 0);\n return fn.EPDFForm_DeleteField(\n this.session.requireDocPtr(),\n resolved.fieldObjectNumber,\n buf,\n 256,\n countPtr,\n );\n });\n if (!ok) {\n throw new EngineError(EngineErrorCode.InvalidArg, 'field cannot be deleted');\n }\n\n this.session.noteMutation();\n return {\n deletedFieldObjectNumber: resolved.fieldObjectNumber,\n detachedWidgets: before.widgets.map((w) => ({\n annotObjectNumber: w.annotObjectNumber,\n pageObjectNumber: w.pageObjectNumber,\n })),\n };\n }\n\n attachWidget(\n ref: FormFieldRef,\n widget: FormWidgetRef,\n onState: string | undefined,\n signal: AbortSignal,\n ): { field: FormFieldDTO } {\n throwIfAborted(signal);\n const { fn } = this.runtime;\n const model = acquireFormModel(this.runtime, this.session);\n const resolved = resolveFieldRef(this.runtime, model, ref);\n this.assertWritable(resolved.fieldObjectNumber);\n const before = readFieldAt(this.runtime, model, resolved.fieldIndex);\n const toggle = before.family === 'checkbox' || before.family === 'radio';\n const state = toggle ? (onState ?? (before.family === 'checkbox' ? 'Yes' : '')) : '';\n if (toggle && (!state || state === 'Off')) {\n throw new EngineError(\n EngineErrorCode.InvalidArg,\n 'attaching to a radio group needs a non-\"Off\" onState',\n );\n }\n if (\n !fn.EPDFForm_AttachWidget(\n this.session.requireDocPtr(),\n resolved.fieldObjectNumber,\n widget.annotObjectNumber,\n state,\n )\n ) {\n throw new EngineError(\n EngineErrorCode.InvalidArg,\n 'widget cannot be adopted (already attached, merged, or not a widget)',\n );\n }\n this.session.noteMutation();\n return { field: this.readBackField(resolved.fieldObjectNumber) };\n }\n\n detachWidget(\n ref: FormFieldRef,\n widget: FormWidgetRef,\n signal: AbortSignal,\n ): { field: FormFieldDTO } {\n throwIfAborted(signal);\n const { fn } = this.runtime;\n const model = acquireFormModel(this.runtime, this.session);\n const resolved = resolveFieldRef(this.runtime, model, ref);\n this.assertWritable(resolved.fieldObjectNumber);\n if (\n !fn.EPDFForm_DetachWidget(\n this.session.requireDocPtr(),\n resolved.fieldObjectNumber,\n widget.annotObjectNumber,\n )\n ) {\n throw new EngineError(EngineErrorCode.InvalidArg, 'widget is not attached to this field');\n }\n this.session.noteMutation();\n return { field: this.readBackField(resolved.fieldObjectNumber) };\n }\n\n private placementsOf(draft: FormFieldDraft): WidgetPlacement[] {\n if (draft.family === 'radio') {\n return draft.widgets ?? [];\n }\n return draft.widget ? [draft.widget] : [];\n }\n\n private applyOptions(\n fieldObjectNumber: number,\n options: ReadonlyArray<{ label: string; value: string }>,\n ): void {\n const { fn } = this.runtime;\n const docPtr = this.session.requireDocPtr();\n const ok = withWideStringArray(\n this.runtime,\n options.map((o) => o.label),\n (labelsPtr) =>\n withWideStringArray(\n this.runtime,\n options.map((o) => o.value),\n (exportsPtr, count) =>\n fn.EPDFForm_SetFieldOptions(docPtr, fieldObjectNumber, labelsPtr, exportsPtr, count),\n ),\n );\n if (!ok) {\n throw new EngineError(EngineErrorCode.InvalidArg, 'options rejected');\n }\n }\n\n private applyWideSetter(\n setter: (docPtr: Ptr, fieldObjectNumber: number, valuePtr: Ptr) => boolean,\n fieldObjectNumber: number,\n value: string,\n errorMessage: string,\n ): void {\n const { mem } = this.runtime;\n const docPtr = this.session.requireDocPtr();\n const valuePtr = mem.writeU16String(value);\n try {\n if (!setter(docPtr, fieldObjectNumber, valuePtr)) {\n throw new EngineError(EngineErrorCode.InvalidArg, errorMessage);\n }\n } finally {\n mem.free(valuePtr);\n }\n }\n\n private applyDefaultValues(fieldObjectNumber: number, values: readonly string[]): void {\n const { fn } = this.runtime;\n const docPtr = this.session.requireDocPtr();\n const ok = withWideStringArray(this.runtime, values, (valuesPtr, count) =>\n fn.EPDFForm_SetFieldDefaultValues(docPtr, fieldObjectNumber, valuesPtr, count),\n );\n if (!ok) {\n throw new EngineError(EngineErrorCode.InvalidArg, 'default value rejected');\n }\n }\n\n private readBackField(fieldObjectNumber: number): FormFieldDTO {\n const fresh = acquireFormModel(this.runtime, this.session);\n const fieldIndex = this.runtime.fn.EPDFForm_GetFieldIndexByObjNum(fresh, fieldObjectNumber);\n if (fieldIndex < 0) {\n throw new EngineError(EngineErrorCode.Unknown, 'form field vanished after write');\n }\n return readFieldAt(this.runtime, fresh, fieldIndex);\n }\n\n private assertWritable(fieldObjectNumber: number): void {\n if (fieldObjectNumber === 0) {\n throw new EngineError(\n EngineErrorCode.InvalidArg,\n 'form field is stored as a direct object and cannot be written',\n );\n }\n }\n\n /** Dispatch the typed native write. Returns the changed widget objnums. */\n private applyWrite(fieldObjectNumber: number, value: FormFieldValue): number[] {\n const { fn, mem } = this.runtime;\n const docPtr = this.session.requireDocPtr();\n\n const changed = this.withChangedWidgets((buf, cap, countPtr) => {\n switch (value.type) {\n default:\n throw new EngineError(EngineErrorCode.InvalidArg, 'unknown form value type');\n case 'text': {\n const textPtr = mem.writeU16String(value.value);\n try {\n return fn.EPDFForm_SetTextValue(docPtr, fieldObjectNumber, textPtr, buf, cap, countPtr);\n } finally {\n mem.free(textPtr);\n }\n }\n case 'toggle':\n // Empty string clears the group, same as the C API's NULL.\n return fn.EPDFForm_SetToggle(\n docPtr,\n fieldObjectNumber,\n value.state ?? '',\n buf,\n cap,\n countPtr,\n );\n case 'choice':\n return withWideStringArray(this.runtime, value.values, (arrayPtr, count) =>\n fn.EPDFForm_SetChoiceValues(\n docPtr,\n fieldObjectNumber,\n arrayPtr,\n count,\n buf,\n cap,\n countPtr,\n ),\n );\n }\n });\n\n if (changed === null) {\n throw new EngineError(\n EngineErrorCode.InvalidArg,\n 'form value rejected (unknown toggle state, length limit, or non-option choice)',\n );\n }\n return changed;\n }\n\n /** Run a native write with the changed-widgets out buffer wired up. */\n private withChangedWidgets(\n call: (buf: Ptr, cap: number, countPtr: Ptr) => boolean,\n ): number[] | null {\n const { mem } = this.runtime;\n return withScratchN(mem, [CHANGED_WIDGETS_CAPACITY * 4, 4], ([buf, countPtr]) => {\n mem.poke(countPtr, 'i32', 0);\n if (!call(buf, CHANGED_WIDGETS_CAPACITY, countPtr)) {\n return null;\n }\n const total = Number(mem.peek(countPtr, 'i32'));\n const reported = Math.min(total, CHANGED_WIDGETS_CAPACITY);\n const changed: number[] = [];\n for (let i = 0; i < reported; i++) {\n changed.push(Number(mem.peek(buf, 'i32', i * 4)));\n }\n return changed;\n });\n }\n\n /** Bump the session version, rebuild the model, and read the field back. */\n private readBack(fieldObjectNumber: number, changedObjNums: number[]): FormSetValueResult {\n this.session.noteMutation();\n const fresh = acquireFormModel(this.runtime, this.session);\n const fieldIndex = this.runtime.fn.EPDFForm_GetFieldIndexByObjNum(fresh, fieldObjectNumber);\n if (fieldIndex < 0) {\n throw new EngineError(EngineErrorCode.Unknown, 'form field vanished after write');\n }\n const field: FormFieldDTO = readFieldAt(this.runtime, fresh, fieldIndex);\n const changedSet = new Set(changedObjNums);\n const changedWidgets: FormWidgetRef[] = field.widgets\n .filter((w) => changedSet.has(w.annotObjectNumber))\n .map((w) => ({\n annotObjectNumber: w.annotObjectNumber,\n pageObjectNumber: w.pageObjectNumber,\n }));\n return { field, changedWidgets, meta: EMPTY_META };\n }\n}\n\n/** `%FDF-…` payloads are FDF; anything starting with markup is XFDF. */\nfunction sniffFormat(bytes: Uint8Array): FormDataFormat {\n for (let i = 0; i < Math.min(bytes.length, 64); i++) {\n const c = bytes[i];\n // Skip UTF-8 BOM and whitespace.\n if (c === 0xef || c === 0xbb || c === 0xbf) continue;\n if (c === 0x20 || c === 0x09 || c === 0x0a || c === 0x0d) continue;\n return c === 0x3c /* '<' */ ? 'xfdf' : 'fdf';\n }\n return 'fdf';\n}\n","import type {\n FormEffect,\n FormEffectResult,\n FormEffectsResult,\n FormFieldDTO,\n FormFieldRef,\n FormFieldValue,\n FormWidgetRef,\n MutationMeta,\n} from '@embedpdf/engine-core/runtime';\nimport { EngineError, EngineErrorCode, serializeError } from '@embedpdf/engine-core/runtime';\nimport type { PdfRuntimeModule, Ptr } from '@embedpdf/engine-runtime';\n\nimport type { DocumentSession } from '../../document-session/DocumentSession';\nimport { withScratchN } from '../../runtime/memory/scratch';\nimport { throwIfAborted } from '../../shared/abort';\nimport { acquireFormModel } from './internal/formModelCache';\nimport { readFieldAt } from './internal/readFormSnapshot';\nimport { resolveFieldRef } from './internal/resolveFieldRef';\nimport { withWideStringArray } from './internal/wideStringArray';\nimport { ActionReadBudgetTracker } from '../actions/ActionModelReader';\n\nconst CHANGED_WIDGETS_CAPACITY = 1024;\nconst EMPTY_META: MutationMeta = { affectedPages: [], cacheDelta: null };\nconst DISPLAY_CODE = { visible: 0, hidden: 1, noPrint: 2, noView: 3 } as const;\n\ninterface PreflightEffect {\n effect: FormEffect;\n fieldObjectNumbers: number[];\n fields: FormFieldDTO[];\n error?: ReturnType<typeof serializeError>;\n}\n\ninterface NativeEffectResult {\n ok: boolean;\n changedWidgetObjectNumbers: number[];\n}\n\n/** Ordered, non-rollback-atomic sink for one committed client script run. */\nexport class FormsEffectsApplier {\n constructor(\n private readonly runtime: PdfRuntimeModule,\n private readonly session: DocumentSession,\n ) {}\n\n apply(effects: FormEffect[], signal: AbortSignal): FormEffectsResult {\n throwIfAborted(signal);\n const preflightActionBudget = new ActionReadBudgetTracker();\n const resultActionBudget = new ActionReadBudgetTracker();\n const preflight = effects.map((effect) => this.preflight(effect, preflightActionBudget));\n const results: FormEffectResult[] = [];\n const allChangedWidgets = new Map<string, FormWidgetRef>();\n let mustFinalize = false;\n let stop = false;\n\n for (let index = 0; index < preflight.length; index++) {\n const item = preflight[index];\n if (stop || (signal.aborted && mustFinalize)) {\n stop = true;\n results.push(emptyResult(index, 'skipped'));\n continue;\n }\n if (signal.aborted) throwIfAborted(signal);\n if (item.error) {\n results.push({\n ...emptyResult(index, 'rejected'),\n fields: item.fields,\n error: item.error,\n });\n continue;\n }\n\n let before: FormFieldDTO[];\n try {\n before = item.fieldObjectNumbers.map((objectNumber) => this.readField(objectNumber));\n } catch (error) {\n // No write has happened for this effect. A race between preflight and\n // apply is a rejection unless an earlier effect already landed.\n const status = mustFinalize ? 'failed' : 'rejected';\n results.push({ ...emptyResult(index, status), error: serializeError(error) });\n if (status === 'failed') stop = true;\n continue;\n }\n\n if (isNoOp(item.effect, before)) {\n results.push({ ...emptyResult(index, 'unchanged'), fields: before });\n continue;\n }\n\n try {\n const native = this.applyNative(item.effect, item.fieldObjectNumbers);\n if (!native.ok) {\n // Native false is outcome-indeterminate at this layer. Finalize the\n // session and stop; compounding writes would make recovery harder.\n mustFinalize = true;\n this.session.noteMutation();\n const fields = this.readFieldsBestEffort(item.fieldObjectNumbers, resultActionBudget);\n const changedWidgets = widgetRefs(native.changedWidgetObjectNumbers, before, fields);\n rememberWidgets(allChangedWidgets, changedWidgets);\n results.push({\n index,\n status: 'failed',\n fields,\n changedWidgets,\n error: serializeError(\n new EngineError(EngineErrorCode.Unknown, 'native form effect failed after preflight'),\n ),\n });\n stop = true;\n continue;\n }\n\n const applied = effectChangedState(item.effect, before, native.changedWidgetObjectNumbers);\n if (!applied) {\n results.push({ ...emptyResult(index, 'unchanged'), fields: before });\n continue;\n }\n\n mustFinalize = true;\n this.session.noteMutation();\n const fields = this.readFieldsBestEffort(item.fieldObjectNumbers, resultActionBudget);\n const changedWidgets = widgetRefs(native.changedWidgetObjectNumbers, before, fields);\n rememberWidgets(allChangedWidgets, changedWidgets);\n results.push({ index, status: 'applied', fields, changedWidgets });\n } catch (error) {\n mustFinalize = true;\n this.session.noteMutation();\n results.push({\n index,\n status: 'failed',\n fields: this.readFieldsBestEffort(item.fieldObjectNumbers, resultActionBudget),\n changedWidgets: [],\n error: serializeError(error),\n });\n stop = true;\n }\n }\n\n return {\n results,\n changedWidgets: [...allChangedWidgets.values()],\n meta: mustFinalize ? EMPTY_META : null,\n };\n }\n\n private preflight(effect: FormEffect, actionBudget: ActionReadBudgetTracker): PreflightEffect {\n try {\n const refs = effect.kind === 'reset' ? effect.refs : [effect.ref];\n if (refs.length === 0) {\n throw new EngineError(\n EngineErrorCode.InvalidArg,\n 'reset effect requires at least one field',\n );\n }\n const model = acquireFormModel(this.runtime, this.session);\n const resolved = refs.map((ref) => this.resolve(model, ref));\n const fields = resolved.map(({ fieldIndex }) =>\n readFieldAt(this.runtime, model, fieldIndex, actionBudget),\n );\n validateEffect(effect, fields);\n return {\n effect,\n fieldObjectNumbers: resolved.map(({ fieldObjectNumber }) => fieldObjectNumber),\n fields,\n };\n } catch (error) {\n return { effect, fieldObjectNumbers: [], fields: [], error: serializeError(error) };\n }\n }\n\n private resolve(\n model: Ptr,\n ref: FormFieldRef,\n ): { fieldIndex: number; fieldObjectNumber: number } {\n const resolved = resolveFieldRef(this.runtime, model, ref);\n if (resolved.fieldObjectNumber <= 0) {\n throw new EngineError(\n EngineErrorCode.InvalidReference,\n 'direct-object form fields cannot be mutated',\n );\n }\n return resolved;\n }\n\n private readField(\n fieldObjectNumber: number,\n actionBudget = new ActionReadBudgetTracker(),\n ): FormFieldDTO {\n const model = acquireFormModel(this.runtime, this.session);\n const index = this.runtime.fn.EPDFForm_GetFieldIndexByObjNum(model, fieldObjectNumber);\n if (index < 0) {\n throw new EngineError(EngineErrorCode.InvalidReference, 'form field disappeared');\n }\n return readFieldAt(this.runtime, model, index, actionBudget);\n }\n\n private readFieldsBestEffort(\n fieldObjectNumbers: number[],\n actionBudget: ActionReadBudgetTracker,\n ): FormFieldDTO[] {\n const fields: FormFieldDTO[] = [];\n for (const objectNumber of fieldObjectNumbers) {\n try {\n fields.push(this.readField(objectNumber, actionBudget));\n } catch {\n // The result vocabulary already marks the effect failed. Never throw\n // here: landed state still has to reach WorkerHost.finishMutation().\n }\n }\n return fields;\n }\n\n private applyNative(effect: FormEffect, fieldObjectNumbers: number[]): NativeEffectResult {\n if (effect.kind === 'reset') {\n const changed: number[] = [];\n for (const objectNumber of fieldObjectNumbers) {\n const result = this.withChangedWidgets((buf, cap, countPtr) =>\n this.runtime.fn.EPDFForm_ResetField(\n this.session.requireDocPtr(),\n objectNumber,\n buf,\n cap,\n countPtr,\n ),\n );\n changed.push(...result.changedWidgetObjectNumbers);\n if (!result.ok) return { ok: false, changedWidgetObjectNumbers: changed };\n }\n return { ok: true, changedWidgetObjectNumbers: changed };\n }\n\n const objectNumber = fieldObjectNumbers[0];\n switch (effect.kind) {\n case 'setValue':\n return this.applyValue(objectNumber, effect.value);\n case 'setDisplay':\n return this.withChangedWidgets((buf, cap, countPtr) =>\n this.runtime.fn.EPDFForm_SetFieldDisplay(\n this.session.requireDocPtr(),\n objectNumber,\n DISPLAY_CODE[effect.display],\n buf,\n cap,\n countPtr,\n ),\n );\n case 'setAppearanceText': {\n const textPtr = this.runtime.mem.writeU16String(effect.text);\n try {\n return this.withChangedWidgets((buf, cap, countPtr) =>\n this.runtime.fn.EPDFForm_SetFieldAppearanceText(\n this.session.requireDocPtr(),\n objectNumber,\n textPtr,\n buf,\n cap,\n countPtr,\n ),\n );\n } finally {\n this.runtime.mem.free(textPtr);\n }\n }\n }\n }\n\n private applyValue(fieldObjectNumber: number, value: FormFieldValue): NativeEffectResult {\n const { fn, mem } = this.runtime;\n const docPtr = this.session.requireDocPtr();\n return this.withChangedWidgets((buf, cap, countPtr) => {\n if (value.type === 'toggle') {\n return fn.EPDFForm_SetToggle(\n docPtr,\n fieldObjectNumber,\n value.state ?? '',\n buf,\n cap,\n countPtr,\n );\n }\n if (value.type === 'choice') {\n return withWideStringArray(this.runtime, value.values, (valuesPtr, count) =>\n fn.EPDFForm_SetChoiceValues(\n docPtr,\n fieldObjectNumber,\n valuesPtr,\n count,\n buf,\n cap,\n countPtr,\n ),\n );\n }\n const valuePtr = mem.writeU16String(value.value);\n try {\n return fn.EPDFForm_SetTextValue(docPtr, fieldObjectNumber, valuePtr, buf, cap, countPtr);\n } finally {\n mem.free(valuePtr);\n }\n });\n }\n\n private withChangedWidgets(\n call: (buf: Ptr, cap: number, countPtr: Ptr) => boolean,\n ): NativeEffectResult {\n const { mem } = this.runtime;\n return withScratchN(mem, [CHANGED_WIDGETS_CAPACITY * 4, 4], ([buf, countPtr]) => {\n mem.poke(countPtr, 'i32', 0);\n const ok = call(buf, CHANGED_WIDGETS_CAPACITY, countPtr);\n const count = Math.min(\n Math.max(0, Number(mem.peek(countPtr, 'i32'))),\n CHANGED_WIDGETS_CAPACITY,\n );\n const changedWidgetObjectNumbers: number[] = [];\n for (let index = 0; index < count; index++) {\n changedWidgetObjectNumbers.push(Number(mem.peek(buf, 'i32', index * 4)));\n }\n return { ok, changedWidgetObjectNumbers };\n });\n }\n}\n\nfunction validateEffect(effect: FormEffect, fields: FormFieldDTO[]): void {\n if (effect.kind === 'reset') {\n for (const field of fields) {\n if (field.family === 'pushbutton' || field.family === 'signature') {\n throw new EngineError(EngineErrorCode.InvalidArg, `${field.family} fields cannot be reset`);\n }\n }\n return;\n }\n const field = fields[0];\n if (effect.kind === 'setAppearanceText') {\n if (field.family !== 'text' && field.family !== 'combobox') {\n throw new EngineError(\n EngineErrorCode.InvalidArg,\n `appearance text does not apply to a ${field.family} field`,\n );\n }\n return;\n }\n if (effect.kind === 'setDisplay') return;\n validateValue(field, effect.value);\n}\n\nfunction validateValue(field: FormFieldDTO, value: FormFieldValue): void {\n if (value.type === 'text') {\n if (field.family !== 'text') mismatch(field, value);\n return;\n }\n if (value.type === 'toggle') {\n if (field.family !== 'checkbox' && field.family !== 'radio') mismatch(field, value);\n if (value.state !== null && !field.widgets.some((widget) => widget.onState === value.state)) {\n throw new EngineError(EngineErrorCode.InvalidArg, 'unknown toggle appearance state');\n }\n return;\n }\n if (field.family !== 'combobox' && field.family !== 'listbox') mismatch(field, value);\n if (new Set(value.values).size !== value.values.length) {\n throw new EngineError(EngineErrorCode.InvalidArg, 'choice values must not contain duplicates');\n }\n if (field.family === 'combobox' && value.values.length > 1) {\n throw new EngineError(EngineErrorCode.InvalidArg, 'combo boxes accept at most one value');\n }\n if (field.family === 'listbox' && !field.multiSelect && value.values.length > 1) {\n throw new EngineError(EngineErrorCode.InvalidArg, 'single-select list boxes accept one value');\n }\n const optionValues = new Set(field.options.map((option) => option.value));\n const freeText = field.family === 'combobox' && field.edit && value.values.length === 1;\n if (!freeText && value.values.some((entry) => !optionValues.has(entry))) {\n throw new EngineError(EngineErrorCode.InvalidArg, 'choice value is not a field option');\n }\n}\n\nfunction mismatch(field: FormFieldDTO, value: FormFieldValue): never {\n throw new EngineError(\n EngineErrorCode.InvalidArg,\n `value type '${value.type}' does not apply to a '${field.family}' field`,\n );\n}\n\nfunction isNoOp(effect: FormEffect, fields: FormFieldDTO[]): boolean {\n if (effect.kind === 'setAppearanceText') return fields[0].widgets.length === 0;\n if (effect.kind === 'setDisplay') return fields[0].widgets.length === 0;\n if (effect.kind === 'reset') {\n return fields.every((field) => valueEntriesEqual(field.valueEntry, field.defaultValueEntry));\n }\n const field = fields[0];\n const value = effect.value;\n if (value.type === 'text' && field.family === 'text') return field.value === value.value;\n if (value.type === 'toggle' && (field.family === 'checkbox' || field.family === 'radio')) {\n return field.widgets.every((widget) => widget.checked === (widget.onState === value.state));\n }\n if (value.type === 'choice' && field.family === 'combobox') {\n return value.values.length === 0 ? field.value === '' : field.value === value.values[0];\n }\n if (value.type === 'choice' && field.family === 'listbox') {\n return arraysEqual(field.selectedValues, value.values);\n }\n return false;\n}\n\nfunction effectChangedState(\n effect: FormEffect,\n before: FormFieldDTO[],\n changedWidgetObjectNumbers: number[],\n): boolean {\n if (effect.kind === 'setDisplay' || effect.kind === 'setAppearanceText') {\n return changedWidgetObjectNumbers.length > 0;\n }\n return !isNoOp(effect, before) || changedWidgetObjectNumbers.length > 0;\n}\n\nfunction valueEntriesEqual(\n left: FormFieldDTO['valueEntry'],\n right: FormFieldDTO['defaultValueEntry'],\n): boolean {\n if (left.kind !== right.kind) return false;\n if (left.kind === 'scalar' && right.kind === 'scalar') return left.value === right.value;\n if (left.kind === 'array' && right.kind === 'array')\n return arraysEqual(left.values, right.values);\n return true;\n}\n\nfunction arraysEqual(left: readonly string[], right: readonly string[]): boolean {\n return left.length === right.length && left.every((entry, index) => entry === right[index]);\n}\n\nfunction widgetRefs(\n objectNumbers: number[],\n before: FormFieldDTO[],\n after: FormFieldDTO[],\n): FormWidgetRef[] {\n const byObjectNumber = new Map<number, FormWidgetRef>();\n for (const field of [...before, ...after]) {\n for (const widget of field.widgets) byObjectNumber.set(widget.annotObjectNumber, widget);\n }\n return [...new Set(objectNumbers)]\n .map((objectNumber) => byObjectNumber.get(objectNumber))\n .filter((widget): widget is FormWidgetRef => widget !== undefined)\n .map(({ annotObjectNumber, pageObjectNumber }) => ({ annotObjectNumber, pageObjectNumber }));\n}\n\nfunction rememberWidgets(target: Map<string, FormWidgetRef>, widgets: FormWidgetRef[]): void {\n for (const widget of widgets) {\n target.set(`${widget.pageObjectNumber}:${widget.annotObjectNumber}`, widget);\n }\n}\n\nfunction emptyResult(index: number, status: FormEffectResult['status']): FormEffectResult {\n return { index, status, fields: [], changedWidgets: [] };\n}\n","import type { FoldedText, PageObjectNumber } from '@embedpdf/engine-core/runtime';\nimport { foldText } from '@embedpdf/engine-core/runtime';\nimport type { PdfRuntimeModule } from '@embedpdf/engine-runtime';\n\nimport type { DocumentSession } from '../../../document-session/DocumentSession';\nimport { PageTextReader } from '../../text/PageTextReader';\n\ninterface PageCorpusEntry {\n /** The session mutation sequence the entry was built at. */\n seq: number;\n /** Default-fold (`{}`) corpus; `folded.original` is the raw page text. */\n folded: FoldedText;\n}\n\n/**\n * Per-session, per-page search corpus: the page's extracted text plus its\n * DEFAULT fold (the one literal queries with default options search).\n * This is the local engine's in-memory equivalent of the server's corpus\n * artifacts — same fold version, same shape, built lazily on first search\n * and reused across slices and re-queries.\n *\n * Version-keyed on `DocumentSession.mutationSeq()` per PAGE (not per\n * session): a form fill or annotation edit bumps the sequence, and only\n * the pages actually re-read after that pay the re-extraction — untouched\n * cache entries for other pages are refreshed lazily as they're revisited.\n *\n * Capped: search touches every page of arbitrarily large documents, so\n * entries evict in insertion order past `MAX_CACHED_PAGES` (text of ~500\n * pages ≈ a few MB — bounded regardless of document size).\n */\nconst MAX_CACHED_PAGES = 512;\n\nconst cache = new WeakMap<DocumentSession, Map<PageObjectNumber, PageCorpusEntry>>();\n\nexport function acquirePageCorpus(\n runtime: PdfRuntimeModule,\n session: DocumentSession,\n pageObjectNumber: PageObjectNumber,\n signal: AbortSignal,\n): FoldedText {\n const seq = session.mutationSeq();\n let pages = cache.get(session);\n if (!pages) {\n pages = new Map();\n cache.set(session, pages);\n }\n\n const hit = pages.get(pageObjectNumber);\n if (hit && hit.seq === seq) return hit.folded;\n\n const text = new PageTextReader(runtime, session).read(pageObjectNumber, signal).text;\n const folded = foldText(text);\n\n pages.delete(pageObjectNumber); // re-insert = most recently used\n pages.set(pageObjectNumber, { seq, folded });\n if (pages.size > MAX_CACHED_PAGES) {\n const oldest = pages.keys().next().value;\n if (oldest !== undefined) pages.delete(oldest);\n }\n return folded;\n}\n","import { EngineError, EngineErrorCode } from '@embedpdf/engine-core/runtime';\nimport type { SearchQuery, SearchRequest } from '@embedpdf/engine-core/runtime';\n\n/**\n * The local engine's resume cursor. Opaque to callers by contract; JSON\n * under the hood because a local cursor never crosses a trust boundary\n * (the server mints its own, authenticated, format for the wire).\n *\n * A cursor pins three things and refuses to resume if any moved:\n * - the query+mode identity (`key`) — a cursor is not transferable\n * between queries,\n * - the document version (`seq`) — resuming over mutated content could\n * serve stale pages or, worse, text a redaction just removed,\n * - the scan origin (`start`) — position is meaningless in a different\n * page order.\n */\nexport interface SearchCursorState {\n v: 1;\n seq: number;\n key: string;\n /** startPage pon the scan order was rotated to (0 = natural order). */\n start: number;\n /** Pages of the scan order already consumed. */\n scanned: number;\n}\n\n/** Stable identity for query + mode (option order pinned by hand). */\nexport function searchQueryKey(query: SearchQuery, mode: string): string {\n return JSON.stringify([\n query.regex ? 'r' : 'l',\n query.text,\n query.matchCase ? 1 : 0,\n query.matchDiacritics ? 1 : 0,\n query.wholeWord ? 1 : 0,\n mode,\n ]);\n}\n\nexport function encodeSearchCursor(state: SearchCursorState): string {\n return JSON.stringify(state);\n}\n\nexport function decodeSearchCursor(\n request: SearchRequest,\n cursor: string,\n expectedSeq: number,\n expectedKey: string,\n): SearchCursorState {\n let state: SearchCursorState;\n try {\n state = JSON.parse(cursor) as SearchCursorState;\n } catch {\n throw new EngineError(EngineErrorCode.InvalidArg, 'malformed search cursor');\n }\n if (state?.v !== 1 || typeof state.scanned !== 'number' || typeof state.key !== 'string') {\n throw new EngineError(EngineErrorCode.InvalidArg, 'malformed search cursor');\n }\n if (state.key !== expectedKey) {\n throw new EngineError(\n EngineErrorCode.InvalidArg,\n 'search cursor belongs to a different query — restart the search',\n );\n }\n if (state.seq !== expectedSeq) {\n throw new EngineError(\n EngineErrorCode.InvalidArg,\n 'document changed since this search cursor was issued — restart the search',\n { details: { cursorSeq: state.seq, currentSeq: expectedSeq } },\n );\n }\n // The cursor owns position; a startPage alongside it is a caller bug.\n if (request.startPage !== undefined && request.startPage !== state.start) {\n throw new EngineError(\n EngineErrorCode.InvalidArg,\n 'startPage conflicts with the cursor — omit startPage when resuming',\n );\n }\n return state;\n}\n","import type {\n SearchMatch,\n SearchMatchRange,\n SearchRequest,\n SearchSlice,\n} from '@embedpdf/engine-core/runtime';\nimport {\n EngineError,\n EngineErrorCode,\n buildSnippet,\n foldOptionsFor,\n foldText,\n matchLiteral,\n matchRegex,\n searchRectsForRange,\n validateSearchQuery,\n} from '@embedpdf/engine-core/runtime';\nimport type { PdfRuntimeModule } from '@embedpdf/engine-runtime';\n\nimport type { DocumentSession } from '../../document-session/DocumentSession';\nimport { throwIfAborted } from '../../shared/abort';\nimport { PageGeometryReader } from '../geometry/PageGeometryReader';\nimport { acquirePageCorpus } from './internal/pageCorpusCache';\nimport { decodeSearchCursor, encodeSearchCursor, searchQueryKey } from './internal/searchCursor';\n\n/**\n * Per-slice budget defaults and ceilings. The ceiling is the worker's\n * self-defense: one `query()` call is one synchronous stretch of native\n * work, and no request — whatever budget it asks for — may hold the\n * worker longer than ~a few hundred pages. Callers wanting more issue\n * more slices; the cursor makes that cheap.\n */\nconst DEFAULT_MAX_PAGES = 64;\nconst CEILING_MAX_PAGES = 256;\nconst DEFAULT_MAX_MATCHES = 256;\nconst CEILING_MAX_MATCHES = 1024;\n\n/**\n * The whole search pipeline for one budgeted slice, running inside the\n * trust boundary (worker locally, server process in the cloud):\n *\n * extract — page text via the session corpus cache (version-keyed on\n * `mutationSeq`, so results always reflect the CURRENT layer\n * view — text a redaction removed is unfindable),\n * match — the pure engine-core matcher (identical code on every\n * engine; parity by construction),\n * anchor — geometry read only for pages that actually matched, rects\n * via the selection line-merge (one rect per visual line).\n *\n * Scope gating (`doc.text.search`, `doc.text.copy` for `'full'`) is the\n * caller's job — this reader assumes an authorized request.\n */\nexport class SearchReader {\n constructor(\n private readonly runtime: PdfRuntimeModule,\n private readonly session: DocumentSession,\n ) {}\n\n query(request: SearchRequest, signal: AbortSignal): SearchSlice {\n throwIfAborted(signal);\n const query = request.query;\n const mode = request.mode ?? 'full';\n\n // One validator covers everything: regex dialect AND flag combos\n // (regex + matchDiacritics is the rejected one). Literal queries are\n // always valid.\n const valid = validateSearchQuery(query);\n if (!valid.ok) {\n throw new EngineError(\n EngineErrorCode.InvalidArg,\n `invalid search query (${valid.issue}): ${valid.message}`,\n );\n }\n\n const records = this.session.allRecords();\n const totalPages = records.length;\n\n // Nothing findable — don't burn a scan on an empty needle.\n if (!query.regex && foldText(query.text).folded.trim().length === 0) {\n return { matches: [], nextCursor: null, scannedPages: 0, totalPages };\n }\n\n const seq = this.session.mutationSeq();\n const key = searchQueryKey(query, mode);\n\n let start = 0;\n let scanned = 0;\n if (request.cursor !== undefined) {\n const state = decodeSearchCursor(request, request.cursor, seq, key);\n start = state.start;\n scanned = state.scanned;\n } else {\n if (request.startPage !== undefined) {\n // Throws NotFound for an unknown page — same contract as page(pon).\n this.session.recordByObjectNumber(request.startPage);\n start = request.startPage;\n }\n if (request.skip !== undefined) {\n // Trusted-position resume: the caller pins content versions\n // externally (the cloud wire's search token carries the content\n // epoch), so no sequence check applies here. Clamp into range.\n scanned = Math.min(Math.max(0, Math.floor(request.skip)), totalPages);\n }\n }\n\n // Viewport-first: rotate display order to begin at `start`, wrapping.\n let order = records;\n if (start !== 0) {\n const at = records.findIndex((r) => r.pageObjectNumber === start);\n order = records.slice(at).concat(records.slice(0, at));\n }\n\n const maxPages = clamp(request.budget?.maxPages, DEFAULT_MAX_PAGES, CEILING_MAX_PAGES);\n const maxMatches = clamp(request.budget?.maxMatches, DEFAULT_MAX_MATCHES, CEILING_MAX_MATCHES);\n\n const matches: SearchMatch[] = [];\n let pagesThisSlice = 0;\n // Budget checks sit at page granularity: a page's matches are never\n // split across slices, so the cursor only ever points between pages.\n while (scanned < order.length && pagesThisSlice < maxPages && matches.length < maxMatches) {\n throwIfAborted(signal);\n const pon = order[scanned].pageObjectNumber;\n const corpus = acquirePageCorpus(this.runtime, this.session, pon, signal);\n\n let ranges: SearchMatchRange[];\n if (query.regex) {\n ranges = matchRegex(corpus.original, query);\n } else if (query.matchCase || query.matchDiacritics) {\n // Non-default fold options: re-fold the cached raw text per query.\n ranges = matchLiteral(foldText(corpus.original, foldOptionsFor(query)), query);\n } else {\n ranges = matchLiteral(corpus, query);\n }\n\n if (ranges.length > 0) {\n const geometry = new PageGeometryReader(this.runtime, this.session).read(pon, signal);\n for (const range of ranges) {\n matches.push({\n pageObjectNumber: pon,\n charStart: range.start,\n charCount: range.length,\n rects: searchRectsForRange(geometry, range.start, range.length),\n ...(mode === 'full' ? { snippet: buildSnippet(corpus.original, range) } : {}),\n });\n }\n }\n\n scanned++;\n pagesThisSlice++;\n }\n\n return {\n matches,\n nextCursor:\n scanned < order.length ? encodeSearchCursor({ v: 1, seq, key, start, scanned }) : null,\n scannedPages: scanned,\n totalPages,\n };\n }\n}\n\nfunction clamp(requested: number | undefined, fallback: number, ceiling: number): number {\n if (requested === undefined || !Number.isFinite(requested)) return fallback;\n return Math.max(1, Math.min(Math.floor(requested), ceiling));\n}\n","import type { DocumentActionsSnapshot, PdfActionTree } from '@embedpdf/engine-core/runtime';\nimport { EngineError, EngineErrorCode } from '@embedpdf/engine-core/runtime';\nimport { NULL_PTR, type PdfRuntimeModule } from '@embedpdf/engine-runtime';\n\nimport { ActionReadBudgetTracker, readActionModel } from './ActionModelReader';\nimport type { DocumentSession } from '../../document-session/DocumentSession';\nimport { readUtf16String } from '../../runtime/memory/strings';\nimport { throwIfAborted } from '../../shared/abort';\n\nconst DOCUMENT_ACTION_EVENTS = [\n ['willClose', 0],\n ['willSave', 1],\n ['didSave', 2],\n ['willPrint', 3],\n ['didPrint', 4],\n] as const;\n\n/** Read catalog-owned actions. Extraction only; no action is executed. */\nexport class DocumentActionsReader {\n constructor(\n private readonly runtime: PdfRuntimeModule,\n private readonly session: DocumentSession,\n ) {}\n\n read(signal: AbortSignal): DocumentActionsSnapshot {\n throwIfAborted(signal);\n const { fn, mem } = this.runtime;\n const docPtr = this.session.requireDocPtr();\n const budget = new ActionReadBudgetTracker();\n const count = fn.FPDFDoc_GetJavaScriptActionCount(docPtr);\n if (count < 0) {\n throw new EngineError(\n EngineErrorCode.MalformedPdf,\n 'failed to enumerate PDF name-tree scripts',\n );\n }\n\n const nameTreeScripts: DocumentActionsSnapshot['nameTreeScripts'] = [];\n for (let index = 0; index < count; index++) {\n throwIfAborted(signal);\n const namedPtr = fn.FPDFDoc_GetJavaScriptAction(docPtr, index);\n if (namedPtr === NULL_PTR) {\n throw new EngineError(EngineErrorCode.MalformedPdf, 'invalid PDF name-tree script entry', {\n details: { index },\n });\n }\n let name: string;\n try {\n name =\n readUtf16String(mem, (buf, capacity) =>\n fn.FPDFJavaScriptAction_GetName(namedPtr, buf, capacity),\n ) ?? '';\n } finally {\n fn.FPDFDoc_CloseJavaScriptAction(namedPtr);\n }\n const action = requireAction(\n readActionModel(fn, mem, fn.EPDFDoc_GetNamedJavaScriptActionModel(docPtr, index), budget),\n 'name-tree script',\n index,\n );\n nameTreeScripts.push({ name, action });\n }\n\n const openAction = readActionModel(fn, mem, fn.EPDFDoc_GetOpenActionModel(docPtr), budget);\n const additional: Partial<Record<(typeof DOCUMENT_ACTION_EVENTS)[number][0], PdfActionTree>> =\n {};\n for (const [key, event] of DOCUMENT_ACTION_EVENTS) {\n throwIfAborted(signal);\n const action = readActionModel(\n fn,\n mem,\n fn.EPDFDoc_GetAdditionalActionModel(docPtr, event),\n budget,\n );\n if (action) additional[key] = action;\n }\n return { nameTreeScripts, openAction, ...additional };\n }\n}\n\nfunction requireAction(action: PdfActionTree | null, owner: string, index: number): PdfActionTree {\n if (action) return action;\n throw new EngineError(EngineErrorCode.MalformedPdf, `failed to read ${owner}`, {\n details: { index },\n });\n}\n","import {\n EngineError,\n EngineErrorCode,\n type PageObjectNumber,\n type PieceInfoEntry,\n type PieceInfoPatch,\n type PieceInfoSnapshot,\n} from '@embedpdf/engine-core/runtime';\nimport type { PdfRuntimeModule, Ptr } from '@embedpdf/engine-runtime';\n\nimport type { DocumentSession } from '../../document-session/DocumentSession';\nimport { readUtf8String, readUtf16String, writeUtf16String } from '../../runtime/memory/strings';\nimport { throwIfAborted } from '../../shared/abort';\nimport { formatPdfDate, pdfDateToIso } from '../../shared/pdf-date';\nimport { withWideStringArray } from '../forms/internal/wideStringArray';\n\n// FPDF_OBJECT_* codes reported by EPDFDoc_Get(Page)PieceInfoValueType.\nconst OBJ_BOOLEAN = 1;\nconst OBJ_NUMBER = 2;\nconst OBJ_STRING = 3;\nconst OBJ_NAME = 4;\nconst OBJ_ARRAY = 5;\n\n/**\n * `/PieceInfo` reads and writes for one holder — the document CATALOG\n * (`pageObjectNumber` undefined) or one PAGE. Wraps the fork's symmetric\n * `EPDFDoc_*PieceInfo*` / `EPDFDoc_*PagePieceInfo*` families behind one\n * shape, so the worker host has a single code path for both levels.\n *\n * Writes stamp `content_last_modified` once per job (the worker is\n * single-threaded, so every key written by one job gets one revision date);\n * the native side fans it out to the application dict, the page dict,\n * and — for catalog writes — /Info /ModDate.\n */\nexport class PieceInfoAccessor {\n constructor(\n private readonly runtime: PdfRuntimeModule,\n private readonly session: DocumentSession,\n private readonly pageObjectNumber?: PageObjectNumber,\n ) {\n if (pageObjectNumber !== undefined) {\n // NotFound on a bad pon — same fail-fast as every page verb.\n session.recordByObjectNumber(pageObjectNumber);\n }\n }\n\n read(application: string, signal: AbortSignal): PieceInfoSnapshot | null {\n throwIfAborted(signal);\n requireApplication(application);\n const { fn, mem } = this.runtime;\n const docPtr = this.session.requireDocPtr();\n const pon = this.pageObjectNumber;\n\n const has =\n pon === undefined\n ? fn.EPDFDoc_HasPieceInfoEntry(docPtr, application)\n : fn.EPDFDoc_HasPagePieceInfoEntry(docPtr, pon, application);\n if (!has) return null;\n\n const keyCount =\n pon === undefined\n ? fn.EPDFDoc_GetPieceInfoKeyCount(docPtr, application)\n : fn.EPDFDoc_GetPagePieceInfoKeyCount(docPtr, pon, application);\n\n const entries: Record<string, PieceInfoEntry> = {};\n for (let i = 0; i < keyCount; i++) {\n throwIfAborted(signal);\n const key = readUtf8String(mem, (buf, cap) =>\n pon === undefined\n ? fn.EPDFDoc_GetPieceInfoKeyAt(docPtr, application, i, buf, cap)\n : fn.EPDFDoc_GetPagePieceInfoKeyAt(docPtr, pon, application, i, buf, cap),\n );\n if (key === null) continue;\n entries[key] = this.readEntry(application, key);\n }\n\n const lastModifiedPdf = readUtf16String(\n mem,\n (buf, cap) =>\n pon === undefined\n ? fn.EPDFDoc_GetPieceInfoLastModified(docPtr, application, buf, cap)\n : fn.EPDFDoc_GetPagePieceInfoLastModified(docPtr, pon, application, buf, cap),\n null,\n );\n return {\n entries,\n lastModified: lastModifiedPdf ? pdfDateToIso(lastModifiedPdf) : null,\n };\n }\n\n update(application: string, patch: PieceInfoPatch, signal: AbortSignal): void {\n throwIfAborted(signal);\n requireApplication(application);\n requirePatch(patch);\n const keys = Object.keys(patch);\n if (keys.length === 0) return;\n validatePatch(patch, keys);\n\n // This is the apply boundary. No caller-controlled validation and no\n // cancellation check belongs below it: once the first native setter runs,\n // this deliberately non-rollback-atomic patch may be partially written if\n // a native invariant fails on a later key.\n throwIfAborted(signal);\n\n const { mem } = this.runtime;\n // One revision date per job, however many keys the patch touches.\n const lastModified = formatPdfDate(new Date());\n const lmPtr = mem.writeU16String(lastModified);\n try {\n for (const key of keys) {\n const value = patch[key];\n const ok = this.writeEntry(application, key, value, lmPtr);\n if (!ok) {\n throw new EngineError(\n EngineErrorCode.Unknown,\n `pieceInfo write rejected for key '${key}' after validation`,\n );\n }\n }\n } finally {\n mem.free(lmPtr);\n }\n }\n\n applications(signal: AbortSignal): string[] {\n throwIfAborted(signal);\n const { fn, mem } = this.runtime;\n const docPtr = this.session.requireDocPtr();\n const pon = this.pageObjectNumber;\n const count =\n pon === undefined\n ? fn.EPDFDoc_GetPieceInfoEntryCount(docPtr)\n : fn.EPDFDoc_GetPagePieceInfoEntryCount(docPtr, pon);\n const out: string[] = [];\n for (let i = 0; i < count; i++) {\n const name = readUtf8String(mem, (buf, cap) =>\n pon === undefined\n ? fn.EPDFDoc_GetPieceInfoEntryAt(docPtr, i, buf, cap)\n : fn.EPDFDoc_GetPagePieceInfoEntryAt(docPtr, pon, i, buf, cap),\n );\n if (name !== null) out.push(name);\n }\n return out;\n }\n\n clear(application: string, signal: AbortSignal): void {\n throwIfAborted(signal);\n requireApplication(application);\n const { fn } = this.runtime;\n const docPtr = this.session.requireDocPtr();\n const pon = this.pageObjectNumber;\n const ok =\n pon === undefined\n ? fn.EPDFDoc_ClearPieceInfoEntry(docPtr, application)\n : fn.EPDFDoc_ClearPagePieceInfoEntry(docPtr, pon, application);\n if (!ok) {\n throw new EngineError(\n EngineErrorCode.Unknown,\n `pieceInfo clear rejected for application '${application}'`,\n );\n }\n }\n\n private readEntry(application: string, key: string): PieceInfoEntry {\n const { fn, mem } = this.runtime;\n const docPtr = this.session.requireDocPtr();\n const pon = this.pageObjectNumber;\n const type =\n pon === undefined\n ? fn.EPDFDoc_GetPieceInfoValueType(docPtr, application, key)\n : fn.EPDFDoc_GetPagePieceInfoValueType(docPtr, pon, application, key);\n\n switch (type) {\n case OBJ_STRING: {\n const value = readUtf16String(\n mem,\n (buf, cap) =>\n pon === undefined\n ? fn.EPDFDoc_GetPieceInfoString(docPtr, application, key, buf, cap)\n : fn.EPDFDoc_GetPagePieceInfoString(docPtr, pon, application, key, buf, cap),\n '',\n );\n return value === null ? { type: 'unknown' } : { type: 'string', value };\n }\n case OBJ_NAME: {\n const value = readUtf8String(mem, (buf, cap) =>\n pon === undefined\n ? fn.EPDFDoc_GetPieceInfoName(docPtr, application, key, buf, cap)\n : fn.EPDFDoc_GetPagePieceInfoName(docPtr, pon, application, key, buf, cap),\n );\n return value === null ? { type: 'unknown' } : { type: 'name', value };\n }\n case OBJ_NUMBER: {\n const outPtr = mem.alloc(4);\n try {\n const ok =\n pon === undefined\n ? fn.EPDFDoc_GetPieceInfoNumber(docPtr, application, key, outPtr)\n : fn.EPDFDoc_GetPagePieceInfoNumber(docPtr, pon, application, key, outPtr);\n if (!ok) return { type: 'unknown' };\n return { type: 'number', value: Number(mem.peek(outPtr, 'f32')) };\n } finally {\n mem.free(outPtr);\n }\n }\n case OBJ_BOOLEAN: {\n const outPtr = mem.alloc(4);\n try {\n const ok =\n pon === undefined\n ? fn.EPDFDoc_GetPieceInfoBoolean(docPtr, application, key, outPtr)\n : fn.EPDFDoc_GetPagePieceInfoBoolean(docPtr, pon, application, key, outPtr);\n if (!ok) return { type: 'unknown' };\n return { type: 'boolean', value: Number(mem.peek(outPtr, 'i32')) !== 0 };\n } finally {\n mem.free(outPtr);\n }\n }\n case OBJ_ARRAY: {\n const count =\n pon === undefined\n ? fn.EPDFDoc_GetPieceInfoStringArrayCount(docPtr, application, key)\n : fn.EPDFDoc_GetPagePieceInfoStringArrayCount(docPtr, pon, application, key);\n // -1 = not a pure text-string array — preserved, not readable here.\n if (count < 0) return { type: 'unknown' };\n const value: string[] = [];\n for (let i = 0; i < count; i++) {\n const item = readUtf16String(\n mem,\n (buf, cap) =>\n pon === undefined\n ? fn.EPDFDoc_GetPieceInfoStringArrayAt(docPtr, application, key, i, buf, cap)\n : fn.EPDFDoc_GetPagePieceInfoStringArrayAt(\n docPtr,\n pon,\n application,\n key,\n i,\n buf,\n cap,\n ),\n '',\n );\n if (item === null) return { type: 'unknown' };\n value.push(item);\n }\n return { type: 'string-array', value };\n }\n default:\n return { type: 'unknown' };\n }\n }\n\n private writeEntry(\n application: string,\n key: string,\n value: PieceInfoPatch[string],\n lmPtr: Ptr,\n ): boolean {\n const { fn, mem } = this.runtime;\n const docPtr = this.session.requireDocPtr();\n const pon = this.pageObjectNumber;\n\n if (value === null) {\n return pon === undefined\n ? fn.EPDFDoc_ClearPieceInfoKey(docPtr, application, key, lmPtr)\n : fn.EPDFDoc_ClearPagePieceInfoKey(docPtr, pon, application, key, lmPtr);\n }\n if (typeof value === 'string') {\n return writeUtf16String(mem, value, (ptr) =>\n pon === undefined\n ? fn.EPDFDoc_SetPieceInfoString(docPtr, application, key, ptr, lmPtr)\n : fn.EPDFDoc_SetPagePieceInfoString(docPtr, pon, application, key, ptr, lmPtr),\n );\n }\n if (typeof value === 'number') {\n return pon === undefined\n ? fn.EPDFDoc_SetPieceInfoNumber(docPtr, application, key, value, lmPtr)\n : fn.EPDFDoc_SetPagePieceInfoNumber(docPtr, pon, application, key, value, lmPtr);\n }\n if (typeof value === 'boolean') {\n return pon === undefined\n ? fn.EPDFDoc_SetPieceInfoBoolean(docPtr, application, key, value, lmPtr)\n : fn.EPDFDoc_SetPagePieceInfoBoolean(docPtr, pon, application, key, value, lmPtr);\n }\n if (Array.isArray(value)) {\n return withWideStringArray(this.runtime, value, (arrayPtr, count) =>\n pon === undefined\n ? fn.EPDFDoc_SetPieceInfoStringArray(docPtr, application, key, arrayPtr, count, lmPtr)\n : fn.EPDFDoc_SetPagePieceInfoStringArray(\n docPtr,\n pon,\n application,\n key,\n arrayPtr,\n count,\n lmPtr,\n ),\n );\n }\n if (typeof value === 'object' && value !== null && 'name' in value) {\n return pon === undefined\n ? fn.EPDFDoc_SetPieceInfoName(docPtr, application, key, value.name, lmPtr)\n : fn.EPDFDoc_SetPagePieceInfoName(docPtr, pon, application, key, value.name, lmPtr);\n }\n // validatePatch() makes this unreachable. Keep a loud invariant failure\n // rather than silently ignoring a new wire value if the vocabulary grows.\n throw new EngineError(EngineErrorCode.Unknown, `unvalidated pieceInfo value for '${key}'`);\n }\n}\n\nfunction requireApplication(application: string): void {\n if (typeof application !== 'string' || application.length === 0) {\n throw new EngineError(EngineErrorCode.InvalidArg, 'pieceInfo application must be non-empty');\n }\n}\n\nfunction requirePatch(patch: PieceInfoPatch): void {\n if (typeof patch !== 'object' || patch === null || Array.isArray(patch)) {\n throw new EngineError(EngineErrorCode.InvalidArg, 'pieceInfo patch must be an object');\n }\n}\n\nfunction validatePatch(patch: PieceInfoPatch, keys: string[]): void {\n for (const key of keys) {\n if (key.length === 0) {\n throw new EngineError(EngineErrorCode.InvalidArg, 'pieceInfo keys must be non-empty');\n }\n validatePatchValue(key, patch[key]);\n }\n}\n\nfunction validatePatchValue(key: string, value: PieceInfoPatch[string]): void {\n if (value === null || typeof value === 'string' || typeof value === 'boolean') return;\n\n if (typeof value === 'number') {\n if (!Number.isFinite(value)) {\n throw new EngineError(\n EngineErrorCode.InvalidArg,\n `pieceInfo number for '${key}' must be finite`,\n );\n }\n return;\n }\n\n if (Array.isArray(value)) {\n if (!value.every((item) => typeof item === 'string')) {\n throw new EngineError(\n EngineErrorCode.InvalidArg,\n `pieceInfo string array for '${key}' must contain only strings`,\n );\n }\n return;\n }\n\n if (typeof value === 'object' && value !== null && 'name' in value) {\n if (typeof value.name !== 'string' || value.name.length === 0) {\n throw new EngineError(\n EngineErrorCode.InvalidArg,\n `pieceInfo PDF name for '${key}' must be a non-empty string`,\n );\n }\n return;\n }\n\n throw new EngineError(\n EngineErrorCode.InvalidArg,\n `unsupported pieceInfo value for '${key}': string | number | boolean | string[] | { name } | null`,\n );\n}\n","import {\n EMPTY_TRANSFER,\n EngineError,\n EngineErrorCode,\n serializeError,\n wirePack,\n type AnnotationsCreateWorkerRequest,\n type AnnotationsDeleteWorkerRequest,\n type DocumentCheckPasswordPermissionsWorkerRequest,\n type DocumentProbeSecurityFileWorkerRequest,\n type DocumentRenderPageFileWorkerRequest,\n type DocumentSaveBufferWorkerRequest,\n type DocumentSaveFileWorkerRequest,\n type DocumentSaveLayerBufferWorkerRequest,\n type FormsAttachWidgetWorkerRequest,\n type FormsCreateFieldWorkerRequest,\n type FormsDeleteFieldWorkerRequest,\n type FormsDetachWidgetWorkerRequest,\n type FormsExportWorkerRequest,\n type FormsImportWorkerRequest,\n type FormsListWorkerRequest,\n type FormsRepairWorkerRequest,\n type FormsUpdateFieldWorkerRequest,\n type FormsResetWorkerRequest,\n type FormsSetValueWorkerRequest,\n type FontsRegisterWorkerRequest,\n type FontsAddFallbackWorkerRequest,\n type FontsClearFallbacksWorkerRequest,\n type FontsClearWorkerRequest,\n type AnnotationsListFullPageWorkerRequest,\n type AnnotationsListRawAllWorkerRequest,\n type AnnotationsListRawPageWorkerRequest,\n type AnnotationsRenderAppearancesWorkerRequest,\n type AnnotationsMoveWorkerRequest,\n type AnnotationsUpdateWorkerRequest,\n type CloseWorkerRequest,\n type LayerCloseWorkerRequest,\n type MetadataReadWorkerRequest,\n type MetadataUpdateWorkerRequest,\n type ActionsReadWorkerRequest,\n type OpenWorkerRequest,\n type PagesListWorkerRequest,\n type PagesGeometryWorkerRequest,\n type PagesMoveWorkerRequest,\n type PagesRotateWorkerRequest,\n type PagesDeleteWorkerRequest,\n type PagesExtractWorkerRequest,\n type PagesInsertWorkerRequest,\n type AttachmentsListWorkerRequest,\n type AttachmentsReadFileWorkerRequest,\n type AttachmentsCreateWorkerRequest,\n type AttachmentsDeleteWorkerRequest,\n type AnnotationsReadFileWorkerRequest,\n type PagesFlattenWorkerRequest,\n type RedactionApplyWorkerRequest,\n type PieceInfoApplicationsWorkerRequest,\n type PieceInfoClearWorkerRequest,\n type PieceInfoReadWorkerRequest,\n type PieceInfoUpdateWorkerRequest,\n type PagesRenderWorkerRequest,\n type PagesTextWorkerRequest,\n type SearchQueryWorkerRequest,\n type FormsApplyEffectsWorkerRequest,\n type SerializedEngineError,\n type ShutdownWorkerRequest,\n type WirePack,\n type WorkerJobId,\n type WorkerRequest,\n type WorkerResponse,\n type WorkerResultPayload,\n} from '@embedpdf/engine-core/runtime';\nimport type { MutationMeta } from '@embedpdf/engine-core/runtime';\nimport type { PdfRuntimeModule } from '@embedpdf/engine-runtime';\n\nimport { DocumentSession } from '../document-session/DocumentSession';\nimport { BaseDocumentRegistry } from '../document-session/lifecycle/BaseDocumentRegistry';\nimport {\n openFatMemoryDocument,\n openLayerDocument,\n} from '../document-session/lifecycle/PdfDocumentOpener';\nimport { DocumentActionsReader } from '../features/actions';\nimport {\n AnnotationReader,\n AnnotationAppearanceReader,\n AnnotationMutator,\n RawAnnotationReader,\n} from '../features/annotations';\nimport { AttachmentMutator, AttachmentReader } from '../features/attachments';\nimport { FontRegistrar, type StartupFontSpec } from '../features/fonts';\nimport { FormMutator, FormReader, FormsEffectsApplier, disposeFormModel } from '../features/forms';\nimport { PageGeometryReader } from '../features/geometry';\nimport { MetadataMutator, MetadataReader } from '../features/metadata';\nimport {\n PagesExtractor,\n PagesFlattener,\n PagesInserter,\n PagesMutator,\n PagesReader,\n} from '../features/pages';\nimport { PieceInfoAccessor } from '../features/pieceinfo';\nimport { RedactionApplier } from '../features/redaction';\nimport { PageRenderReader } from '../features/render';\nimport { DocumentSaver } from '../features/save';\nimport { SearchReader } from '../features/search';\nimport { SecurityReader } from '../features/security';\nimport { PageTextReader } from '../features/text';\nimport { ensureInitialized, destroyLibrary } from '../runtime/lifecycle/bootstrap';\n\n/**\n * The piece that runs \"inside the worker\": owns runtime, manages document\n * sessions, dispatches requests to the engine-services synchronous code.\n *\n * Environment-agnostic. Wrap it with a Web Worker entry, a Node\n * worker_thread entry, or an inline transport. The wrapper owns\n * postMessage plumbing and any process/lifecycle concerns; the host only\n * knows about PdfRuntimeModule, DocumentSession, AbortController, and the\n * worker wire shape from @embedpdf/engine-core.\n */\nexport class WorkerHost {\n private readonly sessions = new Map<string, DocumentSession>();\n private readonly baseDocuments: BaseDocumentRegistry;\n private readonly aborts = new Map<WorkerJobId, AbortController>();\n /**\n * Runtime-global registered fonts for this thread. The registry is\n * thread-local in PDFium, so it lives on the host (one per thread), not per\n * document session. `fontIds` maps the stable wire `fontKey` to this\n * thread's volatile native FontId.\n */\n private readonly fontIds = new Map<string, number>();\n private readonly fonts: FontRegistrar;\n private destroyed = false;\n\n constructor(\n private readonly runtime: PdfRuntimeModule,\n /**\n * Receives a fully-typed `WirePack<WorkerResponse>` (the envelope\n * payload plus its transfer manifest). The wrapper (browser\n * `worker-entry.ts`, Node `worker-entry.ts`, or `InlineTransport`)\n * is responsible for actually invoking `postMessage(pack.payload,\n * pack.transfer)` — the host doesn't know which environment it\n * runs in.\n */\n private readonly post: (pack: WirePack<WorkerResponse>) => void,\n ) {\n ensureInitialized(this.runtime);\n this.baseDocuments = new BaseDocumentRegistry(this.runtime);\n this.fonts = new FontRegistrar(this.runtime, this.fontIds);\n }\n\n /**\n * Register deployment-owned fonts on this worker thread, after init and\n * before serving requests. Server-only: the cloud engine never exposes font\n * configuration to clients, so the host (not a wire message) seeds the\n * thread's fallback fonts. Browser engines drive fonts through the\n * `fonts.*` wire path instead. Throws if any font fails to load.\n */\n registerStartupFonts(specs: readonly StartupFontSpec[]): void {\n this.fonts.registerStartup(specs);\n }\n\n receive(msg: WorkerRequest): void {\n if (msg.kind === 'abort') {\n this.aborts.get(msg.jobId)?.abort();\n return;\n }\n\n const ctrl = new AbortController();\n this.aborts.set(msg.jobId, ctrl);\n\n // Abort policy: only handlers that loop over pages/annotations honor\n // `ctrl.signal` (the read/mutation paths below). One-shot native\n // operations — open, document save, security probe, close, shutdown —\n // are effectively atomic from our side and intentionally non-abortable,\n // so they do not receive the signal.\n let resultPack: WirePack<WorkerResultPayload>;\n try {\n switch (msg.kind) {\n case 'open.fatMem':\n case 'open.layerMemBase':\n case 'open.layerFileBase':\n resultPack = this.handleOpen(msg);\n break;\n case 'metadata.read':\n resultPack = this.handleMetadataRead(msg, ctrl.signal);\n break;\n case 'metadata.update':\n resultPack = this.handleMetadataUpdate(msg, ctrl.signal);\n break;\n case 'actions.read':\n resultPack = this.handleActionsRead(msg, ctrl.signal);\n break;\n case 'annotations.listRawAll':\n resultPack = this.handleAnnotationsListRawAll(msg, ctrl.signal);\n break;\n case 'annotations.listRawPage':\n resultPack = this.handleAnnotationsListRawPage(msg, ctrl.signal);\n break;\n case 'annotations.listFullPage':\n resultPack = this.handleAnnotationsListFullPage(msg, ctrl.signal);\n break;\n case 'annotations.renderAppearances':\n resultPack = this.handleAnnotationsRenderAppearances(msg, ctrl.signal);\n break;\n case 'annotations.create':\n resultPack = this.handleAnnotationsCreate(msg, ctrl.signal);\n break;\n case 'annotations.update':\n resultPack = this.handleAnnotationsUpdate(msg, ctrl.signal);\n break;\n case 'annotations.delete':\n resultPack = this.handleAnnotationsDelete(msg, ctrl.signal);\n break;\n case 'annotations.move':\n resultPack = this.handleAnnotationsMove(msg, ctrl.signal);\n break;\n case 'forms.list':\n resultPack = this.handleFormsList(msg, ctrl.signal);\n break;\n case 'forms.setValue':\n resultPack = this.handleFormsSetValue(msg, ctrl.signal);\n break;\n case 'forms.reset':\n resultPack = this.handleFormsReset(msg, ctrl.signal);\n break;\n case 'forms.applyEffects':\n resultPack = this.handleFormsApplyEffects(msg, ctrl.signal);\n break;\n case 'forms.export':\n resultPack = this.handleFormsExport(msg, ctrl.signal);\n break;\n case 'forms.import':\n resultPack = this.handleFormsImport(msg, ctrl.signal);\n break;\n case 'forms.repair':\n resultPack = this.handleFormsRepair(msg, ctrl.signal);\n break;\n case 'forms.createField':\n resultPack = this.handleFormsCreateField(msg, ctrl.signal);\n break;\n case 'forms.updateField':\n resultPack = this.handleFormsUpdateField(msg, ctrl.signal);\n break;\n case 'forms.deleteField':\n resultPack = this.handleFormsDeleteField(msg, ctrl.signal);\n break;\n case 'forms.attachWidget':\n resultPack = this.handleFormsAttachWidget(msg, ctrl.signal);\n break;\n case 'forms.detachWidget':\n resultPack = this.handleFormsDetachWidget(msg, ctrl.signal);\n break;\n case 'pages.list':\n resultPack = this.handlePagesList(msg, ctrl.signal);\n break;\n case 'pages.move':\n resultPack = this.handlePagesMove(msg, ctrl.signal);\n break;\n case 'pages.rotate':\n resultPack = this.handlePagesRotate(msg, ctrl.signal);\n break;\n case 'pages.delete':\n resultPack = this.handlePagesDelete(msg, ctrl.signal);\n break;\n case 'pages.flatten':\n resultPack = this.handlePagesFlatten(msg, ctrl.signal);\n break;\n case 'redaction.apply':\n resultPack = this.handleRedactionApply(msg, ctrl.signal);\n break;\n case 'pages.extract':\n resultPack = this.handlePagesExtract(msg, ctrl.signal);\n break;\n case 'pages.insert':\n resultPack = this.handlePagesInsert(msg, ctrl.signal);\n break;\n case 'attachments.list':\n resultPack = this.handleAttachmentsList(msg, ctrl.signal);\n break;\n case 'attachments.readFile':\n resultPack = this.handleAttachmentsReadFile(msg, ctrl.signal);\n break;\n case 'attachments.create':\n resultPack = this.handleAttachmentsCreate(msg, ctrl.signal);\n break;\n case 'attachments.delete':\n resultPack = this.handleAttachmentsDelete(msg, ctrl.signal);\n break;\n case 'annotations.readFile':\n resultPack = this.handleAnnotationsReadFile(msg, ctrl.signal);\n break;\n case 'pieceInfo.read':\n resultPack = this.handlePieceInfoRead(msg, ctrl.signal);\n break;\n case 'pieceInfo.update':\n resultPack = this.handlePieceInfoUpdate(msg, ctrl.signal);\n break;\n case 'pieceInfo.applications':\n resultPack = this.handlePieceInfoApplications(msg, ctrl.signal);\n break;\n case 'pieceInfo.clear':\n resultPack = this.handlePieceInfoClear(msg, ctrl.signal);\n break;\n case 'pages.text':\n resultPack = this.handlePagesText(msg, ctrl.signal);\n break;\n case 'pages.geometry':\n resultPack = this.handlePagesGeometry(msg, ctrl.signal);\n break;\n case 'pages.render':\n resultPack = this.handlePagesRender(msg, ctrl.signal);\n break;\n case 'search.query':\n resultPack = this.handleSearchQuery(msg, ctrl.signal);\n break;\n case 'document.saveBuffer':\n resultPack = this.handleDocumentSaveBuffer(msg);\n break;\n case 'document.saveLayerBuffer':\n resultPack = this.handleDocumentSaveLayerBuffer(msg);\n break;\n case 'document.saveFile':\n resultPack = this.handleDocumentSaveFile(msg);\n break;\n case 'document.probeSecurityFile':\n resultPack = this.handleDocumentProbeSecurityFile(msg);\n break;\n case 'document.renderPageFile':\n resultPack = this.handleDocumentRenderPageFile(msg, ctrl.signal);\n break;\n case 'document.checkPasswordPermissions':\n resultPack = this.handleDocumentCheckPasswordPermissions(msg);\n break;\n case 'fonts.register':\n resultPack = this.handleFontsRegister(msg);\n break;\n case 'fonts.addFallback':\n resultPack = this.handleFontsAddFallback(msg);\n break;\n case 'fonts.clearFallbacks':\n resultPack = this.handleFontsClearFallbacks(msg);\n break;\n case 'fonts.clear':\n resultPack = this.handleFontsClear(msg);\n break;\n case 'layer.close':\n resultPack = this.handleLayerClose(msg);\n break;\n case 'close':\n resultPack = this.handleClose(msg);\n break;\n case 'shutdown':\n resultPack = this.handleShutdown(msg);\n break;\n default:\n throw new EngineError(\n EngineErrorCode.InvalidArg,\n `unknown request kind: ${(msg as WorkerRequest).kind}`,\n );\n }\n // Lift the handler's transfer manifest onto the response envelope\n // unchanged. The handler decided which buffers to move; the host\n // just relays that decision through the `resolve` envelope.\n this.post(\n wirePack(\n { kind: 'resolve', jobId: msg.jobId, result: resultPack.payload },\n resultPack.transfer,\n ),\n );\n } catch (err) {\n const error: SerializedEngineError = serializeError(err);\n // Reject envelopes never carry binary; explicit EMPTY_TRANSFER\n // documents that intent.\n this.post(wirePack({ kind: 'reject', jobId: msg.jobId, error }, EMPTY_TRANSFER));\n } finally {\n this.aborts.delete(msg.jobId);\n }\n }\n\n private handleOpen(req: OpenWorkerRequest): WirePack<WorkerResultPayload> {\n const key = sessionKey(req.docId, req.kind === 'open.fatMem' ? undefined : req.layerName);\n if (this.sessions.has(key)) {\n throw new EngineError(EngineErrorCode.InvalidArg, `document session already open: ${key}`);\n }\n const session = new DocumentSession(this.runtime);\n if (req.kind === 'open.fatMem') {\n const bytes = new Uint8Array(req.bytes);\n try {\n session.openFromHandle(openFatMemoryDocument(this.runtime, bytes, req.password));\n } catch (error) {\n // Password failures are a STATE, not an error: park the session with\n // the already-transferred bytes and answer with a security probe that\n // says \"password required\". The client handle comes up locked\n // (`security.passwordPrompt === 'required'`); a later\n // `document.checkPasswordPermissions` performs the actual load.\n if (!isPasswordOpenError(error)) throw error;\n session.parkLocked(bytes);\n this.sessions.set(key, session);\n return wirePack({\n tag: 'open',\n docId: req.docId,\n security: passwordRequiredProbe(),\n });\n }\n } else if (req.kind === 'open.layerMemBase') {\n const base = this.baseDocuments.acquireMemoryBase({\n key: req.baseKey,\n bytes: new Uint8Array(req.baseBytes),\n password: req.password,\n });\n session.openFromHandle(openLayerDocument(this.runtime, base, req.layer, req.password));\n } else {\n const base = this.baseDocuments.acquireFileBase({\n key: req.baseKey,\n path: req.basePath,\n password: req.password,\n });\n session.openFromHandle(openLayerDocument(this.runtime, base, req.layer, req.password));\n }\n this.sessions.set(key, session);\n return wirePack({\n tag: 'open',\n docId: req.docId,\n security: new SecurityReader(this.runtime).checkPasswordPermissions(\n session,\n req.password ?? '',\n ),\n });\n }\n\n private handleMetadataRead(\n req: MetadataReadWorkerRequest,\n signal: AbortSignal,\n ): WirePack<WorkerResultPayload> {\n const session = this.requireSession(req);\n const metadata = new MetadataReader(this.runtime, session).read(signal);\n return wirePack({ tag: 'metadata.read', metadata });\n }\n\n private handleMetadataUpdate(\n req: MetadataUpdateWorkerRequest,\n signal: AbortSignal,\n ): WirePack<WorkerResultPayload> {\n const session = this.requireSession(req);\n const mutator = new MetadataMutator(this.runtime, session);\n const result = mutator.update(req.patch, signal);\n return this.finishMutation(session, { tag: 'metadata.update', result }, req.artifactPath);\n }\n\n private handleActionsRead(\n req: ActionsReadWorkerRequest,\n signal: AbortSignal,\n ): WirePack<WorkerResultPayload> {\n const session = this.requireSession(req);\n const snapshot = new DocumentActionsReader(this.runtime, session).read(signal);\n return wirePack({ tag: 'actions.read', snapshot });\n }\n\n private handleAnnotationsListRawAll(\n req: AnnotationsListRawAllWorkerRequest,\n signal: AbortSignal,\n ): WirePack<WorkerResultPayload> {\n const session = this.requireSession(req);\n const reader = new RawAnnotationReader(this.runtime, session);\n const snapshot = reader.listAll(signal);\n return wirePack({ tag: 'annotations.listRawAll', snapshot });\n }\n\n private handleAnnotationsListRawPage(\n req: AnnotationsListRawPageWorkerRequest,\n signal: AbortSignal,\n ): WirePack<WorkerResultPayload> {\n const session = this.requireSession(req);\n const reader = new RawAnnotationReader(this.runtime, session);\n const snapshot = reader.listOne(req.pageObjectNumber, signal);\n return wirePack({ tag: 'annotations.listRawPage', snapshot });\n }\n\n private handleAnnotationsListFullPage(\n req: AnnotationsListFullPageWorkerRequest,\n signal: AbortSignal,\n ): WirePack<WorkerResultPayload> {\n const session = this.requireSession(req);\n const reader = new AnnotationReader(this.runtime, session);\n const snapshot = reader.list(req.pageObjectNumber, signal);\n return wirePack({ tag: 'annotations.listFullPage', snapshot });\n }\n\n private handleAnnotationsRenderAppearances(\n req: AnnotationsRenderAppearancesWorkerRequest,\n signal: AbortSignal,\n ): WirePack<WorkerResultPayload> {\n const session = this.requireSession(req);\n const reader = new AnnotationAppearanceReader(this.runtime, session);\n const result = reader.render(req.pageObjectNumber, req.options ?? {}, signal);\n // Transfer every appearance raster buffer back zero-copy, like pages.render.\n const transfer = result.appearances.map((a) => a.raster.data);\n return wirePack({ tag: 'annotations.renderAppearances', result }, transfer);\n }\n\n private handleAnnotationsCreate(\n req: AnnotationsCreateWorkerRequest,\n signal: AbortSignal,\n ): WirePack<WorkerResultPayload> {\n const session = this.requireSession(req);\n const mutator = new AnnotationMutator(this.runtime, session, this.fonts);\n const result = mutator.create(\n req.pageObjectNumber,\n req.draft,\n signal,\n req.actor,\n req.resources,\n );\n return this.finishMutation(session, { tag: 'annotations.create', result }, req.artifactPath);\n }\n\n private handleAnnotationsUpdate(\n req: AnnotationsUpdateWorkerRequest,\n signal: AbortSignal,\n ): WirePack<WorkerResultPayload> {\n const session = this.requireSession(req);\n const mutator = new AnnotationMutator(this.runtime, session, this.fonts);\n const result = mutator.update(req.ref, req.patch, signal, req.actor, req.resources);\n return this.finishMutation(session, { tag: 'annotations.update', result }, req.artifactPath);\n }\n\n private handleAnnotationsDelete(\n req: AnnotationsDeleteWorkerRequest,\n signal: AbortSignal,\n ): WirePack<WorkerResultPayload> {\n const session = this.requireSession(req);\n const mutator = new AnnotationMutator(this.runtime, session);\n const result = mutator.delete(req.ref, signal);\n return this.finishMutation(session, { tag: 'annotations.delete', result }, req.artifactPath);\n }\n\n private handleAnnotationsMove(\n req: AnnotationsMoveWorkerRequest,\n signal: AbortSignal,\n ): WirePack<WorkerResultPayload> {\n const session = this.requireSession(req);\n const mutator = new AnnotationMutator(this.runtime, session);\n const result = mutator.move(req.pageObjectNumber, req.refs, req.toIndex, signal);\n return this.finishMutation(session, { tag: 'annotations.move', result }, req.artifactPath);\n }\n\n private handlePagesList(\n req: PagesListWorkerRequest,\n signal: AbortSignal,\n ): WirePack<WorkerResultPayload> {\n const session = this.requireSession(req);\n const reader = new PagesReader(this.runtime, session);\n const snapshot = reader.read(signal);\n return wirePack({ tag: 'pages.list', snapshot });\n }\n\n private handlePagesMove(\n req: PagesMoveWorkerRequest,\n signal: AbortSignal,\n ): WirePack<WorkerResultPayload> {\n const session = this.requireSession(req);\n const mutator = new PagesMutator(this.runtime, session);\n const result = mutator.move(req.pageObjectNumbers, req.destIndex, signal);\n return this.finishMutation(session, { tag: 'pages.move', result }, req.artifactPath);\n }\n\n private handlePagesRotate(\n req: PagesRotateWorkerRequest,\n signal: AbortSignal,\n ): WirePack<WorkerResultPayload> {\n const session = this.requireSession(req);\n const mutator = new PagesMutator(this.runtime, session);\n const result = mutator.rotate(req.pageObjectNumbers, req.rotation, signal);\n return this.finishMutation(session, { tag: 'pages.rotate', result }, req.artifactPath);\n }\n\n private handlePagesDelete(\n req: PagesDeleteWorkerRequest,\n signal: AbortSignal,\n ): WirePack<WorkerResultPayload> {\n const session = this.requireSession(req);\n const mutator = new PagesMutator(this.runtime, session);\n const result = mutator.delete(req.pageObjectNumbers, signal);\n return this.finishMutation(session, { tag: 'pages.delete', result }, req.artifactPath);\n }\n\n private handlePagesFlatten(\n req: PagesFlattenWorkerRequest,\n signal: AbortSignal,\n ): WirePack<WorkerResultPayload> {\n const session = this.requireSession(req);\n const result = new PagesFlattener(this.runtime, session).flatten(\n req.pageObjectNumbers,\n req.usage,\n signal,\n );\n if (result.meta === null) return wirePack({ tag: 'pages.flatten', result });\n return this.finishMutation(session, { tag: 'pages.flatten', result }, req.artifactPath);\n }\n\n private handleRedactionApply(\n req: RedactionApplyWorkerRequest,\n signal: AbortSignal,\n ): WirePack<WorkerResultPayload> {\n const session = this.requireSession(req);\n const result = new RedactionApplier(this.runtime, session).apply(req.scope, signal);\n if (result.meta === null) return wirePack({ tag: 'redaction.apply', result });\n return this.finishMutation(session, { tag: 'redaction.apply', result }, req.artifactPath);\n }\n\n private handlePagesExtract(\n req: PagesExtractWorkerRequest,\n signal: AbortSignal,\n ): WirePack<WorkerResultPayload> {\n const session = this.requireSession(req);\n const extracted = new PagesExtractor(this.runtime, session).extract(\n req.pageObjectNumbers,\n signal,\n );\n // A read: no finishMutation, no layer artifact. Bytes transfer zero-copy.\n return wirePack({ tag: 'pages.extract', bytes: extracted.bytes, size: extracted.size }, [\n extracted.bytes,\n ]);\n }\n\n private handlePagesInsert(\n req: PagesInsertWorkerRequest,\n signal: AbortSignal,\n ): WirePack<WorkerResultPayload> {\n const session = this.requireSession(req);\n const inserter = new PagesInserter(this.runtime, session);\n const result = inserter.insert(req.bytes, req.destIndex, signal);\n return this.finishMutation(session, { tag: 'pages.insert', result }, req.artifactPath);\n }\n\n private handleAttachmentsList(\n req: AttachmentsListWorkerRequest,\n signal: AbortSignal,\n ): WirePack<WorkerResultPayload> {\n const session = this.requireSession(req);\n const items = new AttachmentReader(this.runtime, session).list(signal);\n return wirePack({ tag: 'attachments.list', items });\n }\n\n private handleAttachmentsReadFile(\n req: AttachmentsReadFileWorkerRequest,\n signal: AbortSignal,\n ): WirePack<WorkerResultPayload> {\n const session = this.requireSession(req);\n const content = new AttachmentReader(this.runtime, session).readFile(\n req.ref,\n req.path,\n req.maxDecodedBytes,\n signal,\n );\n // A read: no finishMutation, no layer artifact. Buffer-mode bytes\n // transfer zero-copy; path mode carries metadata only.\n return wirePack(\n { tag: 'attachments.readFile', content },\n content.bytes !== undefined ? [content.bytes] : [],\n );\n }\n\n private handleAttachmentsCreate(\n req: AttachmentsCreateWorkerRequest,\n signal: AbortSignal,\n ): WirePack<WorkerResultPayload> {\n const session = this.requireSession(req);\n const mutator = new AttachmentMutator(this.runtime, session);\n const result = mutator.create(req.file, req.resources, signal);\n return this.finishMutation(session, { tag: 'attachments.create', result }, req.artifactPath);\n }\n\n private handleAttachmentsDelete(\n req: AttachmentsDeleteWorkerRequest,\n signal: AbortSignal,\n ): WirePack<WorkerResultPayload> {\n const session = this.requireSession(req);\n const mutator = new AttachmentMutator(this.runtime, session);\n const result = mutator.delete(req.ref, signal);\n return this.finishMutation(session, { tag: 'attachments.delete', result }, req.artifactPath);\n }\n\n private handleAnnotationsReadFile(\n req: AnnotationsReadFileWorkerRequest,\n signal: AbortSignal,\n ): WirePack<WorkerResultPayload> {\n const session = this.requireSession(req);\n const content = new AttachmentReader(this.runtime, session).readAnnotationFile(\n req.pageObjectNumber,\n req.ref,\n req.path,\n req.maxDecodedBytes,\n signal,\n );\n return wirePack(\n { tag: 'annotations.readFile', content },\n content.bytes !== undefined ? [content.bytes] : [],\n );\n }\n\n private handlePieceInfoRead(\n req: PieceInfoReadWorkerRequest,\n signal: AbortSignal,\n ): WirePack<WorkerResultPayload> {\n const session = this.requireSession(req);\n const accessor = new PieceInfoAccessor(this.runtime, session, req.pageObjectNumber);\n const snapshot = accessor.read(req.application, signal);\n return wirePack({ tag: 'pieceInfo.read', snapshot });\n }\n\n private handlePieceInfoUpdate(\n req: PieceInfoUpdateWorkerRequest,\n signal: AbortSignal,\n ): WirePack<WorkerResultPayload> {\n const session = this.requireSession(req);\n const accessor = new PieceInfoAccessor(this.runtime, session, req.pageObjectNumber);\n accessor.update(req.application, req.patch, signal);\n // A mutation: layer sessions persist the artifact like every other write.\n return this.finishMutation(session, { tag: 'pieceInfo.update' }, req.artifactPath);\n }\n\n private handlePieceInfoApplications(\n req: PieceInfoApplicationsWorkerRequest,\n signal: AbortSignal,\n ): WirePack<WorkerResultPayload> {\n const session = this.requireSession(req);\n const accessor = new PieceInfoAccessor(this.runtime, session, req.pageObjectNumber);\n const applications = accessor.applications(signal);\n return wirePack({ tag: 'pieceInfo.applications', applications });\n }\n\n private handlePieceInfoClear(\n req: PieceInfoClearWorkerRequest,\n signal: AbortSignal,\n ): WirePack<WorkerResultPayload> {\n const session = this.requireSession(req);\n const accessor = new PieceInfoAccessor(this.runtime, session, req.pageObjectNumber);\n accessor.clear(req.application, signal);\n return this.finishMutation(session, { tag: 'pieceInfo.clear' }, req.artifactPath);\n }\n\n private handlePagesText(\n req: PagesTextWorkerRequest,\n signal: AbortSignal,\n ): WirePack<WorkerResultPayload> {\n const session = this.requireSession(req);\n const reader = new PageTextReader(this.runtime, session);\n const snapshot = reader.read(req.pageObjectNumber, signal);\n return wirePack({ tag: 'pages.text', snapshot });\n }\n\n private handlePagesGeometry(\n req: PagesGeometryWorkerRequest,\n signal: AbortSignal,\n ): WirePack<WorkerResultPayload> {\n const session = this.requireSession(req);\n const reader = new PageGeometryReader(this.runtime, session);\n const snapshot = reader.read(req.pageObjectNumber, signal);\n return wirePack({ tag: 'pages.geometry', snapshot });\n }\n\n private handleSearchQuery(\n req: SearchQueryWorkerRequest,\n signal: AbortSignal,\n ): WirePack<WorkerResultPayload> {\n const session = this.requireSession(req);\n const reader = new SearchReader(this.runtime, session);\n const slice = reader.query(req.request, signal);\n return wirePack({ tag: 'search.query', slice });\n }\n\n private handlePagesRender(\n req: PagesRenderWorkerRequest,\n signal: AbortSignal,\n ): WirePack<WorkerResultPayload> {\n const session = this.requireSession(req);\n const reader = new PageRenderReader(this.runtime, session);\n const raster = reader.render(req.pageObjectNumber, req.options ?? {}, signal);\n return wirePack({ tag: 'pages.render', raster }, [raster.data]);\n }\n\n private handleDocumentSaveBuffer(\n req: DocumentSaveBufferWorkerRequest,\n ): WirePack<WorkerResultPayload> {\n const session = this.requireSession(req);\n const saved = new DocumentSaver(this.runtime, session).saveStandaloneToBuffer(req.mode);\n return wirePack({ tag: 'document.saveBuffer', bytes: saved.bytes, size: saved.size }, [\n saved.bytes,\n ]);\n }\n\n private handleDocumentSaveFile(\n req: DocumentSaveFileWorkerRequest,\n ): WirePack<WorkerResultPayload> {\n const session = this.requireSession(req);\n const saved = new DocumentSaver(this.runtime, session).saveStandaloneToFile(req.path, req.mode);\n return wirePack({ tag: 'document.saveFile', path: saved.path });\n }\n\n private handleDocumentSaveLayerBuffer(\n req: DocumentSaveLayerBufferWorkerRequest,\n ): WirePack<WorkerResultPayload> {\n const session = this.requireSession(req);\n if (session.kind !== 'layer') {\n throw new EngineError(\n EngineErrorCode.InvalidArg,\n 'document has no layer to export (opened without a layer)',\n );\n }\n const artifact = new DocumentSaver(this.runtime, session).saveLayerArtifact();\n return wirePack(\n { tag: 'document.saveLayerBuffer', bytes: artifact.bytes, size: artifact.size },\n [artifact.bytes],\n );\n }\n\n private handleDocumentProbeSecurityFile(\n req: DocumentProbeSecurityFileWorkerRequest,\n ): WirePack<WorkerResultPayload> {\n const reader = new SecurityReader(this.runtime);\n const security = reader.probeFile(req.path, req.password);\n return wirePack({ tag: 'document.probeSecurityFile', security });\n }\n\n /**\n * One-shot file render (the derived-artifact warmer's producer): open the\n * base from a file path into a TRANSIENT session — never stored in\n * `this.sessions`, so it can't collide with (or leak into) live document\n * sessions — resolve the display index to its durable page object number,\n * render, close. Shares the base parse with concurrent ad-hoc opens of\n * the same file via the registry refcount.\n */\n private handleDocumentRenderPageFile(\n req: DocumentRenderPageFileWorkerRequest,\n signal: AbortSignal,\n ): WirePack<WorkerResultPayload> {\n const session = new DocumentSession(this.runtime);\n const base = this.baseDocuments.acquireFileBase({\n key: `adhoc-file:${req.path}`,\n path: req.path,\n password: req.password,\n });\n try {\n session.openFromHandle(\n openLayerDocument(this.runtime, base, { kind: 'fresh' }, req.password),\n );\n const layout = new PagesReader(this.runtime, session).read(signal);\n const page = layout.pages[req.pageIndex];\n if (!page) {\n throw new EngineError(\n EngineErrorCode.NotFound,\n `renderPageFile: no page at index ${req.pageIndex} (pageCount=${layout.pageCount})`,\n );\n }\n const raster = new PageRenderReader(this.runtime, session).render(\n page.pageObjectNumber,\n req.options ?? {},\n signal,\n );\n return wirePack(\n {\n tag: 'document.renderPageFile',\n pageObjectNumber: page.pageObjectNumber,\n pageCount: layout.pageCount,\n raster,\n },\n [raster.data],\n );\n } finally {\n // Closing the session releases the base acquisition through the\n // open handle's close stack (same lifecycle as live sessions).\n session.close();\n }\n }\n\n private handleDocumentCheckPasswordPermissions(\n req: DocumentCheckPasswordPermissionsWorkerRequest,\n ): WirePack<WorkerResultPayload> {\n // The one handler that accepts a LOCKED session: on a locked session,\n // \"check this password\" means \"load the parked bytes with it\". A wrong\n // password throws DocPasswordIncorrect and the session stays parked\n // (bytes retained) for the next attempt.\n const parked = this.sessions.get(sessionKey(req.docId));\n let session: DocumentSession;\n if (parked?.isLocked()) {\n parked.openFromHandle(\n openFatMemoryDocument(this.runtime, parked.lockedBytes(), req.password),\n );\n session = parked;\n } else {\n session = this.requireSession(req);\n }\n const security = new SecurityReader(this.runtime).checkPasswordPermissions(\n session,\n req.password,\n req.mode ?? 'any',\n );\n return wirePack({ tag: 'document.checkPasswordPermissions', security });\n }\n\n private handleFontsRegister(req: FontsRegisterWorkerRequest): WirePack<WorkerResultPayload> {\n this.fonts.register(\n req.fontKey,\n req.familyName,\n req.weight,\n req.italic,\n new Uint8Array(req.data),\n );\n return wirePack({ tag: 'fonts.register', fontKey: req.fontKey });\n }\n\n private handleFontsAddFallback(\n req: FontsAddFallbackWorkerRequest,\n ): WirePack<WorkerResultPayload> {\n this.fonts.addFallback(req.fontKey);\n return wirePack({ tag: 'fonts.addFallback' });\n }\n\n private handleFontsClearFallbacks(\n _req: FontsClearFallbacksWorkerRequest,\n ): WirePack<WorkerResultPayload> {\n this.fonts.clearFallbacks();\n return wirePack({ tag: 'fonts.clearFallbacks' });\n }\n\n private handleFontsClear(_req: FontsClearWorkerRequest): WirePack<WorkerResultPayload> {\n this.fonts.clear();\n return wirePack({ tag: 'fonts.clear' });\n }\n\n /**\n * Close exactly ONE layer session — the reload seam for layer-session\n * freshness. The base document's refcount releases through the session's\n * close stack, so sibling layer sessions (and the base session) are\n * untouched. Idempotent: closing an absent session is a no-op ack,\n * because the caller may be reloading a layer this worker never held\n * (e.g. after a pool eviction).\n */\n private handleLayerClose(req: LayerCloseWorkerRequest): WirePack<WorkerResultPayload> {\n const key = sessionKey(req.docId, req.layerName);\n const session = this.sessions.get(key);\n if (session) {\n disposeFormModel(this.runtime, session);\n session.close();\n this.sessions.delete(key);\n }\n return wirePack({ tag: 'close' });\n }\n\n private handleClose(req: CloseWorkerRequest): WirePack<WorkerResultPayload> {\n for (const [key, session] of Array.from(this.sessions.entries())) {\n if (!sessionKeyBelongsToDoc(key, req.docId)) continue;\n disposeFormModel(this.runtime, session);\n session.close();\n this.sessions.delete(key);\n }\n return wirePack({ tag: 'close' });\n }\n\n private handleShutdown(_req: ShutdownWorkerRequest): WirePack<WorkerResultPayload> {\n if (!this.destroyed) {\n this.destroyed = true;\n for (const session of this.sessions.values()) {\n disposeFormModel(this.runtime, session);\n session.close();\n }\n this.sessions.clear();\n this.baseDocuments.releaseAll();\n destroyLibrary(this.runtime);\n }\n return wirePack({ tag: 'shutdown' });\n }\n\n private requireSession(req: { docId: string; layerName?: string }): DocumentSession {\n const key = sessionKey(req.docId, req.layerName);\n const session = this.sessions.get(key);\n if (session?.isLocked()) {\n // Truthful error for any operation reaching a parked session: the\n // document exists but needs `security.unlock()` first.\n throw new EngineError(\n EngineErrorCode.DocPasswordRequired,\n `document session is password-locked: ${key}`,\n );\n }\n if (!session || !session.isOpen()) {\n throw new EngineError(EngineErrorCode.DocNotOpen, `document session not open: ${key}`);\n }\n return session;\n }\n\n /**\n * Finalize a mutation response. For a standalone session the mutation\n * result is returned as-is. For a layer session we additionally persist\n * the layer artifact (to file when `artifactPath` is given, otherwise to\n * a transferable buffer) and merge it onto the response envelope. This\n * is the one place the layer-vs-standalone branch lives, shared by every\n * annotation and page mutation handler.\n */\n private handleFormsList(\n req: FormsListWorkerRequest,\n signal: AbortSignal,\n ): WirePack<WorkerResultPayload> {\n const session = this.requireSession(req);\n const reader = new FormReader(this.runtime, session);\n return wirePack({ tag: 'forms.list', snapshot: reader.snapshot(signal) });\n }\n\n private handleFormsSetValue(\n req: FormsSetValueWorkerRequest,\n signal: AbortSignal,\n ): WirePack<WorkerResultPayload> {\n const session = this.requireSession(req);\n const mutator = new FormMutator(this.runtime, session);\n const result = mutator.setValue(req.ref, req.value, signal);\n return this.finishMutation(session, { tag: 'forms.setValue', result }, req.artifactPath);\n }\n\n private handleFormsReset(\n req: FormsResetWorkerRequest,\n signal: AbortSignal,\n ): WirePack<WorkerResultPayload> {\n const session = this.requireSession(req);\n const mutator = new FormMutator(this.runtime, session);\n const result = mutator.reset(req.ref, signal);\n return this.finishMutation(session, { tag: 'forms.reset', result }, req.artifactPath);\n }\n\n private handleFormsApplyEffects(\n req: FormsApplyEffectsWorkerRequest,\n signal: AbortSignal,\n ): WirePack<WorkerResultPayload> {\n const session = this.requireSession(req);\n const result = new FormsEffectsApplier(this.runtime, session).apply(req.effects, signal);\n if (result.meta === null) return wirePack({ tag: 'forms.applyEffects', result });\n return this.finishMutation(session, { tag: 'forms.applyEffects', result }, req.artifactPath);\n }\n\n private handleFormsExport(\n req: FormsExportWorkerRequest,\n signal: AbortSignal,\n ): WirePack<WorkerResultPayload> {\n const session = this.requireSession(req);\n const reader = new FormReader(this.runtime, session);\n const exported = reader.exportData(req.format, signal);\n return wirePack({ tag: 'forms.export', format: exported.format, bytes: exported.bytes }, [\n exported.bytes,\n ]);\n }\n\n private handleFormsImport(\n req: FormsImportWorkerRequest,\n signal: AbortSignal,\n ): WirePack<WorkerResultPayload> {\n const session = this.requireSession(req);\n const mutator = new FormMutator(this.runtime, session);\n const result = mutator.importData(req.data, req.format, signal);\n return this.finishMutation(session, { tag: 'forms.import', result }, req.artifactPath);\n }\n\n private handleFormsRepair(\n req: FormsRepairWorkerRequest,\n signal: AbortSignal,\n ): WirePack<WorkerResultPayload> {\n const session = this.requireSession(req);\n const mutator = new FormMutator(this.runtime, session);\n const result = mutator.repair(req.bakeAppearances ?? false, signal);\n return this.finishMutation(session, { tag: 'forms.repair', result }, req.artifactPath);\n }\n\n private handleFormsCreateField(\n req: FormsCreateFieldWorkerRequest,\n signal: AbortSignal,\n ): WirePack<WorkerResultPayload> {\n const session = this.requireSession(req);\n const mutator = new FormMutator(this.runtime, session);\n const { field } = mutator.createField(req.draft, signal);\n return this.finishMutation(\n session,\n { tag: 'forms.createField', result: { field, meta: EMPTY_FORM_META } },\n req.artifactPath,\n );\n }\n\n private handleFormsUpdateField(\n req: FormsUpdateFieldWorkerRequest,\n signal: AbortSignal,\n ): WirePack<WorkerResultPayload> {\n const session = this.requireSession(req);\n const mutator = new FormMutator(this.runtime, session);\n const { field } = mutator.updateField(req.ref, req.patch, signal);\n return this.finishMutation(\n session,\n { tag: 'forms.updateField', result: { field, meta: EMPTY_FORM_META } },\n req.artifactPath,\n );\n }\n\n private handleFormsDeleteField(\n req: FormsDeleteFieldWorkerRequest,\n signal: AbortSignal,\n ): WirePack<WorkerResultPayload> {\n const session = this.requireSession(req);\n const mutator = new FormMutator(this.runtime, session);\n const { deletedFieldObjectNumber, detachedWidgets } = mutator.deleteField(req.ref, signal);\n\n // Cascade: the mutator detached the widgets (inert annotations now);\n // deleting them through the annotation feature keeps /Annots\n // bookkeeping, weak-ref invalidation, and page revisions in ONE place.\n const annotations = new AnnotationMutator(this.runtime, session);\n for (const widget of detachedWidgets) {\n if (widget.annotObjectNumber <= 0 || widget.pageObjectNumber <= 0) continue;\n annotations.delete(\n {\n kind: 'objectNumber',\n pageObjectNumber: widget.pageObjectNumber,\n annotObjectNumber: widget.annotObjectNumber,\n },\n signal,\n );\n }\n // The annotation deletes above mutated /Annots after the form\n // mutator's own bump; bump again so the form-model cache rebuilds.\n session.noteMutation();\n\n return this.finishMutation(\n session,\n {\n tag: 'forms.deleteField',\n result: {\n deletedFieldObjectNumber,\n removedWidgets: detachedWidgets,\n meta: EMPTY_FORM_META,\n },\n },\n req.artifactPath,\n );\n }\n\n private handleFormsAttachWidget(\n req: FormsAttachWidgetWorkerRequest,\n signal: AbortSignal,\n ): WirePack<WorkerResultPayload> {\n const session = this.requireSession(req);\n const mutator = new FormMutator(this.runtime, session);\n const { field } = mutator.attachWidget(req.ref, req.widget, req.onState, signal);\n return this.finishMutation(\n session,\n { tag: 'forms.attachWidget', result: { field, meta: EMPTY_FORM_META } },\n req.artifactPath,\n );\n }\n\n private handleFormsDetachWidget(\n req: FormsDetachWidgetWorkerRequest,\n signal: AbortSignal,\n ): WirePack<WorkerResultPayload> {\n const session = this.requireSession(req);\n const mutator = new FormMutator(this.runtime, session);\n const { field } = mutator.detachWidget(req.ref, req.widget, signal);\n return this.finishMutation(\n session,\n { tag: 'forms.detachWidget', result: { field, meta: EMPTY_FORM_META } },\n req.artifactPath,\n );\n }\n\n private finishMutation<P extends WorkerResultPayload>(\n session: DocumentSession,\n payload: P,\n artifactPath?: string,\n ): WirePack<WorkerResultPayload> {\n // Every successful mutation funnels through here; the sequence bump\n // invalidates version-keyed caches (the forms model). Forms mutators\n // bump themselves before reading back, so their tags are skipped to\n // avoid rebuilding the model cache twice per write — as do the\n // flattener and redaction applier, which note the mutation before\n // their post-apply annotation re-read.\n if (\n !payload.tag.startsWith('forms.') &&\n payload.tag !== 'pages.flatten' &&\n payload.tag !== 'redaction.apply'\n ) {\n session.noteMutation();\n }\n if (session.kind !== 'layer') {\n return wirePack(payload);\n }\n const saved = this.saveLayerArtifact(session, artifactPath);\n return wirePack({ ...payload, ...saved.payload }, saved.transfer);\n }\n\n private saveLayerArtifact(session: DocumentSession, artifactPath?: string): LayerArtifactSave {\n const saver = new DocumentSaver(this.runtime, session);\n if (artifactPath) {\n const artifactFile = saver.saveLayerArtifactToFile(artifactPath);\n return { payload: { artifactFile }, transfer: [] };\n }\n const artifact = saver.saveLayerArtifact();\n return { payload: { artifact }, transfer: [artifact.bytes] };\n }\n}\n\ninterface LayerArtifactSave {\n payload: { artifact: { bytes: ArrayBuffer; size: number } } | { artifactFile: { path: string } };\n transfer: ArrayBuffer[];\n}\n\n/** Form mutations are non-structural at the page-list level. */\nconst EMPTY_FORM_META: MutationMeta = { affectedPages: [], cacheDelta: null };\n\nconst BASE_SESSION_SUFFIX = '__base__';\n\nfunction sessionKey(docId: string, layerName?: string): string {\n return `${docId}::${layerName ? `layer:${layerName}` : BASE_SESSION_SUFFIX}`;\n}\n\nfunction sessionKeyBelongsToDoc(key: string, docId: string): boolean {\n return key === sessionKey(docId) || key.startsWith(`${docId}::layer:`);\n}\n\nfunction isPasswordOpenError(error: unknown): boolean {\n return (\n error instanceof EngineError &&\n (error.code === EngineErrorCode.DocPasswordRequired ||\n error.code === EngineErrorCode.DocPasswordIncorrect)\n );\n}\n\n/**\n * The security probe a locked open answers with — identical to what\n * `SecurityReader.probeFile` reports for a password-protected file it\n * couldn't read: encrypted, password required, permissions unknown.\n * `securityStateFromProbe` + `passwordPromptFromState` on the client\n * turn this into `passwordPrompt: { state: 'required' }`.\n */\nfunction passwordRequiredProbe() {\n return {\n encryptionState: 'encrypted' as const,\n encryptionRequiresPassword: true,\n securityHandlerRevision: null,\n pdfPermissionsBits: null,\n pdfPermissionsAllAllowed: null,\n pdfOpenedAs: null,\n securityProbedAt: Date.now(),\n };\n}\n"],"mappings":";;;AAEA,MAAM,8BAAc,IAAI,QAA0B;;;;;;AAOlD,SAAgB,kBAAkB,SAAiC;CACjE,IAAI,YAAY,IAAI,OAAO,GAAG;CAC9B,QAAQ,GAAG,gBAAgB;CAC3B,YAAY,IAAI,OAAO;AACzB;;;;;AAMA,SAAgB,eAAe,SAAiC;CAC9D,IAAI,CAAC,YAAY,IAAI,OAAO,GAAG;CAC/B,QAAQ,GAAG,oBAAoB;CAC/B,YAAY,OAAO,OAAO;AAC5B;;;;;;;;AChBA,SAAgB,eAAe,QAA2B;CACxD,IAAI,OAAO,SAAS;EAClB,MAAM,SAAS,OAAO;EACtB,IAAI,kBAAkB,OAAO,MAAM;EACnC,MAAM,IAAI,WAAW,MAAM;CAC7B;AACF;;;;;;;;;;;;;;;;;;;;ACIA,SAAgB,eAAuB;CACrC,MAAM,QAAQ,WAAW,OAAO,gCAAgB,IAAI,WAAW,EAAE,CAAC;CAElE,MAAM,KAAM,MAAM,KAAM,KAAQ;CAChC,MAAM,KAAM,MAAM,KAAM,KAAQ;CAChC,MAAM,MAAM,MAAM,KAAK,QAAQ,MAAM,EAAE,SAAS,EAAE,CAAC,CAAC,SAAS,GAAG,GAAG,CAAC,CAAC,CAAC,KAAK,EAAE;CAC7E,OAAO,GAAG,IAAI,MAAM,GAAG,CAAC,EAAE,GAAG,IAAI,MAAM,GAAG,EAAE,EAAE,GAAG,IAAI,MAAM,IAAI,EAAE,EAAE,GAAG,IAAI,MAAM,IAAI,EAAE,EAAE,GAAG,IAAI,MAAM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