@hussmartinez/pdf-sdk 0.4.1 → 0.4.3

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.
@@ -1 +1 @@
1
- {"version":3,"file":"en-DiJkcy2X.js","names":[],"sources":["../../src/core/errors/pdf-error.ts","../../src/core/errors/abort.ts","../../src/core/errors/pdf-limits.ts","../../src/core/model/bytes.ts","../../src/core/model/geometry.ts","../../src/core/model/links.ts","../../src/core/ports/pdf-engine.ts","../../src/adapters/pdfjs/binary-data.ts","../../src/adapters/pdfjs/errors.ts","../../src/adapters/pdfjs/pdfjs-engine.ts","../../src/adapters/qpdf/qpdf-processor.ts","../../src/core/model/portable.ts","../../src/core/operations/commands.ts","../../src/core/model/plan.ts","../../src/core/session/source-name.ts","../../src/core/session/session.ts","../../src/messages/en.ts"],"sourcesContent":["import { isSdkError, type SdkCoreErrorCode, SdkError } from \"@hussmartinez/sdk-core\";\n\n/**\n * Error codes of `@hussmartinez/pdf-sdk`: sdk-core's own codes, such as\n * `ABORTED`, `WORKER_CRASHED` and `FILE_TOO_LARGE`, plus the PDF SDK's. They\n * never change meaning once released.\n *\n * - `INVALID_PDF`: the file isn't a PDF, or is too damaged to open.\n * - `PASSWORD_REQUIRED`: the PDF is encrypted, and opening it needs a\n * password.\n * - `PROCESSING_FAILED`: a PDF engine failed in a way no other code\n * describes. `cause` holds the engine's error.\n * - `TOO_MANY_PAGES`: a document, or the pages after an insert, exceed the\n * `maxPages` limit.\n * - `SESSION_TOO_LARGE`: the documents the session holds exceed the\n * `maxSessionSize` limit.\n * - `IMAGE_TOO_LARGE`: an image exceeds the `maxImagePixels` limit. It's\n * reported as a warning, because the image is skipped rather than the\n * document failing (ADR 0004).\n * - `INVALID_COMMAND`: an edit command doesn't apply to the plan, such as\n * one naming a page the plan doesn't have. `details.reason` says why, as\n * a stable token (`PdfCommandRejection`, sdk-core ADR 0045).\n * - `INVALID_DOCUMENT`: a plan document, such as a saved project, isn't\n * valid in its format. `details.reason` says why (`PdfDocumentRejection`).\n * - `UNSUPPORTED_FORMAT`: a plan document of another format, or of a later\n * version than this release reads, with `details.reason`\n * `unknown-format` or `unknown-format-version`.\n *\n * Limit codes carry `details` with the `limit`, its `maximum`, the `actual`\n * value and the `unit`.\n *\n * @public\n */\nexport type PdfErrorCode =\n | SdkCoreErrorCode\n | \"INVALID_PDF\"\n | \"PASSWORD_REQUIRED\"\n | \"PROCESSING_FAILED\"\n | \"TOO_MANY_PAGES\"\n | \"SESSION_TOO_LARGE\"\n | \"IMAGE_TOO_LARGE\"\n | \"INVALID_COMMAND\"\n | \"INVALID_DOCUMENT\"\n | \"UNSUPPORTED_FORMAT\";\n\n/**\n * The error `@hussmartinez/pdf-sdk` throws and rejects with, with a stable\n * `code`, structured `details` and the engine's error as `cause`. Show users\n * the text for its code from {@link pdfMessages}, never its `message`, which\n * is for developers and may contain text from the file.\n *\n * @example\n * ```ts\n * try {\n * await session.open(file);\n * } catch (error) {\n * if (isPdfError(error, \"PASSWORD_REQUIRED\")) {\n * askForPassword();\n * } else {\n * show(messages.error(error));\n * }\n * }\n * ```\n *\n * @public\n */\nexport class PdfError extends SdkError<PdfErrorCode> {\n /** Always `\"PdfError\"`, which survives minification and worker boundaries. */\n override readonly name = \"PdfError\";\n}\n\n/**\n * Checks whether a value is a {@link PdfError}, optionally with a given code.\n *\n * Unlike `instanceof`, it recognises errors from another copy of this\n * package or another realm, and errors rebuilt after crossing a worker\n * boundary.\n *\n * @param value - Any thrown value.\n * @param code - When given, the error must also have this code.\n * @public\n */\nexport function isPdfError<Code extends PdfErrorCode = PdfErrorCode>(\n value: unknown,\n code?: Code,\n): value is PdfError & { readonly code: Code } {\n return isSdkError(value, code) && value.name === \"PdfError\";\n}\n","import { createErrorHelpers } from \"@hussmartinez/sdk-core\";\nimport { PdfError } from \"./pdf-error.js\";\n\n/**\n * The family's error helpers, bound to `PdfError` (sdk-core ADR 0034), so\n * every port and the session make failures `PdfError`s the same way.\n */\nconst helpers = /* @__PURE__ */ createErrorHelpers(PdfError, {\n fallbackCode: \"PROCESSING_FAILED\",\n fallbackMessage: \"PDF processing failed.\",\n});\n\n/**\n * Makes any failure a `PdfError`, as every port promises: a `PdfError` as\n * it is, another `SdkError`, such as the worker client's own `ABORTED` or\n * `WORKER_CRASHED`, with its code, details and message kept, and anything\n * else as `PROCESSING_FAILED`. The original is kept as `cause`.\n *\n * @internal\n */\nexport const asPdfError: (reason: unknown, message?: string) => PdfError = helpers.adapt;\n\n/**\n * The error an aborted call rejects with, as the family's worker client does\n * (ADR 0018, ADR 0020): the reason itself when it's an `SdkError`, such as a\n * file policy's `PROCESSING_TIME_EXCEEDED`, `TIMEOUT` for a timeout, and\n * `ABORTED` otherwise. The reason is kept as `cause`.\n *\n * @internal\n */\nexport const abortError: (signal: AbortSignal) => PdfError = helpers.abortError;\n\n/**\n * Throws {@link abortError} if the signal has been aborted.\n *\n * @internal\n */\nexport const throwIfAborted: (signal: AbortSignal | undefined) => void = helpers.throwIfAborted;\n","import {\n coreLimits,\n defineLimits,\n type FilePolicy,\n type FilePolicyOverrides,\n type Limits,\n} from \"@hussmartinez/sdk-core\";\nimport { PdfError } from \"./pdf-error.js\";\n\n/**\n * The PDF SDK's limit definitions: sdk-core's core limits plus three for PDFs\n * (ADR 0004).\n *\n * | Limit | Code | Default maximum | Default warning |\n * |---|---|---|---|\n * | `maxFileSize` | `FILE_TOO_LARGE` | 100 MB | 50 MB |\n * | `maxFiles` | `TOO_MANY_FILES` | 20 | none |\n * | `maxDecodedSize` | `DECODED_SIZE_TOO_LARGE` | 500 MB | none |\n * | `maxProcessingTime` | `PROCESSING_TIME_EXCEEDED` | 120 s | none |\n * | `maxPages` | `TOO_MANY_PAGES` | 5,000 | 1,000 |\n * | `maxSessionSize` | `SESSION_TOO_LARGE` | 300 MB | 150 MB |\n * | `maxImagePixels` | `IMAGE_TOO_LARGE` | 100 megapixels | none |\n *\n * Sizes are decimal: 1 MB is 1,000,000 bytes.\n *\n * @public\n */\nexport const pdfLimitDefinitions = {\n ...coreLimits,\n maxPages: { code: \"TOO_MANY_PAGES\", unit: \"count\", default: 5_000, warning: 1_000 },\n maxSessionSize: {\n code: \"SESSION_TOO_LARGE\",\n unit: \"bytes\",\n default: 300_000_000,\n warning: 150_000_000,\n },\n maxImagePixels: { code: \"IMAGE_TOO_LARGE\", unit: \"pixels\", default: 100_000_000 },\n} as const;\n\n/**\n * The type of {@link pdfLimitDefinitions}.\n *\n * @public\n */\nexport type PdfLimitDefinitions = typeof pdfLimitDefinitions;\n\n/**\n * The names of the PDF SDK's limits.\n *\n * @public\n */\nexport type PdfLimitName = keyof PdfLimitDefinitions;\n\n/**\n * A host's `filePolicy`: a new maximum, or `{ maximum, warning }`, for any of\n * the PDF SDK's limits. `Infinity` disables a maximum, which removes a\n * protection against hostile files, or disables a warning. Unknown limit\n * names throw `TypeError` when the policy is resolved.\n *\n * @example\n * ```ts\n * const filePolicy: PdfFilePolicyOverrides = {\n * maxFileSize: { maximum: 300e6, warning: 100e6 },\n * maxSessionSize: 600e6,\n * };\n * ```\n *\n * @public\n */\nexport type PdfFilePolicyOverrides = FilePolicyOverrides<PdfLimitDefinitions>;\n\n/**\n * A resolved file policy for the PDF SDK. Violations throw {@link PdfError}.\n *\n * @public\n */\nexport type PdfFilePolicy = FilePolicy<PdfLimitDefinitions>;\n\n/**\n * The PDF SDK's limits, ready to resolve a host's `filePolicy`. Violations\n * are thrown as {@link PdfError}, with `details` naming the limit.\n *\n * @example\n * ```ts\n * const policy = pdfLimits.resolve(props.filePolicy);\n * policy.check(\"maxPages\", pageCount); // throws PdfError(\"TOO_MANY_PAGES\") above 5,000\n * ```\n *\n * @public\n */\nexport const pdfLimits: Limits<PdfLimitDefinitions> = /* @__PURE__ */ defineLimits(\n pdfLimitDefinitions,\n {\n errorClass: PdfError,\n },\n);\n","import type { PdfBytes } from \"./document.js\";\n\n/**\n * Copies PDF bytes into a new buffer that holds exactly them, so a caller's\n * buffer is never detached or changed, and a view into a larger buffer never\n * sends the rest of it (ADR 0002).\n *\n * @internal\n */\nexport function copyBytes(source: PdfBytes): Uint8Array<ArrayBuffer> {\n const view = source instanceof Uint8Array ? source : new Uint8Array(source);\n return new Uint8Array(view);\n}\n\n/**\n * Checks that a zero-based page index exists in a document.\n *\n * @throws `RangeError` otherwise.\n * @internal\n */\nexport function assertPageIndex(pageIndex: number, pageCount: number): void {\n if (!Number.isInteger(pageIndex) || pageIndex < 0 || pageIndex >= pageCount) {\n throw new RangeError(\n `Page index ${pageIndex} is outside the document, which has ${pageCount} pages.`,\n );\n }\n}\n","/**\n * A point on a page, as fractions of the page's unrotated media box: `x`\n * from the left edge and `y` from the top edge, each from 0 to 1. Fractions\n * keep positions independent of zoom and of the rotation the page is shown\n * with (ADR 0003).\n *\n * @public\n */\nexport interface PdfPoint {\n readonly x: number;\n readonly y: number;\n}\n\n/**\n * A rectangle on a page, in the same fractions as {@link PdfPoint}: its\n * top-left corner, width and height.\n *\n * @public\n */\nexport interface PdfRect {\n readonly x: number;\n readonly y: number;\n readonly width: number;\n readonly height: number;\n}\n\n/**\n * A rotation in degrees, clockwise.\n *\n * @public\n */\nexport type PdfRotation = 0 | 90 | 180 | 270;\n\n/**\n * Adds two rotations, such as a page's own `/Rotate` and the rotation the\n * page plan adds to it.\n *\n * @example\n * ```ts\n * addRotation(270, 180); // 90\n * addRotation(90, -90); // 0\n * ```\n *\n * @param rotation - The current rotation.\n * @param angle - The angle to add, positive clockwise, in multiples of 90.\n * @throws `RangeError` if `angle` isn't a multiple of 90.\n * @public\n */\nexport function addRotation(rotation: PdfRotation, angle: number): PdfRotation {\n if (!Number.isInteger(angle) || angle % 90 !== 0) {\n throw new RangeError(`A rotation must be a multiple of 90 degrees, received ${angle}.`);\n }\n return ((((rotation + angle) % 360) + 360) % 360) as PdfRotation;\n}\n","const SAFE_PROTOCOLS = new Set([\"http:\", \"https:\", \"mailto:\"]);\n\n/**\n * The URL, normalised, if it's an absolute `http`, `https` or `mailto` URL\n * without credentials (ADR 0012), and otherwise undefined. Every engine\n * adapter filters links with it, and the viewer checks again before\n * rendering one.\n *\n * URLs with a user name or password are refused: in\n * `https://bank.example@evil.example/`, the part a reader notices is a user\n * name, and the link goes to `evil.example`, a common phishing shape.\n *\n * @public\n */\nexport function safeLinkUrl(url: string): string | undefined {\n if (typeof url !== \"string\" || url.length > 2048) return undefined;\n let parsed: URL;\n try {\n parsed = new URL(url);\n } catch {\n return undefined;\n }\n if (!SAFE_PROTOCOLS.has(parsed.protocol)) return undefined;\n if (parsed.username !== \"\" || parsed.password !== \"\") return undefined;\n return parsed.href;\n}\n\n/**\n * What a link really leads to, for people to check before following it: the\n * host of a web link, without `www.`, or the address of an email link.\n * Undefined for a URL `safeLinkUrl` refuses.\n *\n * @public\n */\nexport function linkDestination(url: string): string | undefined {\n const safe = safeLinkUrl(url);\n if (!safe) return undefined;\n const parsed = new URL(safe);\n if (parsed.protocol === \"mailto:\") {\n return decodeURIComponent(parsed.pathname) || undefined;\n }\n return parsed.hostname.replace(/^www\\./, \"\");\n}\n","import type {\n PdfBytes,\n PdfFormField,\n PdfLink,\n PdfPageInfo,\n PdfTextContent,\n} from \"../model/document.js\";\nimport type { PdfRotation } from \"../model/geometry.js\";\nimport type { PdfCallOptions, PdfTransferOptions } from \"./options.js\";\n\n/**\n * The most pixels an engine draws into one canvas. Larger renders are drawn\n * at a lower resolution instead, because iOS Safari, the strictest\n * supported browser, refuses larger canvases (ADR 0004).\n *\n * @public\n */\nexport const PDF_MAX_CANVAS_PIXELS = 16_777_216;\n\n/**\n * How to render a page.\n *\n * @public\n */\nexport interface PdfRenderOptions extends PdfCallOptions {\n /** CSS pixels per PDF point. `1` renders a US Letter page 612 CSS pixels wide. */\n readonly scale: number;\n /**\n * Device pixels per CSS pixel, usually `window.devicePixelRatio`. Defaults\n * to 1. The engine lowers it as needed to stay within\n * {@link PDF_MAX_CANVAS_PIXELS}.\n */\n readonly pixelRatio?: number;\n /** Rotation added to the page's own, for the page plan (ADR 0003). Defaults to 0. */\n readonly rotation?: PdfRotation;\n}\n\n/**\n * An open document. Pages are addressed by zero-based index.\n *\n * @public\n */\nexport interface PdfDocumentHandle {\n /** The number of pages. */\n readonly pageCount: number;\n /**\n * Reads a page's size and rotation.\n *\n * @throws `RangeError` for an index outside the document.\n */\n getPage(pageIndex: number, options?: PdfCallOptions): Promise<PdfPageInfo>;\n /**\n * Draws a page into a canvas, sizing the canvas's pixel dimensions and its\n * CSS `width` and `height`.\n *\n * @throws `RangeError` for an index outside the document.\n */\n renderPage(\n pageIndex: number,\n canvas: HTMLCanvasElement,\n options: PdfRenderOptions,\n ): Promise<void>;\n /**\n * Reads a page's text, for the text layer and search.\n *\n * @throws `RangeError` for an index outside the document.\n */\n getTextContent(pageIndex: number, options?: PdfCallOptions): Promise<PdfTextContent>;\n /**\n * Reads the form fields on a page.\n *\n * @throws `RangeError` for an index outside the document.\n */\n getFormFields(pageIndex: number, options?: PdfCallOptions): Promise<readonly PdfFormField[]>;\n /**\n * Reads the links on a page to web pages and email addresses, filtered\n * with `safeLinkUrl` (ADR 0012).\n *\n * @throws `RangeError` for an index outside the document.\n */\n getLinks(pageIndex: number, options?: PdfCallOptions): Promise<readonly PdfLink[]>;\n /** Releases the document. Pending calls reject, and later calls throw. */\n destroy(): Promise<void>;\n}\n\n/**\n * The port for viewing PDFs: open a document, then read and render its pages\n * (ADR 0008). The SDK's pdf.js adapter implements it; hosts can pass their\n * own to the editor's `engine` prop, and every implementation must pass the\n * engine's contract tests.\n *\n * Failures reject with `PdfError`: `INVALID_PDF` for a file that can't be\n * parsed, `PASSWORD_REQUIRED` for an encrypted one, and sdk-core's codes for\n * cancellation and worker failures.\n *\n * @public\n */\nexport interface PdfEngine {\n /**\n * Opens a document. The bytes are copied unless `transfer` is set.\n */\n open(source: PdfBytes, options?: PdfTransferOptions): Promise<PdfDocumentHandle>;\n /** Releases the engine and its worker. Open documents are destroyed. */\n destroy(): Promise<void>;\n}\n","/** The kinds of data pdf.js asks the page for when `useWorkerFetch` is off. */\nexport type PdfJsDataKind = \"cMapUrl\" | \"standardFontDataUrl\" | \"wasmUrl\";\n\n/** Called for every data file pdf.js asks for. */\nexport type PdfJsDataListener = (kind: PdfJsDataKind, filename: string) => void;\n\n/**\n * The prefix pdf.js puts before the file name of a JavaScript decoder it\n * imports when a WebAssembly decoder can't start, for example under a\n * Content Security Policy without 'wasm-unsafe-eval'. It isn't a fetchable\n * scheme, so that import fails without a request (docs/adr/0002).\n */\nexport const NO_NETWORK_URL = \"hm-pdf-no-network:/\";\n\nfunction decodeBase64(base64: string): Uint8Array {\n const binary = atob(base64);\n const bytes = new Uint8Array(binary.length);\n for (let index = 0; index < binary.length; index += 1) {\n bytes[index] = binary.charCodeAt(index);\n }\n return bytes;\n}\n\n/**\n * A `BinaryDataFactory` for pdf.js that serves the bundled CMaps, standard\n * fonts and WebAssembly decoders from lazy chunks, without the network\n * (docs/adr/0002). Only those files are served: any other kind or name,\n * such as a path, is refused.\n */\nexport function createInlineDataFactory(listener?: PdfJsDataListener) {\n return class InlineDataFactory {\n async fetch({\n kind,\n filename,\n }: {\n kind: PdfJsDataKind;\n filename: string;\n }): Promise<Uint8Array> {\n listener?.(kind, filename);\n const { pdfJsData } = await import(\"virtual:hm-pdfjs-data\");\n const files = Object.hasOwn(pdfJsData, kind) ? pdfJsData[kind] : undefined;\n const load = files && Object.hasOwn(files, filename) ? files[filename] : undefined;\n if (!load) {\n throw new Error(`The PDF SDK doesn't serve ${kind} data named ${filename}.`);\n }\n return decodeBase64(await load());\n }\n };\n}\n","import { isPdfError, PdfError } from \"../../core/errors/pdf-error.js\";\n\nconst INVALID = new Set([\"InvalidPDFException\", \"FormatError\", \"MissingPDFException\"]);\n\n/**\n * Turns whatever pdf.js rejected with into a `PdfError`, keeping it as\n * `cause`. pdf.js's exceptions cross its worker boundary as plain objects\n * with a `name`, so they're recognised by name.\n */\nexport function fromPdfJsError(reason: unknown, message: string): PdfError | RangeError {\n if (isPdfError(reason) || reason instanceof RangeError) {\n return reason;\n }\n const name = typeof reason === \"object\" && reason !== null ? (reason as Error).name : undefined;\n if (name === \"PasswordException\") {\n return new PdfError(\"PASSWORD_REQUIRED\", \"The PDF is encrypted.\", { cause: reason });\n }\n if (name !== undefined && INVALID.has(name)) {\n return new PdfError(\"INVALID_PDF\", \"The file isn't a readable PDF.\", { cause: reason });\n }\n return new PdfError(\"PROCESSING_FAILED\", message, { cause: reason });\n}\n","import { type AssetsResolver, createAssetsResolver } from \"@hussmartinez/sdk-core\";\nimport type { PDFDocumentLoadingTask, PDFDocumentProxy, PDFPageProxy, PDFWorker } from \"pdfjs-dist\";\nimport { abortError, throwIfAborted } from \"../../core/errors/abort.js\";\nimport { PdfError } from \"../../core/errors/pdf-error.js\";\nimport { pdfLimitDefinitions } from \"../../core/errors/pdf-limits.js\";\nimport { assertPageIndex, copyBytes } from \"../../core/model/bytes.js\";\nimport type {\n PdfBytes,\n PdfFormField,\n PdfLink,\n PdfPageInfo,\n PdfTextContent,\n PdfTextItem,\n} from \"../../core/model/document.js\";\nimport { addRotation, type PdfRect, type PdfRotation } from \"../../core/model/geometry.js\";\nimport { safeLinkUrl } from \"../../core/model/links.js\";\nimport type { PdfCallOptions, PdfTransferOptions } from \"../../core/ports/options.js\";\nimport {\n PDF_MAX_CANVAS_PIXELS,\n type PdfDocumentHandle,\n type PdfEngine,\n type PdfRenderOptions,\n} from \"../../core/ports/pdf-engine.js\";\nimport { createInlineDataFactory, NO_NETWORK_URL } from \"./binary-data.js\";\nimport { fromPdfJsError } from \"./errors.js\";\n\ntype PdfJs = typeof import(\"pdfjs-dist\");\ntype PageViewport = ReturnType<PDFPageProxy[\"getViewport\"]>;\n\n/** The fields of pdf.js's text items this adapter reads. */\ninterface PdfJsTextItem {\n readonly str: string;\n readonly transform: readonly number[];\n readonly width: number;\n readonly hasEOL: boolean;\n}\n\n/**\n * Converts a rectangle in PDF user space to fractions of the unrotated page,\n * from the top-left corner, clamped to the page (ADR 0003).\n */\nfunction toPageRect(viewport: PageViewport, box: readonly number[]): PdfRect {\n const [x1 = 0, y1 = 0, x2 = 0, y2 = 0] = box;\n const [ax = 0, ay = 0] = viewport.convertToViewportPoint(x1, y1) as number[];\n const [bx = 0, by = 0] = viewport.convertToViewportPoint(x2, y2) as number[];\n const left = clamp(Math.min(ax, bx) / viewport.width);\n const top = clamp(Math.min(ay, by) / viewport.height);\n return {\n x: left,\n y: top,\n width: clamp(Math.max(ax, bx) / viewport.width) - left,\n height: clamp(Math.max(ay, by) / viewport.height) - top,\n };\n}\n\n/**\n * Options for {@link createPdfJsEngine}.\n *\n * @public\n */\nexport interface PdfJsEngineOptions {\n /**\n * Where your application serves the package's `dist/assets/` directory,\n * on its own origin, such as `\"/pdf-sdk/\"`. pdf.js then loads its worker\n * and its data files from its `pdfjs/` subdirectory, rather than from the\n * inlined copies. Use it for Content Security Policies without\n * `worker-src blob:`, and for accurate ICC colour, which only this mode\n * supports (docs/adr/0006, docs/adr/0007). Pass the same URL to\n * `createPdfProcessor`.\n */\n readonly assetsUrl?: string | URL;\n /**\n * The largest image pdf.js decodes, in pixels. Larger images are left\n * unpainted. Defaults to the `maxImagePixels` limit, 100 megapixels.\n */\n readonly maxImagePixels?: number;\n /**\n * Called for every data file pdf.js asks for. For tests.\n *\n * @internal\n */\n readonly _onDataRequest?: (\n kind: \"cMapUrl\" | \"standardFontDataUrl\" | \"wasmUrl\",\n filename: string,\n ) => void;\n}\n\n/** How long a cancelled open may take to stop before its worker is terminated (ADR 0018). */\nconst CANCEL_TIMEOUT = 1_000;\n\n/**\n * Creates the SDK's {@link PdfEngine}, backed by pdf.js (ADR 0001, ADR 0002).\n *\n * Nothing loads until the first `open()`: then pdf.js's display layer is\n * imported, and its worker starts. Every document the engine opens shares one\n * worker, and pdf.js runs without scripting or XFA (docs/adr/0001).\n *\n * By default everything is inlined: the worker, and the CMaps, standard\n * fonts and image decoders that some documents need, each loaded only when a\n * document needs it, with no network request. With `assetsUrl`, they load\n * from your own origin instead (docs/adr/0002, docs/adr/0006).\n *\n * @example\n * ```ts\n * const engine = createPdfJsEngine();\n * const document = await engine.open(await file.arrayBuffer(), { signal });\n * await document.renderPage(0, canvas, { scale: 1.5, pixelRatio: devicePixelRatio });\n * ```\n *\n * @public\n */\nexport function createPdfJsEngine(options: PdfJsEngineOptions = {}): PdfEngine {\n return new PdfJsEngine(options);\n}\n\n/**\n * One worker, and everything that fails with it. When the worker crashes or\n * has to be terminated, every call waiting on it rejects, and the engine\n * starts a new one on the next open.\n */\nclass WorkerHost {\n readonly pdfWorker: PDFWorker;\n #worker: Worker;\n #waiting = new Set<(error: PdfError) => void>();\n #failure: PdfError | undefined;\n\n constructor(worker: Worker, pdfWorker: PDFWorker) {\n this.#worker = worker;\n this.pdfWorker = pdfWorker;\n const crash = (event: Event) => {\n // Handled here, so the error isn't also reported to the console.\n event.preventDefault();\n this.fail(new PdfError(\"WORKER_CRASHED\", \"The PDF render worker failed.\"));\n };\n worker.addEventListener(\"error\", crash);\n worker.addEventListener(\"messageerror\", crash);\n }\n\n get failure(): PdfError | undefined {\n return this.#failure;\n }\n\n /** Rejects with the worker's failure, if it fails while the returned function hasn't been called. */\n watch(reject: (error: PdfError) => void): () => void {\n if (this.#failure) {\n reject(this.#failure);\n return () => {};\n }\n this.#waiting.add(reject);\n return () => this.#waiting.delete(reject);\n }\n\n fail(error: PdfError): void {\n if (this.#failure) return;\n this.#failure = error;\n this.#worker.terminate();\n this.pdfWorker.destroy();\n for (const reject of this.#waiting) reject(error);\n this.#waiting.clear();\n }\n}\n\n/**\n * Waits for a pdf.js promise, rejecting at once when the signal aborts or the\n * worker fails, and mapping pdf.js's errors to `PdfError`.\n */\nfunction settle<Value>(\n host: WorkerHost,\n promise: Promise<Value>,\n options: { signal?: AbortSignal | undefined; onAbort?: () => void; message: string },\n): Promise<Value> {\n const { signal } = options;\n return new Promise<Value>((resolve, reject) => {\n if (signal?.aborted) {\n options.onAbort?.();\n reject(abortError(signal));\n return;\n }\n const abort = () => {\n options.onAbort?.();\n reject(abortError(signal as AbortSignal));\n };\n signal?.addEventListener(\"abort\", abort, { once: true });\n const unwatch = host.watch(reject);\n promise.then(resolve, (reason: unknown) => reject(fromPdfJsError(reason, options.message)));\n // Settling twice is harmless; the first outcome wins.\n void promise\n .catch(() => {})\n .finally(() => {\n signal?.removeEventListener(\"abort\", abort);\n unwatch();\n });\n });\n}\n\nconst VERSION_MISMATCH = /The API version \"([^\"]+)\" does not match the Worker version \"([^\"]+)\"/;\n\n/**\n * pdf.js refuses a worker from another pdf.js version, such as a self-hosted\n * copy left over from before an upgrade. That's a start failure, not a\n * problem with the document, so it's reported as one, with the same details\n * as sdk-core's worker client gives (sdk-core ADR 0038).\n */\nfunction workerVersionMismatch(error: unknown, base: string | undefined): PdfError | undefined {\n for (let reason = error; reason instanceof Error; reason = reason.cause) {\n const match = VERSION_MISMATCH.exec(reason.message);\n if (match) {\n return new PdfError(\"WORKER_START_FAILED\", \"The PDF render worker is another version.\", {\n details: {\n asset: base === undefined ? null : `${base}build/pdf.worker.min.mjs`,\n expected: match[1] ?? null,\n actual: match[2] ?? null,\n },\n cause: error,\n });\n }\n }\n return undefined;\n}\n\n/** pdf.js transfers the bytes it's given, so it gets a copy unless the caller transfers. */\nfunction takeBytes(source: PdfBytes, transfer: boolean | undefined): Uint8Array {\n if (transfer) {\n const view = source instanceof Uint8Array ? source : new Uint8Array(source);\n const whole = view.byteOffset === 0 && view.byteLength === view.buffer.byteLength;\n if (whole && view.buffer instanceof ArrayBuffer) return view;\n }\n return copyBytes(source);\n}\n\nfunction normalizeRotation(rotation: number): PdfRotation {\n return addRotation(0, Number.isInteger(rotation) && rotation % 90 === 0 ? rotation : 0);\n}\n\nconst clamp = (value: number) => Math.min(1, Math.max(0, value));\n\nclass PdfJsEngine implements PdfEngine {\n #options: PdfJsEngineOptions;\n /** Files under `assetsUrl`, if it's set. */\n readonly #asset: AssetsResolver | undefined;\n #runtime: Promise<PdfJs> | undefined;\n #host: WorkerHost | undefined;\n #documents = new Set<PdfJsDocument>();\n #destroyed = false;\n\n constructor(options: PdfJsEngineOptions) {\n this.#options = options;\n // Checked now, so a URL with a query or fragment throws TypeError here.\n // A URL relative to the page is resolved on the first open, which only\n // happens in a browser, so the engine can be created on a server\n // (sdk-core ADR 0038).\n this.#asset =\n options.assetsUrl === undefined ? undefined : createAssetsResolver(options.assetsUrl);\n }\n\n async open(source: PdfBytes, options: PdfTransferOptions = {}): Promise<PdfDocumentHandle> {\n if (this.#destroyed) {\n throw new PdfError(\"WORKER_TERMINATED\", \"The PDF engine was destroyed.\");\n }\n throwIfAborted(options.signal);\n const data = takeBytes(source, options.transfer);\n this.#runtime ??= import(\"./runtime.js\").then((module) => module.pdfjs as PdfJs);\n const pdfjs = await this.#runtime;\n throwIfAborted(options.signal);\n const host = await this.#ensureHost(pdfjs);\n\n const base = this.#assetsBase();\n const task = pdfjs.getDocument({\n data,\n worker: host.pdfWorker,\n // Hardening (docs/adr/0001, docs/adr/0002): no XFA, and data files only\n // from the bundle or the application's own origin, never elsewhere.\n enableXfa: false,\n maxImageSize: this.#options.maxImagePixels ?? pdfLimitDefinitions.maxImagePixels.default,\n stopAtErrors: false,\n verbosity: pdfjs.VerbosityLevel.ERRORS,\n useWasm: true,\n ...(base\n ? {\n // Self-hosted: pdf.js fetches from the application's origin, which\n // also enables ICC colour (docs/adr/0006).\n useWorkerFetch: true,\n cMapUrl: `${base}cmaps/`,\n standardFontDataUrl: `${base}standard_fonts/`,\n wasmUrl: `${base}wasm/`,\n iccUrl: `${base}iccs/`,\n }\n : {\n // Inline: every file comes from the bundle, through the factory.\n useWorkerFetch: false,\n BinaryDataFactory: createInlineDataFactory(this.#options._onDataRequest),\n wasmUrl: NO_NETWORK_URL,\n }),\n });\n try {\n const proxy = await settle(host, task.promise, {\n signal: options.signal,\n onAbort: () => this.#cancel(task, host),\n message: \"The PDF couldn't be opened.\",\n });\n const document = new PdfJsDocument(pdfjs, proxy, task, host, () =>\n this.#documents.delete(document),\n );\n this.#documents.add(document);\n return document;\n } catch (error) {\n void task.destroy().catch(() => {});\n const mismatch = workerVersionMismatch(error, base);\n if (mismatch) {\n // The worker is unusable; the next open starts a new one.\n host.fail(mismatch);\n throw mismatch;\n }\n throw error;\n }\n }\n\n async destroy(): Promise<void> {\n if (this.#destroyed) return;\n this.#destroyed = true;\n await Promise.all([...this.#documents].map((document) => document.destroy()));\n this.#host?.fail(new PdfError(\"WORKER_TERMINATED\", \"The PDF engine was destroyed.\"));\n this.#host = undefined;\n }\n\n async #ensureHost(pdfjs: PdfJs): Promise<WorkerHost> {\n if (this.#host && !this.#host.failure) return this.#host;\n let worker: Worker;\n try {\n const base = this.#assetsBase();\n worker = base\n ? new Worker(`${base}build/pdf.worker.min.mjs`, { type: \"module\", name: \"hm-pdf-render\" })\n : (await import(\"./render-worker.js\")).createInlineWorker();\n } catch (cause) {\n throw new PdfError(\"WORKER_START_FAILED\", \"The PDF render worker couldn't start.\", {\n cause,\n });\n }\n this.#host = new WorkerHost(worker, pdfjs.PDFWorker.create({ port: worker }));\n return this.#host;\n }\n\n /** pdf.js's directory under `assetsUrl`, if it's set. */\n #assetsBase(): string | undefined {\n return this.#asset?.(\"pdfjs/\");\n }\n\n /** Stops a cancelled open, and terminates the worker if pdf.js doesn't stop in time. */\n #cancel(task: PDFDocumentLoadingTask, host: WorkerHost): void {\n const timer = setTimeout(\n () =>\n host.fail(\n new PdfError(\"WORKER_TERMINATED\", \"The worker was stopped to cancel an operation.\"),\n ),\n CANCEL_TIMEOUT,\n );\n void task\n .destroy()\n .catch(() => {})\n .finally(() => clearTimeout(timer));\n }\n}\n\nclass PdfJsDocument implements PdfDocumentHandle {\n readonly pageCount: number;\n #pdfjs: PdfJs;\n #proxy: PDFDocumentProxy;\n #task: PDFDocumentLoadingTask;\n #host: WorkerHost;\n #onDestroy: () => void;\n #destroyed = false;\n\n constructor(\n pdfjs: PdfJs,\n proxy: PDFDocumentProxy,\n task: PDFDocumentLoadingTask,\n host: WorkerHost,\n onDestroy: () => void,\n ) {\n this.#pdfjs = pdfjs;\n this.#proxy = proxy;\n this.#task = task;\n this.#host = host;\n this.#onDestroy = onDestroy;\n this.pageCount = proxy.numPages;\n }\n\n async getPage(pageIndex: number, options: PdfCallOptions = {}): Promise<PdfPageInfo> {\n const page = await this.#page(pageIndex, options);\n const { width, height } = page.getViewport({ scale: 1, rotation: 0 });\n return { width, height, rotation: normalizeRotation(page.rotate) };\n }\n\n async renderPage(\n pageIndex: number,\n canvas: HTMLCanvasElement,\n options: PdfRenderOptions,\n ): Promise<void> {\n if (!(options.scale > 0) || !Number.isFinite(options.scale)) {\n throw new RangeError(\n `The render scale must be a positive number, received ${options.scale}.`,\n );\n }\n const page = await this.#page(pageIndex, options);\n const rotation = addRotation(normalizeRotation(page.rotate), options.rotation ?? 0);\n const viewport = page.getViewport({ scale: options.scale, rotation });\n const area = viewport.width * viewport.height;\n const wanted = Math.max(options.pixelRatio ?? 1, Number.MIN_VALUE);\n // Lower the resolution, never the CSS size, to stay within the canvas cap (ADR 0004).\n const ratio = Math.min(wanted, Math.sqrt(PDF_MAX_CANVAS_PIXELS / Math.max(area, 1)));\n canvas.width = Math.max(1, Math.floor(viewport.width * ratio));\n canvas.height = Math.max(1, Math.floor(viewport.height * ratio));\n canvas.style.width = `${viewport.width}px`;\n canvas.style.height = `${viewport.height}px`;\n const context = canvas.getContext(\"2d\", { alpha: false });\n if (!context) {\n throw new PdfError(\"UNSUPPORTED_ENVIRONMENT\", \"The browser can't draw on a canvas.\", {\n details: { feature: \"CanvasRenderingContext2D\" },\n });\n }\n const task = page.render({\n canvas,\n canvasContext: context,\n viewport,\n transform: [canvas.width / viewport.width, 0, 0, canvas.height / viewport.height, 0, 0],\n annotationMode: this.#pdfjs.AnnotationMode.ENABLE,\n });\n try {\n await settle(this.#host, task.promise, {\n signal: options.signal,\n onAbort: () => task.cancel(),\n message: \"The page couldn't be drawn.\",\n });\n } finally {\n page.cleanup();\n }\n }\n\n async getTextContent(pageIndex: number, options: PdfCallOptions = {}): Promise<PdfTextContent> {\n const page = await this.#page(pageIndex, options);\n const content = await settle(this.#host, page.getTextContent(), {\n signal: options.signal,\n message: \"The page's text couldn't be read.\",\n });\n const viewport = page.getViewport({ scale: 1, rotation: 0 });\n const items: PdfTextItem[] = [];\n for (const item of content.items) {\n if (!(\"str\" in item)) continue;\n const { str, transform, width, hasEOL } = item as PdfJsTextItem;\n const [a = 1, b = 0, c = 0, d = 1, e = 0, f = 0] = transform;\n const fontHeight = Math.hypot(c, d);\n items.push({\n text: str,\n rect: toPageRect(viewport, [e, f, e + width, f + fontHeight]),\n angle: (Math.atan2(b, a) * 180) / Math.PI,\n endOfLine: hasEOL,\n });\n }\n return { items };\n }\n\n async getFormFields(\n pageIndex: number,\n options: PdfCallOptions = {},\n ): Promise<readonly PdfFormField[]> {\n const page = await this.#page(pageIndex, options);\n const annotations = (await settle(this.#host, page.getAnnotations({ intent: \"display\" }), {\n signal: options.signal,\n message: \"The page's form fields couldn't be read.\",\n })) as Array<Record<string, unknown>>;\n const viewport = page.getViewport({ scale: 1, rotation: 0 });\n const fields = new Map<string, PdfFormField>();\n for (const annotation of annotations) {\n const name = annotation[\"fieldName\"];\n if (annotation[\"subtype\"] !== \"Widget\" || typeof name !== \"string\" || fields.has(name)) {\n continue;\n }\n const value = annotation[\"fieldValue\"];\n const type =\n annotation[\"fieldType\"] === \"Tx\"\n ? \"text\"\n : annotation[\"fieldType\"] === \"Btn\" && annotation[\"checkBox\"]\n ? \"checkbox\"\n : undefined;\n if (!type) continue;\n fields.set(name, {\n name,\n type,\n rect: toPageRect(viewport, annotation[\"rect\"] as number[]),\n value:\n type === \"text\"\n ? typeof value === \"string\"\n ? value\n : \"\"\n : typeof value === \"string\" && value !== \"\" && value !== \"Off\",\n readOnly: annotation[\"readOnly\"] === true,\n });\n }\n return [...fields.values()];\n }\n\n async getLinks(pageIndex: number, options: PdfCallOptions = {}): Promise<readonly PdfLink[]> {\n const page = await this.#page(pageIndex, options);\n const annotations = (await settle(this.#host, page.getAnnotations({ intent: \"display\" }), {\n signal: options.signal,\n message: \"The page's links couldn't be read.\",\n })) as Array<Record<string, unknown>>;\n const viewport = page.getViewport({ scale: 1, rotation: 0 });\n const links: PdfLink[] = [];\n for (const annotation of annotations) {\n if (annotation[\"subtype\"] !== \"Link\" || typeof annotation[\"url\"] !== \"string\") continue;\n // pdf.js also allows ftp: and tel:, and turns some scripts into URLs;\n // the SDK keeps only http, https and mailto (ADR 0012).\n const url = safeLinkUrl(annotation[\"url\"]);\n if (url) links.push({ rect: toPageRect(viewport, annotation[\"rect\"] as number[]), url });\n }\n return links;\n }\n\n async destroy(): Promise<void> {\n if (this.#destroyed) return;\n this.#destroyed = true;\n this.#onDestroy();\n await this.#task.destroy().catch(() => {});\n }\n\n async #page(pageIndex: number, options: PdfCallOptions): Promise<PDFPageProxy> {\n if (this.#destroyed) {\n throw new PdfError(\"WORKER_TERMINATED\", \"The document was destroyed.\");\n }\n assertPageIndex(pageIndex, this.pageCount);\n throwIfAborted(options.signal);\n return settle(this.#host, this.#proxy.getPage(pageIndex + 1), {\n signal: options.signal,\n message: \"The page couldn't be read.\",\n });\n }\n}\n","import {\n createAssetsResolver,\n createWorkerClient,\n type WorkerClient,\n} from \"@hussmartinez/sdk-core\";\nimport { asPdfError } from \"../../core/errors/abort.js\";\nimport { PdfError } from \"../../core/errors/pdf-error.js\";\nimport type { PdfBuildJob } from \"../../core/model/build-job.js\";\nimport type { PdfBuildOptions, PdfProcessor } from \"../../core/ports/pdf-processor.js\";\nimport type { ProcessingContract } from \"./contract.js\";\n\n/**\n * Options for {@link createPdfProcessor}.\n *\n * @public\n */\nexport interface PdfProcessorOptions {\n /**\n * Where your application serves the package's `dist/assets/` directory,\n * on its own origin, such as `\"/pdf-sdk/\"`, the same URL as the engine's.\n * The worker then loads from `processing/processing.worker.js`, and\n * fetches `processing/qpdf.wasm`, which it checks against this version's\n * hash before using it. Use it for Content Security Policies without\n * `worker-src blob:` (docs/adr/0007). By default the worker is inlined.\n */\n readonly assetsUrl?: string | URL;\n}\n\n/**\n * Creates the SDK's {@link PdfProcessor}, backed by qpdf and pdf-lib in a\n * worker (docs/adr/0001, docs/adr/0002).\n *\n * Nothing starts until the first `build()`. By default the worker is\n * inlined, which needs `worker-src blob:` and `script-src 'wasm-unsafe-eval'`\n * in a Content Security Policy, and it never fetches anything. With\n * `assetsUrl`, it loads from your own origin instead. A build that can't stop\n * when cancelled terminates its worker, which starts again on the next build.\n *\n * @example\n * ```ts\n * const processor = createPdfProcessor();\n * const protectedPdf = await processor.build({\n * sources: [{ id: \"a\", bytes }],\n * pages: [{ source: \"a\", pageIndex: 0 }, { source: \"a\", pageIndex: 1, rotation: 90 }],\n * encrypt: { userPassword: \"correct horse\" },\n * });\n * ```\n *\n * @public\n */\nexport function createPdfProcessor(options: PdfProcessorOptions = {}): PdfProcessor {\n // Throws TypeError now for a URL with a query or fragment. A URL relative\n // to the page is resolved on the first build, which only happens in a\n // browser, so the processor can be created on a server (sdk-core ADR 0038).\n const asset =\n options.assetsUrl === undefined ? undefined : createAssetsResolver(options.assetsUrl);\n const workerPath = \"processing/processing.worker.js\";\n let client: WorkerClient<ProcessingContract> | undefined;\n let destroyed = false;\n\n const start = (): WorkerClient<ProcessingContract> => {\n client ??= createWorkerClient<ProcessingContract>({\n // The worker's chunk loads on the first build, not with this module.\n createWorker: () => {\n if (asset) {\n return new Worker(asset(workerPath), {\n type: \"module\",\n name: \"hm-pdf-processing\",\n });\n }\n if (!inlineWorker) {\n throw new PdfError(\"WORKER_START_FAILED\", \"The processing worker hasn't loaded.\");\n }\n return inlineWorker();\n },\n errorClasses: { PdfError },\n // A worker from another version of the package is refused with\n // WORKER_START_FAILED, naming the file to copy again (sdk-core ADR 0038).\n packageVersion: __PDF_SDK_VERSION__,\n ...(asset ? { workerAsset: asset(workerPath) } : {}),\n });\n return client;\n };\n let inlineWorker: (() => Worker) | undefined;\n\n return {\n async build(job: PdfBuildJob, options: PdfBuildOptions = {}): Promise<Uint8Array> {\n if (destroyed) {\n throw new PdfError(\"WORKER_TERMINATED\", \"The PDF processor was destroyed.\");\n }\n if (!asset) {\n inlineWorker ??= (await import(\"./processing-worker.js\")).createInlineWorker;\n }\n let outcome: Awaited<ReturnType<WorkerClient<ProcessingContract>[\"call\"]>>;\n try {\n outcome = await start().call(\"build\", job, {\n ...(options.signal ? { signal: options.signal } : {}),\n ...(options.onProgress ? { onProgress: options.onProgress } : {}),\n ...(options.transfer ? { transfer: true } : {}),\n });\n } catch (error) {\n // The client's own failures, such as ABORTED or WORKER_CRASHED, are\n // SdkErrors; the port promises PdfError.\n throw asPdfError(error, \"The PDF couldn't be built.\");\n }\n if (!outcome.ok) {\n throw outcome.error === \"RangeError\"\n ? new RangeError(outcome.message)\n : new TypeError(outcome.message);\n }\n return outcome.bytes;\n },\n async destroy(): Promise<void> {\n destroyed = true;\n client?.destroy();\n client = undefined;\n },\n };\n}\n","/**\n * The grid positions and sizes on a page are kept on: millionths of the\n * page (sdk-core ADR 0045, docs/adr/0003). Every position, size, stroke\n * width and text size the session stores is a whole number of millionths,\n * so a document saved in any language reproduces it exactly.\n *\n * @public\n */\nexport const PDF_POSITION_GRID = 1_000_000;\n\n/**\n * The most Unicode code points in a page key, a source id or an annotation\n * id. Lengths count code points, not UTF-16 units (sdk-core ADR 0045).\n *\n * @public\n */\nexport const PDF_MAX_ID_LENGTH = 128;\n\n/**\n * The most Unicode code points in a form field's name.\n *\n * @public\n */\nexport const PDF_MAX_FIELD_NAME_LENGTH = 1_000;\n\n/**\n * The most Unicode code points in a text note, or a form field's text value.\n *\n * @public\n */\nexport const PDF_MAX_TEXT_LENGTH = 10_000;\n\n/**\n * The most points in one pen or highlighter stroke.\n *\n * @public\n */\nexport const PDF_MAX_STROKE_POINTS = 10_000;\n\n/**\n * A fraction of the page, snapped to {@link PDF_POSITION_GRID}. It rounds\n * with `Math.round`, so a half rounds up, toward positive infinity.\n *\n * @internal\n */\nexport function toGrid(fraction: number): number {\n return Math.round(fraction * PDF_POSITION_GRID) / PDF_POSITION_GRID;\n}\n\n/**\n * Whether text has more than `max` Unicode code points. A character outside\n * the Basic Multilingual Plane, such as an emoji, is one code point, though\n * JavaScript's `length` counts it as two.\n *\n * @internal\n */\nexport function longerThan(text: string, max: number): boolean {\n // Every code point is one or two UTF-16 units.\n if (text.length <= max) return false;\n let count = 0;\n for (const _ of text) {\n count += 1;\n if (count > max) return true;\n }\n return false;\n}\n","import type { Applied, Reducer } from \"@hussmartinez/sdk-core\";\nimport { PdfError } from \"../errors/pdf-error.js\";\nimport type {\n PdfAnnotation,\n PdfColor,\n PdfStrokeAnnotation,\n PdfTextAnnotation,\n} from \"../model/annotations.js\";\nimport type { PdfFieldValue } from \"../model/document.js\";\nimport { addRotation, type PdfPoint } from \"../model/geometry.js\";\nimport type { PdfPlan, PdfPlanPage } from \"../model/plan.js\";\nimport {\n longerThan,\n PDF_MAX_FIELD_NAME_LENGTH,\n PDF_MAX_ID_LENGTH,\n PDF_MAX_STROKE_POINTS,\n PDF_MAX_TEXT_LENGTH,\n toGrid,\n} from \"../model/portable.js\";\n\n/**\n * Rotates pages by an angle, added to their current rotation.\n *\n * @public\n */\nexport interface PdfRotatePagesCommand {\n readonly type: \"pdf.rotatePages\";\n /** The keys of the pages to rotate. */\n readonly pages: readonly string[];\n /**\n * Degrees, clockwise, in multiples of 90 from -360 to 360. Negative turns\n * anticlockwise.\n */\n readonly angle: number;\n}\n\n/**\n * Removes pages from the plan. Their sources stay, so undo can bring them back.\n *\n * @public\n */\nexport interface PdfDeletePagesCommand {\n readonly type: \"pdf.deletePages\";\n readonly pages: readonly string[];\n}\n\n/**\n * Puts deleted pages back at their positions. It's what undoing a delete\n * runs, and it can be used directly.\n *\n * @public\n */\nexport interface PdfRestorePagesCommand {\n readonly type: \"pdf.restorePages\";\n /** Each page, and the index it takes in the resulting plan, in increasing order. */\n readonly entries: readonly { readonly index: number; readonly page: PdfPlanPage }[];\n}\n\n/**\n * Moves pages, keeping their relative order, so that the first of them ends\n * up at position `to` of the resulting plan.\n *\n * @public\n */\nexport interface PdfMovePagesCommand {\n readonly type: \"pdf.movePages\";\n readonly pages: readonly string[];\n /** The zero-based position of the first moved page in the resulting plan. */\n readonly to: number;\n}\n\n/**\n * Puts every page in a new order, given as every key exactly once. It's what\n * undoing a move runs.\n *\n * @public\n */\nexport interface PdfReorderPagesCommand {\n readonly type: \"pdf.reorderPages\";\n readonly order: readonly string[];\n}\n\n/**\n * Inserts pages of a registered source document. The session registers the\n * source and fills in `keys`, so redo inserts the same pages.\n *\n * @public\n */\nexport interface PdfInsertPagesCommand {\n readonly type: \"pdf.insertPages\";\n /** The source's ID. */\n readonly source: string;\n /** Zero-based indexes of the source's pages to insert, in order. */\n readonly pageIndexes: readonly number[];\n /** The zero-based position of the first inserted page in the resulting plan. */\n readonly at: number;\n /** The keys of the new pages, one per index. */\n readonly keys: readonly string[];\n}\n\n/**\n * Sets a form field's value in one source, or clears the session's value with\n * `null`, so the document's own value applies again.\n *\n * @public\n */\nexport interface PdfSetFieldValueCommand {\n readonly type: \"pdf.setFieldValue\";\n readonly source: string;\n readonly field: string;\n readonly value: PdfFieldValue | null;\n}\n\n/**\n * Adds an annotation to a page.\n *\n * @public\n */\nexport interface PdfAddAnnotationCommand {\n readonly type: \"pdf.addAnnotation\";\n /** The page's key. */\n readonly page: string;\n readonly annotation: PdfAnnotation;\n /** Its position among the page's annotations. Defaults to the end. */\n readonly index?: number;\n}\n\n/**\n * Removes an annotation from a page.\n *\n * @public\n */\nexport interface PdfRemoveAnnotationCommand {\n readonly type: \"pdf.removeAnnotation\";\n readonly page: string;\n /** The annotation's ID. */\n readonly id: string;\n}\n\n/**\n * An edit to the page plan (docs/adr/0003). Commands are plain,\n * structured-cloneable data, never carry bytes, and each has an exact\n * inverse, which is how undo works (ADR 0010).\n *\n * @public\n */\nexport type PdfCommand =\n | PdfRotatePagesCommand\n | PdfDeletePagesCommand\n | PdfRestorePagesCommand\n | PdfMovePagesCommand\n | PdfReorderPagesCommand\n | PdfInsertPagesCommand\n | PdfSetFieldValueCommand\n | PdfAddAnnotationCommand\n | PdfRemoveAnnotationCommand;\n\n/**\n * Why a command was refused, as a stable token: `details.reason` on the\n * `INVALID_COMMAND` error (sdk-core ADR 0045).\n *\n * - `malformed-command`: not shaped as a command of its type, such as a\n * missing field, a field of the wrong type, an unknown field, an empty\n * list of pages, or an id that's empty or over `PDF_MAX_ID_LENGTH` code\n * points.\n * - `unknown-command`: a `type` the session doesn't know.\n * - `unknown-page`: a page key the plan doesn't have.\n * - `duplicate-page`: a page named twice in one command.\n * - `last-page`: deleting every page; a document keeps at least one.\n * - `invalid-position`: a position outside the plan, or outside a page's\n * annotations.\n * - `invalid-rotation`: an angle that isn't a multiple of 90 degrees from\n * -360 to 360, or a page rotation other than 0, 90, 180 or 270.\n * - `invalid-order`: a new order that doesn't list every page exactly once.\n * - `invalid-keys`: an insert without one key per page.\n * - `duplicate-key`: a new page key the plan already has, or one given twice.\n * - `unknown-source`: a source the session doesn't hold.\n * - `page-out-of-range`: a page index its source doesn't have.\n * - `field-name-too-long`: a form field's name over\n * `PDF_MAX_FIELD_NAME_LENGTH` code points.\n * - `text-too-long`: a text note, or a field's text value, over\n * `PDF_MAX_TEXT_LENGTH` code points.\n * - `unknown-annotation`: an annotation id the page doesn't have.\n * - `duplicate-annotation`: an annotation id the page already has.\n * - `unsupported-annotation`: an annotation type the session doesn't edit,\n * such as `signature`, whose image the portable format can't carry yet.\n * - `outside-page`: a position outside the page, 0 to 1 on each axis.\n * - `invalid-size`: a stroke width or text size that isn't more than 0 and\n * at most 1, after snapping to `PDF_POSITION_GRID`.\n * - `too-many-points`: a stroke with no points, or over\n * `PDF_MAX_STROKE_POINTS`.\n * - `invalid-color`: a colour that isn't `#rrggbb` in lowercase.\n *\n * @public\n */\nexport type PdfCommandRejection =\n | \"malformed-command\"\n | \"unknown-command\"\n | \"unknown-page\"\n | \"duplicate-page\"\n | \"last-page\"\n | \"invalid-position\"\n | \"invalid-rotation\"\n | \"invalid-order\"\n | \"invalid-keys\"\n | \"duplicate-key\"\n | \"unknown-source\"\n | \"page-out-of-range\"\n | \"field-name-too-long\"\n | \"text-too-long\"\n | \"unknown-annotation\"\n | \"duplicate-annotation\"\n | \"unsupported-annotation\"\n | \"outside-page\"\n | \"invalid-size\"\n | \"too-many-points\"\n | \"invalid-color\";\n\n/**\n * A refusal while checking a command, which the reducer turns into a\n * `PdfError`, and a document reader into its own code.\n *\n * @internal\n */\nexport class Invalid extends Error {\n readonly reason: PdfCommandRejection;\n constructor(reason: PdfCommandRejection, message: string) {\n super(message);\n this.reason = reason;\n }\n}\n\nexport function invalid(reason: PdfCommandRejection, message: string): never {\n throw new Invalid(reason, message);\n}\n\nfunction malformed(message: string): never {\n return invalid(\"malformed-command\", message);\n}\n\n/** Whether a value is a plain object: not `null`, and not a list. @internal */\nexport const isRecord = <T>(value: unknown): value is T =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\n/**\n * Refuses a field the object's type doesn't have, rather than dropping it,\n * and requires the others, except the optional ones.\n *\n * @internal\n */\nexport function fields(\n value: object,\n required: readonly string[],\n what: string,\n optional: readonly string[] = [],\n): void {\n for (const name of Object.keys(value)) {\n if (!required.includes(name) && !optional.includes(name)) {\n malformed(`${what} has no field \"${name}\"`);\n }\n }\n for (const name of required) {\n if (!Object.hasOwn(value, name)) malformed(`${what} needs \"${name}\"`);\n }\n}\n\nconst isIndex = (value: unknown): value is number =>\n Number.isSafeInteger(value) && (value as number) >= 0;\n\n/** A page key, source id or annotation id: 1 to `PDF_MAX_ID_LENGTH` code points. @internal */\nexport function checkId(value: unknown, what: string): string {\n if (typeof value !== \"string\" || value === \"\" || longerThan(value, PDF_MAX_ID_LENGTH)) {\n malformed(`${what} is text of 1 to ${PDF_MAX_ID_LENGTH} code points`);\n }\n return value;\n}\n\nfunction checkKeys(value: unknown, what: string): string[] {\n if (!Array.isArray(value) || value.length === 0) malformed(`${what} is a list of page keys`);\n return value.map((key) => checkId(key, \"a page key\"));\n}\n\n/** A number from 0 to 1, a position on the page, snapped to the grid. */\nfunction checkFraction(value: unknown, what: string): number {\n if (typeof value !== \"number\" || !Number.isFinite(value)) malformed(`${what} is a number`);\n if (value < 0 || value > 1) invalid(\"outside-page\", `${what} is from 0 to 1`);\n return toGrid(value);\n}\n\n/** A size, more than 0 and at most 1, snapped to the grid. */\nfunction checkSize(value: unknown, what: string): number {\n if (typeof value !== \"number\" || !Number.isFinite(value)) malformed(`${what} is a number`);\n const size = toGrid(value);\n if (!(size > 0 && size <= 1)) invalid(\"invalid-size\", `${what} is more than 0 and at most 1`);\n return size;\n}\n\nfunction checkPoint(value: unknown, what: string): PdfPoint {\n if (!isRecord<PdfPoint>(value)) malformed(`${what} is an object`);\n fields(value, [\"x\", \"y\"], what);\n return { x: checkFraction(value.x, `${what}.x`), y: checkFraction(value.y, `${what}.y`) };\n}\n\nconst COLOR = /^#[0-9a-f]{6}$/;\n\nfunction checkColor(value: unknown): PdfColor {\n if (typeof value !== \"string\") malformed(\"a colour is text\");\n if (!COLOR.test(value)) invalid(\"invalid-color\", \"a colour is #rrggbb, in lowercase\");\n return value as PdfColor;\n}\n\nfunction checkText(value: unknown, what: string): string {\n if (typeof value !== \"string\") malformed(`${what} is text`);\n if (longerThan(value, PDF_MAX_TEXT_LENGTH)) {\n invalid(\"text-too-long\", `${what} has more than ${PDF_MAX_TEXT_LENGTH} code points`);\n }\n return value;\n}\n\n/**\n * An annotation, checked and copied, with its positions and sizes snapped\n * to the grid. Signatures are refused: the portable format can't carry\n * their image yet (docs/adr/0003).\n *\n * @internal\n */\nexport function checkAnnotation(value: unknown): PdfAnnotation {\n if (!isRecord<{ type: unknown }>(value)) malformed(\"an annotation is an object\");\n const { type } = value;\n if (type === \"signature\") {\n invalid(\"unsupported-annotation\", \"signature annotations can't be edited yet\");\n }\n if (type === \"pen\" || type === \"highlight\") {\n const stroke = value as PdfStrokeAnnotation;\n fields(stroke, [\"id\", \"type\", \"points\", \"color\", \"width\"], \"a stroke\");\n if (!Array.isArray(stroke.points)) malformed(\"a stroke's points are a list\");\n if (stroke.points.length === 0 || stroke.points.length > PDF_MAX_STROKE_POINTS) {\n invalid(\"too-many-points\", `a stroke has 1 to ${PDF_MAX_STROKE_POINTS} points`);\n }\n return {\n id: checkId(stroke.id, \"an annotation id\"),\n type,\n points: stroke.points.map((point) => checkPoint(point, \"a point\")),\n color: checkColor(stroke.color),\n width: checkSize(stroke.width, \"a stroke's width\"),\n };\n }\n if (type === \"text\") {\n const note = value as PdfTextAnnotation;\n fields(note, [\"id\", \"type\", \"at\", \"text\", \"size\", \"color\"], \"a text note\");\n return {\n id: checkId(note.id, \"an annotation id\"),\n type,\n at: checkPoint(note.at, \"a text note's position\"),\n text: checkText(note.text, \"a text note\"),\n size: checkSize(note.size, \"a text size\"),\n color: checkColor(note.color),\n };\n }\n return malformed(\"an annotation is a pen, highlight or text annotation\");\n}\n\n/** Looks up how many pages a source has, or `undefined` for one the session doesn't hold. */\nexport type PdfSourcePageCount = (source: string) => number | undefined;\n\nfunction checkPageOf(source: string, pageIndex: number, pageCount: PdfSourcePageCount): void {\n const count = pageCount(source);\n if (count === undefined) invalid(\"unknown-source\", `the session has no source ${source}`);\n if (pageIndex >= count) {\n invalid(\"page-out-of-range\", `source ${source} has no page index ${pageIndex}`);\n }\n}\n\nconst ROTATIONS: readonly number[] = [0, 90, 180, 270];\n/** The angles a rotation command takes: a whole list, so a schema's `enum` can match it exactly. */\nconst ANGLES: readonly number[] = [-360, -270, -180, -90, 0, 90, 180, 270, 360];\n\n/** A whole plan page, as `pdf.restorePages` carries it. @internal */\nexport function checkPage(value: unknown, pageCount: PdfSourcePageCount): PdfPlanPage {\n if (!isRecord<PdfPlanPage>(value)) malformed(\"a page is an object\");\n fields(value, [\"key\", \"source\", \"pageIndex\", \"rotation\", \"annotations\"], \"a page\");\n const key = checkId(value.key, \"a page key\");\n const source = checkId(value.source, \"a source id\");\n if (!isIndex(value.pageIndex)) malformed(\"a page index is a whole number from 0\");\n if (!ROTATIONS.includes(value.rotation)) {\n invalid(\"invalid-rotation\", \"a page's rotation is 0, 90, 180 or 270\");\n }\n if (!Array.isArray(value.annotations)) malformed(\"a page's annotations are a list\");\n checkPageOf(source, value.pageIndex, pageCount);\n const annotations = value.annotations.map(checkAnnotation);\n if (new Set(annotations.map(({ id }) => id)).size !== annotations.length) {\n invalid(\"duplicate-annotation\", `page ${key} has two annotations with one id`);\n }\n return { key, source, pageIndex: value.pageIndex, rotation: value.rotation, annotations };\n}\n\n/** The positions of the given keys, in plan order, failing on unknown or repeated keys. */\nfunction positions(plan: PdfPlan, keys: readonly string[]): number[] {\n const wanted = new Set(keys);\n if (wanted.size !== keys.length) invalid(\"duplicate-page\", \"a page appears twice\");\n const found = plan.pages.flatMap((page, index) => (wanted.has(page.key) ? [index] : []));\n if (found.length !== wanted.size) {\n const known = new Set(plan.pages.map((page) => page.key));\n const missing = keys.filter((key) => !known.has(key));\n invalid(\"unknown-page\", `the plan has no page ${missing.join(\", \")}`);\n }\n return found;\n}\n\nfunction withPages(plan: PdfPlan, pages: readonly PdfPlanPage[]): PdfPlan {\n return { pages, formValues: plan.formValues };\n}\n\n/**\n * A record with one key set or removed. Keys are data: `__proto__` is an\n * ordinary own key, never the prototype (sdk-core ADR 0045, section 8).\n */\nfunction withKey<V>(\n record: Readonly<Record<string, V>>,\n key: string,\n value: V | undefined,\n): Record<string, V> {\n const entries = Object.entries(record).filter(([name]) => name !== key);\n if (value !== undefined) entries.push([key, value]);\n return Object.fromEntries(entries) as Record<string, V>;\n}\n\n/** Each command's fields: required, and optional. */\nconst COMMAND_FIELDS: Readonly<\n Record<PdfCommand[\"type\"], readonly [readonly string[], readonly string[]]>\n> = {\n \"pdf.rotatePages\": [[\"type\", \"pages\", \"angle\"], []],\n \"pdf.deletePages\": [[\"type\", \"pages\"], []],\n \"pdf.restorePages\": [[\"type\", \"entries\"], []],\n \"pdf.movePages\": [[\"type\", \"pages\", \"to\"], []],\n \"pdf.reorderPages\": [[\"type\", \"order\"], []],\n \"pdf.insertPages\": [[\"type\", \"source\", \"pageIndexes\", \"at\", \"keys\"], []],\n \"pdf.setFieldValue\": [[\"type\", \"source\", \"field\", \"value\"], []],\n \"pdf.addAnnotation\": [[\"type\", \"page\", \"annotation\"], [\"index\"]],\n \"pdf.removeAnnotation\": [[\"type\", \"page\", \"id\"], []],\n};\n\nfunction apply(\n plan: PdfPlan,\n input: unknown,\n pageCount: PdfSourcePageCount,\n): Applied<PdfPlan, PdfCommand> {\n if (!isRecord<{ type: unknown }>(input)) malformed(\"a command is an object\");\n const { type } = input;\n if (typeof type !== \"string\") malformed(\"a command's type is text\");\n if (!Object.hasOwn(COMMAND_FIELDS, type)) invalid(\"unknown-command\", `\"${type}\" isn't a command`);\n const command = input as PdfCommand;\n const [required, optional] = COMMAND_FIELDS[command.type];\n fields(command, required, command.type, optional);\n\n switch (command.type) {\n case \"pdf.rotatePages\": {\n const pages = checkKeys(command.pages, \"pages\");\n const { angle } = command;\n if (typeof angle !== \"number\") malformed(\"an angle is a number\");\n if (!ANGLES.includes(angle)) {\n invalid(\"invalid-rotation\", \"an angle is a multiple of 90 degrees, from -360 to 360\");\n }\n const at = new Set(positions(plan, pages));\n return {\n state: withPages(\n plan,\n plan.pages.map((page, index) =>\n at.has(index) ? { ...page, rotation: addRotation(page.rotation, angle) } : page,\n ),\n ),\n // `0 - angle`, not `-angle`: an angle of 0 must not undo as -0.\n inverse: { type: \"pdf.rotatePages\", pages, angle: 0 - angle },\n };\n }\n\n case \"pdf.deletePages\": {\n const at = positions(plan, checkKeys(command.pages, \"pages\"));\n if (at.length === plan.pages.length) invalid(\"last-page\", \"a document keeps one page\");\n const removed = new Set(at);\n return {\n state: withPages(\n plan,\n plan.pages.filter((_, index) => !removed.has(index)),\n ),\n inverse: {\n type: \"pdf.restorePages\",\n entries: at.map((index) => ({ index, page: plan.pages[index] as PdfPlanPage })),\n },\n };\n }\n\n case \"pdf.restorePages\": {\n if (!Array.isArray(command.entries) || command.entries.length === 0) {\n malformed(\"entries is a list of pages and their positions\");\n }\n const known = new Set(plan.pages.map((page) => page.key));\n const pages = [...plan.pages];\n let previous = -1;\n for (const entry of command.entries as unknown[]) {\n if (!isRecord<{ index: unknown; page: unknown }>(entry)) malformed(\"an entry is an object\");\n fields(entry, [\"index\", \"page\"], \"an entry\");\n const page = checkPage(entry.page, pageCount);\n const { index } = entry;\n if (!isIndex(index)) malformed(\"an entry's index is a whole number from 0\");\n if (known.has(page.key)) invalid(\"duplicate-key\", `the plan already has page ${page.key}`);\n if (index <= previous || index > pages.length) {\n invalid(\"invalid-position\", `page ${page.key} can't be restored at ${index}`);\n }\n pages.splice(index, 0, page);\n known.add(page.key);\n previous = index;\n }\n return {\n state: withPages(plan, pages),\n inverse: {\n type: \"pdf.deletePages\",\n pages: command.entries.map(({ page }) => page.key),\n },\n };\n }\n\n case \"pdf.movePages\": {\n const keys = checkKeys(command.pages, \"pages\");\n if (!isIndex(command.to)) malformed(\"to is a whole number from 0\");\n const moved = new Set(positions(plan, keys));\n const block = plan.pages.filter((_, index) => moved.has(index));\n const rest = plan.pages.filter((_, index) => !moved.has(index));\n if (command.to > rest.length) {\n invalid(\"invalid-position\", `pages can't be moved to ${command.to}`);\n }\n return {\n state: withPages(plan, [...rest.slice(0, command.to), ...block, ...rest.slice(command.to)]),\n inverse: { type: \"pdf.reorderPages\", order: plan.pages.map((page) => page.key) },\n };\n }\n\n case \"pdf.reorderPages\": {\n const order = checkKeys(command.order, \"order\");\n const byKey = new Map(plan.pages.map((page) => [page.key, page]));\n if (\n order.length !== plan.pages.length ||\n new Set(order).size !== order.length ||\n order.some((key) => !byKey.has(key))\n ) {\n invalid(\"invalid-order\", \"a new order lists every page of the plan exactly once\");\n }\n return {\n state: withPages(\n plan,\n order.map((key) => byKey.get(key) as PdfPlanPage),\n ),\n inverse: { type: \"pdf.reorderPages\", order: plan.pages.map((page) => page.key) },\n };\n }\n\n case \"pdf.insertPages\": {\n const source = checkId(command.source, \"a source id\");\n const { pageIndexes, at } = command;\n if (!Array.isArray(pageIndexes) || pageIndexes.length === 0 || !pageIndexes.every(isIndex)) {\n malformed(\"pageIndexes is a list of whole numbers from 0\");\n }\n const keys = checkKeys(command.keys, \"keys\");\n if (!isIndex(at)) malformed(\"at is a whole number from 0\");\n if (keys.length !== pageIndexes.length)\n invalid(\"invalid-keys\", \"an insert needs one key per page\");\n const known = new Set(plan.pages.map((page) => page.key));\n if (new Set(keys).size !== keys.length || keys.some((key) => known.has(key))) {\n invalid(\"duplicate-key\", \"inserted pages need new keys, each once\");\n }\n if (at > plan.pages.length) invalid(\"invalid-position\", `pages can't be inserted at ${at}`);\n for (const pageIndex of pageIndexes) checkPageOf(source, pageIndex, pageCount);\n const inserted = pageIndexes.map(\n (pageIndex, index): PdfPlanPage => ({\n key: keys[index] as string,\n source,\n pageIndex,\n rotation: 0,\n annotations: [],\n }),\n );\n return {\n state: withPages(plan, [...plan.pages.slice(0, at), ...inserted, ...plan.pages.slice(at)]),\n inverse: { type: \"pdf.deletePages\", pages: keys },\n };\n }\n\n case \"pdf.setFieldValue\": {\n const source = checkId(command.source, \"a source id\");\n const { field, value } = command;\n if (typeof field !== \"string\" || field === \"\") malformed(\"a field's name is text\");\n if (longerThan(field, PDF_MAX_FIELD_NAME_LENGTH)) {\n invalid(\n \"field-name-too-long\",\n `a field's name has at most ${PDF_MAX_FIELD_NAME_LENGTH} code points`,\n );\n }\n if (value !== null && typeof value !== \"boolean\") checkText(value, \"a field's value\");\n if (pageCount(source) === undefined) {\n invalid(\"unknown-source\", `the session has no source ${source}`);\n }\n const current = Object.hasOwn(plan.formValues, source)\n ? (plan.formValues[source] as Readonly<Record<string, PdfFieldValue>>)\n : {};\n const previous = Object.hasOwn(current, field) ? (current[field] as PdfFieldValue) : null;\n const next = withKey(current, field, value ?? undefined);\n const formValues = withKey(\n plan.formValues,\n source,\n Object.keys(next).length === 0 ? undefined : next,\n );\n return {\n state: { pages: plan.pages, formValues },\n inverse: { type: \"pdf.setFieldValue\", source, field, value: previous },\n };\n }\n\n case \"pdf.addAnnotation\": {\n const key = checkId(command.page, \"a page key\");\n const annotation = checkAnnotation(command.annotation);\n if (command.index !== undefined && !isIndex(command.index)) {\n malformed(\"an annotation's index is a whole number from 0\");\n }\n const [at] = positions(plan, [key]) as [number];\n const page = plan.pages[at] as PdfPlanPage;\n if (page.annotations.some((existing) => existing.id === annotation.id)) {\n invalid(\"duplicate-annotation\", `page ${key} already has annotation ${annotation.id}`);\n }\n const index = command.index ?? page.annotations.length;\n if (index > page.annotations.length) {\n invalid(\"invalid-position\", `the annotation can't go at ${index}`);\n }\n const annotations = [...page.annotations];\n annotations.splice(index, 0, annotation);\n const pages = [...plan.pages];\n pages[at] = { ...page, annotations };\n return {\n state: withPages(plan, pages),\n inverse: { type: \"pdf.removeAnnotation\", page: key, id: annotation.id },\n };\n }\n\n case \"pdf.removeAnnotation\": {\n const key = checkId(command.page, \"a page key\");\n const id = checkId(command.id, \"an annotation id\");\n const [at] = positions(plan, [key]) as [number];\n const page = plan.pages[at] as PdfPlanPage;\n const index = page.annotations.findIndex((annotation) => annotation.id === id);\n if (index < 0) invalid(\"unknown-annotation\", `page ${key} has no annotation ${id}`);\n const pages = [...plan.pages];\n pages[at] = { ...page, annotations: page.annotations.filter((_, place) => place !== index) };\n return {\n state: withPages(plan, pages),\n inverse: {\n type: \"pdf.addAnnotation\",\n page: key,\n annotation: page.annotations[index] as PdfAnnotation,\n index,\n },\n };\n }\n }\n}\n\n/**\n * Creates the session's reducer: a pure function that applies one command\n * to a plan, without changing it, and returns the new plan with the\n * command's inverse (docs/adr/0003, ADR 0029 in sdk-core). It needs each\n * source's page count, to check the pages a command names.\n *\n * Commands are strict, as the portable format is (sdk-core ADR 0045): an\n * invalid command, including one with a field its type doesn't have,\n * throws `PdfError` with `INVALID_COMMAND` and a {@link PdfCommandRejection}\n * as `details.reason`, and changes nothing. Positions and sizes are snapped\n * to millionths of the page (`PDF_POSITION_GRID`), so the plan only ever\n * holds values on the grid.\n *\n * @internal\n */\nexport function createPdfReducer(pageCount: PdfSourcePageCount): Reducer<PdfPlan, PdfCommand> {\n return (plan, command) => {\n try {\n return apply(plan, command, pageCount);\n } catch (error) {\n if (!(error instanceof Invalid)) throw error;\n throw new PdfError(\"INVALID_COMMAND\", `Invalid command: ${error.message}.`, {\n details: { reason: error.reason },\n });\n }\n };\n}\n","import type { PdfAnnotation } from \"./annotations.js\";\nimport type { PdfFieldValue } from \"./document.js\";\nimport type { PdfRotation } from \"./geometry.js\";\n\n/**\n * One page of the page plan (docs/adr/0003): a page of a source document,\n * with a rotation added to its own, and the annotations drawn on it. The key\n * is stable while the page moves, so annotations, thumbnails and the\n * selection follow it.\n *\n * @public\n */\nexport interface PdfPlanPage {\n /** Unique within the session, and never reused. */\n readonly key: string;\n /** The ID of the source document the page comes from. */\n readonly source: string;\n /** The page's zero-based index in its source. */\n readonly pageIndex: number;\n /** Rotation added to the page's own `/Rotate`. */\n readonly rotation: PdfRotation;\n /** Annotations drawn on the page, in drawing order. */\n readonly annotations: readonly PdfAnnotation[];\n}\n\n/**\n * The document being edited, as a plan over immutable sources\n * (docs/adr/0003): the pages in order, and form values per source. Bytes\n * are only built from it on export.\n *\n * @public\n */\nexport interface PdfPlan {\n readonly pages: readonly PdfPlanPage[];\n /** Form values set in the session, by source ID, then field name. */\n readonly formValues: Readonly<Record<string, Readonly<Record<string, PdfFieldValue>>>>;\n}\n\n/** An empty plan. @internal */\nexport const EMPTY_PLAN: PdfPlan = Object.freeze({\n pages: Object.freeze([]),\n formValues: Object.freeze({}),\n});\n","/** The longest name kept, in code points (docs/adr/0009). */\nexport const MAX_NAME_LENGTH = 128;\n\n/** Control characters (Unicode category Cc: C0, DEL and C1). */\nconst CONTROL = /\\p{Cc}/gu;\n/** Bidirectional formatting characters, which can disguise an extension. */\nconst BIDI = /[\\u061C\\u200E\\u200F\\u202A-\\u202E\\u2066-\\u2069]/gu;\n/** Characters Windows refuses in file names. Separators are handled first. */\nconst REFUSED = /[<>:\"|?*]/gu;\n\n/**\n * Cleans a file name chosen by whoever made the file, which is hostile input\n * (docs/adr/0009). The result is safe as text content and as a download's\n * name: one path segment, with no control or bidirectional formatting\n * characters, no characters Windows refuses, no leading dots and at most\n * {@link MAX_NAME_LENGTH} code points. Returns `undefined` when nothing is\n * left, or for anything that isn't a string.\n */\nexport function cleanFileName(raw: unknown): string | undefined {\n if (typeof raw !== \"string\") return undefined;\n let name = raw.replace(CONTROL, \"\").replace(BIDI, \"\");\n name = name.slice(Math.max(name.lastIndexOf(\"/\"), name.lastIndexOf(\"\\\\\")) + 1);\n // Normalised after the removals, which could leave a base letter and its\n // combining mark side by side.\n name = name.replace(REFUSED, \"\").normalize(\"NFC\");\n // Leading dots would hide the file on some systems, or leave only an\n // extension; whitespace at either end is never meant.\n name = name.replace(/^[\\s.]+/u, \"\").trimEnd();\n // Array.from splits by code points, so no surrogate pair is cut in half.\n const points = Array.from(name);\n if (points.length > MAX_NAME_LENGTH) {\n name = points.slice(0, MAX_NAME_LENGTH).join(\"\").trimEnd();\n }\n return name === \"\" ? undefined : name;\n}\n","import {\n applyCommands,\n checkFile,\n createHistory,\n createStore,\n type HistoryStep,\n withProcessingTime,\n} from \"@hussmartinez/sdk-core\";\nimport { asPdfError, throwIfAborted } from \"../errors/abort.js\";\nimport { isPdfError, PdfError } from \"../errors/pdf-error.js\";\nimport { type PdfFilePolicyOverrides, type PdfLimitName, pdfLimits } from \"../errors/pdf-limits.js\";\nimport type { PdfBuildJob, PdfCompression, PdfEncryption } from \"../model/build-job.js\";\nimport { copyBytes } from \"../model/bytes.js\";\nimport type {\n PdfBytes,\n PdfFormField,\n PdfLink,\n PdfPageInfo,\n PdfTextContent,\n} from \"../model/document.js\";\nimport { addRotation } from \"../model/geometry.js\";\nimport { EMPTY_PLAN, type PdfPlan, type PdfPlanPage } from \"../model/plan.js\";\nimport { createPdfReducer, type PdfCommand } from \"../operations/commands.js\";\nimport type { PdfCallOptions } from \"../ports/options.js\";\nimport type { PdfDocumentHandle, PdfEngine, PdfRenderOptions } from \"../ports/pdf-engine.js\";\nimport type { PdfBuildOptions, PdfProcessor } from \"../ports/pdf-processor.js\";\nimport { cleanFileName } from \"./source-name.js\";\n\n/**\n * A source document the session holds: opened or inserted, never changed.\n *\n * @public\n */\nexport interface PdfSourceInfo {\n /** Unique within the session, and never reused. */\n readonly id: string;\n readonly pageCount: number;\n /** The size of its bytes. */\n readonly byteLength: number;\n /**\n * The file's name, from `File.name` or the `name` option, cleaned as\n * docs/adr/0009 describes: one path segment, without control or\n * bidirectional formatting characters, at most 128 code points. Absent\n * when there was none. Show it only as text; it never reaches `onEvent`.\n */\n readonly name?: string;\n}\n\n/**\n * A file policy warning: a value at or above a limit's warning threshold,\n * but within its maximum (ADR 0020). Show its text from\n * `warnings.<limit>` in the message catalogue, with `actual` as a parameter.\n *\n * @public\n */\nexport interface PdfWarning {\n readonly limit: PdfLimitName;\n readonly actual: number;\n}\n\n/**\n * What the session is doing.\n *\n * - `empty`: no document is open.\n * - `opening`: a document is being opened, replacing any other.\n * - `ready`: a document is open.\n * - `error`: no document is open, because the last open failed; `error`\n * says why. A failed open while a document is open keeps that document,\n * with the status `ready` and `error` set.\n *\n * @public\n */\nexport type PdfSessionStatus = \"empty\" | \"opening\" | \"ready\" | \"error\";\n\n/**\n * The session's state at one moment. Snapshots are immutable: every change\n * makes a new one, so `useSyncExternalStore` and other subscribers can\n * compare them by identity.\n *\n * @public\n */\nexport interface PdfSessionSnapshot {\n readonly status: PdfSessionStatus;\n /** The document being edited: its pages, in order, and form values. */\n readonly plan: PdfPlan;\n /** The source documents the session holds. */\n readonly sources: readonly PdfSourceInfo[];\n readonly canUndo: boolean;\n readonly canRedo: boolean;\n /** Whether a document is being opened or inserted. */\n readonly busy: boolean;\n /** Why the last open or insert failed. Show its text by its code. */\n readonly error: PdfError | undefined;\n /** Limits the open documents are close to. */\n readonly warnings: readonly PdfWarning[];\n /**\n * The bytes of every document the session holds, which the\n * `maxSessionSize` limit counts: those the plan uses, and those the undo\n * and redo history can bring back (docs/adr/0004).\n */\n readonly sessionBytes: number;\n /**\n * Whether undo steps were dropped since the document opened, to make room\n * for an insert within `maxSessionSize`. Editors say so, because the\n * earliest edits can no longer be undone (ADR 0010).\n */\n readonly historyTrimmed: boolean;\n /**\n * The keys of the selected pages, in plan order. Tools act on them, such as\n * rotating the selection. View state: not part of the plan and never in\n * events, but undo and redo bring back the selection and current page\n * that went with each step (docs/adr/0008).\n */\n readonly selection: readonly string[];\n /** The key of the page the user is looking at, if a document is open. */\n readonly currentPage: string | undefined;\n /**\n * The latest request to bring a page into view, from `goToPage`. Viewers\n * scroll to `page` each time `sequence` changes.\n */\n readonly navigation: { readonly page: string; readonly sequence: number } | undefined;\n}\n\n/**\n * Anonymous usage events, for a host's analytics (ADR 0010). They never\n * contain file names, contents, form values or annotation text.\n *\n * @public\n */\nexport type PdfSessionEvent =\n | { readonly type: \"document_opened\"; readonly pageCount: number }\n | { readonly type: \"document_closed\" }\n | { readonly type: \"pages_inserted\"; readonly pageCount: number }\n | { readonly type: \"command\"; readonly commands: readonly PdfCommand[\"type\"][] }\n | { readonly type: \"undo\" }\n | { readonly type: \"redo\" }\n | {\n readonly type: \"document_exported\";\n readonly pageCount: number;\n readonly compressed: boolean;\n readonly encrypted: boolean;\n }\n | {\n readonly type: \"failed\";\n readonly operation: \"open\" | \"insert\" | \"export\";\n readonly code: string;\n };\n\n/**\n * Options for {@link createPdfSession}.\n *\n * @public\n */\nexport interface PdfSessionOptions {\n /** Opens, reads and renders documents, such as `createPdfJsEngine()`. */\n readonly engine: PdfEngine;\n /** Builds exported documents, such as `createPdfProcessor()`. Needed for `export()`. */\n readonly processor?: PdfProcessor;\n /** Limits for untrusted files (docs/adr/0004). Unknown names throw. */\n readonly filePolicy?: PdfFilePolicyOverrides;\n /** Receives anonymous usage events. Errors it throws are ignored. */\n readonly onEvent?: (event: PdfSessionEvent) => void;\n}\n\n/**\n * Options for {@link PdfSession.open}.\n *\n * @public\n */\nexport interface PdfOpenOptions extends PdfCallOptions {\n /**\n * The file's name, for bytes or a `Blob` that isn't a `File`. It wins over\n * `File.name`, and is cleaned before it's kept (docs/adr/0009).\n */\n readonly name?: string;\n}\n\n/**\n * Options for {@link PdfSession.insert}.\n *\n * @public\n */\nexport interface PdfInsertOptions extends PdfOpenOptions {\n /** The position of the first inserted page. Defaults to the end. */\n readonly at?: number;\n /** Zero-based indexes of the pages to insert. Defaults to every page. */\n readonly pageIndexes?: readonly number[];\n}\n\n/**\n * Options for {@link PdfSession.export}.\n *\n * @public\n */\nexport interface PdfExportOptions extends PdfCallOptions {\n /** Compress the result, losslessly unless `images` is set. */\n readonly compress?: PdfCompression;\n /** Encrypt the result with AES-256. */\n readonly encrypt?: PdfEncryption;\n /** Called as the export moves through its steps. */\n readonly onProgress?: PdfBuildOptions[\"onProgress\"];\n}\n\n/**\n * The document being edited, as a framework-agnostic store (ADR 0008): a\n * page plan over the documents opened and inserted, edited with commands,\n * with undo and redo (ADR 0010, docs/adr/0003). React binds to it with\n * `useSyncExternalStore`, and the element binds to the same store.\n *\n * @public\n */\nexport interface PdfSession {\n /** The current snapshot, the same object until something changes. */\n getSnapshot(): PdfSessionSnapshot;\n /** Calls the listener after every change. Returns a function that unsubscribes. */\n subscribe(listener: () => void): () => void;\n /**\n * Opens a document, replacing the current one and its history once it has\n * opened. The file is checked against the file policy before it's read.\n * Rejects with a `PdfError`, which the snapshot also holds; the current\n * document, if any, stays open.\n */\n open(file: Blob | PdfBytes, options?: PdfOpenOptions): Promise<void>;\n /**\n * Inserts the pages of another document, as one undoable step. If the\n * documents held would then exceed `maxSessionSize`, the session first\n * drops the redo steps, then the oldest undo steps, as far as needed to\n * release documents only they refer to, and sets `historyTrimmed`. If even\n * that isn't enough, it rejects with `SESSION_TOO_LARGE` and changes\n * nothing.\n */\n insert(file: Blob | PdfBytes, options?: PdfInsertOptions): Promise<void>;\n /**\n * Runs one command, or several as one undoable step. Throws `PdfError`\n * with `INVALID_COMMAND` for a command that doesn't fit the plan, with a\n * `PdfCommandRejection` as `details.reason`, and changes nothing then.\n * Positions and sizes are snapped to millionths of the page\n * (`PDF_POSITION_GRID`).\n */\n execute(commands: PdfCommand | readonly PdfCommand[]): void;\n undo(): void;\n redo(): void;\n /** A plan page's size, and its rotation as shown: its own plus the plan's. */\n getPage(key: string, options?: PdfCallOptions): Promise<PdfPageInfo>;\n /** Renders a plan page with its rotation. */\n renderPage(\n key: string,\n canvas: HTMLCanvasElement,\n options: Omit<PdfRenderOptions, \"rotation\">,\n ): Promise<void>;\n /** A plan page's text, positioned on the unrotated page. */\n getTextContent(key: string, options?: PdfCallOptions): Promise<PdfTextContent>;\n /** A plan page's form fields, with the session's values applied. */\n getFormFields(key: string, options?: PdfCallOptions): Promise<readonly PdfFormField[]>;\n /** A plan page's web and email links, positioned on the unrotated page. */\n getLinks(key: string, options?: PdfCallOptions): Promise<readonly PdfLink[]>;\n /**\n * Builds the document as it is now: its pages in plan order, with their\n * rotations, form values and annotations, compressed or encrypted if asked.\n * An unchanged document with no options is returned as its original bytes,\n * without the processor. The result is a new buffer the caller owns.\n */\n export(options?: PdfExportOptions): Promise<Uint8Array>;\n /**\n * Selects pages, by key, replacing the selection. Keys the plan doesn't\n * have are ignored.\n */\n select(keys: readonly string[]): void;\n /** Records the page the user is looking at, as a viewer scrolls. */\n setCurrentPage(key: string): void;\n /** Makes a page current and asks viewers to bring it into view. */\n goToPage(key: string): void;\n /** Closes the document and releases its sources. */\n close(): Promise<void>;\n}\n\n/** The view state kept beside a history step (docs/adr/0008). */\ninterface View {\n readonly selection: readonly string[];\n readonly currentPage: string | undefined;\n}\n\ninterface Source extends PdfSourceInfo {\n readonly bytes: Uint8Array;\n readonly document: PdfDocumentHandle;\n}\n\n/**\n * Creates a {@link PdfSession}. Pass the engine to use; the headless core\n * doesn't choose one, so it can't pull pdf.js into applications that don't\n * want it.\n *\n * @example\n * ```ts\n * const session = createPdfSession({ engine: createPdfJsEngine() });\n * await session.open(file);\n * const [first] = session.getSnapshot().plan.pages;\n * session.execute({ type: \"pdf.rotatePages\", pages: [first.key], angle: 90 });\n * session.undo();\n * ```\n *\n * @public\n */\nexport function createPdfSession(options: PdfSessionOptions): PdfSession {\n const { engine } = options;\n const policy = pdfLimits.resolve(options.filePolicy);\n // Undo and redo stacks of command steps, which the memory policy below\n // trims (ADR 0010 and ADR 0029 in sdk-core, docs/adr/0004).\n const history = createHistory<PdfCommand>();\n /**\n * The view before each step, and the view when it was last undone, by the\n * history's own step object. Steps the history drops are released with it.\n */\n const views = new WeakMap<HistoryStep<PdfCommand>, { readonly before: View; after?: View }>();\n const sources = new Map<string, Source>();\n // Checks commands against the sources the session holds (sdk-core ADR 0045).\n const reduce = createPdfReducer((id) => sources.get(id)?.pageCount);\n let plan: PdfPlan = EMPTY_PLAN;\n let status: PdfSessionStatus = \"empty\";\n let error: PdfError | undefined;\n let warnings: PdfWarning[] = [];\n let busy = 0;\n let selection: readonly string[] = [];\n let currentPage: string | undefined;\n let navigation: { page: string; sequence: number } | undefined;\n let nextKey = 0;\n let nextSource = 0;\n /** Cancels the load in progress when a newer open replaces it. */\n let loading: AbortController | undefined;\n const heldBytes = (): number =>\n [...sources.values()].reduce((total, source) => total + source.byteLength, 0);\n\n /** The sources the plan and the given history steps refer to: only pages need bytes. */\n function referenced(steps: readonly HistoryStep<PdfCommand>[]): Set<string> {\n const ids = new Set(plan.pages.map((page) => page.source));\n for (const { commands, inverses } of steps) {\n for (const command of [...commands, ...inverses]) {\n if (command.type === \"pdf.insertPages\") ids.add(command.source);\n if (command.type === \"pdf.restorePages\") {\n for (const { page } of command.entries) ids.add(page.source);\n }\n }\n }\n return ids;\n }\n\n /** Releases the sources nothing refers to any more, and their engine documents. */\n function collect(): void {\n const keep = referenced(history.steps);\n for (const [id, source] of sources) {\n if (keep.has(id)) continue;\n sources.delete(id);\n void source.document.destroy().catch(() => {});\n }\n }\n\n /**\n * How many history steps must be dropped, in drop order, for the held\n * sources plus `extra` bytes to fit `maxSessionSize`, or undefined if\n * dropping every step isn't enough.\n */\n function stepsToDrop(extra: number): number | undefined {\n const { maximum } = policy.limits.maxSessionSize;\n const order = history.dropOrder;\n for (let count = 0; count <= order.length; count += 1) {\n const kept = new Set(order.slice(count));\n const ids = referenced(history.steps.filter((entry) => kept.has(entry)));\n const total = [...ids].reduce((sum, id) => sum + (sources.get(id)?.byteLength ?? 0), 0);\n if (total + extra <= maximum) return count;\n }\n return undefined;\n }\n\n // Each change makes a new frozen snapshot (ADR 0029 in sdk-core).\n const store = createStore(makeSnapshot());\n\n /** The load warnings, and the session size warning, which follows every change. */\n function sessionWarnings(): PdfWarning[] {\n const bytes = heldBytes();\n const sessionWarning =\n bytes > 0 && bytes >= policy.limits.maxSessionSize.warning\n ? [{ limit: \"maxSessionSize\" as const, actual: bytes }]\n : [];\n return [...warnings, ...sessionWarning];\n }\n\n function makeSnapshot(): PdfSessionSnapshot {\n return Object.freeze({\n status,\n plan,\n sources: Object.freeze(\n [...sources.values()].map(({ id, pageCount, byteLength, name }) =>\n Object.freeze({ id, pageCount, byteLength, ...(name === undefined ? {} : { name }) }),\n ),\n ),\n canUndo: history.canUndo,\n canRedo: history.canRedo,\n busy: busy > 0,\n error,\n warnings: Object.freeze(sessionWarnings()),\n sessionBytes: heldBytes(),\n historyTrimmed: history.trimmed,\n selection: Object.freeze([...selection]),\n currentPage,\n navigation: navigation ? Object.freeze({ ...navigation }) : undefined,\n });\n }\n\n function changed(): void {\n // View state follows the plan: pages that left it can't be selected or current.\n const keys = new Set(plan.pages.map((page) => page.key));\n if (selection.some((key) => !keys.has(key))) {\n selection = selection.filter((key) => keys.has(key));\n }\n if (currentPage !== undefined && !keys.has(currentPage)) {\n currentPage = plan.pages[0]?.key;\n }\n if (currentPage === undefined && plan.pages.length > 0) currentPage = plan.pages[0]?.key;\n if (navigation && !keys.has(navigation.page)) navigation = undefined;\n store.set(makeSnapshot());\n }\n\n function emit(event: PdfSessionEvent): void {\n try {\n options.onEvent?.(event);\n } catch {\n // A host's analytics must never break editing.\n }\n }\n\n /** Reads, checks and opens one file as a source, without registering it. */\n async function load(\n file: Blob | PdfBytes,\n signal: AbortSignal,\n given: string | undefined,\n ): Promise<Source> {\n // File isn't a global in every runtime the core supports (ADR 0007 in sdk-core).\n const fileName = typeof File !== \"undefined\" && file instanceof File ? file.name : undefined;\n const name = cleanFileName(given ?? fileName);\n const found: PdfWarning[] = [];\n const warnAt = (limit: PdfLimitName, actual: number) => {\n if (policy.check(limit, actual) === \"warning\") found.push({ limit, actual });\n };\n // The file size, before anything is read (ADR 0020).\n if (file instanceof Blob) {\n if (checkFile(policy, file) === \"warning\")\n found.push({ limit: \"maxFileSize\", actual: file.size });\n } else {\n warnAt(\"maxFileSize\", file.byteLength);\n }\n const bytes = file instanceof Blob ? new Uint8Array(await file.arrayBuffer()) : copyBytes(file);\n throwIfAborted(signal);\n const document = await withProcessingTime(\n policy,\n (limited) => engine.open(bytes, { signal: limited }),\n { signal },\n ).catch((reason: unknown) => {\n throw asPdfError(reason, \"The PDF couldn't be opened.\");\n });\n try {\n throwIfAborted(signal);\n warnAt(\"maxPages\", document.pageCount);\n } catch (reason) {\n await document.destroy();\n throw reason;\n }\n warnings = [...warnings.filter((warning) => warning.limit !== \"maxFileSize\"), ...found];\n nextSource += 1;\n return {\n id: `s${nextSource}`,\n pageCount: document.pageCount,\n byteLength: bytes.byteLength,\n ...(name === undefined ? {} : { name }),\n bytes,\n document,\n };\n }\n\n /** Runs a load, marking the session busy, and cancelling it if a newer open starts. */\n async function track<Value>(\n signal: AbortSignal | undefined,\n replaces: boolean,\n run: (signal: AbortSignal) => Promise<Value>,\n ): Promise<Value> {\n if (replaces) loading?.abort(new PdfError(\"ABORTED\", \"A newer document replaced this one.\"));\n const controller = new AbortController();\n if (replaces) loading = controller;\n const combined = signal ? AbortSignal.any([signal, controller.signal]) : controller.signal;\n busy += 1;\n changed();\n try {\n return await run(combined);\n } finally {\n busy -= 1;\n if (loading === controller) loading = undefined;\n changed();\n }\n }\n\n async function release(): Promise<void> {\n const documents = [...sources.values()].map((source) => source.document);\n sources.clear();\n await Promise.all(documents.map((document) => document.destroy().catch(() => {})));\n }\n\n function pageFor(key: string): { page: PdfPlanPage; source: Source } {\n const page = plan.pages.find((entry) => entry.key === key);\n const source = page && sources.get(page.source);\n if (!page || !source) throw new TypeError(`The plan has no page ${key}.`);\n return { page, source };\n }\n\n /** The selection and current page, which undo and redo bring back (docs/adr/0008). */\n function view(): View {\n return { selection, currentPage };\n }\n\n /**\n * Brings back a view, keeping only pages the plan still has; changed()\n * settles the rest. The current page is brought into view.\n */\n function restore(saved: View): void {\n const keys = new Set(plan.pages.map((page) => page.key));\n selection = saved.selection.filter((key) => keys.has(key));\n if (saved.currentPage !== undefined && keys.has(saved.currentPage)) {\n currentPage = saved.currentPage;\n navigation = { page: saved.currentPage, sequence: (navigation?.sequence ?? 0) + 1 };\n }\n }\n\n function step(commands: readonly PdfCommand[]): void {\n const before = view();\n const result = applyCommands(reduce, plan, commands);\n plan = result.state;\n history.push({ commands, inverses: result.inverses });\n // The history stores its own frozen copy of the step, the object that\n // undo() and redo() return, so the view is kept against that one.\n const stored = history.steps.at(-1);\n if (stored) views.set(stored, { before });\n // A new step drops the redo steps, and the documents only they held.\n collect();\n }\n\n return {\n getSnapshot: store.getSnapshot,\n\n subscribe: store.subscribe,\n\n async open(file, callOptions = {}) {\n status = \"opening\";\n error = undefined;\n try {\n const source = await track(callOptions.signal, true, async (signal) => {\n // The open document is released once this one opens, so this one\n // must fit on its own.\n policy.check(\"maxSessionSize\", file instanceof Blob ? file.size : file.byteLength);\n return load(file, signal, callOptions.name);\n });\n await release();\n sources.set(source.id, source);\n history.clear();\n plan = {\n pages: Array.from({ length: source.pageCount }, (_, pageIndex) => {\n nextKey += 1;\n return {\n key: `p${nextKey}`,\n source: source.id,\n pageIndex,\n rotation: 0,\n annotations: [],\n };\n }),\n formValues: {},\n };\n status = \"ready\";\n changed();\n emit({ type: \"document_opened\", pageCount: source.pageCount });\n } catch (reason) {\n const failure = asPdfError(reason, \"The PDF couldn't be opened.\");\n // A newer open replaced this one; it reports its own outcome.\n if (failure.code === \"ABORTED\" && loading !== undefined) throw failure;\n // A failed open keeps the document that was already open, and its\n // history, so a bad file never costs the user their work.\n status = sources.size > 0 ? \"ready\" : \"error\";\n error = failure;\n changed();\n emit({ type: \"failed\", operation: \"open\", code: failure.code });\n throw failure;\n }\n },\n\n async insert(file, insertOptions = {}) {\n if (status !== \"ready\") {\n throw new PdfError(\"PROCESSING_FAILED\", \"Open a document before inserting another.\");\n }\n error = undefined;\n try {\n const source = await track(insertOptions.signal, false, async (signal) => {\n policy.check(\"maxFiles\", sources.size + 1);\n return load(file, signal, insertOptions.name);\n });\n try {\n const pageIndexes =\n insertOptions.pageIndexes ??\n Array.from({ length: source.pageCount }, (_, index) => index);\n for (const index of pageIndexes) {\n if (!Number.isInteger(index) || index < 0 || index >= source.pageCount) {\n throw new RangeError(`The inserted document has no page index ${index}.`);\n }\n }\n if (policy.check(\"maxPages\", plan.pages.length + pageIndexes.length) === \"warning\") {\n warnings = [\n ...warnings.filter((warning) => warning.limit !== \"maxPages\"),\n { limit: \"maxPages\", actual: plan.pages.length + pageIndexes.length },\n ];\n }\n const keys = pageIndexes.map(() => {\n nextKey += 1;\n return `p${nextKey}`;\n });\n const drop = stepsToDrop(source.byteLength);\n if (drop === undefined) {\n throw policy.error(\"maxSessionSize\", heldBytes() + source.byteLength);\n }\n history.drop(drop);\n collect();\n sources.set(source.id, source);\n step([\n {\n type: \"pdf.insertPages\",\n source: source.id,\n pageIndexes,\n at: insertOptions.at ?? plan.pages.length,\n keys,\n },\n ]);\n changed();\n emit({ type: \"pages_inserted\", pageCount: pageIndexes.length });\n } catch (reason) {\n sources.delete(source.id);\n await source.document.destroy().catch(() => {});\n throw reason;\n }\n } catch (reason) {\n // A mistake in the call, such as a position outside the plan, isn't\n // the file's failure.\n if (\n reason instanceof TypeError ||\n reason instanceof RangeError ||\n isPdfError(reason, \"INVALID_COMMAND\")\n ) {\n throw reason;\n }\n const failure = asPdfError(reason, \"The PDF couldn't be inserted.\");\n error = failure;\n changed();\n emit({ type: \"failed\", operation: \"insert\", code: failure.code });\n throw failure;\n }\n },\n\n execute(commands) {\n const list = Array.isArray(commands) ? commands : [commands as PdfCommand];\n if (list.length === 0) return;\n step(list);\n changed();\n emit({ type: \"command\", commands: list.map((command) => command.type) });\n },\n\n undo() {\n const entry = history.undo();\n if (!entry) return;\n const now = view();\n try {\n plan = applyCommands(reduce, plan, entry.inverses).state;\n } catch (reason) {\n history.restore(\"undo\");\n throw reason;\n }\n const record = views.get(entry);\n if (record) {\n // Redo brings back what the user had when they undid.\n record.after = now;\n restore(record.before);\n }\n changed();\n emit({ type: \"undo\" });\n },\n\n redo() {\n const entry = history.redo();\n if (!entry) return;\n try {\n plan = applyCommands(reduce, plan, entry.commands).state;\n } catch (reason) {\n history.restore(\"redo\");\n throw reason;\n }\n const after = views.get(entry)?.after;\n if (after) restore(after);\n changed();\n emit({ type: \"redo\" });\n },\n\n async getPage(key, callOptions) {\n const { page, source } = pageFor(key);\n const info = await source.document.getPage(page.pageIndex, callOptions);\n return { ...info, rotation: addRotation(info.rotation, page.rotation) };\n },\n\n async renderPage(key, canvas, renderOptions) {\n const { page, source } = pageFor(key);\n await source.document.renderPage(page.pageIndex, canvas, {\n ...renderOptions,\n rotation: page.rotation,\n });\n },\n\n async getTextContent(key, callOptions) {\n const { page, source } = pageFor(key);\n return source.document.getTextContent(page.pageIndex, callOptions);\n },\n\n async getFormFields(key, callOptions) {\n const { page, source } = pageFor(key);\n const fields = await source.document.getFormFields(page.pageIndex, callOptions);\n const values = plan.formValues[source.id] ?? {};\n return fields.map((field) =>\n Object.hasOwn(values, field.name)\n ? { ...field, value: values[field.name] as typeof field.value }\n : field,\n );\n },\n\n async getLinks(key, callOptions) {\n const { page, source } = pageFor(key);\n return source.document.getLinks(page.pageIndex, callOptions);\n },\n\n async export(exportOptions = {}) {\n if (status !== \"ready\" && sources.size === 0) {\n throw new PdfError(\"PROCESSING_FAILED\", \"Open a document before exporting it.\");\n }\n const pages = plan.pages;\n const used = [...new Set(pages.map((page) => page.source))];\n const job: PdfBuildJob = {\n sources: used.map((id) => {\n const values = plan.formValues[id];\n return {\n id,\n bytes: (sources.get(id) as Source).bytes,\n ...(values && Object.keys(values).length > 0 ? { formValues: values } : {}),\n };\n }),\n pages: pages.map((page) => ({\n source: page.source,\n pageIndex: page.pageIndex,\n ...(page.rotation === 0 ? {} : { rotation: page.rotation }),\n ...(page.annotations.length === 0 ? {} : { annotations: page.annotations }),\n })),\n ...(exportOptions.compress ? { compress: exportOptions.compress } : {}),\n ...(exportOptions.encrypt ? { encrypt: exportOptions.encrypt } : {}),\n };\n const done = () =>\n emit({\n type: \"document_exported\",\n pageCount: pages.length,\n compressed: Boolean(exportOptions.compress),\n encrypted: Boolean(exportOptions.encrypt),\n });\n\n // An unchanged document with no options is its original bytes.\n const [only] = job.sources;\n const source = only && sources.get(only.id);\n if (\n job.sources.length === 1 &&\n !only?.formValues &&\n !job.compress &&\n !job.encrypt &&\n source &&\n job.pages.length === source.pageCount &&\n job.pages.every(\n (page, index) => page.pageIndex === index && !page.rotation && !page.annotations,\n )\n ) {\n throwIfAborted(exportOptions.signal);\n done();\n return copyBytes(source.bytes);\n }\n\n const { processor } = options;\n if (!processor) {\n throw new TypeError(\"Exporting an edited document needs a processor in createPdfSession.\");\n }\n busy += 1;\n changed();\n try {\n const output = await withProcessingTime(\n policy,\n (signal) =>\n processor.build(job, {\n signal,\n ...(exportOptions.onProgress ? { onProgress: exportOptions.onProgress } : {}),\n }),\n exportOptions.signal ? { signal: exportOptions.signal } : {},\n );\n done();\n return output;\n } catch (reason) {\n if (reason instanceof TypeError || reason instanceof RangeError) throw reason;\n const failure = asPdfError(reason, \"The PDF couldn't be exported.\");\n emit({ type: \"failed\", operation: \"export\", code: failure.code });\n throw failure;\n } finally {\n busy -= 1;\n changed();\n }\n },\n\n select(keys) {\n const wanted = new Set(keys);\n const next = plan.pages.filter((page) => wanted.has(page.key)).map((page) => page.key);\n if (\n next.length === selection.length &&\n next.every((key, index) => key === selection[index])\n ) {\n return;\n }\n selection = next;\n changed();\n },\n\n setCurrentPage(key) {\n if (key === currentPage || !plan.pages.some((page) => page.key === key)) return;\n currentPage = key;\n changed();\n },\n\n goToPage(key) {\n if (!plan.pages.some((page) => page.key === key)) {\n throw new TypeError(`The plan has no page ${key}.`);\n }\n currentPage = key;\n navigation = { page: key, sequence: (navigation?.sequence ?? 0) + 1 };\n changed();\n },\n\n async close() {\n loading?.abort(new PdfError(\"ABORTED\", \"The document was closed.\"));\n const hadDocument = status === \"ready\";\n await release();\n plan = EMPTY_PLAN;\n history.clear();\n warnings = [];\n error = undefined;\n status = \"empty\";\n changed();\n if (hadDocument) emit({ type: \"document_closed\" });\n },\n };\n}\n","import { defineMessages, type MessageValue, plural, sdkCoreMessages } from \"@hussmartinez/sdk-core\";\nimport type { PdfErrorCode } from \"../core/errors/pdf-error.js\";\nimport type { PdfLimitName } from \"../core/errors/pdf-limits.js\";\n\n/**\n * The PDF SDK's English message catalogue for the server-safe entry:\n * sdk-core's messages, and text for every {@link PdfErrorCode} and every\n * limit's warning. Pass it to `createMessages` from `@hussmartinez/sdk-core`,\n * with the host's locale and overrides.\n *\n * It holds no interface text: the editor's, the viewer's and the\n * thumbnails' text is in `pdfEditorMessages`, from the React entry\n * (docs/adr/0010).\n *\n * Error text is looked up by code, with the error's `details` as\n * parameters, and never taken from `error.message` (ADR 0019).\n *\n * @example\n * ```ts\n * const messages = createMessages(pdfMessages, { locale: \"en\", overrides: props.messages });\n * messages.error(error); // \"This document has 6,200 pages, which is over the 5,000-page limit.\"\n * messages.t(\"warnings.maxPages\", { actual: 1_200 });\n * ```\n *\n * @public\n */\nexport const pdfMessages = /* @__PURE__ */ defineMessages({\n ...sdkCoreMessages,\n \"errors.INVALID_PDF\": \"This file isn't a PDF, or it's too damaged to open.\",\n \"errors.PASSWORD_REQUIRED\": \"This PDF is protected with a password.\",\n \"errors.PROCESSING_FAILED\": \"Something went wrong while processing this PDF. Please try again.\",\n \"errors.TOO_MANY_PAGES\":\n \"This document has {actual, number} pages, which is over the {maximum, number}-page limit.\",\n \"errors.SESSION_TOO_LARGE\":\n \"The open documents would use {actual, fileSize}, which is over the {maximum, fileSize} limit. Close a document, or clear the undo history, and try again.\",\n \"errors.IMAGE_TOO_LARGE\":\n \"Some images are too large to show. They're kept unchanged in the document.\",\n \"errors.INVALID_COMMAND\": \"This edit couldn't be made. Please try again.\",\n \"errors.INVALID_DOCUMENT\": \"This project is damaged, or it isn't a PDF project.\",\n \"errors.UNSUPPORTED_FORMAT\":\n \"This project was saved by a newer version, or by another app. Update the app, and try again.\",\n \"warnings.maxPages\": /* @__PURE__ */ plural(\"actual\", {\n one: \"This document has {actual} page. Large documents may be slow.\",\n other: \"This document has {actual} pages. Large documents may be slow.\",\n }),\n \"warnings.maxSessionSize\":\n \"The open documents use {actual, fileSize}. Clearing the undo history frees memory.\",\n \"warnings.maxImagePixels\": \"Some images are very large and may be slow to show.\",\n}) satisfies Record<`errors.${PdfErrorCode}`, MessageValue> &\n Record<`warnings.${PdfLimitName}`, MessageValue>;\n\n/**\n * The type of {@link pdfMessages}, for typing a host's overrides with\n * `MessageOverrides<PdfMessageCatalogue>`.\n *\n * @public\n */\nexport type PdfMessageCatalogue = typeof pdfMessages;\n"],"mappings":";;AAkEA,IAAa,WAAb,cAA8B,SAAuB;CAEnD,OAAyB;AAC3B;AAaA,SAAgB,WACd,OACA,MAC6C;CAC7C,OAAO,WAAW,OAAO,IAAI,KAAK,MAAM,SAAS;AACnD;;AChFA,IAAM,UAA0B,mCAAmB,UAAU;CAC3D,cAAc;CACd,iBAAiB;AACnB,CAAC;AAUD,IAAa,aAA8D,QAAQ;AAUnF,IAAa,aAAgD,QAAQ;AAOrE,IAAa,iBAA4D,QAAQ;;ACVjF,IAAa,sBAA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AAqC,uBAAO,UAAU;EACpD,KAAK;EACL,OAAO;CACT,CAAC;CACD,2BACE;CACF,2BAA2B;AAC7B,CAAC"}
1
+ {"version":3,"file":"en-DcHRkVwP.js","names":[],"sources":["../../src/core/errors/pdf-error.ts","../../src/core/errors/abort.ts","../../src/core/errors/pdf-limits.ts","../../src/core/model/bytes.ts","../../src/core/model/geometry.ts","../../src/core/model/links.ts","../../src/core/ports/pdf-engine.ts","../../src/adapters/pdfjs/binary-data.ts","../../src/adapters/pdfjs/errors.ts","../../src/adapters/pdfjs/pdfjs-engine.ts","../../src/adapters/qpdf/qpdf-processor.ts","../../src/core/model/portable.ts","../../src/core/operations/commands.ts","../../src/core/model/plan.ts","../../src/core/session/source-name.ts","../../src/core/session/session.ts","../../src/messages/en.ts"],"sourcesContent":["import { isSdkError, type SdkCoreErrorCode, SdkError } from \"@hussmartinez/sdk-core\";\n\n/**\n * Error codes of `@hussmartinez/pdf-sdk`: sdk-core's own codes, such as\n * `ABORTED`, `WORKER_CRASHED` and `FILE_TOO_LARGE`, plus the PDF SDK's. They\n * never change meaning once released.\n *\n * - `INVALID_PDF`: the file isn't a PDF, or is too damaged to open.\n * - `PASSWORD_REQUIRED`: the PDF is encrypted, and opening it needs a\n * password.\n * - `PROCESSING_FAILED`: a PDF engine failed in a way no other code\n * describes. `cause` holds the engine's error.\n * - `TOO_MANY_PAGES`: a document, or the pages after an insert, exceed the\n * `maxPages` limit.\n * - `SESSION_TOO_LARGE`: the documents the session holds exceed the\n * `maxSessionSize` limit.\n * - `IMAGE_TOO_LARGE`: an image exceeds the `maxImagePixels` limit. It's\n * reported as a warning, because the image is skipped rather than the\n * document failing (ADR 0004).\n * - `INVALID_COMMAND`: an edit command doesn't apply to the plan, such as\n * one naming a page the plan doesn't have. `details.reason` says why, as\n * a stable token (`PdfCommandRejection`, sdk-core ADR 0045).\n * - `INVALID_DOCUMENT`: a plan document, such as a saved project, isn't\n * valid in its format. `details.reason` says why (`PdfDocumentRejection`).\n * - `UNSUPPORTED_FORMAT`: a plan document of another format, or of a later\n * version than this release reads, with `details.reason`\n * `unknown-format` or `unknown-format-version`.\n *\n * Limit codes carry `details` with the `limit`, its `maximum`, the `actual`\n * value and the `unit`.\n *\n * @public\n */\nexport type PdfErrorCode =\n | SdkCoreErrorCode\n | \"INVALID_PDF\"\n | \"PASSWORD_REQUIRED\"\n | \"PROCESSING_FAILED\"\n | \"TOO_MANY_PAGES\"\n | \"SESSION_TOO_LARGE\"\n | \"IMAGE_TOO_LARGE\"\n | \"INVALID_COMMAND\"\n | \"INVALID_DOCUMENT\"\n | \"UNSUPPORTED_FORMAT\";\n\n/**\n * The error `@hussmartinez/pdf-sdk` throws and rejects with, with a stable\n * `code`, structured `details` and the engine's error as `cause`. Show users\n * the text for its code from {@link pdfMessages}, never its `message`, which\n * is for developers and may contain text from the file.\n *\n * @example\n * ```ts\n * try {\n * await session.open(file);\n * } catch (error) {\n * if (isPdfError(error, \"PASSWORD_REQUIRED\")) {\n * askForPassword();\n * } else {\n * show(messages.error(error));\n * }\n * }\n * ```\n *\n * @public\n */\nexport class PdfError extends SdkError<PdfErrorCode> {\n /** Always `\"PdfError\"`, which survives minification and worker boundaries. */\n override readonly name = \"PdfError\";\n}\n\n/**\n * Checks whether a value is a {@link PdfError}, optionally with a given code.\n *\n * Unlike `instanceof`, it recognises errors from another copy of this\n * package or another realm, and errors rebuilt after crossing a worker\n * boundary.\n *\n * @param value - Any thrown value.\n * @param code - When given, the error must also have this code.\n * @public\n */\nexport function isPdfError<Code extends PdfErrorCode = PdfErrorCode>(\n value: unknown,\n code?: Code,\n): value is PdfError & { readonly code: Code } {\n return isSdkError(value, code) && value.name === \"PdfError\";\n}\n","import { createErrorHelpers } from \"@hussmartinez/sdk-core\";\nimport { PdfError } from \"./pdf-error.js\";\n\n/**\n * The family's error helpers, bound to `PdfError` (sdk-core ADR 0034), so\n * every port and the session make failures `PdfError`s the same way.\n */\nconst helpers = /* @__PURE__ */ createErrorHelpers(PdfError, {\n fallbackCode: \"PROCESSING_FAILED\",\n fallbackMessage: \"PDF processing failed.\",\n});\n\n/**\n * Makes any failure a `PdfError`, as every port promises: a `PdfError` as\n * it is, another `SdkError`, such as the worker client's own `ABORTED` or\n * `WORKER_CRASHED`, with its code, details and message kept, and anything\n * else as `PROCESSING_FAILED`. The original is kept as `cause`.\n *\n * @internal\n */\nexport const asPdfError: (reason: unknown, message?: string) => PdfError = helpers.adapt;\n\n/**\n * The error an aborted call rejects with, as the family's worker client does\n * (ADR 0018, ADR 0020): the reason itself when it's an `SdkError`, such as a\n * file policy's `PROCESSING_TIME_EXCEEDED`, `TIMEOUT` for a timeout, and\n * `ABORTED` otherwise. The reason is kept as `cause`.\n *\n * @internal\n */\nexport const abortError: (signal: AbortSignal) => PdfError = helpers.abortError;\n\n/**\n * Throws {@link abortError} if the signal has been aborted.\n *\n * @internal\n */\nexport const throwIfAborted: (signal: AbortSignal | undefined) => void = helpers.throwIfAborted;\n","import {\n coreLimits,\n defineLimits,\n type FilePolicy,\n type FilePolicyOverrides,\n type Limits,\n} from \"@hussmartinez/sdk-core\";\nimport { PdfError } from \"./pdf-error.js\";\n\n/**\n * The PDF SDK's limit definitions: sdk-core's core limits plus three for PDFs\n * (ADR 0004).\n *\n * | Limit | Code | Default maximum | Default warning |\n * |---|---|---|---|\n * | `maxFileSize` | `FILE_TOO_LARGE` | 100 MB | 50 MB |\n * | `maxFiles` | `TOO_MANY_FILES` | 20 | none |\n * | `maxDecodedSize` | `DECODED_SIZE_TOO_LARGE` | 500 MB | none |\n * | `maxProcessingTime` | `PROCESSING_TIME_EXCEEDED` | 120 s | none |\n * | `maxPages` | `TOO_MANY_PAGES` | 5,000 | 1,000 |\n * | `maxSessionSize` | `SESSION_TOO_LARGE` | 300 MB | 150 MB |\n * | `maxImagePixels` | `IMAGE_TOO_LARGE` | 100 megapixels | none |\n *\n * Sizes are decimal: 1 MB is 1,000,000 bytes.\n *\n * @public\n */\nexport const pdfLimitDefinitions = {\n ...coreLimits,\n maxPages: { code: \"TOO_MANY_PAGES\", unit: \"count\", default: 5_000, warning: 1_000 },\n maxSessionSize: {\n code: \"SESSION_TOO_LARGE\",\n unit: \"bytes\",\n default: 300_000_000,\n warning: 150_000_000,\n },\n maxImagePixels: { code: \"IMAGE_TOO_LARGE\", unit: \"pixels\", default: 100_000_000 },\n} as const;\n\n/**\n * The type of {@link pdfLimitDefinitions}.\n *\n * @public\n */\nexport type PdfLimitDefinitions = typeof pdfLimitDefinitions;\n\n/**\n * The names of the PDF SDK's limits.\n *\n * @public\n */\nexport type PdfLimitName = keyof PdfLimitDefinitions;\n\n/**\n * A host's `filePolicy`: a new maximum, or `{ maximum, warning }`, for any of\n * the PDF SDK's limits. `Infinity` disables a maximum, which removes a\n * protection against hostile files, or disables a warning. Unknown limit\n * names throw `TypeError` when the policy is resolved.\n *\n * @example\n * ```ts\n * const filePolicy: PdfFilePolicyOverrides = {\n * maxFileSize: { maximum: 300e6, warning: 100e6 },\n * maxSessionSize: 600e6,\n * };\n * ```\n *\n * @public\n */\nexport type PdfFilePolicyOverrides = FilePolicyOverrides<PdfLimitDefinitions>;\n\n/**\n * A resolved file policy for the PDF SDK. Violations throw {@link PdfError}.\n *\n * @public\n */\nexport type PdfFilePolicy = FilePolicy<PdfLimitDefinitions>;\n\n/**\n * The PDF SDK's limits, ready to resolve a host's `filePolicy`. Violations\n * are thrown as {@link PdfError}, with `details` naming the limit.\n *\n * @example\n * ```ts\n * const policy = pdfLimits.resolve(props.filePolicy);\n * policy.check(\"maxPages\", pageCount); // throws PdfError(\"TOO_MANY_PAGES\") above 5,000\n * ```\n *\n * @public\n */\nexport const pdfLimits: Limits<PdfLimitDefinitions> = /* @__PURE__ */ defineLimits(\n pdfLimitDefinitions,\n {\n errorClass: PdfError,\n },\n);\n","import type { PdfBytes } from \"./document.js\";\n\n/**\n * Copies PDF bytes into a new buffer that holds exactly them, so a caller's\n * buffer is never detached or changed, and a view into a larger buffer never\n * sends the rest of it (ADR 0002).\n *\n * @internal\n */\nexport function copyBytes(source: PdfBytes): Uint8Array<ArrayBuffer> {\n const view = source instanceof Uint8Array ? source : new Uint8Array(source);\n return new Uint8Array(view);\n}\n\n/**\n * Checks that a zero-based page index exists in a document.\n *\n * @throws `RangeError` otherwise.\n * @internal\n */\nexport function assertPageIndex(pageIndex: number, pageCount: number): void {\n if (!Number.isInteger(pageIndex) || pageIndex < 0 || pageIndex >= pageCount) {\n throw new RangeError(\n `Page index ${pageIndex} is outside the document, which has ${pageCount} pages.`,\n );\n }\n}\n","/**\n * A point on a page, as fractions of the page's unrotated media box: `x`\n * from the left edge and `y` from the top edge, each from 0 to 1. Fractions\n * keep positions independent of zoom and of the rotation the page is shown\n * with (ADR 0003).\n *\n * @public\n */\nexport interface PdfPoint {\n readonly x: number;\n readonly y: number;\n}\n\n/**\n * A rectangle on a page, in the same fractions as {@link PdfPoint}: its\n * top-left corner, width and height.\n *\n * @public\n */\nexport interface PdfRect {\n readonly x: number;\n readonly y: number;\n readonly width: number;\n readonly height: number;\n}\n\n/**\n * A rotation in degrees, clockwise.\n *\n * @public\n */\nexport type PdfRotation = 0 | 90 | 180 | 270;\n\n/**\n * Adds two rotations, such as a page's own `/Rotate` and the rotation the\n * page plan adds to it.\n *\n * @example\n * ```ts\n * addRotation(270, 180); // 90\n * addRotation(90, -90); // 0\n * ```\n *\n * @param rotation - The current rotation.\n * @param angle - The angle to add, positive clockwise, in multiples of 90.\n * @throws `RangeError` if `angle` isn't a multiple of 90.\n * @public\n */\nexport function addRotation(rotation: PdfRotation, angle: number): PdfRotation {\n if (!Number.isInteger(angle) || angle % 90 !== 0) {\n throw new RangeError(`A rotation must be a multiple of 90 degrees, received ${angle}.`);\n }\n return ((((rotation + angle) % 360) + 360) % 360) as PdfRotation;\n}\n","const SAFE_PROTOCOLS = new Set([\"http:\", \"https:\", \"mailto:\"]);\n\n/**\n * The URL, normalised, if it's an absolute `http`, `https` or `mailto` URL\n * without credentials (ADR 0012), and otherwise undefined. Every engine\n * adapter filters links with it, and the viewer checks again before\n * rendering one.\n *\n * URLs with a user name or password are refused: in\n * `https://bank.example@evil.example/`, the part a reader notices is a user\n * name, and the link goes to `evil.example`, a common phishing shape.\n *\n * @public\n */\nexport function safeLinkUrl(url: string): string | undefined {\n if (typeof url !== \"string\" || url.length > 2048) return undefined;\n let parsed: URL;\n try {\n parsed = new URL(url);\n } catch {\n return undefined;\n }\n if (!SAFE_PROTOCOLS.has(parsed.protocol)) return undefined;\n if (parsed.username !== \"\" || parsed.password !== \"\") return undefined;\n return parsed.href;\n}\n\n/**\n * What a link really leads to, for people to check before following it: the\n * host of a web link, without `www.`, or the address of an email link.\n * Undefined for a URL `safeLinkUrl` refuses.\n *\n * @public\n */\nexport function linkDestination(url: string): string | undefined {\n const safe = safeLinkUrl(url);\n if (!safe) return undefined;\n const parsed = new URL(safe);\n if (parsed.protocol === \"mailto:\") {\n return decodeURIComponent(parsed.pathname) || undefined;\n }\n return parsed.hostname.replace(/^www\\./, \"\");\n}\n","import type {\n PdfBytes,\n PdfFormField,\n PdfLink,\n PdfPageInfo,\n PdfTextContent,\n} from \"../model/document.js\";\nimport type { PdfRotation } from \"../model/geometry.js\";\nimport type { PdfCallOptions, PdfTransferOptions } from \"./options.js\";\n\n/**\n * The most pixels an engine draws into one canvas. Larger renders are drawn\n * at a lower resolution instead, because iOS Safari, the strictest\n * supported browser, refuses larger canvases (ADR 0004).\n *\n * @public\n */\nexport const PDF_MAX_CANVAS_PIXELS = 16_777_216;\n\n/**\n * How to render a page.\n *\n * @public\n */\nexport interface PdfRenderOptions extends PdfCallOptions {\n /** CSS pixels per PDF point. `1` renders a US Letter page 612 CSS pixels wide. */\n readonly scale: number;\n /**\n * Device pixels per CSS pixel, usually `window.devicePixelRatio`. Defaults\n * to 1. The engine lowers it as needed to stay within\n * {@link PDF_MAX_CANVAS_PIXELS}.\n */\n readonly pixelRatio?: number;\n /** Rotation added to the page's own, for the page plan (ADR 0003). Defaults to 0. */\n readonly rotation?: PdfRotation;\n}\n\n/**\n * An open document. Pages are addressed by zero-based index.\n *\n * @public\n */\nexport interface PdfDocumentHandle {\n /** The number of pages. */\n readonly pageCount: number;\n /**\n * Reads a page's size and rotation.\n *\n * @throws `RangeError` for an index outside the document.\n */\n getPage(pageIndex: number, options?: PdfCallOptions): Promise<PdfPageInfo>;\n /**\n * Draws a page into a canvas, sizing the canvas's pixel dimensions and its\n * CSS `width` and `height`.\n *\n * @throws `RangeError` for an index outside the document.\n */\n renderPage(\n pageIndex: number,\n canvas: HTMLCanvasElement,\n options: PdfRenderOptions,\n ): Promise<void>;\n /**\n * Reads a page's text, for the text layer and search.\n *\n * @throws `RangeError` for an index outside the document.\n */\n getTextContent(pageIndex: number, options?: PdfCallOptions): Promise<PdfTextContent>;\n /**\n * Reads the form fields on a page.\n *\n * @throws `RangeError` for an index outside the document.\n */\n getFormFields(pageIndex: number, options?: PdfCallOptions): Promise<readonly PdfFormField[]>;\n /**\n * Reads the links on a page to web pages and email addresses, filtered\n * with `safeLinkUrl` (ADR 0012).\n *\n * @throws `RangeError` for an index outside the document.\n */\n getLinks(pageIndex: number, options?: PdfCallOptions): Promise<readonly PdfLink[]>;\n /** Releases the document. Pending calls reject, and later calls throw. */\n destroy(): Promise<void>;\n}\n\n/**\n * The port for viewing PDFs: open a document, then read and render its pages\n * (ADR 0008). The SDK's pdf.js adapter implements it; hosts can pass their\n * own to the editor's `engine` prop, and every implementation must pass the\n * engine's contract tests.\n *\n * Failures reject with `PdfError`: `INVALID_PDF` for a file that can't be\n * parsed, `PASSWORD_REQUIRED` for an encrypted one, and sdk-core's codes for\n * cancellation and worker failures.\n *\n * @public\n */\nexport interface PdfEngine {\n /**\n * Opens a document. The bytes are copied unless `transfer` is set.\n */\n open(source: PdfBytes, options?: PdfTransferOptions): Promise<PdfDocumentHandle>;\n /** Releases the engine and its worker. Open documents are destroyed. */\n destroy(): Promise<void>;\n}\n","/** The kinds of data pdf.js asks the page for when `useWorkerFetch` is off. */\nexport type PdfJsDataKind = \"cMapUrl\" | \"standardFontDataUrl\" | \"wasmUrl\";\n\n/** Called for every data file pdf.js asks for. */\nexport type PdfJsDataListener = (kind: PdfJsDataKind, filename: string) => void;\n\n/**\n * The prefix pdf.js puts before the file name of a JavaScript decoder it\n * imports when a WebAssembly decoder can't start, for example under a\n * Content Security Policy without 'wasm-unsafe-eval'. It isn't a fetchable\n * scheme, so that import fails without a request (docs/adr/0002).\n */\nexport const NO_NETWORK_URL = \"hm-pdf-no-network:/\";\n\nfunction decodeBase64(base64: string): Uint8Array {\n const binary = atob(base64);\n const bytes = new Uint8Array(binary.length);\n for (let index = 0; index < binary.length; index += 1) {\n bytes[index] = binary.charCodeAt(index);\n }\n return bytes;\n}\n\n/**\n * A `BinaryDataFactory` for pdf.js that serves the bundled CMaps, standard\n * fonts and WebAssembly decoders from lazy chunks, without the network\n * (docs/adr/0002). Only those files are served: any other kind or name,\n * such as a path, is refused.\n */\nexport function createInlineDataFactory(listener?: PdfJsDataListener) {\n return class InlineDataFactory {\n async fetch({\n kind,\n filename,\n }: {\n kind: PdfJsDataKind;\n filename: string;\n }): Promise<Uint8Array> {\n listener?.(kind, filename);\n const { pdfJsData } = await import(\"virtual:hm-pdfjs-data\");\n const files = Object.hasOwn(pdfJsData, kind) ? pdfJsData[kind] : undefined;\n const load = files && Object.hasOwn(files, filename) ? files[filename] : undefined;\n if (!load) {\n throw new Error(`The PDF SDK doesn't serve ${kind} data named ${filename}.`);\n }\n return decodeBase64(await load());\n }\n };\n}\n","import { isPdfError, PdfError } from \"../../core/errors/pdf-error.js\";\n\nconst INVALID = new Set([\"InvalidPDFException\", \"FormatError\", \"MissingPDFException\"]);\n\n/**\n * Turns whatever pdf.js rejected with into a `PdfError`, keeping it as\n * `cause`. pdf.js's exceptions cross its worker boundary as plain objects\n * with a `name`, so they're recognised by name.\n */\nexport function fromPdfJsError(reason: unknown, message: string): PdfError | RangeError {\n if (isPdfError(reason) || reason instanceof RangeError) {\n return reason;\n }\n const name = typeof reason === \"object\" && reason !== null ? (reason as Error).name : undefined;\n if (name === \"PasswordException\") {\n return new PdfError(\"PASSWORD_REQUIRED\", \"The PDF is encrypted.\", { cause: reason });\n }\n if (name !== undefined && INVALID.has(name)) {\n return new PdfError(\"INVALID_PDF\", \"The file isn't a readable PDF.\", { cause: reason });\n }\n return new PdfError(\"PROCESSING_FAILED\", message, { cause: reason });\n}\n","import { type AssetsResolver, createAssetsResolver } from \"@hussmartinez/sdk-core\";\nimport type { PDFDocumentLoadingTask, PDFDocumentProxy, PDFPageProxy, PDFWorker } from \"pdfjs-dist\";\nimport { abortError, throwIfAborted } from \"../../core/errors/abort.js\";\nimport { PdfError } from \"../../core/errors/pdf-error.js\";\nimport { pdfLimitDefinitions } from \"../../core/errors/pdf-limits.js\";\nimport { assertPageIndex, copyBytes } from \"../../core/model/bytes.js\";\nimport type {\n PdfBytes,\n PdfFormField,\n PdfLink,\n PdfPageInfo,\n PdfTextContent,\n PdfTextItem,\n} from \"../../core/model/document.js\";\nimport { addRotation, type PdfRect, type PdfRotation } from \"../../core/model/geometry.js\";\nimport { safeLinkUrl } from \"../../core/model/links.js\";\nimport type { PdfCallOptions, PdfTransferOptions } from \"../../core/ports/options.js\";\nimport {\n PDF_MAX_CANVAS_PIXELS,\n type PdfDocumentHandle,\n type PdfEngine,\n type PdfRenderOptions,\n} from \"../../core/ports/pdf-engine.js\";\nimport { createInlineDataFactory, NO_NETWORK_URL } from \"./binary-data.js\";\nimport { fromPdfJsError } from \"./errors.js\";\n\ntype PdfJs = typeof import(\"pdfjs-dist\");\ntype PageViewport = ReturnType<PDFPageProxy[\"getViewport\"]>;\n\n/** The fields of pdf.js's text items this adapter reads. */\ninterface PdfJsTextItem {\n readonly str: string;\n readonly transform: readonly number[];\n readonly width: number;\n readonly hasEOL: boolean;\n}\n\n/**\n * Converts a rectangle in PDF user space to fractions of the unrotated page,\n * from the top-left corner, clamped to the page (ADR 0003).\n */\nfunction toPageRect(viewport: PageViewport, box: readonly number[]): PdfRect {\n const [x1 = 0, y1 = 0, x2 = 0, y2 = 0] = box;\n const [ax = 0, ay = 0] = viewport.convertToViewportPoint(x1, y1) as number[];\n const [bx = 0, by = 0] = viewport.convertToViewportPoint(x2, y2) as number[];\n const left = clamp(Math.min(ax, bx) / viewport.width);\n const top = clamp(Math.min(ay, by) / viewport.height);\n return {\n x: left,\n y: top,\n width: clamp(Math.max(ax, bx) / viewport.width) - left,\n height: clamp(Math.max(ay, by) / viewport.height) - top,\n };\n}\n\n/**\n * Options for {@link createPdfJsEngine}.\n *\n * @public\n */\nexport interface PdfJsEngineOptions {\n /**\n * Where your application serves the package's `dist/assets/` directory,\n * on its own origin, such as `\"/pdf-sdk/\"`. pdf.js then loads its worker\n * and its data files from its `pdfjs/` subdirectory, rather than from the\n * inlined copies. Use it for Content Security Policies without\n * `worker-src blob:`, and for accurate ICC colour, which only this mode\n * supports (docs/adr/0006, docs/adr/0007). Pass the same URL to\n * `createPdfProcessor`.\n */\n readonly assetsUrl?: string | URL;\n /**\n * The largest image pdf.js decodes, in pixels. Larger images are left\n * unpainted. Defaults to the `maxImagePixels` limit, 100 megapixels.\n */\n readonly maxImagePixels?: number;\n /**\n * Called for every data file pdf.js asks for. For tests.\n *\n * @internal\n */\n readonly _onDataRequest?: (\n kind: \"cMapUrl\" | \"standardFontDataUrl\" | \"wasmUrl\",\n filename: string,\n ) => void;\n}\n\n/** How long a cancelled open may take to stop before its worker is terminated (ADR 0018). */\nconst CANCEL_TIMEOUT = 1_000;\n\n/**\n * Creates the SDK's {@link PdfEngine}, backed by pdf.js (ADR 0001, ADR 0002).\n *\n * Nothing loads until the first `open()`: then pdf.js's display layer is\n * imported, and its worker starts. Every document the engine opens shares one\n * worker, and pdf.js runs without scripting or XFA (docs/adr/0001).\n *\n * By default everything is inlined: the worker, and the CMaps, standard\n * fonts and image decoders that some documents need, each loaded only when a\n * document needs it, with no network request. With `assetsUrl`, they load\n * from your own origin instead (docs/adr/0002, docs/adr/0006).\n *\n * @example\n * ```ts\n * const engine = createPdfJsEngine();\n * const document = await engine.open(await file.arrayBuffer(), { signal });\n * await document.renderPage(0, canvas, { scale: 1.5, pixelRatio: devicePixelRatio });\n * ```\n *\n * @public\n */\nexport function createPdfJsEngine(options: PdfJsEngineOptions = {}): PdfEngine {\n return new PdfJsEngine(options);\n}\n\n/**\n * One worker, and everything that fails with it. When the worker crashes or\n * has to be terminated, every call waiting on it rejects, and the engine\n * starts a new one on the next open.\n */\nclass WorkerHost {\n readonly pdfWorker: PDFWorker;\n #worker: Worker;\n #waiting = new Set<(error: PdfError) => void>();\n #failure: PdfError | undefined;\n\n constructor(worker: Worker, pdfWorker: PDFWorker) {\n this.#worker = worker;\n this.pdfWorker = pdfWorker;\n const crash = (event: Event) => {\n // Handled here, so the error isn't also reported to the console.\n event.preventDefault();\n this.fail(new PdfError(\"WORKER_CRASHED\", \"The PDF render worker failed.\"));\n };\n worker.addEventListener(\"error\", crash);\n worker.addEventListener(\"messageerror\", crash);\n }\n\n get failure(): PdfError | undefined {\n return this.#failure;\n }\n\n /** Rejects with the worker's failure, if it fails while the returned function hasn't been called. */\n watch(reject: (error: PdfError) => void): () => void {\n if (this.#failure) {\n reject(this.#failure);\n return () => {};\n }\n this.#waiting.add(reject);\n return () => this.#waiting.delete(reject);\n }\n\n fail(error: PdfError): void {\n if (this.#failure) return;\n this.#failure = error;\n this.#worker.terminate();\n this.pdfWorker.destroy();\n for (const reject of this.#waiting) reject(error);\n this.#waiting.clear();\n }\n}\n\n/**\n * Waits for a pdf.js promise, rejecting at once when the signal aborts or the\n * worker fails, and mapping pdf.js's errors to `PdfError`.\n */\nfunction settle<Value>(\n host: WorkerHost,\n promise: Promise<Value>,\n options: { signal?: AbortSignal | undefined; onAbort?: () => void; message: string },\n): Promise<Value> {\n const { signal } = options;\n return new Promise<Value>((resolve, reject) => {\n if (signal?.aborted) {\n options.onAbort?.();\n reject(abortError(signal));\n return;\n }\n const abort = () => {\n options.onAbort?.();\n reject(abortError(signal as AbortSignal));\n };\n signal?.addEventListener(\"abort\", abort, { once: true });\n const unwatch = host.watch(reject);\n promise.then(resolve, (reason: unknown) => reject(fromPdfJsError(reason, options.message)));\n // Settling twice is harmless; the first outcome wins.\n void promise\n .catch(() => {})\n .finally(() => {\n signal?.removeEventListener(\"abort\", abort);\n unwatch();\n });\n });\n}\n\nconst VERSION_MISMATCH = /The API version \"([^\"]+)\" does not match the Worker version \"([^\"]+)\"/;\n\n/**\n * pdf.js refuses a worker from another pdf.js version, such as a self-hosted\n * copy left over from before an upgrade. That's a start failure, not a\n * problem with the document, so it's reported as one, with the same details\n * as sdk-core's worker client gives (sdk-core ADR 0038).\n */\nfunction workerVersionMismatch(error: unknown, base: string | undefined): PdfError | undefined {\n for (let reason = error; reason instanceof Error; reason = reason.cause) {\n const match = VERSION_MISMATCH.exec(reason.message);\n if (match) {\n return new PdfError(\"WORKER_START_FAILED\", \"The PDF render worker is another version.\", {\n details: {\n asset: base === undefined ? null : `${base}build/pdf.worker.min.mjs`,\n expected: match[1] ?? null,\n actual: match[2] ?? null,\n },\n cause: error,\n });\n }\n }\n return undefined;\n}\n\n/** pdf.js transfers the bytes it's given, so it gets a copy unless the caller transfers. */\nfunction takeBytes(source: PdfBytes, transfer: boolean | undefined): Uint8Array {\n if (transfer) {\n const view = source instanceof Uint8Array ? source : new Uint8Array(source);\n const whole = view.byteOffset === 0 && view.byteLength === view.buffer.byteLength;\n if (whole && view.buffer instanceof ArrayBuffer) return view;\n }\n return copyBytes(source);\n}\n\nfunction normalizeRotation(rotation: number): PdfRotation {\n return addRotation(0, Number.isInteger(rotation) && rotation % 90 === 0 ? rotation : 0);\n}\n\nconst clamp = (value: number) => Math.min(1, Math.max(0, value));\n\nclass PdfJsEngine implements PdfEngine {\n #options: PdfJsEngineOptions;\n /** Files under `assetsUrl`, if it's set. */\n readonly #asset: AssetsResolver | undefined;\n #runtime: Promise<PdfJs> | undefined;\n #host: WorkerHost | undefined;\n #documents = new Set<PdfJsDocument>();\n #destroyed = false;\n\n constructor(options: PdfJsEngineOptions) {\n this.#options = options;\n // Checked now, so a URL with a query or fragment throws TypeError here.\n // A URL relative to the page is resolved on the first open, which only\n // happens in a browser, so the engine can be created on a server\n // (sdk-core ADR 0038).\n this.#asset =\n options.assetsUrl === undefined ? undefined : createAssetsResolver(options.assetsUrl);\n }\n\n async open(source: PdfBytes, options: PdfTransferOptions = {}): Promise<PdfDocumentHandle> {\n if (this.#destroyed) {\n throw new PdfError(\"WORKER_TERMINATED\", \"The PDF engine was destroyed.\");\n }\n throwIfAborted(options.signal);\n const data = takeBytes(source, options.transfer);\n this.#runtime ??= import(\"./runtime.js\").then((module) => module.pdfjs as PdfJs);\n const pdfjs = await this.#runtime;\n throwIfAborted(options.signal);\n const host = await this.#ensureHost(pdfjs);\n\n const base = this.#assetsBase();\n const task = pdfjs.getDocument({\n data,\n worker: host.pdfWorker,\n // Hardening (docs/adr/0001, docs/adr/0002): no XFA, and data files only\n // from the bundle or the application's own origin, never elsewhere.\n enableXfa: false,\n maxImageSize: this.#options.maxImagePixels ?? pdfLimitDefinitions.maxImagePixels.default,\n stopAtErrors: false,\n verbosity: pdfjs.VerbosityLevel.ERRORS,\n useWasm: true,\n ...(base\n ? {\n // Self-hosted: pdf.js fetches from the application's origin, which\n // also enables ICC colour (docs/adr/0006).\n useWorkerFetch: true,\n cMapUrl: `${base}cmaps/`,\n standardFontDataUrl: `${base}standard_fonts/`,\n wasmUrl: `${base}wasm/`,\n iccUrl: `${base}iccs/`,\n }\n : {\n // Inline: every file comes from the bundle, through the factory.\n useWorkerFetch: false,\n BinaryDataFactory: createInlineDataFactory(this.#options._onDataRequest),\n wasmUrl: NO_NETWORK_URL,\n }),\n });\n try {\n const proxy = await settle(host, task.promise, {\n signal: options.signal,\n onAbort: () => this.#cancel(task, host),\n message: \"The PDF couldn't be opened.\",\n });\n const document = new PdfJsDocument(pdfjs, proxy, task, host, () =>\n this.#documents.delete(document),\n );\n this.#documents.add(document);\n return document;\n } catch (error) {\n void task.destroy().catch(() => {});\n const mismatch = workerVersionMismatch(error, base);\n if (mismatch) {\n // The worker is unusable; the next open starts a new one.\n host.fail(mismatch);\n throw mismatch;\n }\n throw error;\n }\n }\n\n async destroy(): Promise<void> {\n if (this.#destroyed) return;\n this.#destroyed = true;\n await Promise.all([...this.#documents].map((document) => document.destroy()));\n this.#host?.fail(new PdfError(\"WORKER_TERMINATED\", \"The PDF engine was destroyed.\"));\n this.#host = undefined;\n }\n\n async #ensureHost(pdfjs: PdfJs): Promise<WorkerHost> {\n if (this.#host && !this.#host.failure) return this.#host;\n let worker: Worker;\n try {\n const base = this.#assetsBase();\n worker = base\n ? new Worker(`${base}build/pdf.worker.min.mjs`, { type: \"module\", name: \"hm-pdf-render\" })\n : (await import(\"./render-worker.js\")).createInlineWorker();\n } catch (cause) {\n throw new PdfError(\"WORKER_START_FAILED\", \"The PDF render worker couldn't start.\", {\n cause,\n });\n }\n this.#host = new WorkerHost(worker, pdfjs.PDFWorker.create({ port: worker }));\n return this.#host;\n }\n\n /** pdf.js's directory under `assetsUrl`, if it's set. */\n #assetsBase(): string | undefined {\n return this.#asset?.(\"pdfjs/\");\n }\n\n /** Stops a cancelled open, and terminates the worker if pdf.js doesn't stop in time. */\n #cancel(task: PDFDocumentLoadingTask, host: WorkerHost): void {\n const timer = setTimeout(\n () =>\n host.fail(\n new PdfError(\"WORKER_TERMINATED\", \"The worker was stopped to cancel an operation.\"),\n ),\n CANCEL_TIMEOUT,\n );\n void task\n .destroy()\n .catch(() => {})\n .finally(() => clearTimeout(timer));\n }\n}\n\nclass PdfJsDocument implements PdfDocumentHandle {\n readonly pageCount: number;\n #pdfjs: PdfJs;\n #proxy: PDFDocumentProxy;\n #task: PDFDocumentLoadingTask;\n #host: WorkerHost;\n #onDestroy: () => void;\n #destroyed = false;\n\n constructor(\n pdfjs: PdfJs,\n proxy: PDFDocumentProxy,\n task: PDFDocumentLoadingTask,\n host: WorkerHost,\n onDestroy: () => void,\n ) {\n this.#pdfjs = pdfjs;\n this.#proxy = proxy;\n this.#task = task;\n this.#host = host;\n this.#onDestroy = onDestroy;\n this.pageCount = proxy.numPages;\n }\n\n async getPage(pageIndex: number, options: PdfCallOptions = {}): Promise<PdfPageInfo> {\n const page = await this.#page(pageIndex, options);\n const { width, height } = page.getViewport({ scale: 1, rotation: 0 });\n return { width, height, rotation: normalizeRotation(page.rotate) };\n }\n\n async renderPage(\n pageIndex: number,\n canvas: HTMLCanvasElement,\n options: PdfRenderOptions,\n ): Promise<void> {\n if (!(options.scale > 0) || !Number.isFinite(options.scale)) {\n throw new RangeError(\n `The render scale must be a positive number, received ${options.scale}.`,\n );\n }\n const page = await this.#page(pageIndex, options);\n const rotation = addRotation(normalizeRotation(page.rotate), options.rotation ?? 0);\n const viewport = page.getViewport({ scale: options.scale, rotation });\n const area = viewport.width * viewport.height;\n const wanted = Math.max(options.pixelRatio ?? 1, Number.MIN_VALUE);\n // Lower the resolution, never the CSS size, to stay within the canvas cap (ADR 0004).\n const ratio = Math.min(wanted, Math.sqrt(PDF_MAX_CANVAS_PIXELS / Math.max(area, 1)));\n canvas.width = Math.max(1, Math.floor(viewport.width * ratio));\n canvas.height = Math.max(1, Math.floor(viewport.height * ratio));\n canvas.style.width = `${viewport.width}px`;\n canvas.style.height = `${viewport.height}px`;\n const context = canvas.getContext(\"2d\", { alpha: false });\n if (!context) {\n throw new PdfError(\"UNSUPPORTED_ENVIRONMENT\", \"The browser can't draw on a canvas.\", {\n details: { feature: \"CanvasRenderingContext2D\" },\n });\n }\n const task = page.render({\n canvas,\n canvasContext: context,\n viewport,\n transform: [canvas.width / viewport.width, 0, 0, canvas.height / viewport.height, 0, 0],\n annotationMode: this.#pdfjs.AnnotationMode.ENABLE,\n });\n try {\n await settle(this.#host, task.promise, {\n signal: options.signal,\n onAbort: () => task.cancel(),\n message: \"The page couldn't be drawn.\",\n });\n } finally {\n page.cleanup();\n }\n }\n\n async getTextContent(pageIndex: number, options: PdfCallOptions = {}): Promise<PdfTextContent> {\n const page = await this.#page(pageIndex, options);\n const content = await settle(this.#host, page.getTextContent(), {\n signal: options.signal,\n message: \"The page's text couldn't be read.\",\n });\n const viewport = page.getViewport({ scale: 1, rotation: 0 });\n const items: PdfTextItem[] = [];\n for (const item of content.items) {\n if (!(\"str\" in item)) continue;\n const { str, transform, width, hasEOL } = item as PdfJsTextItem;\n const [a = 1, b = 0, c = 0, d = 1, e = 0, f = 0] = transform;\n const fontHeight = Math.hypot(c, d);\n items.push({\n text: str,\n rect: toPageRect(viewport, [e, f, e + width, f + fontHeight]),\n angle: (Math.atan2(b, a) * 180) / Math.PI,\n endOfLine: hasEOL,\n });\n }\n return { items };\n }\n\n async getFormFields(\n pageIndex: number,\n options: PdfCallOptions = {},\n ): Promise<readonly PdfFormField[]> {\n const page = await this.#page(pageIndex, options);\n const annotations = (await settle(this.#host, page.getAnnotations({ intent: \"display\" }), {\n signal: options.signal,\n message: \"The page's form fields couldn't be read.\",\n })) as Array<Record<string, unknown>>;\n const viewport = page.getViewport({ scale: 1, rotation: 0 });\n const fields = new Map<string, PdfFormField>();\n for (const annotation of annotations) {\n const name = annotation[\"fieldName\"];\n if (annotation[\"subtype\"] !== \"Widget\" || typeof name !== \"string\" || fields.has(name)) {\n continue;\n }\n const value = annotation[\"fieldValue\"];\n const type =\n annotation[\"fieldType\"] === \"Tx\"\n ? \"text\"\n : annotation[\"fieldType\"] === \"Btn\" && annotation[\"checkBox\"]\n ? \"checkbox\"\n : undefined;\n if (!type) continue;\n fields.set(name, {\n name,\n type,\n rect: toPageRect(viewport, annotation[\"rect\"] as number[]),\n value:\n type === \"text\"\n ? typeof value === \"string\"\n ? value\n : \"\"\n : typeof value === \"string\" && value !== \"\" && value !== \"Off\",\n readOnly: annotation[\"readOnly\"] === true,\n });\n }\n return [...fields.values()];\n }\n\n async getLinks(pageIndex: number, options: PdfCallOptions = {}): Promise<readonly PdfLink[]> {\n const page = await this.#page(pageIndex, options);\n const annotations = (await settle(this.#host, page.getAnnotations({ intent: \"display\" }), {\n signal: options.signal,\n message: \"The page's links couldn't be read.\",\n })) as Array<Record<string, unknown>>;\n const viewport = page.getViewport({ scale: 1, rotation: 0 });\n const links: PdfLink[] = [];\n for (const annotation of annotations) {\n if (annotation[\"subtype\"] !== \"Link\" || typeof annotation[\"url\"] !== \"string\") continue;\n // pdf.js also allows ftp: and tel:, and turns some scripts into URLs;\n // the SDK keeps only http, https and mailto (ADR 0012).\n const url = safeLinkUrl(annotation[\"url\"]);\n if (url) links.push({ rect: toPageRect(viewport, annotation[\"rect\"] as number[]), url });\n }\n return links;\n }\n\n async destroy(): Promise<void> {\n if (this.#destroyed) return;\n this.#destroyed = true;\n this.#onDestroy();\n await this.#task.destroy().catch(() => {});\n }\n\n async #page(pageIndex: number, options: PdfCallOptions): Promise<PDFPageProxy> {\n if (this.#destroyed) {\n throw new PdfError(\"WORKER_TERMINATED\", \"The document was destroyed.\");\n }\n assertPageIndex(pageIndex, this.pageCount);\n throwIfAborted(options.signal);\n return settle(this.#host, this.#proxy.getPage(pageIndex + 1), {\n signal: options.signal,\n message: \"The page couldn't be read.\",\n });\n }\n}\n","import {\n createAssetsResolver,\n createWorkerClient,\n type WorkerClient,\n} from \"@hussmartinez/sdk-core\";\nimport { asPdfError } from \"../../core/errors/abort.js\";\nimport { PdfError } from \"../../core/errors/pdf-error.js\";\nimport type { PdfBuildJob } from \"../../core/model/build-job.js\";\nimport type { PdfBuildOptions, PdfProcessor } from \"../../core/ports/pdf-processor.js\";\nimport type { ProcessingContract } from \"./contract.js\";\n\n/**\n * Options for {@link createPdfProcessor}.\n *\n * @public\n */\nexport interface PdfProcessorOptions {\n /**\n * Where your application serves the package's `dist/assets/` directory,\n * on its own origin, such as `\"/pdf-sdk/\"`, the same URL as the engine's.\n * The worker then loads from `processing/processing.worker.js`, and\n * fetches `processing/qpdf.wasm`, which it checks against this version's\n * hash before using it. Use it for Content Security Policies without\n * `worker-src blob:` (docs/adr/0007). By default the worker is inlined.\n */\n readonly assetsUrl?: string | URL;\n}\n\n/**\n * Creates the SDK's {@link PdfProcessor}, backed by qpdf and pdf-lib in a\n * worker (docs/adr/0001, docs/adr/0002).\n *\n * Nothing starts until the first `build()`. By default the worker is\n * inlined, which needs `worker-src blob:` and `script-src 'wasm-unsafe-eval'`\n * in a Content Security Policy, and it never fetches anything. With\n * `assetsUrl`, it loads from your own origin instead. A build that can't stop\n * when cancelled terminates its worker, which starts again on the next build.\n *\n * @example\n * ```ts\n * const processor = createPdfProcessor();\n * const protectedPdf = await processor.build({\n * sources: [{ id: \"a\", bytes }],\n * pages: [{ source: \"a\", pageIndex: 0 }, { source: \"a\", pageIndex: 1, rotation: 90 }],\n * encrypt: { userPassword: \"correct horse\" },\n * });\n * ```\n *\n * @public\n */\nexport function createPdfProcessor(options: PdfProcessorOptions = {}): PdfProcessor {\n // Throws TypeError now for a URL with a query or fragment. A URL relative\n // to the page is resolved on the first build, which only happens in a\n // browser, so the processor can be created on a server (sdk-core ADR 0038).\n const asset =\n options.assetsUrl === undefined ? undefined : createAssetsResolver(options.assetsUrl);\n const workerPath = \"processing/processing.worker.js\";\n let client: WorkerClient<ProcessingContract> | undefined;\n let destroyed = false;\n\n const start = (): WorkerClient<ProcessingContract> => {\n client ??= createWorkerClient<ProcessingContract>({\n // The worker's chunk loads on the first build, not with this module.\n createWorker: () => {\n if (asset) {\n return new Worker(asset(workerPath), {\n type: \"module\",\n name: \"hm-pdf-processing\",\n });\n }\n if (!inlineWorker) {\n throw new PdfError(\"WORKER_START_FAILED\", \"The processing worker hasn't loaded.\");\n }\n return inlineWorker();\n },\n errorClasses: { PdfError },\n // A worker from another version of the package is refused with\n // WORKER_START_FAILED, naming the file to copy again (sdk-core ADR 0038).\n packageVersion: __PDF_SDK_VERSION__,\n ...(asset ? { workerAsset: asset(workerPath) } : {}),\n });\n return client;\n };\n let inlineWorker: (() => Worker) | undefined;\n\n return {\n async build(job: PdfBuildJob, options: PdfBuildOptions = {}): Promise<Uint8Array> {\n if (destroyed) {\n throw new PdfError(\"WORKER_TERMINATED\", \"The PDF processor was destroyed.\");\n }\n if (!asset) {\n inlineWorker ??= (await import(\"./processing-worker.js\")).createInlineWorker;\n }\n let outcome: Awaited<ReturnType<WorkerClient<ProcessingContract>[\"call\"]>>;\n try {\n outcome = await start().call(\"build\", job, {\n ...(options.signal ? { signal: options.signal } : {}),\n ...(options.onProgress ? { onProgress: options.onProgress } : {}),\n ...(options.transfer ? { transfer: true } : {}),\n });\n } catch (error) {\n // The client's own failures, such as ABORTED or WORKER_CRASHED, are\n // SdkErrors; the port promises PdfError.\n throw asPdfError(error, \"The PDF couldn't be built.\");\n }\n if (!outcome.ok) {\n throw outcome.error === \"RangeError\"\n ? new RangeError(outcome.message)\n : new TypeError(outcome.message);\n }\n return outcome.bytes;\n },\n async destroy(): Promise<void> {\n destroyed = true;\n client?.destroy();\n client = undefined;\n },\n };\n}\n","/**\n * The grid positions and sizes on a page are kept on: millionths of the\n * page (sdk-core ADR 0045, docs/adr/0003). Every position, size, stroke\n * width and text size the session stores is a whole number of millionths,\n * so a document saved in any language reproduces it exactly.\n *\n * @public\n */\nexport const PDF_POSITION_GRID = 1_000_000;\n\n/**\n * The most Unicode code points in a page key, a source id or an annotation\n * id. Lengths count code points, not UTF-16 units (sdk-core ADR 0045).\n *\n * @public\n */\nexport const PDF_MAX_ID_LENGTH = 128;\n\n/**\n * The most Unicode code points in a form field's name.\n *\n * @public\n */\nexport const PDF_MAX_FIELD_NAME_LENGTH = 1_000;\n\n/**\n * The most Unicode code points in a text note, or a form field's text value.\n *\n * @public\n */\nexport const PDF_MAX_TEXT_LENGTH = 10_000;\n\n/**\n * The most points in one pen or highlighter stroke.\n *\n * @public\n */\nexport const PDF_MAX_STROKE_POINTS = 10_000;\n\n/**\n * A fraction of the page, snapped to {@link PDF_POSITION_GRID}. It rounds\n * with `Math.round`, so a half rounds up, toward positive infinity.\n *\n * @internal\n */\nexport function toGrid(fraction: number): number {\n return Math.round(fraction * PDF_POSITION_GRID) / PDF_POSITION_GRID;\n}\n\n/**\n * Whether text has more than `max` Unicode code points. A character outside\n * the Basic Multilingual Plane, such as an emoji, is one code point, though\n * JavaScript's `length` counts it as two.\n *\n * @internal\n */\nexport function longerThan(text: string, max: number): boolean {\n // Every code point is one or two UTF-16 units.\n if (text.length <= max) return false;\n let count = 0;\n for (const _ of text) {\n count += 1;\n if (count > max) return true;\n }\n return false;\n}\n","import type { Applied, Reducer } from \"@hussmartinez/sdk-core\";\nimport { PdfError } from \"../errors/pdf-error.js\";\nimport type {\n PdfAnnotation,\n PdfColor,\n PdfStrokeAnnotation,\n PdfTextAnnotation,\n} from \"../model/annotations.js\";\nimport type { PdfFieldValue } from \"../model/document.js\";\nimport { addRotation, type PdfPoint } from \"../model/geometry.js\";\nimport type { PdfPlan, PdfPlanPage } from \"../model/plan.js\";\nimport {\n longerThan,\n PDF_MAX_FIELD_NAME_LENGTH,\n PDF_MAX_ID_LENGTH,\n PDF_MAX_STROKE_POINTS,\n PDF_MAX_TEXT_LENGTH,\n toGrid,\n} from \"../model/portable.js\";\n\n/**\n * Rotates pages by an angle, added to their current rotation.\n *\n * @public\n */\nexport interface PdfRotatePagesCommand {\n readonly type: \"pdf.rotatePages\";\n /** The keys of the pages to rotate. */\n readonly pages: readonly string[];\n /**\n * Degrees, clockwise, in multiples of 90 from -360 to 360. Negative turns\n * anticlockwise.\n */\n readonly angle: number;\n}\n\n/**\n * Removes pages from the plan. Their sources stay, so undo can bring them back.\n *\n * @public\n */\nexport interface PdfDeletePagesCommand {\n readonly type: \"pdf.deletePages\";\n readonly pages: readonly string[];\n}\n\n/**\n * Puts deleted pages back at their positions. It's what undoing a delete\n * runs, and it can be used directly.\n *\n * @public\n */\nexport interface PdfRestorePagesCommand {\n readonly type: \"pdf.restorePages\";\n /** Each page, and the index it takes in the resulting plan, in increasing order. */\n readonly entries: readonly { readonly index: number; readonly page: PdfPlanPage }[];\n}\n\n/**\n * Moves pages, keeping their relative order, so that the first of them ends\n * up at position `to` of the resulting plan.\n *\n * @public\n */\nexport interface PdfMovePagesCommand {\n readonly type: \"pdf.movePages\";\n readonly pages: readonly string[];\n /** The zero-based position of the first moved page in the resulting plan. */\n readonly to: number;\n}\n\n/**\n * Puts every page in a new order, given as every key exactly once. It's what\n * undoing a move runs.\n *\n * @public\n */\nexport interface PdfReorderPagesCommand {\n readonly type: \"pdf.reorderPages\";\n readonly order: readonly string[];\n}\n\n/**\n * Inserts pages of a registered source document. The session registers the\n * source and fills in `keys`, so redo inserts the same pages.\n *\n * @public\n */\nexport interface PdfInsertPagesCommand {\n readonly type: \"pdf.insertPages\";\n /** The source's ID. */\n readonly source: string;\n /** Zero-based indexes of the source's pages to insert, in order. */\n readonly pageIndexes: readonly number[];\n /** The zero-based position of the first inserted page in the resulting plan. */\n readonly at: number;\n /** The keys of the new pages, one per index. */\n readonly keys: readonly string[];\n}\n\n/**\n * Sets a form field's value in one source, or clears the session's value with\n * `null`, so the document's own value applies again.\n *\n * @public\n */\nexport interface PdfSetFieldValueCommand {\n readonly type: \"pdf.setFieldValue\";\n readonly source: string;\n readonly field: string;\n readonly value: PdfFieldValue | null;\n}\n\n/**\n * Adds an annotation to a page.\n *\n * @public\n */\nexport interface PdfAddAnnotationCommand {\n readonly type: \"pdf.addAnnotation\";\n /** The page's key. */\n readonly page: string;\n readonly annotation: PdfAnnotation;\n /** Its position among the page's annotations. Defaults to the end. */\n readonly index?: number;\n}\n\n/**\n * Removes an annotation from a page.\n *\n * @public\n */\nexport interface PdfRemoveAnnotationCommand {\n readonly type: \"pdf.removeAnnotation\";\n readonly page: string;\n /** The annotation's ID. */\n readonly id: string;\n}\n\n/**\n * An edit to the page plan (docs/adr/0003). Commands are plain,\n * structured-cloneable data, never carry bytes, and each has an exact\n * inverse, which is how undo works (ADR 0010).\n *\n * @public\n */\nexport type PdfCommand =\n | PdfRotatePagesCommand\n | PdfDeletePagesCommand\n | PdfRestorePagesCommand\n | PdfMovePagesCommand\n | PdfReorderPagesCommand\n | PdfInsertPagesCommand\n | PdfSetFieldValueCommand\n | PdfAddAnnotationCommand\n | PdfRemoveAnnotationCommand;\n\n/**\n * Why a command was refused, as a stable token: `details.reason` on the\n * `INVALID_COMMAND` error (sdk-core ADR 0045).\n *\n * - `malformed-command`: not shaped as a command of its type, such as a\n * missing field, a field of the wrong type, an unknown field, an empty\n * list of pages, or an id that's empty or over `PDF_MAX_ID_LENGTH` code\n * points.\n * - `unknown-command`: a `type` the session doesn't know.\n * - `unknown-page`: a page key the plan doesn't have.\n * - `duplicate-page`: a page named twice in one command.\n * - `last-page`: deleting every page; a document keeps at least one.\n * - `invalid-position`: a position outside the plan, or outside a page's\n * annotations.\n * - `invalid-rotation`: an angle that isn't a multiple of 90 degrees from\n * -360 to 360, or a page rotation other than 0, 90, 180 or 270.\n * - `invalid-order`: a new order that doesn't list every page exactly once.\n * - `invalid-keys`: an insert without one key per page.\n * - `duplicate-key`: a new page key the plan already has, or one given twice.\n * - `unknown-source`: a source the session doesn't hold.\n * - `page-out-of-range`: a page index its source doesn't have.\n * - `field-name-too-long`: a form field's name over\n * `PDF_MAX_FIELD_NAME_LENGTH` code points.\n * - `text-too-long`: a text note, or a field's text value, over\n * `PDF_MAX_TEXT_LENGTH` code points.\n * - `unknown-annotation`: an annotation id the page doesn't have.\n * - `duplicate-annotation`: an annotation id the page already has.\n * - `unsupported-annotation`: an annotation type the session doesn't edit,\n * such as `signature`, whose image the portable format can't carry yet.\n * - `outside-page`: a position outside the page, 0 to 1 on each axis.\n * - `invalid-size`: a stroke width or text size that isn't more than 0 and\n * at most 1, after snapping to `PDF_POSITION_GRID`.\n * - `too-many-points`: a stroke with no points, or over\n * `PDF_MAX_STROKE_POINTS`.\n * - `invalid-color`: a colour that isn't `#rrggbb` in lowercase.\n *\n * @public\n */\nexport type PdfCommandRejection =\n | \"malformed-command\"\n | \"unknown-command\"\n | \"unknown-page\"\n | \"duplicate-page\"\n | \"last-page\"\n | \"invalid-position\"\n | \"invalid-rotation\"\n | \"invalid-order\"\n | \"invalid-keys\"\n | \"duplicate-key\"\n | \"unknown-source\"\n | \"page-out-of-range\"\n | \"field-name-too-long\"\n | \"text-too-long\"\n | \"unknown-annotation\"\n | \"duplicate-annotation\"\n | \"unsupported-annotation\"\n | \"outside-page\"\n | \"invalid-size\"\n | \"too-many-points\"\n | \"invalid-color\";\n\n/**\n * A refusal while checking a command, which the reducer turns into a\n * `PdfError`, and a document reader into its own code.\n *\n * @internal\n */\nexport class Invalid extends Error {\n readonly reason: PdfCommandRejection;\n constructor(reason: PdfCommandRejection, message: string) {\n super(message);\n this.reason = reason;\n }\n}\n\nexport function invalid(reason: PdfCommandRejection, message: string): never {\n throw new Invalid(reason, message);\n}\n\nfunction malformed(message: string): never {\n return invalid(\"malformed-command\", message);\n}\n\n/** Whether a value is a plain object: not `null`, and not a list. @internal */\nexport const isRecord = <T>(value: unknown): value is T =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\n/**\n * Refuses a field the object's type doesn't have, rather than dropping it,\n * and requires the others, except the optional ones.\n *\n * @internal\n */\nexport function fields(\n value: object,\n required: readonly string[],\n what: string,\n optional: readonly string[] = [],\n): void {\n for (const name of Object.keys(value)) {\n if (!required.includes(name) && !optional.includes(name)) {\n malformed(`${what} has no field \"${name}\"`);\n }\n }\n for (const name of required) {\n if (!Object.hasOwn(value, name)) malformed(`${what} needs \"${name}\"`);\n }\n}\n\nconst isIndex = (value: unknown): value is number =>\n Number.isSafeInteger(value) && (value as number) >= 0;\n\n/** A page key, source id or annotation id: 1 to `PDF_MAX_ID_LENGTH` code points. @internal */\nexport function checkId(value: unknown, what: string): string {\n if (typeof value !== \"string\" || value === \"\" || longerThan(value, PDF_MAX_ID_LENGTH)) {\n malformed(`${what} is text of 1 to ${PDF_MAX_ID_LENGTH} code points`);\n }\n return value;\n}\n\nfunction checkKeys(value: unknown, what: string): string[] {\n if (!Array.isArray(value) || value.length === 0) malformed(`${what} is a list of page keys`);\n return value.map((key) => checkId(key, \"a page key\"));\n}\n\n/** A number from 0 to 1, a position on the page, snapped to the grid. */\nfunction checkFraction(value: unknown, what: string): number {\n if (typeof value !== \"number\" || !Number.isFinite(value)) malformed(`${what} is a number`);\n if (value < 0 || value > 1) invalid(\"outside-page\", `${what} is from 0 to 1`);\n return toGrid(value);\n}\n\n/** A size, more than 0 and at most 1, snapped to the grid. */\nfunction checkSize(value: unknown, what: string): number {\n if (typeof value !== \"number\" || !Number.isFinite(value)) malformed(`${what} is a number`);\n const size = toGrid(value);\n if (!(size > 0 && size <= 1)) invalid(\"invalid-size\", `${what} is more than 0 and at most 1`);\n return size;\n}\n\nfunction checkPoint(value: unknown, what: string): PdfPoint {\n if (!isRecord<PdfPoint>(value)) malformed(`${what} is an object`);\n fields(value, [\"x\", \"y\"], what);\n return { x: checkFraction(value.x, `${what}.x`), y: checkFraction(value.y, `${what}.y`) };\n}\n\nconst COLOR = /^#[0-9a-f]{6}$/;\n\nfunction checkColor(value: unknown): PdfColor {\n if (typeof value !== \"string\") malformed(\"a colour is text\");\n if (!COLOR.test(value)) invalid(\"invalid-color\", \"a colour is #rrggbb, in lowercase\");\n return value as PdfColor;\n}\n\nfunction checkText(value: unknown, what: string): string {\n if (typeof value !== \"string\") malformed(`${what} is text`);\n if (longerThan(value, PDF_MAX_TEXT_LENGTH)) {\n invalid(\"text-too-long\", `${what} has more than ${PDF_MAX_TEXT_LENGTH} code points`);\n }\n return value;\n}\n\n/**\n * An annotation, checked and copied, with its positions and sizes snapped\n * to the grid. Signatures are refused: the portable format can't carry\n * their image yet (docs/adr/0003).\n *\n * @internal\n */\nexport function checkAnnotation(value: unknown): PdfAnnotation {\n if (!isRecord<{ type: unknown }>(value)) malformed(\"an annotation is an object\");\n const { type } = value;\n if (type === \"signature\") {\n invalid(\"unsupported-annotation\", \"signature annotations can't be edited yet\");\n }\n if (type === \"pen\" || type === \"highlight\") {\n const stroke = value as PdfStrokeAnnotation;\n fields(stroke, [\"id\", \"type\", \"points\", \"color\", \"width\"], \"a stroke\");\n if (!Array.isArray(stroke.points)) malformed(\"a stroke's points are a list\");\n if (stroke.points.length === 0 || stroke.points.length > PDF_MAX_STROKE_POINTS) {\n invalid(\"too-many-points\", `a stroke has 1 to ${PDF_MAX_STROKE_POINTS} points`);\n }\n return {\n id: checkId(stroke.id, \"an annotation id\"),\n type,\n points: stroke.points.map((point) => checkPoint(point, \"a point\")),\n color: checkColor(stroke.color),\n width: checkSize(stroke.width, \"a stroke's width\"),\n };\n }\n if (type === \"text\") {\n const note = value as PdfTextAnnotation;\n fields(note, [\"id\", \"type\", \"at\", \"text\", \"size\", \"color\"], \"a text note\");\n return {\n id: checkId(note.id, \"an annotation id\"),\n type,\n at: checkPoint(note.at, \"a text note's position\"),\n text: checkText(note.text, \"a text note\"),\n size: checkSize(note.size, \"a text size\"),\n color: checkColor(note.color),\n };\n }\n return malformed(\"an annotation is a pen, highlight or text annotation\");\n}\n\n/** Looks up how many pages a source has, or `undefined` for one the session doesn't hold. */\nexport type PdfSourcePageCount = (source: string) => number | undefined;\n\nfunction checkPageOf(source: string, pageIndex: number, pageCount: PdfSourcePageCount): void {\n const count = pageCount(source);\n if (count === undefined) invalid(\"unknown-source\", `the session has no source ${source}`);\n if (pageIndex >= count) {\n invalid(\"page-out-of-range\", `source ${source} has no page index ${pageIndex}`);\n }\n}\n\nconst ROTATIONS: readonly number[] = [0, 90, 180, 270];\n/** The angles a rotation command takes: a whole list, so a schema's `enum` can match it exactly. */\nconst ANGLES: readonly number[] = [-360, -270, -180, -90, 0, 90, 180, 270, 360];\n\n/** A whole plan page, as `pdf.restorePages` carries it. @internal */\nexport function checkPage(value: unknown, pageCount: PdfSourcePageCount): PdfPlanPage {\n if (!isRecord<PdfPlanPage>(value)) malformed(\"a page is an object\");\n fields(value, [\"key\", \"source\", \"pageIndex\", \"rotation\", \"annotations\"], \"a page\");\n const key = checkId(value.key, \"a page key\");\n const source = checkId(value.source, \"a source id\");\n if (!isIndex(value.pageIndex)) malformed(\"a page index is a whole number from 0\");\n if (!ROTATIONS.includes(value.rotation)) {\n invalid(\"invalid-rotation\", \"a page's rotation is 0, 90, 180 or 270\");\n }\n if (!Array.isArray(value.annotations)) malformed(\"a page's annotations are a list\");\n checkPageOf(source, value.pageIndex, pageCount);\n const annotations = value.annotations.map(checkAnnotation);\n if (new Set(annotations.map(({ id }) => id)).size !== annotations.length) {\n invalid(\"duplicate-annotation\", `page ${key} has two annotations with one id`);\n }\n return { key, source, pageIndex: value.pageIndex, rotation: value.rotation, annotations };\n}\n\n/** The positions of the given keys, in plan order, failing on unknown or repeated keys. */\nfunction positions(plan: PdfPlan, keys: readonly string[]): number[] {\n const wanted = new Set(keys);\n if (wanted.size !== keys.length) invalid(\"duplicate-page\", \"a page appears twice\");\n const found = plan.pages.flatMap((page, index) => (wanted.has(page.key) ? [index] : []));\n if (found.length !== wanted.size) {\n const known = new Set(plan.pages.map((page) => page.key));\n const missing = keys.filter((key) => !known.has(key));\n invalid(\"unknown-page\", `the plan has no page ${missing.join(\", \")}`);\n }\n return found;\n}\n\nfunction withPages(plan: PdfPlan, pages: readonly PdfPlanPage[]): PdfPlan {\n return { pages, formValues: plan.formValues };\n}\n\n/**\n * A record with one key set or removed. Keys are data: `__proto__` is an\n * ordinary own key, never the prototype (sdk-core ADR 0045, section 8).\n */\nfunction withKey<V>(\n record: Readonly<Record<string, V>>,\n key: string,\n value: V | undefined,\n): Record<string, V> {\n const entries = Object.entries(record).filter(([name]) => name !== key);\n if (value !== undefined) entries.push([key, value]);\n return Object.fromEntries(entries) as Record<string, V>;\n}\n\n/** Each command's fields: required, and optional. */\nconst COMMAND_FIELDS: Readonly<\n Record<PdfCommand[\"type\"], readonly [readonly string[], readonly string[]]>\n> = {\n \"pdf.rotatePages\": [[\"type\", \"pages\", \"angle\"], []],\n \"pdf.deletePages\": [[\"type\", \"pages\"], []],\n \"pdf.restorePages\": [[\"type\", \"entries\"], []],\n \"pdf.movePages\": [[\"type\", \"pages\", \"to\"], []],\n \"pdf.reorderPages\": [[\"type\", \"order\"], []],\n \"pdf.insertPages\": [[\"type\", \"source\", \"pageIndexes\", \"at\", \"keys\"], []],\n \"pdf.setFieldValue\": [[\"type\", \"source\", \"field\", \"value\"], []],\n \"pdf.addAnnotation\": [[\"type\", \"page\", \"annotation\"], [\"index\"]],\n \"pdf.removeAnnotation\": [[\"type\", \"page\", \"id\"], []],\n};\n\nfunction apply(\n plan: PdfPlan,\n input: unknown,\n pageCount: PdfSourcePageCount,\n): Applied<PdfPlan, PdfCommand> {\n if (!isRecord<{ type: unknown }>(input)) malformed(\"a command is an object\");\n const { type } = input;\n if (typeof type !== \"string\") malformed(\"a command's type is text\");\n if (!Object.hasOwn(COMMAND_FIELDS, type)) invalid(\"unknown-command\", `\"${type}\" isn't a command`);\n const command = input as PdfCommand;\n const [required, optional] = COMMAND_FIELDS[command.type];\n fields(command, required, command.type, optional);\n\n switch (command.type) {\n case \"pdf.rotatePages\": {\n const pages = checkKeys(command.pages, \"pages\");\n const { angle } = command;\n if (typeof angle !== \"number\") malformed(\"an angle is a number\");\n if (!ANGLES.includes(angle)) {\n invalid(\"invalid-rotation\", \"an angle is a multiple of 90 degrees, from -360 to 360\");\n }\n const at = new Set(positions(plan, pages));\n return {\n state: withPages(\n plan,\n plan.pages.map((page, index) =>\n at.has(index) ? { ...page, rotation: addRotation(page.rotation, angle) } : page,\n ),\n ),\n // `0 - angle`, not `-angle`: an angle of 0 must not undo as -0.\n inverse: { type: \"pdf.rotatePages\", pages, angle: 0 - angle },\n };\n }\n\n case \"pdf.deletePages\": {\n const at = positions(plan, checkKeys(command.pages, \"pages\"));\n if (at.length === plan.pages.length) invalid(\"last-page\", \"a document keeps one page\");\n const removed = new Set(at);\n return {\n state: withPages(\n plan,\n plan.pages.filter((_, index) => !removed.has(index)),\n ),\n inverse: {\n type: \"pdf.restorePages\",\n entries: at.map((index) => ({ index, page: plan.pages[index] as PdfPlanPage })),\n },\n };\n }\n\n case \"pdf.restorePages\": {\n if (!Array.isArray(command.entries) || command.entries.length === 0) {\n malformed(\"entries is a list of pages and their positions\");\n }\n const known = new Set(plan.pages.map((page) => page.key));\n const pages = [...plan.pages];\n let previous = -1;\n for (const entry of command.entries as unknown[]) {\n if (!isRecord<{ index: unknown; page: unknown }>(entry)) malformed(\"an entry is an object\");\n fields(entry, [\"index\", \"page\"], \"an entry\");\n const page = checkPage(entry.page, pageCount);\n const { index } = entry;\n if (!isIndex(index)) malformed(\"an entry's index is a whole number from 0\");\n if (known.has(page.key)) invalid(\"duplicate-key\", `the plan already has page ${page.key}`);\n if (index <= previous || index > pages.length) {\n invalid(\"invalid-position\", `page ${page.key} can't be restored at ${index}`);\n }\n pages.splice(index, 0, page);\n known.add(page.key);\n previous = index;\n }\n return {\n state: withPages(plan, pages),\n inverse: {\n type: \"pdf.deletePages\",\n pages: command.entries.map(({ page }) => page.key),\n },\n };\n }\n\n case \"pdf.movePages\": {\n const keys = checkKeys(command.pages, \"pages\");\n if (!isIndex(command.to)) malformed(\"to is a whole number from 0\");\n const moved = new Set(positions(plan, keys));\n const block = plan.pages.filter((_, index) => moved.has(index));\n const rest = plan.pages.filter((_, index) => !moved.has(index));\n if (command.to > rest.length) {\n invalid(\"invalid-position\", `pages can't be moved to ${command.to}`);\n }\n return {\n state: withPages(plan, [...rest.slice(0, command.to), ...block, ...rest.slice(command.to)]),\n inverse: { type: \"pdf.reorderPages\", order: plan.pages.map((page) => page.key) },\n };\n }\n\n case \"pdf.reorderPages\": {\n const order = checkKeys(command.order, \"order\");\n const byKey = new Map(plan.pages.map((page) => [page.key, page]));\n if (\n order.length !== plan.pages.length ||\n new Set(order).size !== order.length ||\n order.some((key) => !byKey.has(key))\n ) {\n invalid(\"invalid-order\", \"a new order lists every page of the plan exactly once\");\n }\n return {\n state: withPages(\n plan,\n order.map((key) => byKey.get(key) as PdfPlanPage),\n ),\n inverse: { type: \"pdf.reorderPages\", order: plan.pages.map((page) => page.key) },\n };\n }\n\n case \"pdf.insertPages\": {\n const source = checkId(command.source, \"a source id\");\n const { pageIndexes, at } = command;\n if (!Array.isArray(pageIndexes) || pageIndexes.length === 0 || !pageIndexes.every(isIndex)) {\n malformed(\"pageIndexes is a list of whole numbers from 0\");\n }\n const keys = checkKeys(command.keys, \"keys\");\n if (!isIndex(at)) malformed(\"at is a whole number from 0\");\n if (keys.length !== pageIndexes.length)\n invalid(\"invalid-keys\", \"an insert needs one key per page\");\n const known = new Set(plan.pages.map((page) => page.key));\n if (new Set(keys).size !== keys.length || keys.some((key) => known.has(key))) {\n invalid(\"duplicate-key\", \"inserted pages need new keys, each once\");\n }\n if (at > plan.pages.length) invalid(\"invalid-position\", `pages can't be inserted at ${at}`);\n for (const pageIndex of pageIndexes) checkPageOf(source, pageIndex, pageCount);\n const inserted = pageIndexes.map(\n (pageIndex, index): PdfPlanPage => ({\n key: keys[index] as string,\n source,\n pageIndex,\n rotation: 0,\n annotations: [],\n }),\n );\n return {\n state: withPages(plan, [...plan.pages.slice(0, at), ...inserted, ...plan.pages.slice(at)]),\n inverse: { type: \"pdf.deletePages\", pages: keys },\n };\n }\n\n case \"pdf.setFieldValue\": {\n const source = checkId(command.source, \"a source id\");\n const { field, value } = command;\n if (typeof field !== \"string\" || field === \"\") malformed(\"a field's name is text\");\n if (longerThan(field, PDF_MAX_FIELD_NAME_LENGTH)) {\n invalid(\n \"field-name-too-long\",\n `a field's name has at most ${PDF_MAX_FIELD_NAME_LENGTH} code points`,\n );\n }\n if (value !== null && typeof value !== \"boolean\") checkText(value, \"a field's value\");\n if (pageCount(source) === undefined) {\n invalid(\"unknown-source\", `the session has no source ${source}`);\n }\n const current = Object.hasOwn(plan.formValues, source)\n ? (plan.formValues[source] as Readonly<Record<string, PdfFieldValue>>)\n : {};\n const previous = Object.hasOwn(current, field) ? (current[field] as PdfFieldValue) : null;\n const next = withKey(current, field, value ?? undefined);\n const formValues = withKey(\n plan.formValues,\n source,\n Object.keys(next).length === 0 ? undefined : next,\n );\n return {\n state: { pages: plan.pages, formValues },\n inverse: { type: \"pdf.setFieldValue\", source, field, value: previous },\n };\n }\n\n case \"pdf.addAnnotation\": {\n const key = checkId(command.page, \"a page key\");\n const annotation = checkAnnotation(command.annotation);\n if (command.index !== undefined && !isIndex(command.index)) {\n malformed(\"an annotation's index is a whole number from 0\");\n }\n const [at] = positions(plan, [key]) as [number];\n const page = plan.pages[at] as PdfPlanPage;\n if (page.annotations.some((existing) => existing.id === annotation.id)) {\n invalid(\"duplicate-annotation\", `page ${key} already has annotation ${annotation.id}`);\n }\n const index = command.index ?? page.annotations.length;\n if (index > page.annotations.length) {\n invalid(\"invalid-position\", `the annotation can't go at ${index}`);\n }\n const annotations = [...page.annotations];\n annotations.splice(index, 0, annotation);\n const pages = [...plan.pages];\n pages[at] = { ...page, annotations };\n return {\n state: withPages(plan, pages),\n inverse: { type: \"pdf.removeAnnotation\", page: key, id: annotation.id },\n };\n }\n\n case \"pdf.removeAnnotation\": {\n const key = checkId(command.page, \"a page key\");\n const id = checkId(command.id, \"an annotation id\");\n const [at] = positions(plan, [key]) as [number];\n const page = plan.pages[at] as PdfPlanPage;\n const index = page.annotations.findIndex((annotation) => annotation.id === id);\n if (index < 0) invalid(\"unknown-annotation\", `page ${key} has no annotation ${id}`);\n const pages = [...plan.pages];\n pages[at] = { ...page, annotations: page.annotations.filter((_, place) => place !== index) };\n return {\n state: withPages(plan, pages),\n inverse: {\n type: \"pdf.addAnnotation\",\n page: key,\n annotation: page.annotations[index] as PdfAnnotation,\n index,\n },\n };\n }\n }\n}\n\n/**\n * Creates the session's reducer: a pure function that applies one command\n * to a plan, without changing it, and returns the new plan with the\n * command's inverse (docs/adr/0003, ADR 0029 in sdk-core). It needs each\n * source's page count, to check the pages a command names.\n *\n * Commands are strict, as the portable format is (sdk-core ADR 0045): an\n * invalid command, including one with a field its type doesn't have,\n * throws `PdfError` with `INVALID_COMMAND` and a {@link PdfCommandRejection}\n * as `details.reason`, and changes nothing. Positions and sizes are snapped\n * to millionths of the page (`PDF_POSITION_GRID`), so the plan only ever\n * holds values on the grid.\n *\n * @internal\n */\nexport function createPdfReducer(pageCount: PdfSourcePageCount): Reducer<PdfPlan, PdfCommand> {\n return (plan, command) => {\n try {\n return apply(plan, command, pageCount);\n } catch (error) {\n if (!(error instanceof Invalid)) throw error;\n throw new PdfError(\"INVALID_COMMAND\", `Invalid command: ${error.message}.`, {\n details: { reason: error.reason },\n });\n }\n };\n}\n","import type { PdfAnnotation } from \"./annotations.js\";\nimport type { PdfFieldValue } from \"./document.js\";\nimport type { PdfRotation } from \"./geometry.js\";\n\n/**\n * One page of the page plan (docs/adr/0003): a page of a source document,\n * with a rotation added to its own, and the annotations drawn on it. The key\n * is stable while the page moves, so annotations, thumbnails and the\n * selection follow it.\n *\n * @public\n */\nexport interface PdfPlanPage {\n /** Unique within the session, and never reused. */\n readonly key: string;\n /** The ID of the source document the page comes from. */\n readonly source: string;\n /** The page's zero-based index in its source. */\n readonly pageIndex: number;\n /** Rotation added to the page's own `/Rotate`. */\n readonly rotation: PdfRotation;\n /** Annotations drawn on the page, in drawing order. */\n readonly annotations: readonly PdfAnnotation[];\n}\n\n/**\n * The document being edited, as a plan over immutable sources\n * (docs/adr/0003): the pages in order, and form values per source. Bytes\n * are only built from it on export.\n *\n * @public\n */\nexport interface PdfPlan {\n readonly pages: readonly PdfPlanPage[];\n /** Form values set in the session, by source ID, then field name. */\n readonly formValues: Readonly<Record<string, Readonly<Record<string, PdfFieldValue>>>>;\n}\n\n/** An empty plan. @internal */\nexport const EMPTY_PLAN: PdfPlan = Object.freeze({\n pages: Object.freeze([]),\n formValues: Object.freeze({}),\n});\n","/** The longest name kept, in code points (docs/adr/0009). */\nexport const MAX_NAME_LENGTH = 128;\n\n/** Control characters (Unicode category Cc: C0, DEL and C1). */\nconst CONTROL = /\\p{Cc}/gu;\n/** Bidirectional formatting characters, which can disguise an extension. */\nconst BIDI = /[\\u061C\\u200E\\u200F\\u202A-\\u202E\\u2066-\\u2069]/gu;\n/** Characters Windows refuses in file names. Separators are handled first. */\nconst REFUSED = /[<>:\"|?*]/gu;\n\n/**\n * Cleans a file name chosen by whoever made the file, which is hostile input\n * (docs/adr/0009). The result is safe as text content and as a download's\n * name: one path segment, with no control or bidirectional formatting\n * characters, no characters Windows refuses, no leading dots and at most\n * {@link MAX_NAME_LENGTH} code points. Returns `undefined` when nothing is\n * left, or for anything that isn't a string.\n */\nexport function cleanFileName(raw: unknown): string | undefined {\n if (typeof raw !== \"string\") return undefined;\n let name = raw.replace(CONTROL, \"\").replace(BIDI, \"\");\n name = name.slice(Math.max(name.lastIndexOf(\"/\"), name.lastIndexOf(\"\\\\\")) + 1);\n // Normalised after the removals, which could leave a base letter and its\n // combining mark side by side.\n name = name.replace(REFUSED, \"\").normalize(\"NFC\");\n // Leading dots would hide the file on some systems, or leave only an\n // extension; whitespace at either end is never meant.\n name = name.replace(/^[\\s.]+/u, \"\").trimEnd();\n // Array.from splits by code points, so no surrogate pair is cut in half.\n const points = Array.from(name);\n if (points.length > MAX_NAME_LENGTH) {\n name = points.slice(0, MAX_NAME_LENGTH).join(\"\").trimEnd();\n }\n return name === \"\" ? undefined : name;\n}\n","import {\n applyCommands,\n checkFile,\n createHistory,\n createStore,\n type HistoryStep,\n withProcessingTime,\n} from \"@hussmartinez/sdk-core\";\nimport { asPdfError, throwIfAborted } from \"../errors/abort.js\";\nimport { isPdfError, PdfError } from \"../errors/pdf-error.js\";\nimport { type PdfFilePolicyOverrides, type PdfLimitName, pdfLimits } from \"../errors/pdf-limits.js\";\nimport type { PdfBuildJob, PdfCompression, PdfEncryption } from \"../model/build-job.js\";\nimport { copyBytes } from \"../model/bytes.js\";\nimport type {\n PdfBytes,\n PdfFormField,\n PdfLink,\n PdfPageInfo,\n PdfTextContent,\n} from \"../model/document.js\";\nimport { addRotation } from \"../model/geometry.js\";\nimport { EMPTY_PLAN, type PdfPlan, type PdfPlanPage } from \"../model/plan.js\";\nimport { createPdfReducer, type PdfCommand } from \"../operations/commands.js\";\nimport type { PdfCallOptions } from \"../ports/options.js\";\nimport type { PdfDocumentHandle, PdfEngine, PdfRenderOptions } from \"../ports/pdf-engine.js\";\nimport type { PdfBuildOptions, PdfProcessor } from \"../ports/pdf-processor.js\";\nimport { cleanFileName } from \"./source-name.js\";\n\n/**\n * A source document the session holds: opened or inserted, never changed.\n *\n * @public\n */\nexport interface PdfSourceInfo {\n /** Unique within the session, and never reused. */\n readonly id: string;\n readonly pageCount: number;\n /** The size of its bytes. */\n readonly byteLength: number;\n /**\n * The file's name, from `File.name` or the `name` option, cleaned as\n * docs/adr/0009 describes: one path segment, without control or\n * bidirectional formatting characters, at most 128 code points. Absent\n * when there was none. Show it only as text; it never reaches `onEvent`.\n */\n readonly name?: string;\n}\n\n/**\n * A file policy warning: a value at or above a limit's warning threshold,\n * but within its maximum (ADR 0020). Show its text from\n * `warnings.<limit>` in the message catalogue, with `actual` as a parameter.\n *\n * @public\n */\nexport interface PdfWarning {\n readonly limit: PdfLimitName;\n readonly actual: number;\n}\n\n/**\n * What the session is doing.\n *\n * - `empty`: no document is open.\n * - `opening`: a document is being opened, replacing any other.\n * - `ready`: a document is open.\n * - `error`: no document is open, because the last open failed; `error`\n * says why. A failed open while a document is open keeps that document,\n * with the status `ready` and `error` set.\n *\n * @public\n */\nexport type PdfSessionStatus = \"empty\" | \"opening\" | \"ready\" | \"error\";\n\n/**\n * The session's state at one moment. Snapshots are immutable: every change\n * makes a new one, so `useSyncExternalStore` and other subscribers can\n * compare them by identity.\n *\n * @public\n */\nexport interface PdfSessionSnapshot {\n readonly status: PdfSessionStatus;\n /** The document being edited: its pages, in order, and form values. */\n readonly plan: PdfPlan;\n /** The source documents the session holds. */\n readonly sources: readonly PdfSourceInfo[];\n readonly canUndo: boolean;\n readonly canRedo: boolean;\n /** Whether a document is being opened or inserted. */\n readonly busy: boolean;\n /** Why the last open or insert failed. Show its text by its code. */\n readonly error: PdfError | undefined;\n /** Limits the open documents are close to. */\n readonly warnings: readonly PdfWarning[];\n /**\n * The bytes of every document the session holds, which the\n * `maxSessionSize` limit counts: those the plan uses, and those the undo\n * and redo history can bring back (docs/adr/0004).\n */\n readonly sessionBytes: number;\n /**\n * Whether undo steps were dropped since the document opened, to make room\n * for an insert within `maxSessionSize`. Editors say so, because the\n * earliest edits can no longer be undone (ADR 0010).\n */\n readonly historyTrimmed: boolean;\n /**\n * The keys of the selected pages, in plan order. Tools act on them, such as\n * rotating the selection. View state: not part of the plan and never in\n * events, but undo and redo bring back the selection and current page\n * that went with each step (docs/adr/0008).\n */\n readonly selection: readonly string[];\n /** The key of the page the user is looking at, if a document is open. */\n readonly currentPage: string | undefined;\n /**\n * The latest request to bring a page into view, from `goToPage`. Viewers\n * scroll to `page` each time `sequence` changes.\n */\n readonly navigation: { readonly page: string; readonly sequence: number } | undefined;\n}\n\n/**\n * Anonymous usage events, for a host's analytics (ADR 0010). They never\n * contain file names, contents, form values or annotation text.\n *\n * @public\n */\nexport type PdfSessionEvent =\n | { readonly type: \"document_opened\"; readonly pageCount: number }\n | { readonly type: \"document_closed\" }\n | { readonly type: \"pages_inserted\"; readonly pageCount: number }\n | { readonly type: \"command\"; readonly commands: readonly PdfCommand[\"type\"][] }\n | { readonly type: \"undo\" }\n | { readonly type: \"redo\" }\n | {\n readonly type: \"document_exported\";\n readonly pageCount: number;\n readonly compressed: boolean;\n readonly encrypted: boolean;\n }\n | {\n readonly type: \"failed\";\n readonly operation: \"open\" | \"insert\" | \"export\";\n readonly code: string;\n };\n\n/**\n * Options for {@link createPdfSession}.\n *\n * @public\n */\nexport interface PdfSessionOptions {\n /** Opens, reads and renders documents, such as `createPdfJsEngine()`. */\n readonly engine: PdfEngine;\n /** Builds exported documents, such as `createPdfProcessor()`. Needed for `export()`. */\n readonly processor?: PdfProcessor;\n /** Limits for untrusted files (docs/adr/0004). Unknown names throw. */\n readonly filePolicy?: PdfFilePolicyOverrides;\n /** Receives anonymous usage events. Errors it throws are ignored. */\n readonly onEvent?: (event: PdfSessionEvent) => void;\n}\n\n/**\n * Options for {@link PdfSession.open}.\n *\n * @public\n */\nexport interface PdfOpenOptions extends PdfCallOptions {\n /**\n * The file's name, for bytes or a `Blob` that isn't a `File`. It wins over\n * `File.name`, and is cleaned before it's kept (docs/adr/0009).\n */\n readonly name?: string;\n}\n\n/**\n * Options for {@link PdfSession.insert}.\n *\n * @public\n */\nexport interface PdfInsertOptions extends PdfOpenOptions {\n /** The position of the first inserted page. Defaults to the end. */\n readonly at?: number;\n /** Zero-based indexes of the pages to insert. Defaults to every page. */\n readonly pageIndexes?: readonly number[];\n}\n\n/**\n * Options for {@link PdfSession.export}.\n *\n * @public\n */\nexport interface PdfExportOptions extends PdfCallOptions {\n /** Compress the result, losslessly unless `images` is set. */\n readonly compress?: PdfCompression;\n /** Encrypt the result with AES-256. */\n readonly encrypt?: PdfEncryption;\n /** Called as the export moves through its steps. */\n readonly onProgress?: PdfBuildOptions[\"onProgress\"];\n}\n\n/**\n * The document being edited, as a framework-agnostic store (ADR 0008): a\n * page plan over the documents opened and inserted, edited with commands,\n * with undo and redo (ADR 0010, docs/adr/0003). React binds to it with\n * `useSyncExternalStore`, and the element binds to the same store.\n *\n * @public\n */\nexport interface PdfSession {\n /** The current snapshot, the same object until something changes. */\n getSnapshot(): PdfSessionSnapshot;\n /** Calls the listener after every change. Returns a function that unsubscribes. */\n subscribe(listener: () => void): () => void;\n /**\n * Opens a document, replacing the current one and its history once it has\n * opened. The file is checked against the file policy before it's read.\n * Rejects with a `PdfError`, which the snapshot also holds; the current\n * document, if any, stays open.\n */\n open(file: Blob | PdfBytes, options?: PdfOpenOptions): Promise<void>;\n /**\n * Inserts the pages of another document, as one undoable step. If the\n * documents held would then exceed `maxSessionSize`, the session first\n * drops the redo steps, then the oldest undo steps, as far as needed to\n * release documents only they refer to, and sets `historyTrimmed`. If even\n * that isn't enough, it rejects with `SESSION_TOO_LARGE` and changes\n * nothing.\n */\n insert(file: Blob | PdfBytes, options?: PdfInsertOptions): Promise<void>;\n /**\n * Runs one command, or several as one undoable step. Throws `PdfError`\n * with `INVALID_COMMAND` for a command that doesn't fit the plan, with a\n * `PdfCommandRejection` as `details.reason`, and changes nothing then.\n * Positions and sizes are snapped to millionths of the page\n * (`PDF_POSITION_GRID`).\n */\n execute(commands: PdfCommand | readonly PdfCommand[]): void;\n undo(): void;\n redo(): void;\n /** A plan page's size, and its rotation as shown: its own plus the plan's. */\n getPage(key: string, options?: PdfCallOptions): Promise<PdfPageInfo>;\n /** Renders a plan page with its rotation. */\n renderPage(\n key: string,\n canvas: HTMLCanvasElement,\n options: Omit<PdfRenderOptions, \"rotation\">,\n ): Promise<void>;\n /** A plan page's text, positioned on the unrotated page. */\n getTextContent(key: string, options?: PdfCallOptions): Promise<PdfTextContent>;\n /** A plan page's form fields, with the session's values applied. */\n getFormFields(key: string, options?: PdfCallOptions): Promise<readonly PdfFormField[]>;\n /** A plan page's web and email links, positioned on the unrotated page. */\n getLinks(key: string, options?: PdfCallOptions): Promise<readonly PdfLink[]>;\n /**\n * Builds the document as it is now: its pages in plan order, with their\n * rotations, form values and annotations, compressed or encrypted if asked.\n * An unchanged document with no options is returned as its original bytes,\n * without the processor. The result is a new buffer the caller owns.\n */\n export(options?: PdfExportOptions): Promise<Uint8Array>;\n /**\n * Selects pages, by key, replacing the selection. Keys the plan doesn't\n * have are ignored.\n */\n select(keys: readonly string[]): void;\n /** Records the page the user is looking at, as a viewer scrolls. */\n setCurrentPage(key: string): void;\n /** Makes a page current and asks viewers to bring it into view. */\n goToPage(key: string): void;\n /** Closes the document and releases its sources. */\n close(): Promise<void>;\n}\n\n/** The view state kept beside a history step (docs/adr/0008). */\ninterface View {\n readonly selection: readonly string[];\n readonly currentPage: string | undefined;\n}\n\ninterface Source extends PdfSourceInfo {\n readonly bytes: Uint8Array;\n readonly document: PdfDocumentHandle;\n}\n\n/**\n * Creates a {@link PdfSession}. Pass the engine to use; the headless core\n * doesn't choose one, so it can't pull pdf.js into applications that don't\n * want it.\n *\n * @example\n * ```ts\n * const session = createPdfSession({ engine: createPdfJsEngine() });\n * await session.open(file);\n * const [first] = session.getSnapshot().plan.pages;\n * session.execute({ type: \"pdf.rotatePages\", pages: [first.key], angle: 90 });\n * session.undo();\n * ```\n *\n * @public\n */\nexport function createPdfSession(options: PdfSessionOptions): PdfSession {\n const { engine } = options;\n const policy = pdfLimits.resolve(options.filePolicy);\n // Undo and redo stacks of command steps, which the memory policy below\n // trims (ADR 0010 and ADR 0029 in sdk-core, docs/adr/0004).\n const history = createHistory<PdfCommand>();\n /**\n * The view before each step, and the view when it was last undone, by the\n * history's own step object. Steps the history drops are released with it.\n */\n const views = new WeakMap<HistoryStep<PdfCommand>, { readonly before: View; after?: View }>();\n const sources = new Map<string, Source>();\n // Checks commands against the sources the session holds (sdk-core ADR 0045).\n const reduce = createPdfReducer((id) => sources.get(id)?.pageCount);\n let plan: PdfPlan = EMPTY_PLAN;\n let status: PdfSessionStatus = \"empty\";\n let error: PdfError | undefined;\n let warnings: PdfWarning[] = [];\n let busy = 0;\n let selection: readonly string[] = [];\n let currentPage: string | undefined;\n let navigation: { page: string; sequence: number } | undefined;\n let nextKey = 0;\n let nextSource = 0;\n /** Cancels the load in progress when a newer open replaces it. */\n let loading: AbortController | undefined;\n const heldBytes = (): number =>\n [...sources.values()].reduce((total, source) => total + source.byteLength, 0);\n\n /** The sources the plan and the given history steps refer to: only pages need bytes. */\n function referenced(steps: readonly HistoryStep<PdfCommand>[]): Set<string> {\n const ids = new Set(plan.pages.map((page) => page.source));\n for (const { commands, inverses } of steps) {\n for (const command of [...commands, ...inverses]) {\n if (command.type === \"pdf.insertPages\") ids.add(command.source);\n if (command.type === \"pdf.restorePages\") {\n for (const { page } of command.entries) ids.add(page.source);\n }\n }\n }\n return ids;\n }\n\n /** Releases the sources nothing refers to any more, and their engine documents. */\n function collect(): void {\n const keep = referenced(history.steps);\n for (const [id, source] of sources) {\n if (keep.has(id)) continue;\n sources.delete(id);\n void source.document.destroy().catch(() => {});\n }\n }\n\n /**\n * How many history steps must be dropped, in drop order, for the held\n * sources plus `extra` bytes to fit `maxSessionSize`, or undefined if\n * dropping every step isn't enough.\n */\n function stepsToDrop(extra: number): number | undefined {\n const { maximum } = policy.limits.maxSessionSize;\n const order = history.dropOrder;\n for (let count = 0; count <= order.length; count += 1) {\n const kept = new Set(order.slice(count));\n const ids = referenced(history.steps.filter((entry) => kept.has(entry)));\n const total = [...ids].reduce((sum, id) => sum + (sources.get(id)?.byteLength ?? 0), 0);\n if (total + extra <= maximum) return count;\n }\n return undefined;\n }\n\n // Each change makes a new frozen snapshot (ADR 0029 in sdk-core).\n const store = createStore(makeSnapshot());\n\n /** The load warnings, and the session size warning, which follows every change. */\n function sessionWarnings(): PdfWarning[] {\n const bytes = heldBytes();\n const sessionWarning =\n bytes > 0 && bytes >= policy.limits.maxSessionSize.warning\n ? [{ limit: \"maxSessionSize\" as const, actual: bytes }]\n : [];\n return [...warnings, ...sessionWarning];\n }\n\n function makeSnapshot(): PdfSessionSnapshot {\n return Object.freeze({\n status,\n plan,\n sources: Object.freeze(\n [...sources.values()].map(({ id, pageCount, byteLength, name }) =>\n Object.freeze({ id, pageCount, byteLength, ...(name === undefined ? {} : { name }) }),\n ),\n ),\n canUndo: history.canUndo,\n canRedo: history.canRedo,\n busy: busy > 0,\n error,\n warnings: Object.freeze(sessionWarnings()),\n sessionBytes: heldBytes(),\n historyTrimmed: history.trimmed,\n selection: Object.freeze([...selection]),\n currentPage,\n navigation: navigation ? Object.freeze({ ...navigation }) : undefined,\n });\n }\n\n function changed(): void {\n // View state follows the plan: pages that left it can't be selected or current.\n const keys = new Set(plan.pages.map((page) => page.key));\n if (selection.some((key) => !keys.has(key))) {\n selection = selection.filter((key) => keys.has(key));\n }\n if (currentPage !== undefined && !keys.has(currentPage)) {\n currentPage = plan.pages[0]?.key;\n }\n if (currentPage === undefined && plan.pages.length > 0) currentPage = plan.pages[0]?.key;\n if (navigation && !keys.has(navigation.page)) navigation = undefined;\n store.set(makeSnapshot());\n }\n\n function emit(event: PdfSessionEvent): void {\n try {\n options.onEvent?.(event);\n } catch {\n // A host's analytics must never break editing.\n }\n }\n\n /** Reads, checks and opens one file as a source, without registering it. */\n async function load(\n file: Blob | PdfBytes,\n signal: AbortSignal,\n given: string | undefined,\n ): Promise<Source> {\n // File isn't a global in every runtime the core supports (ADR 0007 in sdk-core).\n const fileName = typeof File !== \"undefined\" && file instanceof File ? file.name : undefined;\n const name = cleanFileName(given ?? fileName);\n const found: PdfWarning[] = [];\n const warnAt = (limit: PdfLimitName, actual: number) => {\n if (policy.check(limit, actual) === \"warning\") found.push({ limit, actual });\n };\n // The file size, before anything is read (ADR 0020).\n if (file instanceof Blob) {\n if (checkFile(policy, file) === \"warning\")\n found.push({ limit: \"maxFileSize\", actual: file.size });\n } else {\n warnAt(\"maxFileSize\", file.byteLength);\n }\n const bytes = file instanceof Blob ? new Uint8Array(await file.arrayBuffer()) : copyBytes(file);\n throwIfAborted(signal);\n const document = await withProcessingTime(\n policy,\n (limited) => engine.open(bytes, { signal: limited }),\n { signal },\n ).catch((reason: unknown) => {\n throw asPdfError(reason, \"The PDF couldn't be opened.\");\n });\n try {\n throwIfAborted(signal);\n warnAt(\"maxPages\", document.pageCount);\n } catch (reason) {\n await document.destroy();\n throw reason;\n }\n warnings = [...warnings.filter((warning) => warning.limit !== \"maxFileSize\"), ...found];\n nextSource += 1;\n return {\n id: `s${nextSource}`,\n pageCount: document.pageCount,\n byteLength: bytes.byteLength,\n ...(name === undefined ? {} : { name }),\n bytes,\n document,\n };\n }\n\n /** Runs a load, marking the session busy, and cancelling it if a newer open starts. */\n async function track<Value>(\n signal: AbortSignal | undefined,\n replaces: boolean,\n run: (signal: AbortSignal) => Promise<Value>,\n ): Promise<Value> {\n if (replaces) loading?.abort(new PdfError(\"ABORTED\", \"A newer document replaced this one.\"));\n const controller = new AbortController();\n if (replaces) loading = controller;\n const combined = signal ? AbortSignal.any([signal, controller.signal]) : controller.signal;\n busy += 1;\n changed();\n try {\n return await run(combined);\n } finally {\n busy -= 1;\n if (loading === controller) loading = undefined;\n changed();\n }\n }\n\n async function release(): Promise<void> {\n const documents = [...sources.values()].map((source) => source.document);\n sources.clear();\n await Promise.all(documents.map((document) => document.destroy().catch(() => {})));\n }\n\n function pageFor(key: string): { page: PdfPlanPage; source: Source } {\n const page = plan.pages.find((entry) => entry.key === key);\n const source = page && sources.get(page.source);\n if (!page || !source) throw new TypeError(`The plan has no page ${key}.`);\n return { page, source };\n }\n\n /** The selection and current page, which undo and redo bring back (docs/adr/0008). */\n function view(): View {\n return { selection, currentPage };\n }\n\n /**\n * Brings back a view, keeping only pages the plan still has; changed()\n * settles the rest. The current page is brought into view.\n */\n function restore(saved: View): void {\n const keys = new Set(plan.pages.map((page) => page.key));\n selection = saved.selection.filter((key) => keys.has(key));\n if (saved.currentPage !== undefined && keys.has(saved.currentPage)) {\n currentPage = saved.currentPage;\n navigation = { page: saved.currentPage, sequence: (navigation?.sequence ?? 0) + 1 };\n }\n }\n\n function step(commands: readonly PdfCommand[]): void {\n const before = view();\n const result = applyCommands(reduce, plan, commands);\n plan = result.state;\n history.push({ commands, inverses: result.inverses });\n // The history stores its own frozen copy of the step, the object that\n // undo() and redo() return, so the view is kept against that one.\n const stored = history.steps.at(-1);\n if (stored) views.set(stored, { before });\n // A new step drops the redo steps, and the documents only they held.\n collect();\n }\n\n return {\n getSnapshot: store.getSnapshot,\n\n subscribe: store.subscribe,\n\n async open(file, callOptions = {}) {\n status = \"opening\";\n error = undefined;\n try {\n const source = await track(callOptions.signal, true, async (signal) => {\n // The open document is released once this one opens, so this one\n // must fit on its own.\n policy.check(\"maxSessionSize\", file instanceof Blob ? file.size : file.byteLength);\n return load(file, signal, callOptions.name);\n });\n await release();\n sources.set(source.id, source);\n history.clear();\n plan = {\n pages: Array.from({ length: source.pageCount }, (_, pageIndex) => {\n nextKey += 1;\n return {\n key: `p${nextKey}`,\n source: source.id,\n pageIndex,\n rotation: 0,\n annotations: [],\n };\n }),\n formValues: {},\n };\n status = \"ready\";\n changed();\n emit({ type: \"document_opened\", pageCount: source.pageCount });\n } catch (reason) {\n const failure = asPdfError(reason, \"The PDF couldn't be opened.\");\n // A newer open replaced this one; it reports its own outcome.\n if (failure.code === \"ABORTED\" && loading !== undefined) throw failure;\n // A failed open keeps the document that was already open, and its\n // history, so a bad file never costs the user their work.\n status = sources.size > 0 ? \"ready\" : \"error\";\n error = failure;\n changed();\n emit({ type: \"failed\", operation: \"open\", code: failure.code });\n throw failure;\n }\n },\n\n async insert(file, insertOptions = {}) {\n if (status !== \"ready\") {\n throw new PdfError(\"PROCESSING_FAILED\", \"Open a document before inserting another.\");\n }\n error = undefined;\n try {\n const source = await track(insertOptions.signal, false, async (signal) => {\n policy.check(\"maxFiles\", sources.size + 1);\n return load(file, signal, insertOptions.name);\n });\n try {\n const pageIndexes =\n insertOptions.pageIndexes ??\n Array.from({ length: source.pageCount }, (_, index) => index);\n for (const index of pageIndexes) {\n if (!Number.isInteger(index) || index < 0 || index >= source.pageCount) {\n throw new RangeError(`The inserted document has no page index ${index}.`);\n }\n }\n if (policy.check(\"maxPages\", plan.pages.length + pageIndexes.length) === \"warning\") {\n warnings = [\n ...warnings.filter((warning) => warning.limit !== \"maxPages\"),\n { limit: \"maxPages\", actual: plan.pages.length + pageIndexes.length },\n ];\n }\n const keys = pageIndexes.map(() => {\n nextKey += 1;\n return `p${nextKey}`;\n });\n const drop = stepsToDrop(source.byteLength);\n if (drop === undefined) {\n throw policy.error(\"maxSessionSize\", heldBytes() + source.byteLength);\n }\n history.drop(drop);\n collect();\n sources.set(source.id, source);\n step([\n {\n type: \"pdf.insertPages\",\n source: source.id,\n pageIndexes,\n at: insertOptions.at ?? plan.pages.length,\n keys,\n },\n ]);\n changed();\n emit({ type: \"pages_inserted\", pageCount: pageIndexes.length });\n } catch (reason) {\n sources.delete(source.id);\n await source.document.destroy().catch(() => {});\n throw reason;\n }\n } catch (reason) {\n // A mistake in the call, such as a position outside the plan, isn't\n // the file's failure.\n if (\n reason instanceof TypeError ||\n reason instanceof RangeError ||\n isPdfError(reason, \"INVALID_COMMAND\")\n ) {\n throw reason;\n }\n const failure = asPdfError(reason, \"The PDF couldn't be inserted.\");\n error = failure;\n changed();\n emit({ type: \"failed\", operation: \"insert\", code: failure.code });\n throw failure;\n }\n },\n\n execute(commands) {\n const list = Array.isArray(commands) ? commands : [commands as PdfCommand];\n if (list.length === 0) return;\n step(list);\n changed();\n emit({ type: \"command\", commands: list.map((command) => command.type) });\n },\n\n undo() {\n const entry = history.undo();\n if (!entry) return;\n const now = view();\n try {\n plan = applyCommands(reduce, plan, entry.inverses).state;\n } catch (reason) {\n history.restore(\"undo\");\n throw reason;\n }\n const record = views.get(entry);\n if (record) {\n // Redo brings back what the user had when they undid.\n record.after = now;\n restore(record.before);\n }\n changed();\n emit({ type: \"undo\" });\n },\n\n redo() {\n const entry = history.redo();\n if (!entry) return;\n try {\n plan = applyCommands(reduce, plan, entry.commands).state;\n } catch (reason) {\n history.restore(\"redo\");\n throw reason;\n }\n const after = views.get(entry)?.after;\n if (after) restore(after);\n changed();\n emit({ type: \"redo\" });\n },\n\n async getPage(key, callOptions) {\n const { page, source } = pageFor(key);\n const info = await source.document.getPage(page.pageIndex, callOptions);\n return { ...info, rotation: addRotation(info.rotation, page.rotation) };\n },\n\n async renderPage(key, canvas, renderOptions) {\n const { page, source } = pageFor(key);\n await source.document.renderPage(page.pageIndex, canvas, {\n ...renderOptions,\n rotation: page.rotation,\n });\n },\n\n async getTextContent(key, callOptions) {\n const { page, source } = pageFor(key);\n return source.document.getTextContent(page.pageIndex, callOptions);\n },\n\n async getFormFields(key, callOptions) {\n const { page, source } = pageFor(key);\n const fields = await source.document.getFormFields(page.pageIndex, callOptions);\n const values = plan.formValues[source.id] ?? {};\n return fields.map((field) =>\n Object.hasOwn(values, field.name)\n ? { ...field, value: values[field.name] as typeof field.value }\n : field,\n );\n },\n\n async getLinks(key, callOptions) {\n const { page, source } = pageFor(key);\n return source.document.getLinks(page.pageIndex, callOptions);\n },\n\n async export(exportOptions = {}) {\n if (status !== \"ready\" && sources.size === 0) {\n throw new PdfError(\"PROCESSING_FAILED\", \"Open a document before exporting it.\");\n }\n const pages = plan.pages;\n const used = [...new Set(pages.map((page) => page.source))];\n const job: PdfBuildJob = {\n sources: used.map((id) => {\n const values = plan.formValues[id];\n return {\n id,\n bytes: (sources.get(id) as Source).bytes,\n ...(values && Object.keys(values).length > 0 ? { formValues: values } : {}),\n };\n }),\n pages: pages.map((page) => ({\n source: page.source,\n pageIndex: page.pageIndex,\n ...(page.rotation === 0 ? {} : { rotation: page.rotation }),\n ...(page.annotations.length === 0 ? {} : { annotations: page.annotations }),\n })),\n ...(exportOptions.compress ? { compress: exportOptions.compress } : {}),\n ...(exportOptions.encrypt ? { encrypt: exportOptions.encrypt } : {}),\n };\n const done = () =>\n emit({\n type: \"document_exported\",\n pageCount: pages.length,\n compressed: Boolean(exportOptions.compress),\n encrypted: Boolean(exportOptions.encrypt),\n });\n\n // An unchanged document with no options is its original bytes.\n const [only] = job.sources;\n const source = only && sources.get(only.id);\n if (\n job.sources.length === 1 &&\n !only?.formValues &&\n !job.compress &&\n !job.encrypt &&\n source &&\n job.pages.length === source.pageCount &&\n job.pages.every(\n (page, index) => page.pageIndex === index && !page.rotation && !page.annotations,\n )\n ) {\n throwIfAborted(exportOptions.signal);\n done();\n return copyBytes(source.bytes);\n }\n\n const { processor } = options;\n if (!processor) {\n throw new TypeError(\"Exporting an edited document needs a processor in createPdfSession.\");\n }\n busy += 1;\n changed();\n try {\n const output = await withProcessingTime(\n policy,\n (signal) =>\n processor.build(job, {\n signal,\n ...(exportOptions.onProgress ? { onProgress: exportOptions.onProgress } : {}),\n }),\n exportOptions.signal ? { signal: exportOptions.signal } : {},\n );\n done();\n return output;\n } catch (reason) {\n if (reason instanceof TypeError || reason instanceof RangeError) throw reason;\n const failure = asPdfError(reason, \"The PDF couldn't be exported.\");\n emit({ type: \"failed\", operation: \"export\", code: failure.code });\n throw failure;\n } finally {\n busy -= 1;\n changed();\n }\n },\n\n select(keys) {\n const wanted = new Set(keys);\n const next = plan.pages.filter((page) => wanted.has(page.key)).map((page) => page.key);\n if (\n next.length === selection.length &&\n next.every((key, index) => key === selection[index])\n ) {\n return;\n }\n selection = next;\n changed();\n },\n\n setCurrentPage(key) {\n if (key === currentPage || !plan.pages.some((page) => page.key === key)) return;\n currentPage = key;\n changed();\n },\n\n goToPage(key) {\n if (!plan.pages.some((page) => page.key === key)) {\n throw new TypeError(`The plan has no page ${key}.`);\n }\n currentPage = key;\n navigation = { page: key, sequence: (navigation?.sequence ?? 0) + 1 };\n changed();\n },\n\n async close() {\n loading?.abort(new PdfError(\"ABORTED\", \"The document was closed.\"));\n const hadDocument = status === \"ready\";\n await release();\n plan = EMPTY_PLAN;\n history.clear();\n warnings = [];\n error = undefined;\n status = \"empty\";\n changed();\n if (hadDocument) emit({ type: \"document_closed\" });\n },\n };\n}\n","import { defineMessages, type MessageValue, plural, sdkCoreMessages } from \"@hussmartinez/sdk-core\";\nimport type { PdfErrorCode } from \"../core/errors/pdf-error.js\";\nimport type { PdfLimitName } from \"../core/errors/pdf-limits.js\";\n\n/**\n * The PDF SDK's English message catalogue for the server-safe entry:\n * sdk-core's messages, and text for every {@link PdfErrorCode} and every\n * limit's warning. Pass it to `createMessages` from `@hussmartinez/sdk-core`,\n * with the host's locale and overrides.\n *\n * It holds no interface text: the editor's, the viewer's and the\n * thumbnails' text is in `pdfEditorMessages`, from the React entry\n * (docs/adr/0010).\n *\n * Error text is looked up by code, with the error's `details` as\n * parameters, and never taken from `error.message` (ADR 0019).\n *\n * @example\n * ```ts\n * const messages = createMessages(pdfMessages, { locale: \"en\", overrides: props.messages });\n * messages.error(error); // \"This document has 6,200 pages, which is over the 5,000-page limit.\"\n * messages.t(\"warnings.maxPages\", { actual: 1_200 });\n * ```\n *\n * @public\n */\nexport const pdfMessages = /* @__PURE__ */ defineMessages({\n ...sdkCoreMessages,\n \"errors.INVALID_PDF\": \"This file isn't a PDF, or it's too damaged to open.\",\n \"errors.PASSWORD_REQUIRED\": \"This PDF is protected with a password.\",\n \"errors.PROCESSING_FAILED\": \"Something went wrong while processing this PDF. Please try again.\",\n \"errors.TOO_MANY_PAGES\":\n \"This document has {actual, number} pages, which is over the {maximum, number}-page limit.\",\n \"errors.SESSION_TOO_LARGE\":\n \"The open documents would use {actual, fileSize}, which is over the {maximum, fileSize} limit. Close a document, or clear the undo history, and try again.\",\n \"errors.IMAGE_TOO_LARGE\":\n \"Some images are too large to show. They're kept unchanged in the document.\",\n \"errors.INVALID_COMMAND\": \"This edit couldn't be made. Please try again.\",\n \"errors.INVALID_DOCUMENT\": \"This project is damaged, or it isn't a PDF project.\",\n \"errors.UNSUPPORTED_FORMAT\":\n \"This project was saved by a newer version, or by another app. Update the app, and try again.\",\n \"warnings.maxPages\": /* @__PURE__ */ plural(\"actual\", {\n one: \"This document has {actual} page. Large documents may be slow.\",\n other: \"This document has {actual} pages. Large documents may be slow.\",\n }),\n \"warnings.maxSessionSize\":\n \"The open documents use {actual, fileSize}. Clearing the undo history frees memory.\",\n \"warnings.maxImagePixels\": \"Some images are very large and may be slow to show.\",\n}) satisfies Record<`errors.${PdfErrorCode}`, MessageValue> &\n Record<`warnings.${PdfLimitName}`, MessageValue>;\n\n/**\n * The type of {@link pdfMessages}, for typing a host's overrides with\n * `MessageOverrides<PdfMessageCatalogue>`.\n *\n * @public\n */\nexport type PdfMessageCatalogue = typeof pdfMessages;\n"],"mappings":";;AAkEA,IAAa,WAAb,cAA8B,SAAuB;CAEnD,OAAyB;AAC3B;AAaA,SAAgB,WACd,OACA,MAC6C;CAC7C,OAAO,WAAW,OAAO,IAAI,KAAK,MAAM,SAAS;AACnD;;AChFA,IAAM,UAA0B,mCAAmB,UAAU;CAC3D,cAAc;CACd,iBAAiB;AACnB,CAAC;AAUD,IAAa,aAA8D,QAAQ;AAUnF,IAAa,aAAgD,QAAQ;AAOrE,IAAa,iBAA4D,QAAQ;;ACVjF,IAAa,sBAAsB;CACjC,GAAG;CACH,UAAU;EAAE,MAAM;E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