@embedpdf/engine-core 3.0.0-next.14 → 3.0.0-next.16
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/AnnotationList-DcyhF2kU.d.cts +27691 -0
- package/dist/AnnotationList-DcyhF2kU.d.ts +27691 -0
- package/dist/Change-Ct-dB8D5.cjs +1133 -0
- package/dist/Change-Ct-dB8D5.cjs.map +1 -0
- package/dist/Change-tMR34hTU.js +978 -0
- package/dist/Change-tMR34hTU.js.map +1 -0
- package/dist/DocumentRenderService-9IjSQEIU.cjs +121 -0
- package/dist/DocumentRenderService-9IjSQEIU.cjs.map +1 -0
- package/dist/DocumentRenderService-DFrZ9wfW.js +86 -0
- package/dist/DocumentRenderService-DFrZ9wfW.js.map +1 -0
- package/dist/{DocumentSecurityService-Ca6EK3-3.d.ts → DocumentSecurityService-D2zA4NKi.d.cts} +100 -112
- package/dist/{DocumentSecurityService-CIx1MT0T.d.cts → DocumentSecurityService-YJV9df8P.d.ts} +100 -112
- package/dist/LocalDocumentHandle-D02FMm-Z.cjs +53 -0
- package/dist/LocalDocumentHandle-D02FMm-Z.cjs.map +1 -0
- package/dist/LocalDocumentHandle-DAPdaOt_.js +30 -0
- package/dist/LocalDocumentHandle-DAPdaOt_.js.map +1 -0
- package/dist/LocalEngine-DBt2-GWF.d.ts +1649 -0
- package/dist/LocalEngine-IA9zh3Jh.d.cts +1649 -0
- package/dist/PageInsertBlankInput-CXHAM7l6.cjs +17 -0
- package/dist/PageInsertBlankInput-CXHAM7l6.cjs.map +1 -0
- package/dist/PageInsertBlankInput-DhVYVJ_S.js +12 -0
- package/dist/PageInsertBlankInput-DhVYVJ_S.js.map +1 -0
- package/dist/authority-BFp6XM04.cjs +2997 -0
- package/dist/authority-BFp6XM04.cjs.map +1 -0
- package/dist/authority-PuxpGFhJ.js +2506 -0
- package/dist/authority-PuxpGFhJ.js.map +1 -0
- package/dist/builders-DV62HA3I.js +165 -0
- package/dist/builders-DV62HA3I.js.map +1 -0
- package/dist/builders-DgTAj_tP.cjs +188 -0
- package/dist/builders-DgTAj_tP.cjs.map +1 -0
- package/dist/calibrate-DJbi1wuK.cjs +3012 -0
- package/dist/calibrate-DJbi1wuK.cjs.map +1 -0
- package/dist/calibrate-nQFgCuki.js +2461 -0
- package/dist/calibrate-nQFgCuki.js.map +1 -0
- package/dist/charmap-Cprti1ta.js +239 -0
- package/dist/charmap-Cprti1ta.js.map +1 -0
- package/dist/charmap-aYlefQP9.cjs +304 -0
- package/dist/charmap-aYlefQP9.cjs.map +1 -0
- package/dist/conformance.cjs +18146 -5258
- package/dist/conformance.cjs.map +1 -1
- package/dist/conformance.d.cts +1024 -170
- package/dist/conformance.d.ts +1024 -170
- package/dist/conformance.js +18148 -5309
- package/dist/conformance.js.map +1 -1
- package/dist/format-Bp3QFSH1.cjs +574 -0
- package/dist/format-Bp3QFSH1.cjs.map +1 -0
- package/dist/format-Dgg428Kb.js +461 -0
- package/dist/format-Dgg428Kb.js.map +1 -0
- package/dist/index.cjs +342 -116
- package/dist/index.d.cts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +14 -5
- package/dist/pageRefs-B3ur7Ckm.cjs +51 -0
- package/dist/pageRefs-B3ur7Ckm.cjs.map +1 -0
- package/dist/pageRefs-DkbuxSCV.js +40 -0
- package/dist/pageRefs-DkbuxSCV.js.map +1 -0
- package/dist/public.cjs +59 -0
- package/dist/public.d.cts +5 -0
- package/dist/public.d.ts +5 -0
- package/dist/public.js +9 -0
- package/dist/resolveAnnotationDraft-7Ke4nV7F.cjs +3646 -0
- package/dist/resolveAnnotationDraft-7Ke4nV7F.cjs.map +1 -0
- package/dist/resolveAnnotationDraft-CUpf0SMh.js +3167 -0
- package/dist/resolveAnnotationDraft-CUpf0SMh.js.map +1 -0
- package/dist/{resolver-inAVzsWt.js → resolver-BBggAxQc.js} +298 -145
- package/dist/resolver-BBggAxQc.js.map +1 -0
- package/dist/{resolver-CYVNV4hn.cjs → resolver-BWSWSF6R.cjs} +351 -144
- package/dist/resolver-BWSWSF6R.cjs.map +1 -0
- package/dist/runtime-BaDKjxiu.d.ts +1959 -0
- package/dist/runtime-CWEuiwbk.d.cts +1959 -0
- package/dist/runtime.cjs +986 -297
- package/dist/runtime.cjs.map +1 -1
- package/dist/runtime.d.cts +5 -1372
- package/dist/runtime.d.ts +5 -1372
- package/dist/runtime.js +634 -179
- package/dist/runtime.js.map +1 -1
- package/dist/schema-6S2VmlAj.js +2087 -0
- package/dist/schema-6S2VmlAj.js.map +1 -0
- package/dist/schema-miH6tWQC.cjs +3046 -0
- package/dist/schema-miH6tWQC.cjs.map +1 -0
- package/dist/schemas-BE2QGOit.js +1851 -0
- package/dist/schemas-BE2QGOit.js.map +1 -0
- package/dist/schemas-DljJR9ut.cjs +2798 -0
- package/dist/schemas-DljJR9ut.cjs.map +1 -0
- package/dist/subtype-CG4WpIRj.js +129 -0
- package/dist/subtype-CG4WpIRj.js.map +1 -0
- package/dist/subtype-aDt5TFmK.cjs +158 -0
- package/dist/subtype-aDt5TFmK.cjs.map +1 -0
- package/dist/validation.cjs +578 -0
- package/dist/validation.cjs.map +1 -0
- package/dist/validation.d.cts +174 -0
- package/dist/validation.d.ts +174 -0
- package/dist/validation.js +571 -0
- package/dist/validation.js.map +1 -0
- package/dist/value-BFS1R8ek.cjs +435 -0
- package/dist/value-BFS1R8ek.cjs.map +1 -0
- package/dist/value-Dhc8eYcx.js +340 -0
- package/dist/value-Dhc8eYcx.js.map +1 -0
- package/dist/viewport-CHG9qQUb.cjs +671 -0
- package/dist/viewport-CHG9qQUb.cjs.map +1 -0
- package/dist/viewport-DQR5LyX3.js +540 -0
- package/dist/viewport-DQR5LyX3.js.map +1 -0
- package/dist/wire.cjs +1242 -420
- package/dist/wire.cjs.map +1 -1
- package/dist/wire.d.cts +14840 -830
- package/dist/wire.d.ts +14840 -830
- package/dist/wire.js +985 -261
- package/dist/wire.js.map +1 -1
- package/package.json +10 -1
- package/dist/AbortError-DwuHPK_I.js +0 -27
- package/dist/AbortError-DwuHPK_I.js.map +0 -1
- package/dist/AbortError-P0RU0Mgg.cjs +0 -38
- package/dist/AbortError-P0RU0Mgg.cjs.map +0 -1
- package/dist/AnnotationListSnapshot-D9R5n2Kf.d.cts +0 -7101
- package/dist/AnnotationListSnapshot-D9R5n2Kf.d.ts +0 -7101
- package/dist/Engine-EWWHhEIi.d.ts +0 -1277
- package/dist/Engine-FNaAEjfb.d.cts +0 -1277
- package/dist/derive-BbsDk_Kz.cjs +0 -880
- package/dist/derive-BbsDk_Kz.cjs.map +0 -1
- package/dist/derive-DAFJolWu.js +0 -647
- package/dist/derive-DAFJolWu.js.map +0 -1
- package/dist/format-Bbphf4zR.js +0 -435
- package/dist/format-Bbphf4zR.js.map +0 -1
- package/dist/format-D_epWlob.cjs +0 -518
- package/dist/format-D_epWlob.cjs.map +0 -1
- package/dist/resolver-CYVNV4hn.cjs.map +0 -1
- package/dist/resolver-inAVzsWt.js.map +0 -1
- package/dist/schemas-CFQGvWiu.js +0 -3243
- package/dist/schemas-CFQGvWiu.js.map +0 -1
- package/dist/schemas-D0g6tKa9.cjs +0 -4694
- package/dist/schemas-D0g6tKa9.cjs.map +0 -1
- package/dist/viewport-BWeNHZmb.cjs +0 -3503
- package/dist/viewport-BWeNHZmb.cjs.map +0 -1
- package/dist/viewport-CvMcadfQ.js +0 -3072
- package/dist/viewport-CvMcadfQ.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"authority-BFp6XM04.cjs","names":["pdfRectIntersection","PermissionDenied","EngineError","EngineErrorCode","AbortablePromise","EngineError","EngineErrorCode","PermissionDenied","resolveBinarySource","EngineError","EngineErrorCode","encodePageKey","annotationKey","EngineError","EngineErrorCode","kindFactsOf","applyResolvedPatch","pageBoxOf","mapPageActions","pageDestinationOf","EngineError","EngineErrorCode","pdfRectOf","pageBoxOf","pdfRectOf","mapTriggerActions","pdfDestinationOf","mapFieldActions","pageDestinationOf","pageAnnotationOf","mapLinkTarget","mapActionTree","pageDestinationOf","pdfDestinationOf","writesScripts","EngineError","EngineErrorCode","pdfRectTurnedBounds","normalizePdfRect","deriveProtection","edgeKey","levelAllows","lockCovers","minLevel","levelFromPermission","matchRegex","matchLiteral","foldText","foldOptionsFor","foldText","EngineError","EngineErrorCode","EngineErrorCode","checkCapability","PermissionDenied","protectedCapabilities","EngineError","EngineErrorCode","describeProtection","checkSetGroup","checkCollab","collabTargetOf","checkFieldAction","checkAnyFieldAction"],"sources":["../src/geometry/pageBoxes.ts","../src/dto/PageRender.ts","../src/dto/PageExtract.ts","../src/dto/PdfSaveMode.ts","../src/identity/uuid.ts","../src/annotation/family.ts","../src/dto/normalizeAttachmentFileSource.ts","../src/transfer/annotationImport.ts","../src/transfer/exportSelection.ts","../src/annotation/AnnotationList.ts","../src/mutation/AnnotationMutationResults.ts","../src/annotation/resolve/patchBetween.ts","../src/pageSpace/pages.ts","../src/pageSpace/rendering.ts","../src/pageSpace/forms.ts","../src/pageSpace/outline.ts","../src/forms/draft.ts","../src/forms/placement.ts","../src/signature/analysis/pdf-value.ts","../src/signature/analysis/verdict.ts","../src/signature/analysis/evaluate.ts","../src/signature/analysis/restrictions.ts","../src/signature/analysis/resolve.ts","../src/search/types.ts","../src/search/matcher.ts","../src/search/snippet.ts","../src/search/epoch.ts","../src/mutation/WriteOptions.ts","../src/mutation/changeOutcome.ts","../src/mutation/OutlineMutationResults.ts","../src/auth/scope/pdf-bits.ts","../src/auth/scope/authority.ts"],"sourcesContent":["import { pdfRectIntersection } from './convert';\nimport type { PdfRect, PdfRotation } from './primitives';\nimport type { PageBoxes } from '../dto/PageLayout';\nimport type { PdfCoordinates } from '../pageSpace/coordinates';\n\n/**\n * A page's boxes as its dictionary writes them (ISO 32000-1 Table 30): the\n * media and crop boxes as inherited through the page tree, the bleed, trim\n * and art boxes the page's own, each with its corners in order. A box that\n * is absent, empty or not four numbers is left out.\n */\nexport interface WrittenPageBoxes {\n media?: PdfRect;\n crop?: PdfRect;\n bleed?: PdfRect;\n trim?: PdfRect;\n art?: PdfRect;\n}\n\n/** The media box of a page that has none, which the file needs: US Letter. */\nexport const DEFAULT_MEDIA_BOX: PdfRect = { left: 0, bottom: 0, right: 612, top: 792 };\n\n/** A box that shares nothing with the media box: no size, at the origin. */\nconst EMPTY_BOX: PdfRect = { left: 0, right: 0, bottom: 0, top: 0 };\n\n/**\n * The page's five boxes as ISO 32000-1 §14.11.2 defines them: the crop box\n * defaults to the media box and the other three to the crop box, and each is\n * reduced to the part it shares with the media box. The crop box is then the\n * visible page, what the page shows.\n *\n * For broken files, which the standard doesn't cover, we do what Acrobat\n * does: a page without a media box is US Letter, and a box that shares\n * nothing with the media box is empty, so a crop box off the page leaves a\n * page with no size.\n */\nexport function pageBoxesOf(written: WrittenPageBoxes): PageBoxes<PdfCoordinates> {\n const media = written.media ?? DEFAULT_MEDIA_BOX;\n const within = (box: PdfRect): PdfRect => pdfRectIntersection(box, media) ?? EMPTY_BOX;\n const crop = within(written.crop ?? media);\n return {\n media,\n crop,\n bleed: within(written.bleed ?? crop),\n trim: within(written.trim ?? crop),\n art: within(written.art ?? crop),\n };\n}\n\n/**\n * A page's turn from its `/Rotate`, degrees clockwise. ISO 32000-1 Table 30\n * allows multiples of 90; a negative one or one past 360 is the same turn.\n * For a value that isn't a multiple of 90, which the file shouldn't hold, we\n * do what Acrobat does: no turn.\n */\nexport function pageRotationOf(written: number): PdfRotation {\n if (!Number.isInteger(written) || written % 90 !== 0) return 0;\n return (((written % 360) + 360) % 360) as PdfRotation;\n}\n","import { PermissionDenied } from '../auth/scope/errors';\nimport { EngineError } from '../errors/EngineError';\nimport { EngineErrorCode } from '../errors/EngineErrorCode';\nimport type { PageRenderTransform } from '../geometry/pageTransform';\nimport type { PdfRotation } from '../geometry/primitives';\nimport type { PageFlattenUsage } from '../mutation/PageFlattenResult';\nimport type { Coordinates, PageCoordinates } from '../pageSpace/coordinates';\nimport { AbortablePromise } from '../promise/AbortablePromise';\n\nexport type PageRenderEncodedFormat = 'png' | 'webp' | 'bmp';\n\n/**\n * Formats that are acceptable for cacheable cloud HTTP render endpoints.\n * BMP and raw RGBA stay local-only because they are intentionally huge.\n */\nexport type PageNetworkRenderFormat = 'png' | 'webp';\n\nexport type PageRenderFormat = PageRenderEncodedFormat | 'rgba';\n\nexport type PageRenderBackground = 'white' | 'transparent';\n\n/** What a caller may read, for {@link resolvePageLayers}. */\nexport interface PageLayerRights {\n /** `doc.annotate.read`. */\n readonly annotations: boolean;\n /** `doc.forms.read`. */\n readonly formFields: boolean;\n}\n\n/** What a page picture draws beside the page content. */\nexport interface PageRenderLayers {\n readonly includeAnnotations: boolean;\n readonly includeFormFields: boolean;\n}\n\n/**\n * What a page picture draws: the options as passed, and for each one left\n * out, what the caller may read. A left-out option never asks for more than\n * the caller may see; `true` for something they may not read is refused\n * (`PermissionDenied`, naming the option).\n */\nexport function resolvePageLayers(\n options: { includeAnnotations?: boolean; includeFormFields?: boolean } | undefined,\n may: PageLayerRights,\n): PageRenderLayers {\n const { includeAnnotations, includeFormFields } = options ?? {};\n if (includeAnnotations === true && !may.annotations) {\n throw new PermissionDenied('doc.annotate.read', 'includeAnnotations');\n }\n if (includeFormFields === true && !may.formFields) {\n throw new PermissionDenied('doc.forms.read', 'includeFormFields');\n }\n return {\n includeAnnotations: includeAnnotations ?? may.annotations,\n includeFormFields: includeFormFields ?? (includeAnnotations === false ? false : may.formFields),\n };\n}\n\n/**\n * The two print resolutions, one per print right: 150 for `doc.print`, 300\n * for `doc.print.high` (Acrobat's low and high resolution printing).\n */\nexport type PrintDpi = 150 | 300;\n\n/** What a caller may print, for {@link checkRenderUsage}. */\nexport interface PagePrintRights {\n /** `doc.print`. */\n readonly print: boolean;\n /** `doc.print.high`. */\n readonly printHigh: boolean;\n}\n\n/**\n * Check what a render is for. A print picture (`usage: 'print'`) takes a\n * `{ kind: 'dpi', dpi }` viewport with a DPI of 150 or 300, and no `target`,\n * `rotation` or `background`: it is the whole page, upright, on white. A\n * `dpi` viewport is for print pictures only. Anything else is `InvalidArg`,\n * naming the option. With the caller's rights, a print they may not make is\n * refused (`PermissionDenied`): any print without `doc.print`, 300 DPI\n * without `doc.print.high`. Without them (a cloud caller whose rights the\n * client can't know), the server decides.\n */\nexport function checkRenderUsage<C extends Coordinates>(\n options:\n | Pick<PageRenderOptions<C>, 'usage' | 'viewport' | 'target' | 'rotation' | 'background'>\n | undefined,\n may: PagePrintRights | null,\n): void {\n const { usage, viewport } = options ?? {};\n if (usage === undefined || usage === 'display') {\n if (viewport?.kind === 'dpi') {\n invalid('viewport', 'a dpi viewport is only for a print picture (usage: \"print\")');\n }\n return;\n }\n if (usage !== 'print') invalid('usage', 'usage must be \"display\" or \"print\"');\n if (viewport?.kind !== 'dpi' || (viewport.dpi !== 150 && viewport.dpi !== 300)) {\n invalid('viewport', \"a print picture needs viewport: { kind: 'dpi', dpi: 150 or 300 }\");\n }\n for (const field of ['target', 'rotation', 'background'] as const) {\n if (options?.[field] !== undefined) {\n invalid(field, `a print picture takes no ${field}: it is the whole page, upright, on white`);\n }\n }\n if (may === null) return;\n if (!may.print) throw new PermissionDenied('doc.print', 'usage');\n if (viewport.dpi === 300 && !may.printHigh) {\n throw new PermissionDenied('doc.print.high', 'viewport');\n }\n}\n\n/** A print picture's DPI: its viewport's, when it is one; otherwise `undefined`. */\nexport function printDpiOf(\n options: Pick<PageRenderOptions, 'usage' | 'viewport'> | undefined,\n): PrintDpi | undefined {\n return options?.usage === 'print' && options.viewport?.kind === 'dpi'\n ? options.viewport.dpi\n : undefined;\n}\n\nfunction invalid(field: string, message: string): never {\n throw new EngineError(EngineErrorCode.InvalidArg, message, { details: { field } });\n}\n\n/** A screen picture's size: by its scale, or by its width. */\nexport type PageScreenViewport =\n | {\n /**\n * Render one point as `scale` device pixels. Callers\n * that care about devicePixelRatio should fold it into this value.\n */\n kind: 'scale';\n scale?: number;\n }\n | {\n /**\n * Exact output width in device pixels. Height preserves the region's\n * aspect ratio after rotation.\n */\n kind: 'width';\n width: number;\n };\n\n/** A picture's size: a screen size, or a print picture's DPI. */\nexport type PageRenderViewport =\n | PageScreenViewport\n | {\n /**\n * A print picture's size (`usage: 'print'` only): `dpi` dots per inch\n * of the paper the page prints on, A4 or Letter. A page that fits on\n * that paper is drawn at its own size at this DPI. A bigger one gets\n * no more pixels than it needs shrunk to fit the paper, since the\n * printer would throw the rest away: an A0 drawing at 300 DPI is\n * 2482 × 3508 pixels, not 9933 × 14043. 150 needs `doc.print`, 300\n * `doc.print.high`.\n */\n kind: 'dpi';\n dpi: PrintDpi;\n };\n\nexport type PageRenderTarget<C extends Coordinates = PageCoordinates> =\n | { kind: 'page' }\n | {\n kind: 'rect';\n /** The area to render, in page space: from the page's top-left, y down. */\n rect: C['box'];\n };\n\nexport interface PageRenderOptions<C extends Coordinates = PageCoordinates> {\n target?: PageRenderTarget<C>;\n viewport?: PageRenderViewport;\n rotation?: PdfRotation;\n background?: PageRenderBackground;\n /**\n * Draw the page's annotations into the picture, from their appearances.\n * Default: `true` when the caller may read annotations\n * (`doc.annotate.read`), so the page is drawn as the caller may see it.\n * `true` for a caller who may not is refused.\n */\n includeAnnotations?: boolean;\n /**\n * Draw the form fields too: the widgets, each in the state its field\n * shows. Default: `false` when `includeAnnotations` is `false`, otherwise\n * `true` when the caller may read the form (`doc.forms.read`), so a page\n * with annotations is the page as printed, filled form included. Pass\n * `false` when something else paints the fields over the picture, as a\n * viewer's form layer does. `true` for a caller who may not read the form\n * is refused. Hidden fields are never drawn, and no-view ones only when\n * printing.\n */\n includeFormFields?: boolean;\n /**\n * What the picture is for: the screen (`'display'`, the default) or paper\n * (`'print'`). A print picture follows the print rules: layers in their\n * print state, and only the annotations and form fields with the `print`\n * flag (no-view ones included, hidden ones never). It needs `doc.print`\n * and a `{ kind: 'dpi', dpi }` viewport, and takes no `target`,\n * `rotation` or `background`.\n */\n usage?: PageFlattenUsage;\n /**\n * Output-pixel budget: the renderer rejects (InvalidArg) instead of\n * allocating when `outputWidth × outputHeight` exceeds it. A width\n * lattice bounds width but not height — a 1×14,400pt page still\n * explodes vertically — so the guard lives where the allocation\n * happens (the decode-bomb-guard pattern). Server requests carry it\n * from the deployment's render policy; local engines inject it only\n * when `localEngine({ renderPolicy })` configured a budget — the\n * default local policy stays continuous and unbudgeted (exactness is\n * the local product promise).\n */\n maxOutputPixels?: number;\n}\n\nexport interface PageImageOptions<\n C extends Coordinates = PageCoordinates,\n> extends PageRenderOptions<C> {\n format?: PageRenderEncodedFormat;\n /**\n * WebP quality from 0 (smallest) to 1 (best), the same scale as\n * `canvas.toBlob`. PNG and BMP are lossless and ignore it.\n */\n quality?: number;\n}\n\n/** `InvalidArg` unless `quality` is absent or between 0 and 1. */\nexport function checkImageQuality(quality: number | undefined): void {\n if (quality === undefined || (quality >= 0 && quality <= 1)) return;\n throw new EngineError(EngineErrorCode.InvalidArg, 'quality must be between 0 and 1', {\n details: { field: 'quality' },\n });\n}\n\nexport interface PageRenderQuery {\n options: PageImageOptions;\n contentVersion?: number;\n annotationVersion?: number;\n widgetVersion?: number;\n}\n\n/**\n * Raw renderer output shared by local workers and server workers. The pixel\n * buffer is a first-class ArrayBuffer so worker transports can transfer\n * ownership instead of cloning it.\n */\nexport interface PageRaster {\n width: number;\n height: number;\n stride: number;\n color: 'rgba8';\n premultipliedAlpha: false;\n data: ArrayBuffer;\n}\n\nexport interface PageImageResult {\n /** Image width in pixels. */\n width: number;\n /** Image height in pixels. */\n height: number;\n format: PageRenderEncodedFormat;\n contentType: string;\n source: PageImageSource;\n}\n\nexport type PageImageSource = { kind: 'bytes'; bytes: Uint8Array } | { kind: 'url'; url: string };\n\nexport interface PageImageObjectUrl {\n url: string;\n revoke(): void;\n}\n\n/** An encoded image, as a renderer takes it: a blob, or a URL to paint. */\nexport interface ImageSource {\n /**\n * A `blob:` URL for the image, and `revoke()` to free it. Cancel with\n * `.abort()`: a URL made after the cancel is revoked, never leaked.\n */\n objectUrl(): AbortablePromise<PageImageObjectUrl>;\n /**\n * The encoded image. The same call on both engines: the cloud engine\n * fetches it with the document's token. Cancel with `.abort()`.\n */\n blob(): AbortablePromise<Blob>;\n}\n\nexport interface PageImageHandle extends PageImageResult, ImageSource {}\n\n/** What `render.image()` gives: the image, and how its pixels map to page space. */\nexport interface PageRenderImage extends PageImageHandle {\n transform: PageRenderTransform;\n}\n\n/** What `render.raw()` gives: the pixels, and how they map to page space. */\nexport interface PageRenderRaster extends PageRaster {\n transform: PageRenderTransform;\n}\n\nexport interface PageImageBlobSource {\n blob(signal?: AbortSignal): Promise<Blob>;\n}\n\nexport function createPageImageHandle(\n result: PageImageResult,\n blobSource: PageImageBlobSource,\n): PageImageHandle {\n return { ...result, ...imageSourceOf(blobSource) };\n}\n\n/**\n * An image whose encoded bytes this device holds (a picture it made, such as\n * a stamp's preview), to paint like one an engine rendered.\n */\nexport function imageSourceOfBytes(bytes: Uint8Array, contentType: string): ImageSource {\n return imageSourceOf({\n blob: async () => new Blob([bytes.slice()], { type: contentType }),\n });\n}\n\n/** The image `blobSource` gives, as a blob and as an object URL. */\nfunction imageSourceOf(blobSource: PageImageBlobSource): ImageSource {\n return {\n blob() {\n return AbortablePromise.run(async (signal) => {\n if (typeof Blob === 'undefined') {\n throw new EngineError(\n EngineErrorCode.RuntimeUnavailable,\n 'Blob is not available in this environment',\n );\n }\n const blob = await blobSource.blob(signal);\n if (signal.aborted) throw signal.reason;\n return blob;\n });\n },\n objectUrl() {\n return AbortablePromise.run(async (signal) => {\n if (typeof Blob === 'undefined' || typeof URL === 'undefined' || !URL.createObjectURL) {\n throw new EngineError(\n EngineErrorCode.RuntimeUnavailable,\n 'Object URLs are not available in this environment',\n );\n }\n\n const blob = await blobSource.blob(signal);\n const url = URL.createObjectURL(blob);\n // Cancelled while the blob arrived: nobody will revoke it but us.\n if (signal.aborted) {\n URL.revokeObjectURL(url);\n throw signal.reason;\n }\n return { url, revoke: () => URL.revokeObjectURL(url) };\n });\n },\n };\n}\n","import { PermissionDenied } from '../auth/scope/errors';\nimport { EngineError } from '../errors/EngineError';\nimport { EngineErrorCode } from '../errors/EngineErrorCode';\nimport type { PageRef } from '../identity/PageRef';\nimport type { FlattenOptions, PageFlattenUsage } from '../mutation/PageFlattenResult';\nimport { resolvePageLayers, type PageLayerRights, type PageRenderLayers } from './PageRender';\n\n/** Options of `pages.extract()`. */\nexport interface PageExtractOptions {\n /**\n * Copy the pages as they draw, with `pages.flatten()`'s options: the\n * annotations and form fields that draw for `usage` painted into the pages,\n * an annotation without a stored appearance included, and nothing\n * interactive left (no annotations, no page actions). Layers keep the\n * state they have for `usage`. `{ usage: 'print' }` makes a print copy.\n * Needs `doc.download` or `doc.download.flattened`.\n */\n flatten?: FlattenOptions;\n /**\n * With `flatten`: paint the annotations. Default: `true` when the caller\n * may read annotations (`doc.annotate.read`). `true` for a caller who may\n * not is refused.\n */\n includeAnnotations?: boolean;\n /**\n * With `flatten`: paint the form fields, as filled. Default: `false` when\n * `includeAnnotations` is `false`, otherwise `true` when the caller may\n * read the form (`doc.forms.read`). `true` for a caller who may not is\n * refused.\n */\n includeFormFields?: boolean;\n}\n\n/** The body of `POST …/pages/extract`: the pages, and the options. */\nexport interface PageExtractInput extends PageExtractOptions {\n pages: PageRef[];\n}\n\n/** What a flattened copy paints, resolved against what the caller may read. */\nexport interface PageExtractFlatten extends PageRenderLayers {\n readonly usage: PageFlattenUsage;\n}\n\n/** What a caller may do, for {@link resolvePageExtract}. */\nexport interface PageExtractRights extends PageLayerRights {\n /** `doc.download`. */\n readonly download: boolean;\n /** `doc.download.flattened`. */\n readonly downloadFlattened: boolean;\n}\n\n/**\n * What `pages.extract()` makes: `null` for a plain copy, else what the\n * flattened copy paints. A plain copy needs `doc.download`; a flattened one\n * `doc.download` or `doc.download.flattened`, and paints only what the caller\n * may read, with the defaults of a page picture (`resolvePageLayers`). The\n * include options belong to `flatten`: given without it, they're refused.\n */\nexport function resolvePageExtract(\n options: PageExtractOptions | undefined,\n may: PageExtractRights,\n): PageExtractFlatten | null {\n const flatten = options?.flatten;\n if (flatten === undefined) {\n for (const field of ['includeAnnotations', 'includeFormFields'] as const) {\n if (options?.[field] !== undefined) {\n throw new EngineError(EngineErrorCode.InvalidArg, `${field} takes flatten`, {\n details: { field },\n });\n }\n }\n if (!may.download) throw new PermissionDenied('doc.download');\n return null;\n }\n\n const usage = flatten.usage ?? 'display';\n if (usage !== 'display' && usage !== 'print') {\n throw new EngineError(EngineErrorCode.InvalidArg, 'usage must be \"display\" or \"print\"', {\n details: { field: 'flatten.usage' },\n });\n }\n if (!may.download && !may.downloadFlattened) {\n throw new PermissionDenied('doc.download', 'flatten', [\n 'doc.download',\n 'doc.download.flattened',\n ]);\n }\n return { usage, ...resolvePageLayers(options, may) };\n}\n","export type PdfSaveMode = 'incremental' | 'rewrite';\n\nexport const DEFAULT_PDF_SAVE_MODE: PdfSaveMode = 'incremental';\n\n/** Options of `doc.download()`. */\nexport interface DownloadOptions {\n /** `'incremental'` (the default) appends the changes; `'rewrite'` writes a new file. */\n mode?: PdfSaveMode;\n}\n","/**\n * Generate an RFC 4122 v4 UUID using the Web Crypto API surface available in\n * every realm this code runs in: Node 19+, Web Workers, browsers on https,\n * http, intranet and file: pages, and edge runtimes.\n *\n * Why this implementation:\n * - `crypto.randomUUID()` is limited to secure contexts in some browsers;\n * `getRandomValues()` has no such restriction.\n * - `import { randomUUID } from 'crypto'` makes Vite externalize the\n * `crypto` module for browser builds and fail at runtime.\n *\n * Output is the canonical hex form: `xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx`,\n * where `y` is one of `8/9/a/b` (variant nibble = 10xx).\n */\nexport function generateUuid(): string {\n const bytes = globalThis.crypto.getRandomValues(new Uint8Array(16));\n // RFC 4122 §4.4: version nibble = 4, variant nibble = 10xx.\n bytes[6] = (bytes[6]! & 0x0f) | 0x40;\n bytes[8] = (bytes[8]! & 0x3f) | 0x80;\n return formatUuid(bytes);\n}\n\n/**\n * Generate an RFC 9562 v7 UUID: the Unix time in milliseconds in the first\n * 48 bits, then random bits. Names made later sort later, which is what an\n * annotation's `/NM` gets when the data names none.\n */\nexport function generateUuidV7(now: number = Date.now()): string {\n const bytes = globalThis.crypto.getRandomValues(new Uint8Array(16));\n // 48-bit big-endian milliseconds. Division, not shifts: the value passes\n // 32 bits.\n let time = Math.max(0, Math.floor(now));\n for (let i = 5; i >= 0; i--) {\n bytes[i] = time % 256;\n time = Math.floor(time / 256);\n }\n // RFC 9562 §5.7: version nibble = 7, variant nibble = 10xx.\n bytes[6] = (bytes[6]! & 0x0f) | 0x70;\n bytes[8] = (bytes[8]! & 0x3f) | 0x80;\n return formatUuid(bytes);\n}\n\nfunction formatUuid(bytes: Uint8Array): string {\n const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('');\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;\n}\n","/**\n * The two read families a page's `/Annots` splits into: its annotations,\n * every subtype but `/Widget` (`doc.annotations.list()`), and its widgets,\n * which are the form's (`doc.forms.list()`). The subtype alone decides, in\n * the reads, the events, the permissions and the pictures.\n */\nexport type AnnotationFamily = 'annotations' | 'widgets';\n\n/** The family an annotation of `subtype` belongs to. */\nexport function familyOfSubtype(subtype: string): AnnotationFamily {\n return subtype === 'widget' ? 'widgets' : 'annotations';\n}\n","import type { AttachmentFileSource, WireAttachmentFile } from './Attachment';\nimport { EngineError } from '../errors/EngineError';\nimport { EngineErrorCode } from '../errors/EngineErrorCode';\nimport { resolveBinarySource, type WireResource } from '../resource/BinarySource';\n\n/**\n * Resolve an attachment `file` into its wire halves: metadata into the\n * JSON body, bytes into the resource map. Unlike stamps there is no\n * format allowlist — attaching arbitrary files is the point — so the\n * declared mime type wins, then the Blob's; attachment formats cannot be\n * reliably sniffed, so without either the file has no type.\n * Used by the document-level `attachments.create`.\n */\nexport async function normalizeAttachmentFileSource(\n file: AttachmentFileSource,\n key: string,\n): Promise<{ wireFile: WireAttachmentFile; resource: WireResource }> {\n const resolved = await resolveBinarySource(\n file.data instanceof ArrayBuffer ? new Uint8Array(file.data) : file.data,\n );\n const name = file.name ?? resolved.name;\n if (!name) {\n throw new EngineError(\n EngineErrorCode.InvalidArg,\n 'attachment file requires a name — pass { data, name } or a File whose name is set',\n );\n }\n const mimeType = file.mimeType ?? resolved.mimeType;\n return {\n wireFile: {\n resources: { file: key },\n name,\n ...(mimeType !== undefined ? { mimeType } : {}),\n ...(file.description !== undefined ? { description: file.description } : {}),\n },\n resource: { bytes: resolved.bytes, ...(mimeType !== undefined ? { mimeType } : {}), name },\n };\n}\n","import type { AnnotationBundle } from './AnnotationBundle';\nimport type { BundleImportPages } from './bundle';\nimport type { Annotation } from '../annotation/kinds';\nimport type { AnnotationRef } from '../identity/AnnotationRef';\nimport type { PageRef } from '../identity/PageRef';\nimport type { AnnotationListMutationMeta } from '../mutation/AnnotationListMutationMeta';\nimport type { AnnotationCreateResult } from '../mutation/AnnotationMutationResults';\nimport type { WriteOptions } from '../mutation/WriteOptions';\nimport type { Coordinates, PageCoordinates } from '../pageSpace/coordinates';\n\n/**\n * How to import. The `opId` names the import: its events share it as\n * `origin.tx.id`, and on the cloud a retry with the same id applies once.\n */\nexport interface AnnotationImportOptions extends WriteOptions {\n /** Default `'same'`. A page an item is on or points at that maps nowhere refuses the import. */\n readonly pages?: BundleImportPages;\n /**\n * `'restore'` (the default) writes the authors, dates and names (`nm`) as\n * the bundle has them, and needs `doc.annotate.import`; an item whose name\n * its page already has is dropped as `'name-conflict'`. `'stamp'` makes\n * copies: it stamps the session and the time, as `create` does, and gives\n * every annotation a fresh name.\n */\n readonly attribution?: 'restore' | 'stamp';\n}\n\n/**\n * An import as it travels to a server: the bundle without its bytes (each\n * resource is a part of its own) and the options, apart from the `opId`,\n * which is the request's `Idempotency-Key`.\n */\nexport interface AnnotationImportBody {\n readonly bundle: Omit<AnnotationBundle, 'resources'>;\n readonly options: Omit<AnnotationImportOptions, 'opId'>;\n}\n\n/** Why an import left an annotation, or one of its fields, out. */\nexport type AnnotationDropReason =\n /** A kind the engine doesn't model (`subtype: 'unsupported'`). */\n | 'unsupported-kind'\n /** A widget, in a field or not: widgets are the form's, and travel with it. */\n | 'widget'\n /** A geospatial measure, which the engine reads only as a marker. */\n | 'geospatial'\n /** A measure of a kind the engine doesn't know, read only as a marker. */\n | 'unknown-measure'\n /**\n * An action a write can't make: a link's target of a kind a write can't\n * make (JavaScript, launch, named, remote go-to), or actions (`/A`, `/AA`)\n * that no field of the kind writes.\n */\n | 'unsupported-action'\n /**\n * A value another app wrote that a write can't make: a shape's beveled or\n * inset border, a typewriter's intent, a polyline of one point. An\n * optional field is left out; an item whose shape it is, is left out.\n */\n | 'unsupported-value'\n /** Its `nm` is used on the target page already, or by an earlier item. */\n | 'name-conflict'\n /** Its `reply.to` or `parent` is an item that was left out. */\n | 'parent-dropped'\n /** Its `reply.to` or `parent` is no item of the bundle on its page. */\n | 'parent-missing'\n /** A popup whose parent has another, an earlier item: an annotation has one popup. */\n | 'popup-taken';\n\nexport interface AnnotationImportDrop {\n /** The annotation, as the bundle names it. */\n readonly ref: AnnotationRef;\n /** Set when only this field was left out: the annotation was imported without it. */\n readonly field?: string;\n readonly reason: AnnotationDropReason;\n}\n\nexport interface AnnotationImportResult<C extends Coordinates = PageCoordinates> {\n /** In bundle order, each as it is now. */\n annotations: Annotation<C>[];\n /** Each imported annotation's ref in the bundle, and its ref in this document. */\n refMap: Array<{ from: AnnotationRef; to: AnnotationRef }>;\n /** What was left out, in bundle order. */\n dropped: AnnotationImportDrop[];\n meta: AnnotationListMutationMeta;\n}\n\n/**\n * The facts an import committed: one `annotations.created` per annotation, in\n * bundle order, each with the envelope of its own page and its own id. The\n * cache pins move once, with the last.\n */\nexport function annotationImportFacts(\n result: AnnotationImportResult,\n): Array<{ page: PageRef } & AnnotationCreateResult> {\n const last = result.annotations.length - 1;\n return result.annotations.map((annotation, index) => {\n const { page } = annotation.ref;\n return {\n page,\n annotation,\n meta: {\n affectedPages: result.meta.affectedPages.filter(\n (affected) => affected.objectNumber === page.objectNumber,\n ),\n cacheDelta: index === last ? result.meta.cacheDelta : null,\n opId: result.meta.opId,\n undoable: result.meta.undoable,\n changed: [annotation.ref],\n },\n };\n });\n}\n","import type { Annotation } from '../annotation/kinds';\nimport type { PdfCoordinates } from '../pageSpace/coordinates';\nimport { EngineError } from '../errors/EngineError';\nimport { EngineErrorCode } from '../errors/EngineErrorCode';\nimport { annotationKey } from '../identity/annotationKey';\nimport type { AnnotationRef } from '../identity/AnnotationRef';\nimport { encodePageKey, type PageRef } from '../identity/PageRef';\n\n/** Which annotations an export takes. Without `refs` or `pages`, every one in the document. */\nexport interface AnnotationExportSelection {\n readonly refs?: readonly AnnotationRef[];\n readonly pages?: readonly PageRef[];\n /**\n * `'threads'` (the default): the selection, what it points at, and every\n * reply below a selected annotation, so a comment travels with its\n * discussion. `'references'`: the selection and only what it points at.\n */\n readonly include?: 'references' | 'threads';\n}\n\n/**\n * The annotations an export takes, in document order: page order, then each\n * page's annotation order. Besides the selection:\n *\n * - a reply brings its parent, and the parent's, up to the root;\n * - an annotation brings its popup, and a popup brings its parent;\n * - with `include: 'threads'`, the default, every reply below a selected\n * annotation.\n *\n * A reply is on its parent's page (ISO 32000-2 §12.5.6.2, `/IRT`) and a popup\n * on its parent's, so none of this reaches another page. `readPage` returns a\n * page's annotations in `/Annots` order and is called once for each page\n * the selection is on. `pages` is the document's pages in order. A selected\n * page or annotation the document doesn't have is refused with `NotFound`.\n */\nexport function closeExportSelection<A extends Annotation | Annotation<PdfCoordinates>>(\n selection: AnnotationExportSelection,\n pages: readonly PageRef[],\n readPage: (page: PageRef) => readonly A[],\n): A[] {\n const inDocument = new Set(pages.map(encodePageKey));\n const read = new Map<string, readonly A[]>();\n const byKey = new Map<string, A>();\n // A ref may name a page the document doesn't have (a broken /IRT): it\n // finds nothing.\n const readOnce = (page: PageRef) => {\n const pageKey = encodePageKey(page);\n if (read.has(pageKey) || !inDocument.has(pageKey)) return;\n const annotations = readPage(page);\n read.set(pageKey, annotations);\n for (const annotation of annotations) byKey.set(annotationKey(annotation.ref), annotation);\n };\n const find = (ref: AnnotationRef): A | undefined => {\n readOnce(ref.page);\n return byKey.get(annotationKey(ref));\n };\n\n for (const page of selection.pages ?? []) {\n if (!inDocument.has(encodePageKey(page))) {\n throw new EngineError(\n EngineErrorCode.NotFound,\n `export: the document has no page ${encodePageKey(page)}`,\n );\n }\n }\n const everything = !selection.refs && !selection.pages;\n const threads = (selection.include ?? 'threads') === 'threads';\n for (const page of everything ? pages : (selection.pages ?? [])) readOnce(page);\n\n const taken = new Set<string>();\n const pending: A[] = [];\n const take = (annotation: A | undefined) => {\n if (!annotation) return;\n const key = annotationKey(annotation.ref);\n if (taken.has(key)) return;\n taken.add(key);\n pending.push(annotation);\n };\n\n if (everything) {\n for (const annotations of read.values()) annotations.forEach(take);\n } else {\n for (const page of selection.pages ?? []) read.get(encodePageKey(page))?.forEach(take);\n for (const ref of selection.refs ?? []) {\n const annotation = find(ref);\n if (!annotation) {\n throw new EngineError(\n EngineErrorCode.NotFound,\n `export: the document has no annotation ${annotationKey(ref)}`,\n );\n }\n take(annotation);\n }\n }\n\n if (threads) {\n // A popup is its parent's window: selecting it selects the comment, and\n // so the comment's replies.\n for (const annotation of [...pending]) {\n if (annotation.subtype === 'popup' && annotation.parent) take(find(annotation.parent));\n }\n const replies = new Map<string, A[]>();\n for (const annotations of read.values()) {\n for (const annotation of annotations) {\n const parent = annotation.reply ? find(annotation.reply.to) : undefined;\n if (!parent) continue;\n const key = annotationKey(parent.ref);\n replies.set(key, [...(replies.get(key) ?? []), annotation]);\n }\n }\n for (let i = 0; i < pending.length; i++) {\n replies.get(annotationKey(pending[i]!.ref))?.forEach(take);\n }\n }\n\n for (let i = 0; i < pending.length; i++) {\n const annotation = pending[i]!;\n if (annotation.reply) take(find(annotation.reply.to));\n if (annotation.popup) take(find(annotation.popup));\n if (annotation.subtype === 'popup' && annotation.parent) take(find(annotation.parent));\n }\n\n const ordered: A[] = [];\n for (const page of pages) {\n for (const annotation of read.get(encodePageKey(page)) ?? []) {\n if (taken.has(annotationKey(annotation.ref))) ordered.push(annotation);\n }\n }\n return ordered;\n}\n","import type { Annotation } from './kinds';\nimport type { Coordinates, PageCoordinates } from '../pageSpace/coordinates';\nimport type { PageRef } from '../identity/PageRef';\n\n/**\n * What `doc.annotations.list()` and `page.annotations.list()` return, and\n * what the server's annotation list endpoints send: the annotations of the\n * listed pages, each page's in display order, and the pages it listed. Every\n * annotation names its `page`.\n *\n * A whole-document list's page order is unspecified — the local engine\n * reads in document order, the cloud in its page registry's order; join\n * `pages[i].page` against `pages.list()` (by ref) when display order matters.\n */\nexport interface AnnotationList<C extends Coordinates = PageCoordinates> {\n annotations: Annotation<C>[];\n pages: PageRef[];\n /**\n * Cloud, whole document only: the audit-log position the list is\n * consistent with. Every page reflects exactly the mutations with\n * `serverId <= auditHead` and none newer — the read is pinned to one\n * manifest, whose `auditHead` is written in the same transaction as its\n * version bumps.\n *\n * This is the reconciliation cursor for consumers that keep a list fresh\n * from `doc.events`: drop events with `origin.serverId <= auditHead`\n * (already inside the list), apply the rest.\n */\n auditHead?: number;\n}\n\n/** Which pages `doc.annotations.list()` reads. */\nexport interface AnnotationListOptions {\n /** The pages to list, in the order to list them. Every page when omitted. */\n pages?: readonly PageRef[];\n}\n\n/** Lists of different pages as one, in their order. */\nexport function concatAnnotationLists<C extends Coordinates>(\n lists: readonly AnnotationList<C>[],\n): AnnotationList<C> {\n return {\n annotations: lists.flatMap((list) => list.annotations),\n pages: lists.flatMap((list) => list.pages),\n };\n}\n","import type { AnnotationListMutationMeta } from './AnnotationListMutationMeta';\nimport type { AppearanceOutcome } from '../annotation/appearance';\nimport type { Annotation } from '../annotation/kinds';\nimport type { AnnotationRef } from '../identity/AnnotationRef';\nimport type { Coordinates, PageCoordinates } from '../pageSpace/coordinates';\n\n/**\n * Created annotation, fully materialised. It is born as a PDF object, so\n * it is named by its object number.\n */\nexport interface AnnotationCreateResult<C extends Coordinates = PageCoordinates> {\n annotation: Annotation<C>;\n meta: AnnotationListMutationMeta;\n}\n\nexport interface AnnotationUpdateResult<C extends Coordinates = PageCoordinates> {\n /**\n * The updated annotation, fully materialised after the patch, under the\n * name it had: an update never renames an annotation, and never writes\n * its /NM.\n *\n * The /NM value is data to the engine. Callers that keep their own id\n * in it set `draft.nm` at creation (a create refuses a name its page\n * already has) and find the annotation by it in a read. There is no\n * `patch.nm`.\n */\n annotation: Annotation<C>;\n /**\n * The engine's appearance verdict for this update (see\n * {@link AppearanceOutcome}). Clients drive raster invalidation off\n * `appearance.changed` — never off the shape of the patch they sent: the\n * engine value-diffs and verifies, so a full-object patch that only moved\n * the annotation still reports `preserved`.\n */\n appearance: AppearanceOutcome;\n meta: AnnotationListMutationMeta;\n}\n\n/**\n * A delete: nothing exists after it, so only `meta`. Deleting an annotation\n * deletes its replies, grouped parts, review states and popups with it;\n * `meta.changed` names them all, the annotation first.\n */\nexport interface AnnotationDeleteResult {\n meta: AnnotationListMutationMeta;\n}\n\n/**\n * What a delete removed, as its `annotations.deleted` event names it for\n * listeners that didn't make the call: the refs in `meta.changed`, the\n * annotation first.\n */\nexport function deletedAnnotationsOf(result: AnnotationDeleteResult): AnnotationRef[] {\n return result.meta.changed;\n}\n\n/**\n * Result of a stacking-order change (`page.annotations.reorder()`): the\n * page's annotations in their new paint order, whole, as refs (widgets\n * excepted: they paint above every annotation, in their own order). The\n * moved annotations keep their names and their data, so nothing else is\n * read back.\n */\nexport interface AnnotationReorderResult {\n /** Every annotation of the page, widgets excepted, bottom to top. */\n order: AnnotationRef[];\n /** `meta.changed` names the annotations that moved, in the order given. */\n meta: AnnotationListMutationMeta;\n}\n","import type { Coordinates } from '../../pageSpace/coordinates';\nimport { kindFactsOf } from '../kind-facts';\nimport type { Annotation, AnnotationPatch } from '../kinds';\nimport { applyResolvedPatch } from './applyAnnotationPatch';\n\n/** Exact deep equality: the same value, or arrays and objects whose members are. */\nfunction sameValue(left: unknown, right: unknown): boolean {\n if (Object.is(left, right)) return true;\n if (typeof left !== 'object' || typeof right !== 'object' || left === null || right === null) {\n return false;\n }\n if (Array.isArray(left) !== Array.isArray(right)) return false;\n const leftRecord = left as Record<string, unknown>;\n const rightRecord = right as Record<string, unknown>;\n const names = Object.keys(leftRecord).filter((name) => leftRecord[name] !== undefined);\n const others = Object.keys(rightRecord).filter((name) => rightRecord[name] !== undefined);\n return (\n names.length === others.length &&\n names.every((name) => sameValue(leftRecord[name], rightRecord[name]))\n );\n}\n\n/**\n * What `after` changed from `before`, as `update` takes it: each data field\n * whose value differs, whole. Fields the engine works out, stamps or keeps as\n * found (a drawn kind's `rect`, the dates and authors, the refs it keeps) are\n * left out. Values are compared exactly, so a value rebuilt with the same\n * content is no change. Works in either space: it only compares values by\n * field name.\n */\nexport function annotationPatchBetween<C extends Coordinates>(\n before: Annotation<C>,\n after: Annotation<C>,\n): AnnotationPatch<C> {\n const patch: Record<string, unknown> = {};\n if (before === after) return patch as AnnotationPatch<C>;\n const owners = kindFactsOf(after.subtype)?.owners ?? {};\n const was = before as unknown as Record<string, unknown>;\n const now = after as unknown as Record<string, unknown>;\n for (const [name, owner] of Object.entries(owners)) {\n if (owner !== 'data' || sameValue(was[name], now[name])) continue;\n // A field `after` doesn't have any more is removed.\n patch[name] = now[name] === undefined ? null : now[name];\n }\n return patch as AnnotationPatch<C>;\n}\n\n/**\n * `current` with `patch`'s data fields set, each as a read spells it: the\n * patch as given. No field follows from another here; `applyAnnotationPatch`\n * adds what the engine's rules make follow. Works in either space.\n */\nexport function mergeAnnotationPatch<A extends Annotation<Coordinates>>(\n current: A,\n patch: AnnotationPatch<Coordinates>,\n): A {\n return applyResolvedPatch(current, patch);\n}\n","import type { PageCoordinates, PdfCoordinates } from './coordinates';\nimport { mapPageActions, pageDestinationOf, type VisibleBoxOf } from './destinations';\nimport type { PageBoxes, PageLayout } from '../dto/PageLayout';\nimport type { PageListSnapshot } from '../dto/PageListSnapshot';\nimport { EngineError } from '../errors/EngineError';\nimport { EngineErrorCode } from '../errors/EngineErrorCode';\nimport { pageBoxOf } from '../geometry/pageSpace';\nimport type { PdfRect } from '../geometry/primitives';\n\n/**\n * A page's five boxes in page space: measured from the top-left of the crop\n * box, the visible page, which is therefore `{ x: 0, y: 0, width, height }`.\n */\nexport function pageSpaceBoxesOf(boxes: PageBoxes<PdfCoordinates>): PageBoxes<PageCoordinates> {\n const visible = boxes.crop;\n return {\n media: pageBoxOf(boxes.media, visible),\n crop: pageBoxOf(boxes.crop, visible),\n bleed: pageBoxOf(boxes.bleed, visible),\n trim: pageBoxOf(boxes.trim, visible),\n art: pageBoxOf(boxes.art, visible),\n };\n}\n\n/**\n * A page's layout in page space. Its actions may go to other pages, so each\n * destination is measured with `boxOf`, the box of the page it goes to.\n */\nexport function pageLayoutOf(\n layout: PageLayout<PdfCoordinates>,\n boxOf: VisibleBoxOf,\n): PageLayout<PageCoordinates> {\n const { actions, ...rest } = layout;\n return {\n ...rest,\n boxes: pageSpaceBoxesOf(layout.boxes),\n ...(actions\n ? {\n actions: mapPageActions(actions, (destination) => pageDestinationOf(destination, boxOf)),\n }\n : {}),\n };\n}\n\n/** Every page's visible box, by page, from the pages' layouts. */\nexport function visibleBoxesOf(pages: readonly PageLayout<PdfCoordinates>[]): VisibleBoxOf {\n const boxes = new Map<number, PdfRect>(\n pages.map((page) => [page.ref.objectNumber, page.boxes.crop]),\n );\n return (page) => {\n const box = boxes.get(page.objectNumber);\n if (!box) {\n throw new EngineError(\n EngineErrorCode.InvalidArg,\n `No page ${page.objectNumber} in this document`,\n );\n }\n return box;\n };\n}\n\n/** The document's pages in page space. */\nexport function pageListOf(\n snapshot: PageListSnapshot<PdfCoordinates>,\n): PageListSnapshot<PageCoordinates> {\n const boxOf = visibleBoxesOf(snapshot.pages);\n return { ...snapshot, pages: snapshot.pages.map((page) => pageLayoutOf(page, boxOf)) };\n}\n","import type { PageCoordinates, PdfCoordinates } from './coordinates';\nimport type { PageRenderTarget } from '../dto/PageRender';\nimport { pageBoxOf, pdfRectOf, type PageBox } from '../geometry/pageSpace';\nimport type { PdfRect } from '../geometry/primitives';\n\n/** A page-space render target in the file's coordinates. `visible` is the page's visible box. */\nexport function pdfRenderTargetOf(\n target: PageRenderTarget<PageCoordinates>,\n visible: PdfRect,\n): PageRenderTarget<PdfCoordinates> {\n return target.kind === 'rect' ? { ...target, rect: pdfRectOf(target.rect, visible) } : target;\n}\n\n/**\n * Where each rendered appearance goes, in page space: raster or encoded, each\n * placed by its `rect`. `visible` is the page's visible box.\n */\nexport function pageAppearancesOf<Appearance extends { rect: PdfRect }>(\n appearances: readonly Appearance[],\n visible: PdfRect,\n): Array<Omit<Appearance, 'rect'> & { rect: PageBox }> {\n return appearances.map((appearance) => ({\n ...appearance,\n rect: pageBoxOf(appearance.rect, visible),\n }));\n}\n","import { pageAnnotationOf } from './annotations';\nimport type { PageCoordinates, PdfCoordinates } from './coordinates';\nimport {\n mapFieldActions,\n mapTriggerActions,\n pageDestinationOf,\n pdfDestinationOf,\n type VisibleBoxOf,\n} from './destinations';\nimport type { WidgetAnnotation } from '../annotation/kinds/widget';\nimport type { PdfFieldActions } from '../dto/PdfAction';\nimport type { PageDestination, PdfDestination } from '../dto/PdfDestination';\nimport type { FormFieldDraft, WidgetPlacement } from '../forms/draft';\nimport type { FormFieldDTO } from '../forms/field';\nimport type { FormSnapshot } from '../forms/snapshot';\nimport { pdfRectOf } from '../geometry/pageSpace';\n\n/** A page-space widget placement in the file's coordinates, measured on its page. */\nexport function pdfWidgetPlacementOf(\n placement: WidgetPlacement<PageCoordinates>,\n boxOf: VisibleBoxOf,\n): WidgetPlacement<PdfCoordinates> {\n const { actions, ...rest } = placement;\n const visible = boxOf(placement.page);\n return {\n ...rest,\n ...(placement.rect ? { rect: pdfRectOf(placement.rect, visible) } : {}),\n ...(placement.box ? { box: pdfRectOf(placement.box, visible) } : {}),\n ...(actions\n ? {\n actions: mapTriggerActions(actions, (destination: PageDestination) =>\n pdfDestinationOf(destination, boxOf),\n ),\n }\n : {}),\n } as WidgetPlacement<PdfCoordinates>;\n}\n\n/** A field draft in the file's coordinates: each widget measured on its own page. */\nexport function pdfFormFieldDraftOf(\n draft: FormFieldDraft<PageCoordinates>,\n boxOf: VisibleBoxOf,\n): FormFieldDraft<PdfCoordinates> {\n if (!draft.widgets) return draft as FormFieldDraft<PdfCoordinates>;\n return {\n ...draft,\n widgets: draft.widgets.map((widget) => pdfWidgetPlacementOf(widget, boxOf)),\n } as FormFieldDraft<PdfCoordinates>;\n}\n\n/** A field's actions in page space, each destination measured on its page. */\nexport function pageFieldActionsOf(\n actions: PdfFieldActions<PdfDestination>,\n boxOf: VisibleBoxOf,\n): PdfFieldActions<PageDestination> {\n return mapFieldActions(actions, (destination) => pageDestinationOf(destination, boxOf));\n}\n\n/** A form field in page space: each destination of its actions on the page it goes to. */\nexport function pageFormFieldOf(\n field: FormFieldDTO<PdfCoordinates>,\n boxOf: VisibleBoxOf,\n): FormFieldDTO {\n if (!field.actions) return field as FormFieldDTO;\n return { ...field, actions: pageFieldActionsOf(field.actions, boxOf) } as FormFieldDTO;\n}\n\n/** A widget row in page space, measured on its page. */\nexport function pageWidgetOf(\n widget: WidgetAnnotation<PdfCoordinates>,\n boxOf: VisibleBoxOf,\n): WidgetAnnotation {\n return pageAnnotationOf(widget, boxOf(widget.page), boxOf) as WidgetAnnotation;\n}\n\n/** A form in page space: its fields, and each widget row on its page. */\nexport function pageFormSnapshotOf(\n snapshot: FormSnapshot<PdfCoordinates>,\n boxOf: VisibleBoxOf,\n): FormSnapshot {\n return {\n ...snapshot,\n fields: snapshot.fields.map((field) => pageFormFieldOf(field, boxOf)),\n widgets: snapshot.widgets.map((widget) => pageWidgetOf(widget, boxOf)),\n };\n}\n","import { mapActionTree, mapLinkTarget, pageDestinationOf, pdfDestinationOf } from './destinations';\nimport type { VisibleBoxOf } from './destinations';\nimport type {\n DocumentOutline,\n OutlineItem,\n OutlineItemDraft,\n OutlineItemPatch,\n} from '../dto/DocumentOutline';\nimport type { PageDestination, PdfDestination } from '../dto/PdfDestination';\nimport type { PdfLinkTargetWritable } from '../dto/PdfLinkTarget';\n\n/**\n * The outline between the file's coordinates and page space: only the\n * destinations an item goes to change, each measured on the page it goes to.\n */\n\n/** An item, its target's and its action's destinations converted. */\nexport function mapOutlineItem<From, To>(\n item: OutlineItem<From>,\n convert: (destination: From) => To,\n): OutlineItem<To> {\n return {\n ...item,\n target: item.target && mapLinkTarget(item.target, convert),\n action: item.action && mapActionTree(item.action, convert),\n };\n}\n\n/** A draft or a patch, its target's destination converted. */\nfunction mapOutlineWrite<From, To, W extends { target?: PdfLinkTargetWritable<From> | null }>(\n write: W,\n convert: (destination: From) => To,\n): Omit<W, 'target'> & { target?: PdfLinkTargetWritable<To> | null } {\n const { target, ...rest } = write;\n if (target === undefined) return rest;\n return {\n ...rest,\n target:\n target && target.kind === 'goto'\n ? { ...target, destination: convert(target.destination) }\n : (target as PdfLinkTargetWritable<To> | null),\n };\n}\n\n/** The outline as a read hands it out: every destination in page space. */\nexport function pageOutlineOf(\n outline: DocumentOutline<PdfDestination>,\n boxOf: VisibleBoxOf,\n): DocumentOutline<PageDestination> {\n return {\n ...outline,\n items: outline.items.map((item) => pageOutlineItemOf(item, boxOf)),\n };\n}\n\nexport function pageOutlineItemOf(\n item: OutlineItem<PdfDestination>,\n boxOf: VisibleBoxOf,\n): OutlineItem<PageDestination> {\n return mapOutlineItem(item, (destination) => pageDestinationOf(destination, boxOf));\n}\n\n/** A draft in the file's coordinates, as the engine writes it. */\nexport function pdfOutlineDraftOf(\n draft: OutlineItemDraft<PageDestination>,\n boxOf: VisibleBoxOf,\n): OutlineItemDraft<PdfDestination> {\n return mapOutlineWrite(draft, (destination: PageDestination) =>\n pdfDestinationOf(destination, boxOf),\n ) as OutlineItemDraft<PdfDestination>;\n}\n\n/** A patch in the file's coordinates, as the engine writes it. */\nexport function pdfOutlinePatchOf(\n patch: OutlineItemPatch<PageDestination>,\n boxOf: VisibleBoxOf,\n): OutlineItemPatch<PdfDestination> {\n return mapOutlineWrite(patch, (destination: PageDestination) =>\n pdfDestinationOf(destination, boxOf),\n ) as OutlineItemPatch<PdfDestination>;\n}\n","import type { WidgetStyleDraftFields } from '../annotation/kinds/widget.shared';\nimport { writesScripts, type FieldActionsPatch, type WidgetActionsPatch } from '../dto/PdfAction';\nimport type { PdfRotation } from '../geometry/primitives';\nimport type { PageRef } from '../identity/PageRef';\nimport type { Coordinates, PageCoordinates } from '../pageSpace/coordinates';\n\n/**\n * Where a widget goes and how it looks: its page, its place on it and its\n * turn, and the same style fields a widget annotation's update takes.\n * `create()` places a field's widgets with these, and `addWidget()` adds one.\n *\n * The place is `rect` or `box`, as for every kind that turns: where the\n * widget stands on the page, or the frame its contents are laid out in,\n * before the turn. Give one; with both, `box` is the shape.\n */\nexport interface WidgetPlacement<\n C extends Coordinates = PageCoordinates,\n> extends WidgetStyleDraftFields {\n page: PageRef;\n /** Where the widget stands on the page: its `box`, turned. */\n rect?: C['box'];\n /** The frame its contents are laid out in, before the turn: `rect` with its sides swapped under 90 and 270. */\n box?: C['box'];\n /**\n * How its contents turn, degrees clockwise: a quarter turn (`/MK /R`).\n * With 90 or 270 the text runs along the rect's height, as Acrobat's\n * Orientation turns it. Upright when left out.\n */\n rotation?: PdfRotation;\n /**\n * A checkbox or radio widget's export value: what the form data holds\n * while it's checked. Required for a radio button (and never `'Off'`);\n * `'Yes'` for a checkbox when left out. Other families take none.\n */\n exportValue?: string;\n /**\n * What the widget does when clicked (`activate`), entered, focused and so\n * on. A JavaScript, submit-form or URI action takes `doc.forms.script` too.\n */\n actions?: WidgetActionsPatch<C['destination']>;\n}\n\n/**\n * Whether creating a field from `draft` takes `doc.forms.script`: a script\n * among its actions, or a widget action that holds JavaScript, a submit or a\n * link.\n */\nexport function draftWritesScripts(draft: {\n readonly actions?: FieldActionsPatch;\n readonly widgets?: readonly { readonly actions?: WidgetActionsPatch<unknown> }[];\n}): boolean {\n return (\n writesScripts(draft.actions) ||\n (draft.widgets ?? []).some((placement) => writesScripts(placement.actions))\n );\n}\n\n/** An option of a choice field at authoring time. */\nexport interface FormFieldOptionInput {\n label: string;\n /** Export value (used by /V, interchange, and choice writes). */\n value: string;\n}\n\ninterface FormFieldDraftBase {\n /**\n * Dotted fully qualified name (\"billing.name\"). Missing non-terminal\n * ancestors are created; a sibling name collision fails with\n * `InvalidArg`.\n */\n name: string;\n readOnly?: boolean;\n required?: boolean;\n noExport?: boolean;\n /** /TU — the accessible tooltip. */\n alternateName?: string;\n /** /TM — the export mapping name. */\n mappingName?: string;\n /**\n * The group the field goes in: who fills it in. Default: the session's own\n * group (`identity.groupId`). Another group takes `fields:set-group` for it.\n */\n groupId?: string;\n /**\n * The field's scripts, by event (JavaScript only). A `calculate` script\n * puts the field at the end of the form's calculation order. Writing a\n * script takes `doc.forms.script` too.\n */\n actions?: FieldActionsPatch;\n}\n\nexport interface TextFieldDraft<\n C extends Coordinates = PageCoordinates,\n> extends FormFieldDraftBase {\n family: 'text';\n defaultValue?: string;\n maxLength?: number;\n multiline?: boolean;\n password?: boolean;\n comb?: boolean;\n widgets?: WidgetPlacement<C>[];\n}\n\nexport interface CheckboxFieldDraft<\n C extends Coordinates = PageCoordinates,\n> extends FormFieldDraftBase {\n family: 'checkbox';\n widgets?: WidgetPlacement<C>[];\n}\n\n/** One field, N widgets — the ISO radio model. */\nexport interface RadioFieldDraft<\n C extends Coordinates = PageCoordinates,\n> extends FormFieldDraftBase {\n family: 'radio';\n radiosInUnison?: boolean;\n noToggleToOff?: boolean;\n /** One per button, each with its `exportValue`. */\n widgets?: WidgetPlacement<C>[];\n}\n\nexport interface ComboBoxFieldDraft<\n C extends Coordinates = PageCoordinates,\n> extends FormFieldDraftBase {\n family: 'combobox';\n /** Free text allowed in addition to the options. */\n edit?: boolean;\n options?: FormFieldOptionInput[];\n defaultValue?: string;\n widgets?: WidgetPlacement<C>[];\n}\n\nexport interface ListBoxFieldDraft<\n C extends Coordinates = PageCoordinates,\n> extends FormFieldDraftBase {\n family: 'listbox';\n multiSelect?: boolean;\n options?: FormFieldOptionInput[];\n /** Option values `reset()` selects. */\n defaultValue?: string[];\n widgets?: WidgetPlacement<C>[];\n}\n\n/**\n * A signature field: identity and (usually) one widget. Created unsigned;\n * signing it is `doc.signatures`' job, drawing a mark into it without\n * signing is `doc.forms.setSignatureAppearance`.\n */\nexport interface SignatureFieldDraft<\n C extends Coordinates = PageCoordinates,\n> extends FormFieldDraftBase {\n family: 'signature';\n widgets?: WidgetPlacement<C>[];\n}\n\n/**\n * A push button: no value, only widgets, each with its `caption` and\n * usually an `activate` action (reset the form, go to a page, submit).\n */\nexport interface PushButtonFieldDraft<\n C extends Coordinates = PageCoordinates,\n> extends FormFieldDraftBase {\n family: 'pushbutton';\n widgets?: WidgetPlacement<C>[];\n}\n\n/** What `doc.forms.create` takes: per family, mirroring the DTO union. */\nexport type FormFieldDraft<C extends Coordinates = PageCoordinates> =\n | TextFieldDraft<C>\n | CheckboxFieldDraft<C>\n | RadioFieldDraft<C>\n | ComboBoxFieldDraft<C>\n | ListBoxFieldDraft<C>\n | PushButtonFieldDraft<C>\n | SignatureFieldDraft<C>;\n","import { EngineError } from '../errors/EngineError';\nimport { EngineErrorCode } from '../errors/EngineErrorCode';\nimport { normalizePdfRect, pdfRectTurnedBounds } from '../geometry/convert';\nimport type { PdfRect } from '../geometry/primitives';\nimport type { PdfCoordinates } from '../pageSpace/coordinates';\nimport type { WidgetPlacement } from './draft';\n\n/** A placement once resolved (`placedWidgetOf`): where the widget stands is stated. */\nexport type PlacedWidget = Omit<WidgetPlacement<PdfCoordinates>, 'rect' | 'box'> & {\n rect: PdfRect;\n};\n\n/**\n * A placement as the file holds it: `/Rect`, where the widget stands, and\n * its turn. A `box` given is turned into the rect it stands in, as a box\n * kind's create turns it; without one, `rect` is that place.\n *\n * Refused with `InvalidArg`: a placement with neither, and a turn that\n * isn't a quarter turn (a widget's contents turn only so, `/MK /R`).\n */\nexport function placedWidgetOf(placement: WidgetPlacement<PdfCoordinates>): PlacedWidget {\n const { box, rect, rotation, ...rest } = placement;\n if (rotation !== undefined && ![0, 90, 180, 270].includes(rotation)) {\n throw new EngineError(\n EngineErrorCode.InvalidArg,\n `a widget turns by a quarter turn (0, 90, 180 or 270), not ${rotation}`,\n { details: { field: 'rotation' } },\n );\n }\n const place = box ? pdfRectTurnedBounds(normalizePdfRect(box), rotation ?? 0) : rect;\n if (!place) {\n throw new EngineError(\n EngineErrorCode.InvalidArg,\n \"a widget's placement needs its `rect` or its `box`\",\n { details: { field: 'rect' } },\n );\n }\n return { ...rest, rect: place, ...(rotation !== undefined ? { rotation } : {}) };\n}\n","import type { PdfValue } from './types';\n\n/**\n * Parse the fork's canonical shallow serialisation:\n * dict <</Key value/Key2 value>> (keys sorted, `#xx`-escaped)\n * array [item item]\n * ref n 0 R\n * stream stream(length,sha256hex)<<dict>>\n * name /Name (with #xx escapes)\n * string (literal with backslash escapes) or <hex>\n * number -12.5 bool true|false null\n */\nexport function parsePdfValue(text: string): PdfValue {\n const parser = new Parser(text);\n const value = parser.value();\n parser.skipSpaces();\n if (!parser.atEnd())\n throw new Error(`trailing input at ${parser.pos}: ${text.slice(parser.pos, parser.pos + 20)}`);\n return value;\n}\n\nclass Parser {\n pos = 0;\n constructor(private readonly text: string) {}\n\n atEnd(): boolean {\n return this.pos >= this.text.length;\n }\n\n skipSpaces(): void {\n while (this.pos < this.text.length && this.text[this.pos] === ' ') this.pos++;\n }\n\n value(): PdfValue {\n this.skipSpaces();\n const t = this.text;\n if (t.startsWith('<<', this.pos)) return this.dict();\n if (t.startsWith('stream(', this.pos)) return this.stream();\n if (t[this.pos] === '[') return this.array();\n if (t[this.pos] === '/') return { t: 'name', v: this.name() };\n if (t[this.pos] === '(') return { t: 'string', v: this.literalString() };\n if (t[this.pos] === '<') return { t: 'string', v: this.hexString() };\n if (t.startsWith('true', this.pos)) {\n this.pos += 4;\n return { t: 'bool', v: true };\n }\n if (t.startsWith('false', this.pos)) {\n this.pos += 5;\n return { t: 'bool', v: false };\n }\n if (t.startsWith('null', this.pos)) {\n this.pos += 4;\n return { t: 'null' };\n }\n const ref = /^(\\d+) 0 R(?![0-9A-Za-z])/.exec(t.slice(this.pos));\n if (ref) {\n this.pos += ref[0].length;\n return { t: 'ref', num: Number(ref[1]) };\n }\n const num = /^[+-]?(?:\\d+\\.?\\d*|\\.\\d+)/.exec(t.slice(this.pos));\n if (num) {\n this.pos += num[0].length;\n return { t: 'number', v: Number(num[0]) };\n }\n throw new Error(`unexpected input at ${this.pos}: ${t.slice(this.pos, this.pos + 20)}`);\n }\n\n private dict(): PdfValue {\n return { t: 'dict', entries: this.dictEntries() };\n }\n\n private dictEntries(): Record<string, PdfValue> {\n this.expect('<<');\n const entries: Record<string, PdfValue> = {};\n for (;;) {\n this.skipSpaces();\n if (this.text.startsWith('>>', this.pos)) {\n this.pos += 2;\n return entries;\n }\n if (this.text[this.pos] !== '/') throw new Error(`expected a key at ${this.pos}`);\n const key = this.name();\n this.skipSpaces();\n entries[key] = this.value();\n }\n }\n\n private stream(): PdfValue {\n const m = /^stream\\((\\d+),([0-9a-fA-F]*)\\)/.exec(this.text.slice(this.pos));\n if (!m) throw new Error(`malformed stream signature at ${this.pos}`);\n this.pos += m[0].length;\n const dict = this.dictEntries();\n return { t: 'stream', length: Number(m[1]), sha256: m[2].toLowerCase(), dict };\n }\n\n private array(): PdfValue {\n this.expect('[');\n const items: PdfValue[] = [];\n for (;;) {\n this.skipSpaces();\n if (this.text[this.pos] === ']') {\n this.pos++;\n return { t: 'array', items };\n }\n items.push(this.value());\n }\n }\n\n private name(): string {\n this.expect('/');\n let out = '';\n while (this.pos < this.text.length) {\n const ch = this.text[this.pos];\n if (\n ch === ' ' ||\n ch === '/' ||\n ch === '[' ||\n ch === ']' ||\n ch === '<' ||\n ch === '>' ||\n ch === '(' ||\n ch === ')'\n ) {\n break;\n }\n if (ch === '#' && /^[0-9A-Fa-f]{2}/.test(this.text.slice(this.pos + 1, this.pos + 3))) {\n out += String.fromCharCode(parseInt(this.text.slice(this.pos + 1, this.pos + 3), 16));\n this.pos += 3;\n continue;\n }\n out += ch;\n this.pos++;\n }\n return out;\n }\n\n private literalString(): string {\n this.expect('(');\n let depth = 1;\n let out = '';\n while (this.pos < this.text.length) {\n const ch = this.text[this.pos++];\n if (ch === '\\\\') {\n const next = this.text[this.pos++];\n switch (next) {\n case 'n':\n out += '\\n';\n break;\n case 'r':\n out += '\\r';\n break;\n case 't':\n out += '\\t';\n break;\n case 'b':\n out += '\\b';\n break;\n case 'f':\n out += '\\f';\n break;\n case '\\n':\n break;\n case '\\r':\n if (this.text[this.pos] === '\\n') this.pos++;\n break;\n default: {\n const oct = /^[0-7]{1,3}/.exec(this.text.slice(this.pos - 1));\n if (oct) {\n out += String.fromCharCode(parseInt(oct[0], 8));\n this.pos += oct[0].length - 1;\n } else {\n out += next;\n }\n }\n }\n continue;\n }\n if (ch === '(') depth++;\n if (ch === ')') {\n depth--;\n if (depth === 0) return out;\n }\n out += ch;\n }\n throw new Error('unterminated string');\n }\n\n private hexString(): string {\n this.expect('<');\n const end = this.text.indexOf('>', this.pos);\n if (end < 0) throw new Error('unterminated hex string');\n const hex = this.text.slice(this.pos, end).replace(/\\s+/g, '');\n this.pos = end + 1;\n let out = '';\n for (let i = 0; i < hex.length; i += 2) {\n out += String.fromCharCode(parseInt(hex.slice(i, i + 2).padEnd(2, '0'), 16));\n }\n return out;\n }\n\n private expect(token: string): void {\n if (!this.text.startsWith(token, this.pos)) throw new Error(`expected ${token} at ${this.pos}`);\n this.pos += token.length;\n }\n}\n\n/** Structural equality of two parsed values. */\nexport function pdfValueEquals(a: PdfValue | null, b: PdfValue | null): boolean {\n return stableStringify(a) === stableStringify(b);\n}\n\nexport function stableStringify(value: PdfValue | null): string {\n if (value === null) return 'null';\n switch (value.t) {\n case 'dict':\n return `<<${Object.keys(value.entries)\n .sort()\n .map((k) => `/${k} ${stableStringify(value.entries[k])}`)\n .join('')}>>`;\n case 'stream':\n return `stream(${value.length},${value.sha256})${stableStringify({ t: 'dict', entries: value.dict })}`;\n case 'array':\n return `[${value.items.map(stableStringify).join(' ')}]`;\n case 'ref':\n return `${value.num} 0 R`;\n case 'name':\n return `/${encodeName(value.v)}`;\n case 'string':\n return `(${value.v.replace(/[\\\\()]/g, (ch) => `\\\\${ch}`)})`;\n case 'number':\n return String(value.v);\n case 'bool':\n return value.v ? 'true' : 'false';\n case 'null':\n return 'null';\n }\n}\n\nexport function dictEntries(value: PdfValue | null): Record<string, PdfValue> | null {\n if (!value) return null;\n if (value.t === 'dict') return value.entries;\n if (value.t === 'stream') return value.dict;\n return null;\n}\n\n/** Keys whose value differs (added, removed, or changed) between two dictionaries. */\nexport function changedKeys(a: PdfValue | null, b: PdfValue | null): Set<string> {\n const ea = dictEntries(a) ?? {};\n const eb = dictEntries(b) ?? {};\n const out = new Set<string>();\n for (const key of new Set([...Object.keys(ea), ...Object.keys(eb)])) {\n if (!pdfValueEquals(ea[key] ?? null, eb[key] ?? null)) out.add(key);\n }\n return out;\n}\n\nexport function refsOf(value: PdfValue | null | undefined): number[] {\n if (!value) return [];\n if (value.t === 'ref') return [value.num];\n if (value.t === 'array') return value.items.flatMap(refsOf);\n return [];\n}\n\n/** `#xx`-escape a name the way the PDF writer does: delimiters, whitespace, `#`, and non-printables. */\nexport function encodeName(name: string): string {\n let out = '';\n for (const ch of name) {\n const code = ch.charCodeAt(0);\n if (code < 0x21 || code > 0x7e || '#/[]<>(){}%'.includes(ch)) {\n out += `#${code.toString(16).toUpperCase().padStart(2, '0')}`;\n } else {\n out += ch;\n }\n }\n return out;\n}\n","import type { Assessment, ChangeFinding, RevisionAnalysis, StepVerdict } from './types';\n\nconst RANK: Record<StepVerdict, number> = {\n unchanged: 0,\n permitted: 1,\n indeterminate: 2,\n forbidden: 3,\n};\n\n/** The worst of several verdicts (a certification replay's steps). */\nexport function worstVerdict(steps: ReadonlyArray<{ verdict: StepVerdict }>): StepVerdict {\n let worst: StepVerdict = 'unchanged';\n for (const s of steps) if (RANK[s.verdict] > RANK[worst]) worst = s.verdict;\n return worst;\n}\n\n/**\n * One aggregation rule everywhere: a proven violation decides, whatever\n * else could not be established; missing evidence never becomes a pass.\n */\nexport function conclude(\n findings: ReadonlyArray<ChangeFinding>,\n hasEffectiveChanges: boolean,\n): StepVerdict {\n if (findings.some((f) => f.verdict === 'forbidden')) return 'forbidden';\n if (findings.some((f) => f.verdict === 'incomplete')) return 'indeterminate';\n return hasEffectiveChanges ? 'permitted' : 'unchanged';\n}\n\n/** The finding that explains a verdict: the violation, else the gap, else the most notable allowance. */\nexport function primaryFinding(\n findings: ReadonlyArray<ChangeFinding>,\n): ChangeFinding | undefined {\n return (\n findings.find((f) => f.verdict === 'forbidden') ??\n findings.find((f) => f.verdict === 'incomplete') ??\n findings.find((f) => f.verdict === 'permitted')\n );\n}\n\nexport function assessmentOf(step: RevisionAnalysis): Assessment {\n const primary = primaryFinding(step.findings);\n return {\n verdict: step.verdict,\n complete: !step.findings.some((f) => f.verdict === 'incomplete'),\n ...(primary ? { primary } : {}),\n findings: step.findings,\n };\n}\n\n/**\n * A certification window: the net verdict and every replayed step, under\n * the same rule. A step's violation is a violation of the certification\n * even when the final state no longer shows it (corpus v3/83).\n */\nexport function combine(net: RevisionAnalysis, steps: ReadonlyArray<RevisionAnalysis>): Assessment {\n const findings = [...net.findings];\n for (const s of steps) {\n if (s === net) continue;\n for (const f of s.findings) {\n if (f.verdict === 'permitted') continue;\n findings.push({ ...f, detail: `revision ${s.newer}: ${f.detail ?? f.rule}` });\n }\n }\n const verdict = conclude(findings, net.verdict !== 'unchanged' || steps.some((s) => s.verdict !== 'unchanged'));\n const primary = primaryFinding(findings);\n return {\n verdict,\n complete: !findings.some((f) => f.verdict === 'incomplete'),\n ...(primary ? { primary } : {}),\n findings,\n };\n}\n","import type { DocumentFieldLock, ModificationLevel } from '../types';\nimport type { PdfValue } from './types';\nimport { conclude } from './verdict';\nimport { deriveProtection, levelAllows, lockCovers } from '../protection';\nimport { changedKeys, dictEntries, pdfValueEquals, refsOf } from './pdf-value';\nimport type {\n ChangeFinding,\n ObjectChange,\n ObjectReferrer,\n RevisionAnalysis,\n RevisionField,\n RevisionStructure,\n StepInput,\n StepVerdict,\n} from './types';\n\ntype Side = 'old' | 'new';\nconst SIDES: Side[] = ['old', 'new'];\n\nconst TRAILER_KEYS = new Set([\n 'Size',\n 'Prev',\n 'XRefStm',\n 'Info',\n 'ID',\n 'Root',\n 'Type',\n 'W',\n 'Index',\n 'Filter',\n 'DecodeParms',\n 'Length',\n 'Encrypt',\n]);\nconst CATALOG_KEYS = new Set(['Metadata', 'Extensions', 'Version', 'DSS', 'AcroForm', 'Perms']);\nconst ACROFORM_KEYS = new Set(['DR', 'DA', 'Q', 'SigFlags', 'NeedAppearances', 'Fields']);\n/**\n * What a form field may change after a signature, by the level in force.\n * Every key here has a corpus case behind it (`signature-compat`); a key\n * not listed is forbidden until one does.\n *\n * annotate (an approval signature: \"Form Fill-in, Signing and Commenting\n * are allowed\"): everything but the field's identity and its place in\n * the tree. v1/08 /V+/AP, 09 /Ff, 10 /Rect, 11 /F, 18 /TU, 21 /DA; 13 /T\n * forbidden. /AA (v1/12) and /A are accepted by Acrobat and deliberately\n * not listed: an action on a signed form is executable content.\n *\n * fill (a P=2 certification): value and appearance. v1/26 /V+/AP, v3/64\n * /Ff (ReadOnly added), 65 /DA, 68 /AP stream; v3/66 /TU, 67 /F, v2/50\n * /Rect forbidden.\n */\nconst FIELD_KEYS_BY_LEVEL: Record<'annotate' | 'fill', ReadonlySet<string>> = {\n annotate: new Set([\n 'V', 'AS', 'AP', 'I', 'DA', 'Ff', 'RV', 'MK', 'Q', 'TU', 'F', 'Rect', 'BS', 'Opt', 'DV', 'MaxLen',\n ]),\n fill: new Set(['V', 'AS', 'AP', 'I', 'RV', 'DA', 'Ff']),\n};\n/** A separate widget dictionary: the presentation subset of the same tables. */\nconst WIDGET_KEYS_BY_LEVEL: Record<'annotate' | 'fill', ReadonlySet<string>> = {\n annotate: new Set(['AS', 'AP', 'DA', 'MK', 'Q', 'TU', 'F', 'Rect', 'BS']),\n fill: new Set(['AS', 'AP', 'DA']),\n};\n/**\n * Signing an existing field: its value, appearance and ReadOnly at any\n * level; after an approval signature also its tooltip and a /Lock installed\n * with the signature (v1/18, 19: both valid; under P=2 the combination is\n * rejected, v3/69, so neither is allowed at `fill`).\n */\nconst SIGNED_FIELD_KEYS_BY_LEVEL: Record<'annotate' | 'fill', ReadonlySet<string>> = {\n annotate: new Set(['V', 'AP', 'AS', 'Ff', 'TU', 'Lock']),\n fill: new Set(['V', 'AP', 'AS', 'Ff']),\n};\nconst SIGNED_WIDGET_KEYS = new Set(['AP', 'AS']);\nconst FF_READ_ONLY = 1;\n\nfunction fieldKeysFor(level: ModificationLevel): ReadonlySet<string> {\n return level === 'annotate' ? FIELD_KEYS_BY_LEVEL.annotate : FIELD_KEYS_BY_LEVEL.fill;\n}\nfunction widgetKeysFor(level: ModificationLevel): ReadonlySet<string> {\n return level === 'annotate' ? WIDGET_KEYS_BY_LEVEL.annotate : WIDGET_KEYS_BY_LEVEL.fill;\n}\nfunction signedFieldKeysFor(level: ModificationLevel): ReadonlySet<string> {\n return level === 'annotate' ? SIGNED_FIELD_KEYS_BY_LEVEL.annotate : SIGNED_FIELD_KEYS_BY_LEVEL.fill;\n}\n\n/**\n * Rules whose permitted findings do not make a revision a change of the\n * document: an object written again with the sealed value, an object nobody\n * references, a cross-reference container, the trailer's own bookkeeping.\n * A window with nothing else is `unchanged` (Acrobat: \"not modified\").\n */\nconst NON_EFFECTIVE_RULES = new Set(['identical-rewrite', 'orphan', 'xref-container', 'trailer']);\n\n/** The level a step runs at, and the locks it enforces: what the older revision's signatures established. */\nexport function restrictionsOf(before: RevisionStructure): {\n level: ModificationLevel;\n locks: DocumentFieldLock[];\n} {\n const protection = deriveProtection(before.signatures);\n // The judged level: what a validator holds this step to. Nothing signed\n // yet: nothing forbids, the rule set explains what it can.\n return { level: protection.judged ?? 'annotate', locks: protection.fieldLocks };\n}\n\n/**\n * Judge one pairwise step. Every reference to a changed object, in the\n * older and the newer revision, must be claimed by a rule that inspected\n * that use; an unclaimed reference is `unexplained` and forbidden. A\n * truncated value is `incomplete`, never permitted. Pure: JSON in, JSON\n * out, the same code in the browser worker, on the server and in tests.\n */\nexport function evaluateStep(input: StepInput): RevisionAnalysis {\n const changes = withEvidenceCheck(input.changes);\n const { level, locks } = input.restrictions ?? restrictionsOf(input.before);\n const levelInForce = input.levelOverride ?? level;\n const ctx = new StepContext({ ...input, changes }, levelInForce, locks);\n\n ruleRevisionHealth(ctx);\n ruleXrefContainer(ctx);\n ruleIdenticalRewrite(ctx);\n // Locks first: a frozen object is condemned before any rule could vouch for it.\n ruleFieldLock(ctx);\n ruleTrailer(ctx);\n ruleInfo(ctx);\n ruleMetadata(ctx);\n ruleCatalog(ctx);\n ruleAcroForm(ctx);\n ruleDss(ctx);\n ruleSignatureFieldAdded(ctx);\n ruleSignatureAdded(ctx);\n ruleFormFill(ctx);\n ruleAnnotation(ctx);\n ruleUnexplained(ctx);\n\n const verdict: StepVerdict = conclude(\n ctx.findings,\n ctx.findings.some((f) => f.verdict === 'permitted' && !NON_EFFECTIVE_RULES.has(f.rule)),\n );\n\n return {\n older: input.older,\n newer: input.newer,\n levelInForce,\n locks,\n verdict,\n findings: ctx.findings,\n changes,\n };\n}\n\n/**\n * The evaluator never trusts its transport to be honest about gaps: a side\n * that exists must carry a value, and an object whose value is missing is\n * judged as truncated, whatever the flag says. Cross-reference containers\n * are exempt (their members are judged on their own).\n */\nfunction withEvidenceCheck(changes: ObjectChange[]): ObjectChange[] {\n return changes.map((c) => {\n if (c.value.truncated || c.kind === 'xref' || c.kind === 'objstm') return c;\n const missingOld = c.present.old && (c.value.old === null || c.read?.old === 'failed');\n const missingNew = c.present.new && (c.value.new === null || c.read?.new === 'failed');\n return missingOld || missingNew ? { ...c, value: { ...c.value, truncated: true } } : c;\n });\n}\n\n/**\n * The transport's verdict on each revision as a whole. A sealed revision\n * Acrobat cannot judge later changes to (sparse cross-reference table, a\n * reachable bare-reference object) makes every step over it indeterminate:\n * our verdict would otherwise disagree with the validator recipients use,\n * and for a reason that has nothing to do with the change. An incomplete\n * reachability walk on either side leaves every use unproven.\n */\nfunction ruleRevisionHealth(ctx: StepContext): void {\n const health = ctx.input.health;\n if (!health) return;\n const base = health.old;\n if (base.sparseXref || base.bareReferences > 0) {\n const why = [\n base.sparseXref ? 'its cross-reference table has no entry for some object numbers below /Size' : null,\n base.bareReferences > 0\n ? `${base.bareReferences} reachable indirect object(s) consist of a bare reference`\n : null,\n ]\n .filter((x) => x !== null)\n .join('; ');\n ctx.findings.push({\n rule: 'base-unverifiable',\n verdict: 'incomplete',\n objectNumber: 0,\n detail: `the signed revision cannot be verified against later changes by Acrobat (${why}); no verdict is given rather than one Acrobat would contradict`,\n });\n }\n for (const side of SIDES) {\n if (!health[side].referrersComplete) {\n ctx.findings.push({\n rule: 'unexplained',\n verdict: 'incomplete',\n objectNumber: 0,\n detail: `the ${side === 'old' ? 'older' : 'newer'} revision's reachability walk hit its budget; not every use of a changed object is known`,\n });\n }\n }\n}\n\n/**\n * Same effective value on both sides: same canonical serialisation (keys\n * sorted, whitespace normalised - Acrobat compares dictionaries by value,\n * corpus v3/61-62), same stream data (by bytes, v2/45), and both sides\n * actually read. A failed read serialises as \"null\" and would match another\n * failed read - evidence of nothing.\n */\nexport function sameEffectiveValue(c: ObjectChange): boolean {\n return (\n c.change === 'modified' &&\n !c.value.truncated &&\n c.read?.old !== 'failed' &&\n c.read?.new !== 'failed' &&\n c.raw.old !== null &&\n c.raw.new !== null &&\n c.raw.old === c.raw.new &&\n !c.streamDataChanged\n );\n}\n\n// ---------------------------------------------------------------------------\n\ninterface RoleIndex {\n fieldByObj: Map<number, RevisionField>;\n widgetToField: Map<number, number>;\n pages: Set<number>;\n signedFields: Set<number>;\n sigFields: Set<number>;\n}\n\nfunction indexRoles(s: RevisionStructure): RoleIndex {\n const fieldByObj = new Map<number, RevisionField>();\n const widgetToField = new Map<number, number>();\n const sigFields = new Set<number>();\n for (const f of s.fields) {\n fieldByObj.set(f.objectNumber, f);\n if (f.family === 'signature') sigFields.add(f.objectNumber);\n for (const w of f.widgets) widgetToField.set(w, f.objectNumber);\n }\n const signedFields = new Set<number>();\n for (const sig of s.signatures) {\n if (sig.signed && sig.field.kind === 'objectNumber')\n signedFields.add(sig.field.objectNumber);\n }\n return { fieldByObj, widgetToField, pages: new Set(s.pages), signedFields, sigFields };\n}\n\nfunction edgeKey(e: ObjectReferrer): string {\n return `${e.parent}:${e.label}`;\n}\n\nclass StepContext {\n readonly findings: ChangeFinding[] = [];\n readonly byNum = new Map<number, ObjectChange>();\n readonly before: RoleIndex;\n readonly after: RoleIndex;\n /**\n * `${objectNumber}:${side}:${edge}` → the rule that inspected the use, and\n * whether it allowed it. A claim explains an edge in the report; only an\n * allowing claim can vouch for a shared object joining a subtree.\n */\n private readonly claims = new Map<string, { rule: string; allow: boolean }>();\n /** Objects a lock forbids touching this step. */\n readonly locked = new Set<number>();\n\n constructor(\n readonly input: StepInput,\n readonly level: ModificationLevel,\n readonly locks: DocumentFieldLock[],\n ) {\n for (const c of input.changes) this.byNum.set(c.objectNumber, c);\n this.before = indexRoles(input.before);\n this.after = indexRoles(input.after);\n }\n\n get changes(): ObjectChange[] {\n return this.input.changes;\n }\n\n allows(needed: ModificationLevel): boolean {\n return levelAllows(this.level, needed);\n }\n\n claimEdge(c: ObjectChange, side: Side, edge: ObjectReferrer, rule: string, allow = true): void {\n if (this.locked.has(c.objectNumber)) return;\n const key = `${c.objectNumber}:${side}:${edgeKey(edge)}`;\n if (!this.claims.has(key)) this.claims.set(key, { rule, allow });\n }\n\n claimAll(c: ObjectChange, rule: string, allow = true): void {\n for (const side of SIDES) for (const e of c.usage[side]) this.claimEdge(c, side, e, rule, allow);\n }\n\n /**\n * Claim the references that are the same in both revisions; a reference\n * gained or lost stays unexplained. `allow: false` explains a condemned\n * object's edges (one cause in the report, not a cascade) without letting\n * anything hang off it.\n */\n claimStable(c: ObjectChange, rule: string, allow = true): void {\n const oldKeys = new Set(c.usage.old.map(edgeKey));\n const newKeys = new Set(c.usage.new.map(edgeKey));\n for (const e of c.usage.old)\n if (newKeys.has(edgeKey(e))) this.claimEdge(c, 'old', e, rule, allow);\n for (const e of c.usage.new)\n if (oldKeys.has(edgeKey(e))) this.claimEdge(c, 'new', e, rule, allow);\n }\n\n isClaimed(c: ObjectChange, side: Side, edge: ObjectReferrer): boolean {\n return this.claims.has(`${c.objectNumber}:${side}:${edgeKey(edge)}`);\n }\n\n /** The use was inspected by a rule that allowed it. */\n isAllowed(c: ObjectChange, side: Side, edge: ObjectReferrer): boolean {\n return this.claims.get(`${c.objectNumber}:${side}:${edgeKey(edge)}`)?.allow === true;\n }\n\n permitted(c: ObjectChange, rule: string, detail?: string): void {\n if (this.locked.has(c.objectNumber)) return;\n this.findings.push({ rule, verdict: 'permitted', objectNumber: c.objectNumber, detail });\n }\n\n /**\n * A violation is only proven on evidence: a rule condemning an object\n * whose value could not be read or inspected is reporting what it could\n * not see, and that is `incomplete`, never `forbidden`.\n */\n forbidden(c: ObjectChange, rule: string, detail: string, edge?: ObjectReferrer): void {\n this.findings.push({\n rule,\n verdict: c.value.truncated ? 'incomplete' : 'forbidden',\n objectNumber: c.objectNumber,\n edge: edge ? edgeKey(edge) : undefined,\n detail: c.value.truncated ? `${detail} (judged on missing evidence: not proven)` : detail,\n });\n }\n\n /**\n * Claim every reference under a set of parents (an appearance subtree,\n * the DSS): objects whose references come from `parents` through labels\n * `accept`, then everything referenced from those objects, and so on.\n * Runs per side, because a replaced appearance stream exists on one\n * side only.\n */\n claimSubtree(\n side: Side,\n roots: Set<number>,\n accept: (label: string) => boolean,\n rule: string,\n ): void {\n // Two sets, never merged: an edge from a root is inside the subtree\n // only through an accepted label, on every pass; an edge from an object\n // that joined is inside through any label. Folding the roots into the\n // frontier would let one accepted child (an appearance stream, a DSS\n // update) vouch for every other edge off the same parent.\n const joined = new Set<number>();\n let grew = true;\n while (grew) {\n grew = false;\n for (const c of this.changes) {\n if (roots.has(c.objectNumber) || joined.has(c.objectNumber)) continue;\n if (this.locked.has(c.objectNumber)) continue;\n const edges = c.usage[side];\n if (edges.length === 0) continue;\n const inside = edges.filter(\n (e) => (roots.has(e.parent) && accept(e.label)) || joined.has(e.parent),\n );\n if (inside.length === 0) continue;\n for (const e of inside) this.claimEdge(c, side, e, rule);\n // A changed object joins the subtree - and brings its own children\n // in - only when every use of it is allowed: by this subtree, or by\n // another rule that permitted the owner (a font shared between a\n // filled field's appearance and /AcroForm /DR, corpus v1/16, 21). A\n // use nobody allowed - a signed page's content (v1/30, v2/39, 52),\n // a locked field's appearance (v3/79) - keeps the object, and\n // everything under it, unexplained.\n if (edges.every((e) => inside.includes(e) || this.isAllowed(c, side, e))) {\n joined.add(c.objectNumber);\n grew = true;\n }\n }\n }\n }\n\n isIdentical(c: ObjectChange): boolean {\n return sameEffectiveValue(c);\n }\n\n /** Signatures signed in the newer revision but not the older: this step's signing events. */\n newlySigned(): Array<{\n fieldObjectNumber: number;\n sig: RevisionStructure['signatures'][number];\n }> {\n const out: Array<{ fieldObjectNumber: number; sig: RevisionStructure['signatures'][number] }> =\n [];\n for (const sig of this.input.after.signatures) {\n if (!sig.signed || sig.field.kind !== 'objectNumber') continue;\n if (this.before.signedFields.has(sig.field.objectNumber)) continue;\n out.push({ fieldObjectNumber: sig.field.objectNumber, sig });\n }\n return out;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Rules. Each claims the exact references it inspected and records a finding.\n// ---------------------------------------------------------------------------\n\nfunction ruleXrefContainer(ctx: StepContext): void {\n for (const c of ctx.changes) {\n if (c.kind === 'xref' || c.kind === 'objstm') {\n ctx.claimAll(c, 'xref-container');\n ctx.permitted(\n c,\n 'xref-container',\n 'cross-reference container; members are judged on their own',\n );\n }\n }\n}\n\n/**\n * An object written again with the value the sealed revision holds is not\n * a modification: Acrobat compares objects by value and reports such a\n * revision as \"not modified\" for every role tried - document information,\n * a custom catalog entry, a page, the signed signature's own widget, a text\n * field, an annotation, the encryption dictionary, reserialised with keys\n * reordered, under a certification, under a field lock (corpus v1/02-07,\n * 23, v2/47, v3/54-62, 70, 71, 77). Under P=1 nothing is established and\n * the rewrite stays forbidden. Claimed here so the object-kind rules skip\n * it; the verdict treats it as no effective change.\n */\nfunction ruleIdenticalRewrite(ctx: StepContext): void {\n for (const c of ctx.changes) {\n if (!ctx.isIdentical(c)) continue;\n if (ctx.allows('fill')) {\n ctx.claimAll(c, 'identical-rewrite');\n ctx.permitted(c, 'identical-rewrite', 'written again with the sealed value');\n } else {\n ctx.claimAll(c, 'identical-rewrite', false);\n ctx.forbidden(\n c,\n 'identical-rewrite',\n `written again with the sealed value under level '${ctx.level}' (not established for this level)`,\n );\n }\n }\n}\n\nfunction ruleTrailer(ctx: StepContext): void {\n const c = ctx.byNum.get(0);\n if (!c) return;\n const changed = changedKeys(c.value.old, c.value.new);\n const bad = [...changed].filter((k) => !TRAILER_KEYS.has(k));\n const oldRoot = dictEntries(c.value.old)?.Root;\n const newRoot = dictEntries(c.value.new)?.Root;\n if (bad.length > 0) {\n ctx.forbidden(c, 'trailer', `trailer keys changed: ${bad.join(', ')}`);\n return;\n }\n if (changed.has('Root') && !pdfValueEquals(oldRoot ?? null, newRoot ?? null)) {\n ctx.forbidden(c, 'trailer', 'the trailer points at a different catalog');\n return;\n }\n if (\n changed.has('Encrypt') &&\n !pdfValueEquals(\n dictEntries(c.value.old)?.Encrypt ?? null,\n dictEntries(c.value.new)?.Encrypt ?? null,\n )\n ) {\n ctx.forbidden(c, 'trailer', 'the trailer points at a different encryption dictionary');\n return;\n }\n ctx.claimAll(c, 'trailer');\n ctx.permitted(c, 'trailer');\n}\n\nfunction onlyEdges(c: ObjectChange, test: (e: ObjectReferrer) => boolean): boolean {\n const all = [...c.usage.old, ...c.usage.new];\n return all.length > 0 && all.every(test);\n}\n\nfunction ruleInfo(ctx: StepContext): void {\n for (const c of ctx.changes) {\n if (ctx.isIdentical(c)) continue;\n if (c.objectNumber !== 0 && onlyEdges(c, (e) => e.parent === 0 && e.label === 'Info')) {\n ctx.claimAll(c, 'info');\n ctx.permitted(c, 'info', 'document information dictionary');\n }\n }\n}\n\nfunction ruleMetadata(ctx: StepContext): void {\n const roots = new Set([ctx.input.before.root, ctx.input.after.root]);\n for (const c of ctx.changes) {\n if (ctx.isIdentical(c)) continue;\n if (onlyEdges(c, (e) => roots.has(e.parent) && e.label === 'Metadata')) {\n ctx.claimAll(c, 'metadata');\n ctx.permitted(c, 'metadata', 'XMP metadata stream');\n }\n }\n}\n\nfunction ruleCatalog(ctx: StepContext): void {\n const root = ctx.input.after.root;\n const c = ctx.byNum.get(root);\n if (!c || ctx.isIdentical(c)) return;\n const changed = changedKeys(c.value.old, c.value.new);\n const bad = [...changed].filter((k) => !CATALOG_KEYS.has(k));\n if (bad.length > 0) {\n ctx.forbidden(c, 'catalog-housekeeping', `catalog keys changed: ${bad.join(', ')}`);\n return;\n }\n // A direct /AcroForm dictionary changes with the catalog: judge it by the\n // AcroForm rules, and let its default resources ride the catalog's edges.\n if (changed.has('AcroForm') && !ctx.input.after.acroForm && !ctx.input.before.acroForm) {\n const problem = acroFormProblem(\n ctx,\n dictEntries(c.value.old)?.AcroForm ?? null,\n dictEntries(c.value.new)?.AcroForm ?? null,\n );\n if (problem) {\n ctx.forbidden(c, 'acroform-housekeeping', problem);\n return;\n }\n for (const side of SIDES) {\n ctx.claimSubtree(\n side,\n new Set([root]),\n (label) => label.startsWith('AcroForm/DR/'),\n 'acroform-housekeeping',\n );\n }\n }\n if (changed.has('Perms')) {\n const after = deriveProtection(ctx.input.after.signatures);\n const before = deriveProtection(ctx.input.before.signatures);\n if (!after.certification || before.judged !== null) {\n ctx.forbidden(\n c,\n 'catalog-housekeeping',\n '/Perms may only appear with the certification signature, in the first signed revision',\n );\n return;\n }\n }\n ctx.claimAll(c, 'catalog-housekeeping');\n ctx.permitted(c, 'catalog-housekeeping');\n}\n\nfunction ruleAcroForm(ctx: StepContext): void {\n const acro = ctx.input.after.acroForm || ctx.input.before.acroForm;\n if (!acro) return;\n const c = ctx.byNum.get(acro);\n if (!c || ctx.isIdentical(c)) return;\n const problem = acroFormProblem(ctx, c.value.old, c.value.new);\n if (problem) {\n ctx.forbidden(c, 'acroform-housekeeping', problem);\n return;\n }\n ctx.claimAll(c, 'acroform-housekeeping');\n ctx.permitted(c, 'acroform-housekeeping');\n // Default resources (fonts for appearances) live under /DR.\n for (const side of SIDES) {\n ctx.claimSubtree(\n side,\n new Set([acro]),\n (label) => label.startsWith('DR/'),\n 'acroform-housekeeping',\n );\n }\n}\n\n/** What is wrong with an AcroForm dictionary change, or null when it is housekeeping. */\nfunction acroFormProblem(\n ctx: StepContext,\n oldValue: PdfValue | null,\n newValue: PdfValue | null,\n): string | null {\n const changed = changedKeys(oldValue, newValue);\n const bad = [...changed].filter((k) => !ACROFORM_KEYS.has(k));\n if (bad.length > 0) return `AcroForm keys changed: ${bad.join(', ')}`;\n if (changed.has('Fields')) {\n const oldRefs = refsOf(dictEntries(oldValue)?.Fields);\n const newRefs = refsOf(dictEntries(newValue)?.Fields);\n if (oldRefs.length > newRefs.length || oldRefs.some((n, i) => newRefs[i] !== n)) {\n return '/AcroForm /Fields is not append-only';\n }\n const newSigFields = newSignatureFields(ctx);\n const strangers = newRefs.slice(oldRefs.length).filter((n) => !newSigFields.has(n));\n if (strangers.length > 0)\n return `/AcroForm /Fields gained non-signature fields: ${strangers.join(', ')}`;\n }\n return null;\n}\n\n/** The refs appended to an array-valued key when the old array is a prefix of the new one; null otherwise. */\nfunction appendedRefs(c: ObjectChange, key: string): number[] | null {\n const oldItems = dictEntries(c.value.old)?.[key];\n const newItems = dictEntries(c.value.new)?.[key];\n const oldRefs = refsOf(oldItems);\n const newRefs = refsOf(newItems);\n if (oldItems && oldItems.t !== 'array') return null;\n if (!newItems || newItems.t !== 'array') return null;\n if (oldRefs.length > newRefs.length) return null;\n for (let i = 0; i < oldRefs.length; i++) if (oldRefs[i] !== newRefs[i]) return null;\n return newRefs.slice(oldRefs.length);\n}\n\nfunction newSignatureFields(ctx: StepContext): Set<number> {\n const out = new Set<number>();\n for (const n of ctx.after.sigFields) if (!ctx.before.fieldByObj.has(n)) out.add(n);\n return out;\n}\n\nfunction ruleDss(ctx: StepContext): void {\n const roots = new Set([ctx.input.before.root, ctx.input.after.root]);\n for (const side of SIDES) {\n ctx.claimSubtree(side, roots, (label) => label === 'DSS' || label.startsWith('DSS/'), 'dss');\n }\n for (const c of ctx.changes) {\n if (\n c.usage.new.some((e) => roots.has(e.parent) && e.label === 'DSS') &&\n !ctx.findings.some((f) => f.objectNumber === c.objectNumber)\n ) {\n ctx.permitted(c, 'dss', 'document security store');\n }\n }\n}\n\nfunction ruleSignatureFieldAdded(ctx: StepContext): void {\n const added = newSignatureFields(ctx);\n if (added.size === 0) return;\n const rule = 'signature-field-added';\n if (!ctx.allows('fill')) {\n for (const n of added) {\n const c = ctx.byNum.get(n);\n if (c) ctx.forbidden(c, rule, `a signature field was added under level '${ctx.level}'`);\n }\n return;\n }\n const newWidgets = new Set<number>();\n for (const n of added) {\n const field = ctx.after.fieldByObj.get(n)!;\n const c = ctx.byNum.get(n);\n if (c) {\n ctx.claimAll(c, rule);\n ctx.permitted(c, rule, `new signature field \"${field.name}\"`);\n }\n for (const w of field.widgets) {\n newWidgets.add(w);\n if (w === n) continue;\n const wc = ctx.byNum.get(w);\n if (wc) {\n ctx.claimAll(wc, rule);\n ctx.permitted(wc, rule, `widget of new signature field \"${field.name}\"`);\n }\n }\n }\n // The page that lists the new widget: /Annots append-only.\n for (const p of ctx.after.pages) {\n const c = ctx.byNum.get(p);\n if (!c || ctx.isIdentical(c)) continue;\n const changed = changedKeys(c.value.old, c.value.new);\n if (changed.size !== 1 || !changed.has('Annots')) continue;\n const appended = appendedRefs(c, 'Annots');\n if (appended && appended.every((n) => newWidgets.has(n))) {\n ctx.claimAll(c, rule);\n ctx.permitted(c, rule, 'page /Annots gained the new signature widget');\n }\n }\n // A parent field whose /Kids gained the new field.\n for (const c of ctx.changes) {\n if (c.kind !== 'dictionary' || ctx.isIdentical(c)) continue;\n const changed = changedKeys(c.value.old, c.value.new);\n if (changed.size !== 1 || !changed.has('Kids')) continue;\n const appended = appendedRefs(c, 'Kids');\n if (\n appended &&\n appended.length > 0 &&\n appended.every((n) => added.has(n) || newWidgets.has(n))\n ) {\n ctx.claimAll(c, rule);\n ctx.permitted(c, rule, 'field /Kids gained the new signature field');\n }\n }\n}\n\nfunction ruleSignatureAdded(ctx: StepContext): void {\n const rule = 'signature-added';\n const events = ctx.newlySigned();\n if (events.length === 0) return;\n const addedThisStep = newSignatureFields(ctx);\n const beforeProtection = deriveProtection(ctx.input.before.signatures);\n const afterProtection = deriveProtection(ctx.input.after.signatures);\n const parents = new Set<number>();\n const values = new Set<number>();\n for (const { fieldObjectNumber, sig } of events) {\n const needed: ModificationLevel = sig.kind === 'timestamp' ? 'lta' : 'fill';\n if (!ctx.allows(needed)) {\n const c = ctx.byNum.get(fieldObjectNumber);\n if (c) ctx.forbidden(c, rule, `a ${sig.kind} was added under level '${ctx.level}'`);\n continue;\n }\n if (sig.catalogCertification && beforeProtection.judged !== null) {\n const c = ctx.byNum.get(fieldObjectNumber);\n if (c) ctx.forbidden(c, rule, 'a certification signature after another signature');\n continue;\n }\n const field = ctx.after.fieldByObj.get(fieldObjectNumber);\n parents.add(fieldObjectNumber);\n for (const w of field?.widgets ?? []) parents.add(w);\n\n // A field added in this very step was judged, and its edges claimed, by\n // signature-field-added; the table below is for signing an existing\n // field. Before the first signature nothing governs the document, and\n // the /Lock mirror written at authoring time is legitimate whatever the\n // level.\n const fieldIsNew = addedThisStep.has(fieldObjectNumber);\n const allowedFieldKeys =\n beforeProtection.judged === null\n ? new Set([...signedFieldKeysFor(ctx.level), 'Lock'])\n : signedFieldKeysFor(ctx.level);\n const fc = ctx.byNum.get(fieldObjectNumber);\n if (fc && fieldIsNew) {\n ctx.permitted(fc, rule, `new field \"${sig.fieldName}\" signed`);\n } else if (fc && !ctx.isIdentical(fc)) {\n const changed = changedKeys(fc.value.old, fc.value.new);\n const bad = [...changed].filter((k) => !allowedFieldKeys.has(k));\n // A condemned field still claims its stable edges: the report names\n // the cause once, not once per reference to the field.\n if (bad.length > 0) {\n ctx.forbidden(fc, rule, `signature field keys changed: ${bad.join(', ')}`);\n ctx.claimStable(fc, rule, false);\n } else if (\n changed.has('Ff') &&\n !readOnlyOnlyChange(fc, ctx.before.fieldByObj.get(fieldObjectNumber)?.flags)\n ) {\n ctx.forbidden(fc, rule, 'signature field flags changed beyond ReadOnly');\n ctx.claimStable(fc, rule, false);\n } else {\n ctx.claimStable(fc, rule);\n ctx.permitted(fc, rule, `field \"${sig.fieldName}\" signed`);\n }\n }\n for (const w of field?.widgets ?? []) {\n if (w === fieldObjectNumber || fieldIsNew) continue;\n const wc = ctx.byNum.get(w);\n if (!wc || ctx.isIdentical(wc)) continue;\n const bad = [...changedKeys(wc.value.old, wc.value.new)].filter(\n (k) => !SIGNED_WIDGET_KEYS.has(k),\n );\n if (bad.length > 0) {\n ctx.forbidden(wc, rule, `signature widget keys changed: ${bad.join(', ')}`);\n ctx.claimStable(wc, rule, false);\n continue;\n }\n ctx.claimStable(wc, rule);\n ctx.permitted(wc, rule, 'signature widget appearance');\n }\n // The /V value (referenced from the field, and from /Perms for a\n // certification) and the /Lock dictionary installed with the signature.\n // Claimed even when the field itself was condemned above: the report\n // then names one cause, not a cascade of unexplained edges.\n for (const c of ctx.changes) {\n if (c.change !== 'added') continue;\n const asValue = c.usage.new.filter((e) => e.parent === fieldObjectNumber && e.label === 'V');\n const asLock = c.usage.new.filter(\n (e) => e.parent === fieldObjectNumber && e.label === 'Lock',\n );\n const type = dictEntries(c.value.new)?.Type;\n if (asValue.length > 0) {\n const isSig = type?.t === 'name' && (type.v === 'Sig' || type.v === 'DocTimeStamp');\n if (!isSig && type !== undefined) continue;\n for (const e of c.usage.new) {\n if ((e.parent === fieldObjectNumber && e.label === 'V') || e.label === 'DocMDP')\n ctx.claimEdge(c, 'new', e, rule);\n }\n ctx.permitted(c, rule, 'signature value');\n values.add(c.objectNumber);\n } else if (asLock.length > 0) {\n const isLock = type === undefined || (type.t === 'name' && type.v === 'SigFieldLock');\n if (!isLock) continue;\n for (const e of asLock) ctx.claimEdge(c, 'new', e, rule);\n ctx.permitted(c, rule, 'field lock installed with the signature');\n }\n }\n }\n // /Perms: only with the certification, only in the first signed revision.\n if (afterProtection.certification && beforeProtection.judged === null) {\n const root = ctx.input.after.root;\n for (const c of ctx.changes) {\n if (c.change === 'added' && onlyEdges(c, (e) => e.parent === root && e.label === 'Perms')) {\n ctx.claimAll(c, rule);\n ctx.permitted(c, rule, 'certification permissions');\n }\n }\n }\n // Appearance streams and their resources, through the signed field or its\n // widget; and the signature value's own indirect children (/Prop_Build and\n // the like, v1/20), which the value dictionary brings with it.\n for (const side of SIDES)\n ctx.claimSubtree(side, parents, (label) => label === 'AP' || label.startsWith('AP/'), rule);\n if (values.size > 0) ctx.claimSubtree('new', values, () => true, rule);\n}\n\n/**\n * Did `/Ff` change by gaining ReadOnly and nothing else? `/Ff` is\n * inheritable, and a lock writes `effective | ReadOnly` into the terminal\n * dictionary, so a terminal that carried no `/Ff` of its own is judged\n * against the effective flags the older revision's form model reported.\n */\nfunction readOnlyOnlyChange(c: ObjectChange, effectiveBefore?: number): boolean {\n const oldFf = dictEntries(c.value.old)?.Ff;\n const newFf = dictEntries(c.value.new)?.Ff;\n const before = oldFf?.t === 'number' ? oldFf.v : (effectiveBefore ?? 0);\n const after = newFf?.t === 'number' ? newFf.v : 0;\n return (before | FF_READ_ONLY) === after;\n}\n\nfunction ruleFormFill(ctx: StepContext): void {\n const rule = 'form-fill';\n const fieldKeys = fieldKeysFor(ctx.level);\n const widgetKeys = widgetKeysFor(ctx.level);\n const parents = new Set<number>();\n const fields = new Map<number, RevisionField>([\n ...ctx.before.fieldByObj,\n ...ctx.after.fieldByObj,\n ]);\n for (const [num, field] of fields) {\n if (field.family === 'signature') continue;\n const fc = ctx.byNum.get(num);\n const widgetChanges = field.widgets\n .filter((w) => w !== num)\n .map((w) => ctx.byNum.get(w))\n .filter(Boolean) as ObjectChange[];\n // An appearance regenerated under an untouched field and widget (viewers\n // do this for NeedAppearances): the objects hanging off the field's or a\n // widget's /AP. Form filling at P=2 covers it (pyHanko agrees); what the\n // subtree may contain is still judged by the claim below.\n const owners = new Set([num, ...field.widgets]);\n const isAp = (label: string) => label === 'AP' || label.startsWith('AP/');\n // An appearance object shared with another field's /AP is nobody's\n // regeneration (pyHanko: \"used in multiple contexts\"); its foreign edge\n // stays unexplained unless that field is filled in the same step.\n const appearanceOnly =\n !fc && widgetChanges.length === 0\n ? ctx.changes.filter(\n (c) =>\n SIDES.some((side) =>\n c.usage[side].some((e) => owners.has(e.parent) && isAp(e.label)),\n ) &&\n SIDES.every((side) =>\n c.usage[side].every((e) => !isAp(e.label) || owners.has(e.parent)),\n ),\n )\n : [];\n if (!fc && widgetChanges.length === 0 && appearanceOnly.length === 0) continue;\n if (!ctx.allows('fill')) {\n for (const c of [fc, ...widgetChanges, ...appearanceOnly])\n if (c && !ctx.isIdentical(c))\n ctx.forbidden(c, rule, `form fill under level '${ctx.level}'`);\n continue;\n }\n if (appearanceOnly.length > 0) {\n for (const c of appearanceOnly)\n ctx.permitted(c, rule, `appearance of field \"${field.name}\" regenerated`);\n parents.add(num);\n for (const w of field.widgets) parents.add(w);\n continue;\n }\n let ok = true;\n if (fc && !ctx.isIdentical(fc)) {\n const changed = changedKeys(fc.value.old, fc.value.new);\n const bad = [...changed].filter((k) => !fieldKeys.has(k));\n if (bad.length > 0) {\n ctx.forbidden(fc, rule, `field \"${field.name}\" keys changed: ${bad.join(', ')}`);\n ctx.claimStable(fc, rule, false);\n ok = false;\n } else if (\n changed.has('Ff') &&\n !readOnlyOnlyChange(fc, ctx.before.fieldByObj.get(num)?.flags)\n ) {\n // ReadOnly may be added, on its own (v1/09, v3/64, 76); no other bit\n // has a case behind it.\n ctx.forbidden(fc, rule, `field \"${field.name}\" flags changed beyond adding ReadOnly`);\n ctx.claimStable(fc, rule, false);\n ok = false;\n } else {\n ctx.claimStable(fc, rule);\n const properties = [...changed].filter((k) => k !== 'V' && k !== 'AP' && k !== 'AS' && k !== 'I' && k !== 'RV');\n ctx.permitted(\n fc,\n rule,\n properties.length > 0\n ? `field \"${field.name}\" ${changed.has('V') || changed.has('AS') ? 'filled, ' : ''}properties changed: ${properties.join(', ')}`\n : `field \"${field.name}\" filled`,\n );\n }\n }\n for (const wc of widgetChanges) {\n if (ctx.isIdentical(wc)) continue;\n const bad = [...changedKeys(wc.value.old, wc.value.new)].filter((k) => !widgetKeys.has(k));\n if (bad.length > 0) {\n ctx.forbidden(wc, rule, `widget of \"${field.name}\" keys changed: ${bad.join(', ')}`);\n ctx.claimStable(wc, rule, false);\n ok = false;\n continue;\n }\n ctx.claimStable(wc, rule);\n ctx.permitted(wc, rule, `widget of \"${field.name}\" appearance`);\n }\n if (ok) {\n parents.add(num);\n for (const w of field.widgets) parents.add(w);\n }\n }\n for (const side of SIDES)\n ctx.claimSubtree(side, parents, (label) => label === 'AP' || label.startsWith('AP/'), rule);\n}\n\nfunction ruleAnnotation(ctx: StepContext): void {\n const rule = 'annotation';\n const pages = new Set([...ctx.before.pages, ...ctx.after.pages]);\n const widgets = new Set([...ctx.before.widgetToField.keys(), ...ctx.after.widgetToField.keys()]);\n const isWidget = (c: ObjectChange): boolean => {\n if (widgets.has(c.objectNumber)) return true;\n const sub = dictEntries(c.value.new ?? c.value.old)?.Subtype;\n return sub?.t === 'name' && sub.v === 'Widget';\n };\n const annots: ObjectChange[] = [];\n for (const c of ctx.changes) {\n if (c.kind !== 'dictionary' || ctx.isIdentical(c)) continue;\n const onPage = [...c.usage.old, ...c.usage.new].some(\n (e) => pages.has(e.parent) && e.label.startsWith('Annots/'),\n );\n if (onPage && !isWidget(c)) annots.push(c);\n }\n if (annots.length === 0) {\n // Pages whose /Annots changed without a known annotation are judged below.\n }\n if (!ctx.allows('annotate')) {\n for (const c of annots) ctx.forbidden(c, rule, `annotation change under level '${ctx.level}'`);\n return;\n }\n const parents = new Set<number>();\n for (const c of annots) {\n ctx.claimAll(c, rule);\n ctx.permitted(c, rule, `${c.change} annotation`);\n parents.add(c.objectNumber);\n }\n for (const p of pages) {\n const c = ctx.byNum.get(p);\n if (!c || ctx.isIdentical(c)) continue;\n const changed = changedKeys(c.value.old, c.value.new);\n if (changed.size === 1 && changed.has('Annots')) {\n const removed = refsOf(dictEntries(c.value.old)?.Annots).filter(\n (n) => !refsOf(dictEntries(c.value.new)?.Annots).includes(n),\n );\n const added = refsOf(dictEntries(c.value.new)?.Annots).filter(\n (n) => !refsOf(dictEntries(c.value.old)?.Annots).includes(n),\n );\n const touchesWidget = [...removed, ...added].some(\n (n) =>\n widgets.has(n) &&\n !ctx.findings.some((f) => f.objectNumber === n && f.verdict === 'permitted'),\n );\n if (touchesWidget) {\n ctx.forbidden(c, rule, 'page /Annots added or removed a form widget');\n continue;\n }\n ctx.claimAll(c, rule);\n ctx.permitted(c, rule, 'page /Annots changed');\n }\n }\n for (const side of SIDES) {\n ctx.claimSubtree(\n side,\n parents,\n (label) => label === 'AP' || label.startsWith('AP/') || label === 'Popup' || label === 'IRT',\n rule,\n );\n }\n}\n\nfunction ruleFieldLock(ctx: StepContext): void {\n if (ctx.locks.length === 0) return;\n const lockedFields = ctx.input.before.fields.filter((f) =>\n ctx.locks.some((l) => lockCovers(l.spec, f.name)),\n );\n const lockedObjects = new Set<number>();\n for (const f of lockedFields) {\n lockedObjects.add(f.objectNumber);\n for (const w of f.widgets) lockedObjects.add(w);\n }\n // Their appearance subtrees (old side: what the lock froze).\n const frontier = new Set(lockedObjects);\n let grew = true;\n while (grew) {\n grew = false;\n for (const c of ctx.changes) {\n if (frontier.has(c.objectNumber)) continue;\n if (c.usage.old.length > 0 && c.usage.old.every((e) => frontier.has(e.parent))) {\n frontier.add(c.objectNumber);\n grew = true;\n }\n }\n }\n for (const c of ctx.changes) {\n if (!frontier.has(c.objectNumber) || ctx.isIdentical(c)) continue;\n const field = lockedFields.find(\n (f) => f.objectNumber === c.objectNumber || f.widgets.includes(c.objectNumber),\n );\n // A locked field may still gain ReadOnly and nothing else (v3/76: \"not\n // modified\"). Its value, appearance, tooltip, visibility and placement\n // are frozen (v1/28, v2/51, v3/73, 74, 80; 49 and 75 are accepted by\n // Acrobat and kept frozen on purpose: a lock that lets the field move\n // or redraw is not the guarantee it promises).\n if (field && field.objectNumber === c.objectNumber) {\n const changed = changedKeys(c.value.old, c.value.new);\n if (\n changed.size === 1 &&\n changed.has('Ff') &&\n readOnlyOnlyChange(c, ctx.before.fieldByObj.get(c.objectNumber)?.flags)\n ) {\n ctx.claimStable(c, 'field-lock');\n ctx.permitted(c, 'field-lock', `ReadOnly set on locked field \"${field.name}\"`);\n continue;\n }\n }\n ctx.locked.add(c.objectNumber);\n ctx.forbidden(\n c,\n 'field-lock',\n field\n ? `field \"${field.name}\" is locked by the signature`\n : 'part of a locked field changed',\n );\n }\n}\n\nfunction ruleUnexplained(ctx: StepContext): void {\n for (const c of ctx.changes) {\n if (c.value.truncated) {\n ctx.findings.push({\n rule: 'unexplained',\n verdict: 'incomplete',\n objectNumber: c.objectNumber,\n detail: 'value too large to inspect',\n });\n continue;\n }\n if (c.usageIncomplete) {\n ctx.findings.push({\n rule: 'unexplained',\n verdict: 'incomplete',\n objectNumber: c.objectNumber,\n detail: 'references could not be resolved within budget (depth, fan-out or total reads)',\n });\n continue;\n }\n if (ctx.locked.has(c.objectNumber)) continue;\n for (const side of SIDES) {\n for (const e of c.usage[side]) {\n if (!ctx.isClaimed(c, side, e)) {\n ctx.forbidden(\n c,\n 'unexplained',\n `${side === 'old' ? 'was' : 'is'} referenced from object ${e.parent} at ${e.label} and no rule explains it`,\n e,\n );\n }\n }\n }\n if (\n c.usage.old.length === 0 &&\n c.usage.new.length === 0 &&\n !ctx.findings.some((f) => f.objectNumber === c.objectNumber)\n ) {\n ctx.permitted(c, 'orphan', 'referenced from nowhere reachable');\n }\n }\n}\n","import type { Coordinates } from '../../pageSpace/coordinates';\nimport type { DocumentFieldLock, ModificationLevel, SignatureDTO } from '../types';\nimport { APPROVAL_BASELINE, levelFromPermission, minLevel } from '../protection';\nimport type { RestrictionAnchor, RevisionStructure } from './types';\n\n/**\n * The restrictions a window is judged under, read from the sealed\n * revision's structure (what that revision declared, not what the final\n * file says).\n *\n * - `judged` given (a signature-anchored analysis): its own FieldMDP and\n * /Lock bind the window; other signatures' locks do not (corpus v3/85:\n * a second signature is valid with a fill of a field the first locked).\n * Every certification's level, own or earlier, applies (inherited:\n * conservative until observed otherwise), as does a /Lock's /P.\n * - no `judged` (a revision-anchored analysis): every signed signature's\n * locks and levels apply.\n */\nexport function restrictionsFor(\n before: RevisionStructure,\n judged: SignatureDTO | null,\n): { anchors: RestrictionAnchor[]; level: ModificationLevel; locks: DocumentFieldLock[] } {\n const anchors: RestrictionAnchor[] = [];\n const locks: DocumentFieldLock[] = [];\n let enforced: ModificationLevel | null = null;\n let signed = false;\n for (const sig of before.signatures) {\n if (!sig.signed || sig.revisionIndex === null) continue;\n signed = true;\n const own = judged !== null && sig.index === judged.index;\n if (sig.catalogCertification && sig.docMdp !== null) {\n anchors.push({\n signatureIndex: sig.index,\n revisionIndex: sig.revisionIndex,\n source: 'docmdp',\n own,\n permission: sig.docMdp,\n });\n enforced = minLevel(enforced ?? 'annotate', levelFromPermission(sig.docMdp));\n }\n if (sig.lock?.permission !== undefined) {\n enforced = minLevel(enforced ?? 'annotate', levelFromPermission(sig.lock.permission));\n }\n if (judged !== null && !own) continue;\n if (sig.fieldMdp) {\n anchors.push({\n signatureIndex: sig.index,\n revisionIndex: sig.revisionIndex,\n source: 'fieldmdp',\n own,\n fields: sig.fieldMdp,\n });\n locks.push({ signatureIndex: sig.index, source: 'fieldmdp', spec: sig.fieldMdp });\n }\n if (sig.lock) {\n anchors.push({\n signatureIndex: sig.index,\n revisionIndex: sig.revisionIndex,\n source: 'lock',\n own,\n fields: sig.lock,\n });\n locks.push({ signatureIndex: sig.index, source: 'lock', spec: sig.lock });\n }\n }\n const level = signed ? (enforced ?? APPROVAL_BASELINE) : 'annotate';\n return { anchors, level, locks };\n}\n","import type { ObjectReferrer } from './types';\n\n/**\n * Limits on edge resolution. Exceeding any of them makes the object's usage\n * `incomplete`, which the evaluator turns into an indeterminate step: an\n * adversary can make evidence expensive, never make it disappear.\n */\nexport interface EdgeResolverBudget {\n /**\n * Longest chain of unchanged objects an edge may be resolved through. A\n * loop counts the member the edge enters it at, and the member it leaves\n * from when that is another one.\n */\n maxDepth: number;\n /** Most anchored edges one object may end up with. */\n maxEdgesPerObject: number;\n /** Most referrer reads per resolver: each object is read once. */\n maxReads: number;\n}\n\nexport const DEFAULT_EDGE_RESOLVER_BUDGET: EdgeResolverBudget = {\n maxDepth: 16,\n maxEdgesPerObject: 256,\n maxReads: 20_000,\n};\n\nexport const USAGE_INCOMPLETE = 'incomplete';\nexport type ResolvedUsage = ObjectReferrer[] | typeof USAGE_INCOMPLETE;\n\n/**\n * The label segment that stands for a route between two members of a loop.\n * Fork labels are ASCII (keys are `#`-escaped), so it is never a key.\n */\nconst LOOP_ROUTE = '…';\n\n/**\n * Resolves the raw inbound edges of an object (from the fork's referrer\n * index, which covers every reachable object of a revision) into edges\n * from *anchors*: the changed objects and the structural objects of the\n * revision (trailer, catalog, AcroForm, page tree root, pages, fields,\n * widgets). An edge from an unchanged, non-structural parent is replaced by\n * that parent's own anchored edges with the labels joined, so an\n * appearance stream under an unchanged indirect `/AP` dictionary reads\n * `widget:AP/N` rather than `apDict:N`.\n *\n * A graph traversal, not a path enumeration. The unchanged objects above\n * an object are read once each and split into strongly connected\n * components (loops: a structure tree, whose elements point at their\n * parent with `/P` and at their children with `/K`; an outline, whose\n * items point at their neighbours; an annotation and its popup), resolved\n * ancestors first and memoised per object, so a lattice of shared objects\n * costs its size, not the number of paths through it.\n *\n * Every member of a loop reaches every other one, so an edge into a loop\n * reaches all its members: as it is at the member it enters, and as\n * `<label>/…` at every other one, the route between them collapsed. The\n * route consists of unchanged objects, the same in both revisions, so it\n * carries no evidence; the anchor, the way in and the way out (the labels\n * either side of `…`) do, and they are kept. Edges whose label collapses\n * a route are told apart by anchor and label alone.\n */\nexport class EdgeResolver {\n /** Raw inbound edges, per object read. */\n private readonly referrers = new Map<number, ObjectReferrer[]>();\n /** Anchored edges per resolved object; null when they exceeded the budget. */\n private readonly resolved = new Map<number, ObjectReferrer[] | null>();\n private reads = 0;\n private exhausted = false;\n\n constructor(\n private readonly read: (objectNumber: number) => ObjectReferrer[],\n private readonly anchors: ReadonlySet<number>,\n private readonly budget: EdgeResolverBudget = DEFAULT_EDGE_RESOLVER_BUDGET,\n ) {}\n\n /** Anchored edges of `objectNumber`, or `incomplete` when a budget was exceeded. */\n resolve(objectNumber: number): ResolvedUsage {\n if (!this.resolved.has(objectNumber)) {\n const components = this.componentsAbove(objectNumber);\n for (const component of components ?? []) {\n if (!this.resolveComponent(component)) break;\n }\n }\n return this.resolved.get(objectNumber) ?? USAGE_INCOMPLETE;\n }\n\n private readReferrers(n: number): ObjectReferrer[] | null {\n const known = this.referrers.get(n);\n if (known) return known;\n if (this.exhausted || this.reads >= this.budget.maxReads) {\n this.exhausted = true;\n return null;\n }\n this.reads += 1;\n const raw = this.read(n);\n this.referrers.set(n, raw);\n return raw;\n }\n\n /** The parents of an object still to be resolved: unchanged, non-structural, not resolved yet. */\n private pendingParents(raw: ObjectReferrer[]): number[] {\n const out = new Set<number>();\n for (const e of raw) {\n if (!this.anchors.has(e.parent) && !this.resolved.has(e.parent)) out.add(e.parent);\n }\n return [...out];\n }\n\n /**\n * The strongly connected components of the unresolved objects above\n * `start` (Tarjan's algorithm, iterative), ancestors first; null when the\n * read budget ran out.\n */\n private componentsAbove(start: number): number[][] | null {\n const index = new Map<number, number>();\n const low = new Map<number, number>();\n const stack: number[] = [];\n const onStack = new Set<number>();\n const frames: Array<{ node: number; parents: number[]; next: number }> = [];\n const components: number[][] = [];\n\n const enter = (n: number): boolean => {\n const raw = this.readReferrers(n);\n if (!raw) return false;\n index.set(n, index.size);\n low.set(n, index.get(n)!);\n stack.push(n);\n onStack.add(n);\n frames.push({ node: n, parents: this.pendingParents(raw), next: 0 });\n return true;\n };\n\n if (!enter(start)) return null;\n while (frames.length > 0) {\n const frame = frames[frames.length - 1];\n if (frame.next < frame.parents.length) {\n const p = frame.parents[frame.next++];\n if (!index.has(p)) {\n if (!enter(p)) return null;\n } else if (onStack.has(p)) {\n low.set(frame.node, Math.min(low.get(frame.node)!, index.get(p)!));\n }\n continue;\n }\n frames.pop();\n const n = frame.node;\n if (frames.length > 0) {\n const below = frames[frames.length - 1].node;\n low.set(below, Math.min(low.get(below)!, low.get(n)!));\n }\n if (low.get(n) === index.get(n)) {\n const component: number[] = [];\n let m: number;\n do {\n m = stack.pop()!;\n onStack.delete(m);\n component.push(m);\n } while (m !== n);\n components.push(component);\n }\n }\n return components;\n }\n\n /** Resolve one component whose ancestors are all resolved; false when it exceeded the budget. */\n private resolveComponent(component: number[]): boolean {\n const members = new Set(component);\n const result =\n component.length === 1\n ? this.edgesOfSingle(component[0])\n : this.edgesOfLoop(component, members);\n if (!result) {\n for (const n of component) this.resolved.set(n, null);\n return false;\n }\n for (const n of component) this.resolved.set(n, result.get(n)!);\n return true;\n }\n\n /** An object outside any loop: its raw edges, each resolved through its parent. */\n private edgesOfSingle(n: number): Map<number, ObjectReferrer[]> | null {\n const edges: ObjectReferrer[] = [];\n for (const e of this.referrers.get(n)!) {\n if (e.parent === n) continue; // a reference to itself leads to no anchor\n const through = this.through(e);\n if (!through) return null;\n edges.push(...through);\n }\n const unique = withoutCollapsedDuplicates(edges);\n return unique.length > this.budget.maxEdgesPerObject ? null : new Map([[n, unique]]);\n }\n\n /**\n * A loop: every anchored edge into it, as it is at the member it enters\n * and with the route collapsed at every other member.\n */\n private edgesOfLoop(\n component: number[],\n members: Set<number>,\n ): Map<number, ObjectReferrer[]> | null {\n const entering = new Map<number, ObjectReferrer[]>();\n // Each collapsed route, entering at up to two members: one that enters\n // at a single member leads to every member but that one.\n const routes = new Map<string, ObjectReferrer[]>();\n for (const s of component) {\n const own: ObjectReferrer[] = [];\n for (const e of this.referrers.get(s)!) {\n if (members.has(e.parent)) continue;\n const through = this.through(e);\n if (!through) return null;\n for (const u of through) {\n own.push(u);\n const via = [...(u.via ?? []), s];\n if (via.length >= this.budget.maxDepth) return null;\n const route = { parent: u.parent, label: `${u.label}/${LOOP_ROUTE}`, via };\n const known = routes.get(edgeKey(route));\n if (!known) routes.set(edgeKey(route), [route]);\n else if (known.length === 1 && entryOf(known[0]) !== s) known.push(route);\n }\n if (own.length > this.budget.maxEdgesPerObject) return null;\n }\n if (own.length > 0) entering.set(s, withoutCollapsedDuplicates(own));\n }\n if (routes.size > this.budget.maxEdgesPerObject) return null;\n\n const out = new Map<number, ObjectReferrer[]>();\n const toAny = [...routes.values()].map((entries) => entries[0]);\n for (const n of component) {\n const own = entering.get(n);\n if (!own) {\n out.set(n, toAny);\n continue;\n }\n const toThis: ObjectReferrer[] = [];\n for (const entries of routes.values()) {\n const route = entries.find((r) => entryOf(r) !== n);\n if (route) toThis.push(route);\n }\n const edges = [...own, ...toThis];\n if (edges.length > this.budget.maxEdgesPerObject) return null;\n out.set(n, edges);\n }\n return out;\n }\n\n /** The anchored edges one raw edge stands for; null when its parent exceeded the budget. */\n private through(e: ObjectReferrer): ObjectReferrer[] | null {\n if (this.anchors.has(e.parent)) return [e];\n const above = this.resolved.get(e.parent);\n if (!above) return null;\n const out: ObjectReferrer[] = [];\n for (const u of above) {\n const via = [...(u.via ?? []), e.parent];\n if (via.length >= this.budget.maxDepth) return null;\n out.push({ parent: u.parent, label: `${u.label}/${e.label}`, via });\n }\n return out;\n }\n}\n\nfunction edgeKey(e: ObjectReferrer): string {\n return `${e.parent}:${e.label}`;\n}\n\n/** The member a collapsed route enters its loop at: the last object it was resolved through. */\nfunction entryOf(route: ObjectReferrer): number {\n return route.via![route.via!.length - 1];\n}\n\n/** Edges whose label collapses a route are told apart by anchor and label alone. */\nfunction withoutCollapsedDuplicates(edges: ObjectReferrer[]): ObjectReferrer[] {\n const seen = new Set<string>();\n return edges.filter((e) => {\n if (!e.label.includes(LOOP_ROUTE)) return true;\n const key = edgeKey(e);\n if (seen.has(key)) return false;\n seen.add(key);\n return true;\n });\n}\n","import type { PageRef } from '../identity/PageRef';\nimport type { Coordinates, PageCoordinates } from '../pageSpace/coordinates';\nimport type { PdfTextSegment } from '../text/layout';\nimport type { PageTextRange } from '../text/TextRange';\n\n/**\n * What to search for — the one shape, engine → wire → plugin state →\n * search box. One flat object; the flags define behavior per mode instead\n * of the mode changing the shape:\n *\n * | flag | literal | regex |\n * |-------------------|------------------|--------------------------------|\n * | `matchCase` | fold case | `i` flag |\n * | `wholeWord` | boundary check | pattern is `\\b(?:…)\\b`-wrapped |\n * | `matchDiacritics` | mark fold | rejected (`InvalidArg`) |\n * | `ignoreWhitespace`| whitespace drop | rejected (`InvalidArg`) |\n *\n * Literal queries match over folded text; regex queries run the portable\n * dialect against the raw page text — which is why `matchDiacritics` and\n * `ignoreWhitespace` cannot apply to them (diacritic folding and whitespace\n * dropping are properties of the folded text plane; a pattern spells its\n * own `\\s*`). Validate with `validateSearchQuery` for early UI feedback;\n * engines re-validate and reject with `EngineErrorCode.InvalidArg`.\n */\nexport interface SearchQuery {\n /**\n * The literal text — or, when `regex`, a pattern in the portable\n * search-regex dialect: JavaScript `u`-mode syntax minus backreferences\n * and lookaround, so every valid pattern also runs on RE2 (the\n * server-side engine).\n */\n text: string;\n /** Interpret `text` as a regex pattern. Default false (literal). */\n regex?: boolean;\n /** Exact-case matching. Default false (case-folded / `i` semantics). */\n matchCase?: boolean;\n /** Only match at word boundaries (letters/digits end the word). */\n wholeWord?: boolean;\n /**\n * Treat diacritics as significant (\"café\" ≠ \"cafe\"). Default false —\n * marks are stripped on both sides, which is what viewers ship.\n * Literal only: combined with `regex` the query is rejected.\n */\n matchDiacritics?: boolean;\n /**\n * Drop whitespace on both sides instead of collapsing it, so \"invoice\"\n * finds the letter-spaced \"i n v o i c e\" that OCR and tracked-out headings\n * produce, and \"total amount\" finds \"totalamount\". Default false — the default\n * fold collapses whitespace runs to one space, so a needle still has to\n * carry a space wherever the page does. A hit spans the original text\n * including the dropped whitespace; with `wholeWord` the boundaries are\n * checked on the original text (the folded plane has no word gaps left).\n * Literal only: combined with `regex` the query is rejected.\n */\n ignoreWhitespace?: boolean;\n}\n\n/** The query part of a request (or of any object that carries one): its text and flags, set flags only. */\nexport function searchQueryOf(query: SearchQuery): SearchQuery {\n return {\n text: query.text,\n ...(query.regex ? { regex: true } : {}),\n ...(query.matchCase ? { matchCase: true } : {}),\n ...(query.wholeWord ? { wholeWord: true } : {}),\n ...(query.matchDiacritics ? { matchDiacritics: true } : {}),\n ...(query.ignoreWhitespace ? { ignoreWhitespace: true } : {}),\n };\n}\n\n/**\n * How much one `query()` call may do. A call ends as soon as either limit is\n * hit (or the document is exhausted). Engines clamp both to their own\n * ceilings — the server never lets one request scan 40K pages.\n */\nexport interface SearchLimit {\n /** Stop after this many matches (default: engine's ceiling). */\n matches?: number;\n /** Stop after searching this many pages (default: engine's ceiling). */\n pages?: number;\n}\n\n/**\n * One `query()` call = one bounded batch of work: the query, plus how to\n * run it. Search over a large document is a client-driven cursor loop —\n * there is no server-side job to start, poll, or cancel. Cancelling is\n * simply not asking for the next batch.\n */\nexport interface SearchRequest extends SearchQuery {\n /**\n * Include the text around each match. A snippet is text from the\n * document, so this also needs `doc.text.copy`; without it the call is\n * refused rather than leaving the snippets out. Default false: a search\n * needs only `doc.text.search`, and nothing readable leaves the engine.\n */\n snippets?: boolean;\n /**\n * Viewport-first ordering: start searching at this page and wrap around\n * the document, so the matches the user is looking at arrive in the\n * first batch. Ignored when `cursor` is set (the cursor owns position).\n */\n from?: PageRef;\n /**\n * Resume token from the previous batch's `nextCursor`. Opaque — it pins\n * the query and position; the engine rejects a cursor replayed against a\n * different query or a changed document with `EngineErrorCode.InvalidArg`\n * (start the search again).\n */\n cursor?: string;\n limit?: SearchLimit;\n}\n\n/**\n * The text around one match, ready to render: `match` between `before` and\n * `after`, whitespace flattened to spaces.\n */\nexport interface SearchSnippet {\n before: string;\n match: string;\n after: string;\n}\n\n/**\n * One hit: a range of the page's characters — the space selection ranges\n * and geometry live in, not string offsets into `PageTextSnapshot.text`\n * (engines convert match string ranges through the snapshot's `charMap`\n * before building the hit; see engine-core `text/charmap.ts`). That is what\n * lets a match go straight to selection, `text.slice()` and markup\n * creation, and it means zero-width characters adjacent to the matched text\n * are never inside the range. `segments` are the canonical visual-line\n * segments (the same text layout selection uses) — a match highlights\n * exactly like a selection of the same characters, one oriented segment per\n * visual line, never per glyph.\n */\nexport interface SearchMatch<C extends Coordinates = PageCoordinates> extends PageTextRange {\n segments: PdfTextSegment<C>[];\n snippet?: SearchSnippet;\n}\n\n/**\n * The result of one bounded batch. `nextCursor === null` means the search\n * is done — everything findable has been returned. Progress UI:\n * `pagesSearched / pageCount` (`pagesSearched` is cumulative across the\n * cursor chain, not per batch).\n */\nexport interface SearchSlice<C extends Coordinates = PageCoordinates> {\n matches: SearchMatch<C>[];\n nextCursor: string | null;\n pagesSearched: number;\n pageCount: number;\n}\n","import { foldText } from './fold';\nimport type { TextRange } from '../text/TextRange';\nimport { foldOptionsFor, matchLiteral } from './literal';\nimport { matchRegex } from './regex';\nimport type { SearchQuery } from './types';\n\n/**\n * The whole match stage in one pure call: page text in, original-space\n * match ranges out. Engines with a pre-folded corpus for the default fold\n * skip this and call `matchLiteral` on the cached `FoldedText` directly;\n * everything else (non-default fold options, regex, tests) comes through\n * here.\n */\nexport function matchPageText(text: string, query: SearchQuery): TextRange[] {\n if (query.regex) return matchRegex(text, query);\n return matchLiteral(foldText(text, foldOptionsFor(query)), query);\n}\n","import type { TextRange } from '../text/TextRange';\nimport type { SearchSnippet } from './types';\n\n/** Default context on each side of a match, in code units. */\nexport const SEARCH_SNIPPET_CONTEXT = 48;\n\nconst WHITESPACE = /\\s/;\n// Every whitespace unit becomes one plain space.\nconst WHITESPACE_ALL = /\\s/g;\n\nconst isLowSurrogate = (text: string, index: number): boolean => {\n const unit = text.charCodeAt(index);\n return unit >= 0xdc00 && unit <= 0xdfff;\n};\n\n/**\n * The excerpt around one match (`snippets: true`): up to `context` code\n * units of page text on each side, trimmed to a whitespace boundary when one\n * exists inside the window (so snippets start and end on whole words),\n * never splitting a surrogate pair, whitespace flattened to spaces.\n */\nexport function buildSnippet(\n text: string,\n range: TextRange,\n context: number = SEARCH_SNIPPET_CONTEXT,\n): SearchSnippet {\n const matchEnd = range.start + range.count;\n\n let start = Math.max(0, range.start - context);\n if (start > 0) {\n // Cut at the first whitespace inside the leading context, if any —\n // otherwise accept the mid-word cut (one very long token).\n for (let i = start; i < range.start; i++) {\n if (WHITESPACE.test(text[i])) {\n start = i + 1;\n break;\n }\n }\n if (isLowSurrogate(text, start)) start++;\n }\n\n let end = Math.min(text.length, matchEnd + context);\n if (end < text.length) {\n for (let i = end - 1; i >= matchEnd; i--) {\n if (WHITESPACE.test(text[i])) {\n end = i;\n break;\n }\n }\n if (isLowSurrogate(text, end)) end--;\n }\n\n const flat = (from: number, to: number) => text.slice(from, to).replace(WHITESPACE_ALL, ' ');\n return {\n before: flat(start, range.start),\n match: flat(range.start, matchEnd),\n after: flat(matchEnd, end),\n };\n}\n","import type { DocumentManifest } from '../dto/DocumentManifest';\nimport { foldText } from './fold';\nimport { searchQueryOf, type SearchQuery } from './types';\n\n/**\n * The search content epoch: a deterministic fingerprint of everything a\n * search result depends on — page order/structure (`layoutVersion`) and\n * each page's text content (`contentVersion`), nothing else. Annotation\n * and metadata churn deliberately do not move it, so cached search\n * responses in a collaborative document survive comment storms.\n *\n * Both sides compute it from the manifest they already hold: the client\n * to mint versioned search URLs, the server to validate them (mismatch →\n * NotFound, the standard stale-versioned-read signal). FNV-1a 64-bit —\n * dependency-free and stable; not cryptographic, and doesn't need to be:\n * an adversary can only vary his own authorized query results.\n */\nexport function searchContentEpoch(manifest: DocumentManifest): string {\n let input = `${manifest.layoutVersion}`;\n for (const page of manifest.pages) {\n input += `|${page.page.objectNumber}:${page.cache.contentVersion}`;\n }\n return fnv1a64(input);\n}\n\nconst FNV_OFFSET = 0xcbf29ce484222325n;\nconst FNV_PRIME = 0x100000001b3n;\nconst MASK_64 = 0xffffffffffffffffn;\n\nfunction fnv1a64(input: string): string {\n let hash = FNV_OFFSET;\n for (let i = 0; i < input.length; i++) {\n hash ^= BigInt(input.charCodeAt(i));\n hash = (hash * FNV_PRIME) & MASK_64;\n }\n return hash.toString(16).padStart(16, '0');\n}\n\n/**\n * Canonicalize a query for cache keying: default-fold literal queries are\n * pre-folded (\"Café\", \"café\" and \"CAFE\" are the same search, so they\n * should be the same cache entry). Semantics are unchanged — the fold is\n * idempotent and exactly what the matcher applies to the needle anyway.\n * Case- or diacritic-sensitive literals and regex patterns pass through\n * untouched (their raw form is the query).\n */\nexport function canonicalSearchQuery(request: SearchQuery): SearchQuery {\n const query = searchQueryOf(request);\n if (query.regex || query.matchCase || query.matchDiacritics || query.ignoreWhitespace) {\n return query;\n }\n const canonical: SearchQuery = { text: foldText(query.text).folded };\n if (query.wholeWord) canonical.wholeWord = true;\n return canonical;\n}\n","import type { FlattenOptions } from './PageFlattenResult';\nimport type { AnnotationResources } from '../annotation/resources';\nimport { EngineError } from '../errors/EngineError';\nimport { EngineErrorCode } from '../errors/EngineErrorCode';\nimport { generateUuid } from '../identity/uuid';\n\n/**\n * What every write takes besides its data: how to write it, never what to\n * write.\n */\nexport interface WriteOptions {\n /**\n * Names this write. Every event it publishes carries the id as\n * `origin.tx.id`; on the cloud a retry with the same id returns the first\n * result and applies once. Minted when absent.\n */\n readonly opId?: string;\n}\n\n/** What an `opId` may be: what an HTTP header carries (`Idempotency-Key`). */\nconst OP_ID = /^[\\x21-\\x7e]{1,255}$/;\n\n/**\n * The `opId` a write runs under: the caller's, or a fresh one. The caller's\n * must be 1 to 255 visible ASCII characters, on every engine; anything else\n * is refused with `InvalidArg`.\n */\nexport function opIdOf(options: WriteOptions | undefined): string {\n const opId = options?.opId;\n if (opId === undefined) return generateUuid();\n if (!OP_ID.test(opId)) {\n throw new EngineError(\n EngineErrorCode.InvalidArg,\n 'opId must be 1 to 255 visible ASCII characters',\n { details: { field: 'opId' } },\n );\n }\n return opId;\n}\n\n/** `page.annotations.create(data, options)`. */\nexport interface AnnotationCreateOptions extends WriteOptions {\n /**\n * Bytes beside the data, by role: a stamp's `appearance`, a file\n * attachment's `file`. A resource the kind doesn't take is refused.\n */\n readonly resources?: AnnotationResources;\n /**\n * The object number the annotation gets: one this document's\n * `objectNumbers` pool handed out. Without it the engine picks the next\n * free number, and the annotation's ref is known only from the result.\n */\n readonly objectNumber?: number;\n}\n\n/** `page.annotations.update(ref, patch, options)`. */\nexport interface AnnotationUpdateOptions extends WriteOptions {\n /** Replaces what it is for: a stamp's drawing, an attached file's bytes. */\n readonly resources?: AnnotationResources;\n}\n\n/** `page.annotations.flatten(refs, options)` and `pages.flatten(pages, options)`. */\nexport interface FlattenWriteOptions extends FlattenOptions, WriteOptions {}\n\n/** `pages.insertBlank(spec, position, options)`. */\nexport interface PageInsertBlankOptions extends WriteOptions {\n /**\n * The object numbers the new pages get, in order, one per page: numbers\n * this document's `objectNumbers` pool handed out. Without them the engine\n * picks the next free numbers.\n */\n readonly objectNumbers?: readonly number[];\n}\n\n/** `forms.create(draft, options)`. */\nexport interface FormFieldCreateOptions extends WriteOptions {\n /** The object number the field gets, from this document's `objectNumbers` pool. */\n readonly objectNumber?: number;\n /** The object numbers its widgets get, in `draft.widgets` order, from the same pool. */\n readonly widgetObjectNumbers?: readonly number[];\n}\n\n/** `forms.addWidget(ref, placement, options)`. */\nexport interface FormWidgetAddOptions extends WriteOptions {\n /** The object number the new widget gets, from this document's `objectNumbers` pool. */\n readonly objectNumber?: number;\n /**\n * The object number the widget split off a merged field gets, when the\n * field is merged (a field and its only widget in one dictionary): the\n * field keeps its number, its widget moves to this one. Ignored for a\n * field that isn't merged.\n */\n readonly splitObjectNumber?: number;\n}\n","import type { RecordedChange } from './Change';\nimport { EngineErrorCode } from '../errors/EngineErrorCode';\nimport type { Coordinates } from '../pageSpace/coordinates';\n\n/**\n * The refusals a change keeps under its `opId`, like a success: the document\n * or the caller refused it, so asking again gets the same answer, even once\n * the document has changed so that it would apply. Anything else (an abort, a\n * lost race with another writer, an engine failure) applied nothing, is not\n * kept, and may run again.\n */\nconst KEPT_REFUSALS: ReadonlySet<EngineErrorCode> = new Set([\n EngineErrorCode.InvalidArg,\n EngineErrorCode.NotFound,\n EngineErrorCode.Forbidden,\n EngineErrorCode.ProtectedDocument,\n EngineErrorCode.MalformedPdf,\n EngineErrorCode.PayloadTooLarge,\n EngineErrorCode.ObjectNumberUnavailable,\n EngineErrorCode.LayerFull,\n EngineErrorCode.ChangeConflict,\n EngineErrorCode.UndoUnavailable,\n]);\n\n/** Whether a change refused with `code` keeps that answer (see `KEPT_REFUSALS`). */\nexport function isKeptRefusal(code: EngineErrorCode): boolean {\n return KEPT_REFUSALS.has(code);\n}\n\n/**\n * What a retry under the same `opId` must send: the change's fingerprint. The\n * same ops with the same bytes give the same fingerprint whatever the order\n * of their keys; bytes count by their content.\n */\nexport function changeFingerprint<C extends Coordinates, R>(change: RecordedChange<C, R>): string {\n const text = canonicalJson(change);\n return `${text.length.toString(36)}-${hashText(text)}`;\n}\n\n/** `value` as JSON with every object's keys sorted, and bytes as their length and hash. */\nfunction canonicalJson(value: unknown): string {\n if (value instanceof ArrayBuffer || ArrayBuffer.isView(value)) {\n const bytes =\n value instanceof ArrayBuffer\n ? new Uint8Array(value)\n : new Uint8Array(value.buffer, value.byteOffset, value.byteLength);\n return JSON.stringify({ $bytes: `${bytes.byteLength.toString(36)}-${hashBytes(bytes)}` });\n }\n if (Array.isArray(value)) return `[${value.map(canonicalJson).join(',')}]`;\n if (value !== null && typeof value === 'object') {\n const entries = Object.entries(value as Record<string, unknown>)\n .filter(([, entry]) => entry !== undefined)\n .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));\n return `{${entries.map(([key, entry]) => `${JSON.stringify(key)}:${canonicalJson(entry)}`).join(',')}}`;\n }\n return JSON.stringify(value) ?? 'null';\n}\n\n/** A 53-bit hash (cyrb53) of a string's UTF-16 units, in base 36. */\nfunction hashText(text: string): string {\n let h1 = 0xdeadbeef;\n let h2 = 0x41c6ce57;\n for (let i = 0; i < text.length; i++) {\n const unit = text.charCodeAt(i);\n h1 = Math.imul(h1 ^ unit, 2654435761);\n h2 = Math.imul(h2 ^ unit, 1597334677);\n }\n return finish(h1, h2);\n}\n\n/** The same hash over bytes. */\nfunction hashBytes(bytes: Uint8Array): string {\n let h1 = 0xdeadbeef;\n let h2 = 0x41c6ce57;\n for (const byte of bytes) {\n h1 = Math.imul(h1 ^ byte, 2654435761);\n h2 = Math.imul(h2 ^ byte, 1597334677);\n }\n return finish(h1, h2);\n}\n\nfunction finish(h1: number, h2: number): string {\n h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507);\n h1 ^= Math.imul(h2 ^ (h2 >>> 13), 3266489909);\n h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507);\n h2 ^= Math.imul(h1 ^ (h1 >>> 13), 3266489909);\n return (4294967296 * (2097151 & h2) + (h1 >>> 0)).toString(36);\n}\n","import type { MutationMeta } from './MutationMeta';\nimport type { OutlineItem } from '../dto/DocumentOutline';\nimport type { PageDestination } from '../dto/PdfDestination';\nimport type { OutlineItemRef } from '../identity/OutlineItemRef';\n\n/**\n * The meta of every outline write: the items it touched, created, updated,\n * moved and deleted alike; each result says which. Names never change, so\n * nothing a caller holds goes stale.\n */\nexport interface OutlineMutationMeta extends MutationMeta {\n changed: OutlineItemRef[];\n}\n\n/**\n * One parent's children as a write left them, in order: where an item now\n * is, as a fact rather than a position. `parent: null` is the top level.\n */\nexport interface OutlineOrder {\n parent: OutlineItemRef | null;\n children: OutlineItemRef[];\n}\n\n/** Result of `doc.outline.create()`: the new item, and its parent's children with it. */\nexport interface OutlineCreateResult<D = PageDestination> {\n item: OutlineItem<D>;\n order: OutlineOrder;\n meta: OutlineMutationMeta;\n}\n\n/** Result of `doc.outline.update()`: the item as the update left it. */\nexport interface OutlineUpdateResult<D = PageDestination> {\n item: OutlineItem<D>;\n meta: OutlineMutationMeta;\n}\n\n/**\n * Result of `doc.outline.move()`: the children of every parent the move\n * changed (the parents the items left and the one they went to), and in\n * `meta.changed` the items that moved. An item that lost its last child is\n * no longer open: a leaf has no open state.\n */\nexport interface OutlineMoveResult {\n orders: OutlineOrder[];\n meta: OutlineMutationMeta;\n}\n\n/**\n * Result of `doc.outline.delete()`: in `meta.changed`, what went: the item\n * first, then the items under it (see `deletedOutlineItemsOf`).\n */\nexport interface OutlineDeleteResult {\n meta: OutlineMutationMeta;\n}\n\n/**\n * What an undo of a delete brought back: the same items under the refs they\n * had, the item first and the items under it depth first, and its parent's\n * children with it.\n */\nexport interface OutlineRestoreResult<D = PageDestination> {\n items: OutlineItem<D>[];\n order: OutlineOrder;\n meta: OutlineMutationMeta;\n}\n\n/** What a delete removed, as its `outline.deleted` event names it: the item first. */\nexport function deletedOutlineItemsOf(result: OutlineDeleteResult): OutlineItemRef[] {\n return result.meta.changed;\n}\n","import type { PdfBits } from './types';\n\n/**\n * ISO 32000 user-access permission bit positions, expressed as integer\n * masks. Bit numbers in the spec are 1-indexed, so bit 3 = `1 << 2`.\n *\n * Bits 1, 2, 7, 8, and 13+ are reserved and not surfaced here.\n */\nexport const PDF_BITS = {\n /** Bit 3 — print the document. */\n PRINT: 1 << 2,\n /** Bit 4 — modify content streams. */\n MODIFY: 1 << 3,\n /** Bit 5 — copy/extract text and graphics. */\n COPY: 1 << 4,\n /** Bit 6 — annotate + fill forms (+ modify form fields with bit 4). */\n ANNOTATE_FILL: 1 << 5,\n /** Bit 9 — fill existing forms (even if bit 6 is clear). */\n FILL_FORMS: 1 << 8,\n /** Bit 10 — accessibility extraction (deprecated in PDF 2.0). */\n ACCESSIBILITY: 1 << 9,\n /** Bit 11 — assemble document (insert/rotate/delete pages, outline). */\n ASSEMBLE: 1 << 10,\n /** Bit 12 — high-quality print (refines bit 3). */\n PRINT_HIGH: 1 << 11,\n} as const;\n\n/**\n * Decode a raw PDFium permission integer into a typed boolean view.\n *\n * `null` input (the documents row column is nullable until probed)\n * yields all-false bits — i.e., a maximally restrictive interpretation.\n * That keeps `pdf.permissions` expansion safe on unprobed documents.\n */\nexport function decodePdfBits(raw: number | null): PdfBits {\n if (raw === null) {\n return {\n bit3: false,\n bit4: false,\n bit5: false,\n bit6: false,\n bit9: false,\n bit10: false,\n bit11: false,\n bit12: false,\n };\n }\n return {\n bit3: (raw & PDF_BITS.PRINT) !== 0,\n bit4: (raw & PDF_BITS.MODIFY) !== 0,\n bit5: (raw & PDF_BITS.COPY) !== 0,\n bit6: (raw & PDF_BITS.ANNOTATE_FILL) !== 0,\n bit9: (raw & PDF_BITS.FILL_FORMS) !== 0,\n bit10: (raw & PDF_BITS.ACCESSIBILITY) !== 0,\n bit11: (raw & PDF_BITS.ASSEMBLE) !== 0,\n bit12: (raw & PDF_BITS.PRINT_HIGH) !== 0,\n };\n}\n","import { EngineError } from '../../errors/EngineError';\nimport { EngineErrorCode } from '../../errors/EngineErrorCode';\nimport type { AnnotationRef } from '../../identity/AnnotationRef';\nimport { PermissionDenied } from './errors';\nimport {\n checkAnyFieldAction,\n checkCapability,\n checkCollab,\n checkFieldAction,\n checkSetGroup,\n collabTargetOf,\n} from './resolver';\nimport type { AnnotationActor, DocCapability, Identity, PdfBits } from './types';\nimport { describeProtection, protectedCapabilities } from '../../signature/protection';\nimport type { DocumentProtection } from '../../signature/types';\n\n/**\n * Who an annotation write acts for, and what they may do to the annotations\n * it changes. It travels with the write: the worker checks it against each\n * annotation the write finds, inside the write, so the check and the write\n * see one document and a refusal leaves nothing behind.\n */\nexport interface AnnotationAuthority {\n /** Who the write acts for: the attribution it stamps. */\n readonly identity: Identity;\n /**\n * What the caller may do to annotations, checked against each one the\n * write changes; `null` when nothing is checked (a tenant writing its\n * own document).\n */\n readonly grants: { readonly scope: readonly string[]; readonly pdfBits: PdfBits } | null;\n}\n\n/**\n * Everything a change is checked against, inside the write, op by op (the\n * ops of an undo included): who it acts for, their grants, and what the\n * document's signatures forbid.\n */\nexport interface ChangeAuthority extends AnnotationAuthority {\n /** What the signatures in the document forbid; `null` when nothing is enforced. */\n readonly protection: DocumentProtection | null;\n}\n\n/**\n * Check that the caller may use `capability`: `ProtectedDocument` when a\n * signature in the document took it away, `PermissionDenied` when the\n * grants never gave it.\n */\nexport function authorizeCapability(authority: ChangeAuthority, capability: DocCapability): void {\n authorizeUnprotected(authority, capability);\n const { grants, protection } = authority;\n if (grants && !checkCapability(capability, grants.scope, grants.pdfBits, protection)) {\n throw new PermissionDenied(capability, 'target');\n }\n}\n\n/** Whether the caller may use `capability`: what {@link authorizeCapability} checks, as a yes or no. */\nexport function allowsCapability(authority: ChangeAuthority, capability: DocCapability): boolean {\n const { grants, protection } = authority;\n if (protection && protectedCapabilities(protection).has(capability)) return false;\n return !grants || checkCapability(capability, grants.scope, grants.pdfBits, protection);\n}\n\n/**\n * Check only that no signature in the document took `capability` away\n * (`ProtectedDocument`). Annotation creates, updates and deletes take this\n * for `doc.annotate.modify`; their grants are checked per annotation.\n */\nexport function authorizeUnprotected(authority: ChangeAuthority, capability: DocCapability): void {\n const { protection } = authority;\n if (protection && protectedCapabilities(protection).has(capability)) {\n throw new EngineError(\n EngineErrorCode.ProtectedDocument,\n describeProtection(capability, protection),\n );\n }\n}\n\n/** What an annotation is and whose, as the write reads it. */\ninterface Owned {\n subtype?: string;\n userId?: string | null;\n groupId?: string | null;\n}\n\n/**\n * The capability writing an annotation of `subtype` takes. A widget belongs\n * to a form field, so creating, changing, moving or deleting one is\n * designing the form: `doc.forms.modify`. The annotation scopes\n * (`annotations:*`) never apply to it, and it has no group of its own.\n */\nexport function annotationWriteCapability(subtype: string | undefined): DocCapability {\n return subtype === 'widget' ? 'doc.forms.modify' : 'doc.annotate.modify';\n}\n\n/** The capabilities writing all of `annotations` takes, each once. */\nexport function annotationWriteCapabilities(\n annotations: readonly { readonly subtype?: string }[],\n): DocCapability[] {\n return [\n ...new Set(annotations.map((annotation) => annotationWriteCapability(annotation.subtype))),\n ];\n}\n\n/**\n * Check a widget write (see {@link annotationWriteCapability}): form design,\n * and no group to set. Returns the actor the write stamps: the editor.\n */\nfunction authorizeWidgetWrite(\n authority: AnnotationAuthority,\n groupId: string | null | undefined,\n): AnnotationActor | undefined {\n const { identity, grants } = authority;\n if (grants && !checkCapability('doc.forms.modify', grants.scope, grants.pdfBits)) {\n throw new PermissionDenied('doc.forms.modify', 'target');\n }\n if (typeof groupId === 'string') {\n throw new EngineError(\n EngineErrorCode.InvalidArg,\n \"a widget has no group of its own: a form field's group is the field's\",\n );\n }\n const actor: AnnotationActor = {\n ...(identity.userId !== undefined ? { userId: identity.userId } : {}),\n ...(identity.displayName !== undefined ? { displayName: identity.displayName } : {}),\n };\n return actor.userId || actor.displayName ? actor : undefined;\n}\n\n/**\n * Check a create of a `subtype` annotation in `groupId` (the identity's own\n * group without one) and return the actor the write stamps: the creator, in\n * that group. A group other than the identity's takes the authority a\n * reassignment takes. A widget takes form design instead, in no group.\n */\nexport function authorizeAnnotationCreate(\n authority: AnnotationAuthority,\n subtype: string,\n groupId: string | null | undefined,\n): AnnotationActor | undefined {\n if (subtype === 'widget') return authorizeWidgetWrite(authority, groupId);\n const { identity, grants } = authority;\n const group = groupId ?? identity.groupId;\n if (grants) {\n if (\n group !== undefined &&\n !checkSetGroup('annotations', group, identity.groupId, grants.scope)\n ) {\n throw new PermissionDenied(`annotations:set-group:group=${group}`, 'target');\n }\n const target = collabTargetOf({ userId: identity.userId, groupId: group });\n if (!checkCollab('create', target, grants.scope, identity, grants.pdfBits)) {\n throw new PermissionDenied('annotations:create', 'target');\n }\n }\n const actor: AnnotationActor = {\n ...(identity.userId !== undefined ? { userId: identity.userId } : {}),\n ...(group !== undefined ? { groupId: group } : {}),\n ...(identity.displayName !== undefined ? { displayName: identity.displayName } : {}),\n };\n return actor.userId || actor.groupId || actor.displayName ? actor : undefined;\n}\n\n/**\n * Check an update of the annotation `owner` describes and return the actor\n * the write stamps: the editor, and the group only when the patch reassigns\n * it. An existing group can be reassigned, never removed. A widget takes form\n * design instead, and its patch sets no group.\n */\nexport function authorizeAnnotationUpdate(\n authority: AnnotationAuthority,\n owner: Owned,\n patchGroupId: string | null | undefined,\n): AnnotationActor | undefined {\n if (owner.subtype === 'widget') return authorizeWidgetWrite(authority, patchGroupId);\n const { identity, grants } = authority;\n const target = collabTargetOf(owner);\n if (grants && !checkCollab('update', target, grants.scope, identity, grants.pdfBits)) {\n throw new PermissionDenied('annotations:update', 'target');\n }\n if (patchGroupId === null && target.groupId !== undefined) {\n throw new EngineError(EngineErrorCode.InvalidArg, \"an annotation's group can't be removed\");\n }\n const reassigning = typeof patchGroupId === 'string' && patchGroupId !== target.groupId;\n if (\n reassigning &&\n grants &&\n !checkSetGroup('annotations', patchGroupId, identity.groupId, grants.scope)\n ) {\n throw new PermissionDenied(`annotations:set-group:group=${patchGroupId}`, 'target');\n }\n const actor: AnnotationActor = {\n ...(identity.userId !== undefined ? { userId: identity.userId } : {}),\n ...(identity.displayName !== undefined ? { displayName: identity.displayName } : {}),\n ...(reassigning ? { groupId: patchGroupId } : {}),\n };\n return actor.userId || actor.groupId || actor.displayName ? actor : undefined;\n}\n\n/**\n * Check a delete of every annotation it removes (an annotation goes with its\n * thread and popups): all or nothing, `PermissionDenied` naming each one\n * refused. A widget takes form design, never the annotation scopes.\n */\nexport function authorizeAnnotationDelete(\n authority: AnnotationAuthority,\n members: readonly (Owned & { ref: AnnotationRef })[],\n): void {\n const { identity, grants } = authority;\n if (!grants) return;\n const mayDesign = checkCapability('doc.forms.modify', grants.scope, grants.pdfBits);\n const refused = members.filter((member) =>\n member.subtype === 'widget'\n ? !mayDesign\n : !checkCollab('delete', collabTargetOf(member), grants.scope, identity, grants.pdfBits),\n );\n if (refused.length > 0) {\n throw new PermissionDenied(\n 'annotations:delete',\n 'target',\n undefined,\n refused.map((member) => member.ref),\n );\n }\n}\n\n/** Whether a form-field write may fill in a field, or sign a signature field. */\nexport type FieldWriteAction = 'fill' | 'sign';\n\n/**\n * Check that the caller may `action` (fill in, or sign) the field in\n * `groupId`: `ProtectedDocument` when a signature in the document took the\n * capability away, `PermissionDenied` naming the scope it would take when\n * the grants don't reach the field's group.\n */\nexport function authorizeFieldWrite(\n authority: ChangeAuthority,\n groupId: string | null,\n action: FieldWriteAction,\n): void {\n authorizeUnprotected(authority, fieldCapability(action));\n if (!allowsFieldWrite(authority, groupId, action)) {\n throw new PermissionDenied(\n groupId === null ? fieldCapability(action) : `fields:${action}:group=${groupId}`,\n 'target',\n );\n }\n}\n\n/** Whether the caller may `action` the field in `groupId`: what {@link authorizeFieldWrite} checks. */\nexport function allowsFieldWrite(\n authority: ChangeAuthority,\n groupId: string | null,\n action: FieldWriteAction,\n): boolean {\n const { grants, protection } = authority;\n if (protection && protectedCapabilities(protection).has(fieldCapability(action))) return false;\n return !grants || checkFieldAction(action, groupId, grants.scope, grants.pdfBits, protection);\n}\n\n/**\n * Whether the caller may `action` some field: what a form verb checks\n * before it knows which fields it writes. Each field is then checked in\n * the write with {@link authorizeFieldWrite}.\n */\nexport function allowsSomeFieldWrite(\n authority: ChangeAuthority,\n action: FieldWriteAction,\n): boolean {\n const { grants, protection } = authority;\n if (protection && protectedCapabilities(protection).has(fieldCapability(action))) return false;\n return !grants || checkAnyFieldAction(action, grants.scope, grants.pdfBits, protection);\n}\n\n/**\n * Check that the caller may put a form field in `groupId`: their own\n * default group always, another with `fields:set-group` for it.\n */\nexport function authorizeFieldGroup(authority: ChangeAuthority, groupId: string): void {\n const { identity, grants } = authority;\n if (grants && !checkSetGroup('fields', groupId, identity.groupId, grants.scope)) {\n throw new PermissionDenied(`fields:set-group:group=${groupId}`, 'target');\n }\n}\n\n/** The broad capability a field action takes without a `fields:` scope. */\nfunction fieldCapability(action: FieldWriteAction): DocCapability {\n return action === 'fill' ? 'doc.forms.fill' : 'doc.sign';\n}\n"],"mappings":";;;;;;;;AAoBA,MAAa,oBAA6B;CAAE,MAAM;CAAG,QAAQ;CAAG,OAAO;CAAK,KAAK;AAAI;;AAGrF,MAAM,YAAqB;CAAE,MAAM;CAAG,OAAO;CAAG,QAAQ;CAAG,KAAK;AAAE;;;;;;;;;;;;AAalE,SAAgB,YAAY,SAAsD;CAChF,MAAM,QAAQ,QAAQ,SAAS;CAC/B,MAAM,UAAU,QAA0BA,+BAAAA,oBAAoB,KAAK,KAAK,KAAK;CAC7E,MAAM,OAAO,OAAO,QAAQ,QAAQ,KAAK;CACzC,OAAO;EACL;EACA;EACA,OAAO,OAAO,QAAQ,SAAS,IAAI;EACnC,MAAM,OAAO,QAAQ,QAAQ,IAAI;EACjC,KAAK,OAAO,QAAQ,OAAO,IAAI;CACjC;AACF;;;;;;;AAQA,SAAgB,eAAe,SAA8B;CAC3D,IAAI,CAAC,OAAO,UAAU,OAAO,KAAK,UAAU,OAAO,GAAG,OAAO;CAC7D,QAAU,UAAU,MAAO,OAAO;AACpC;;;;;;;;;ACjBA,SAAgB,kBACd,SACA,KACkB;CAClB,MAAM,EAAE,oBAAoB,sBAAsB,WAAW,CAAC;CAC9D,IAAI,uBAAuB,QAAQ,CAAC,IAAI,aACtC,MAAM,IAAIC,iBAAAA,iBAAiB,qBAAqB,oBAAoB;CAEtE,IAAI,sBAAsB,QAAQ,CAAC,IAAI,YACrC,MAAM,IAAIA,iBAAAA,iBAAiB,kBAAkB,mBAAmB;CAElE,OAAO;EACL,oBAAoB,sBAAsB,IAAI;EAC9C,mBAAmB,sBAAsB,uBAAuB,QAAQ,QAAQ,IAAI;CACtF;AACF;;;;;;;;;;;AA0BA,SAAgB,iBACd,SAGA,KACM;CACN,MAAM,EAAE,OAAO,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