@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.
Files changed (135) hide show
  1. package/dist/AnnotationList-DcyhF2kU.d.cts +27691 -0
  2. package/dist/AnnotationList-DcyhF2kU.d.ts +27691 -0
  3. package/dist/Change-Ct-dB8D5.cjs +1133 -0
  4. package/dist/Change-Ct-dB8D5.cjs.map +1 -0
  5. package/dist/Change-tMR34hTU.js +978 -0
  6. package/dist/Change-tMR34hTU.js.map +1 -0
  7. package/dist/DocumentRenderService-9IjSQEIU.cjs +121 -0
  8. package/dist/DocumentRenderService-9IjSQEIU.cjs.map +1 -0
  9. package/dist/DocumentRenderService-DFrZ9wfW.js +86 -0
  10. package/dist/DocumentRenderService-DFrZ9wfW.js.map +1 -0
  11. package/dist/{DocumentSecurityService-Ca6EK3-3.d.ts → DocumentSecurityService-D2zA4NKi.d.cts} +100 -112
  12. package/dist/{DocumentSecurityService-CIx1MT0T.d.cts → DocumentSecurityService-YJV9df8P.d.ts} +100 -112
  13. package/dist/LocalDocumentHandle-D02FMm-Z.cjs +53 -0
  14. package/dist/LocalDocumentHandle-D02FMm-Z.cjs.map +1 -0
  15. package/dist/LocalDocumentHandle-DAPdaOt_.js +30 -0
  16. package/dist/LocalDocumentHandle-DAPdaOt_.js.map +1 -0
  17. package/dist/LocalEngine-DBt2-GWF.d.ts +1649 -0
  18. package/dist/LocalEngine-IA9zh3Jh.d.cts +1649 -0
  19. package/dist/PageInsertBlankInput-CXHAM7l6.cjs +17 -0
  20. package/dist/PageInsertBlankInput-CXHAM7l6.cjs.map +1 -0
  21. package/dist/PageInsertBlankInput-DhVYVJ_S.js +12 -0
  22. package/dist/PageInsertBlankInput-DhVYVJ_S.js.map +1 -0
  23. package/dist/authority-BFp6XM04.cjs +2997 -0
  24. package/dist/authority-BFp6XM04.cjs.map +1 -0
  25. package/dist/authority-PuxpGFhJ.js +2506 -0
  26. package/dist/authority-PuxpGFhJ.js.map +1 -0
  27. package/dist/builders-DV62HA3I.js +165 -0
  28. package/dist/builders-DV62HA3I.js.map +1 -0
  29. package/dist/builders-DgTAj_tP.cjs +188 -0
  30. package/dist/builders-DgTAj_tP.cjs.map +1 -0
  31. package/dist/calibrate-DJbi1wuK.cjs +3012 -0
  32. package/dist/calibrate-DJbi1wuK.cjs.map +1 -0
  33. package/dist/calibrate-nQFgCuki.js +2461 -0
  34. package/dist/calibrate-nQFgCuki.js.map +1 -0
  35. package/dist/charmap-Cprti1ta.js +239 -0
  36. package/dist/charmap-Cprti1ta.js.map +1 -0
  37. package/dist/charmap-aYlefQP9.cjs +304 -0
  38. package/dist/charmap-aYlefQP9.cjs.map +1 -0
  39. package/dist/conformance.cjs +18146 -5258
  40. package/dist/conformance.cjs.map +1 -1
  41. package/dist/conformance.d.cts +1024 -170
  42. package/dist/conformance.d.ts +1024 -170
  43. package/dist/conformance.js +18148 -5309
  44. package/dist/conformance.js.map +1 -1
  45. package/dist/format-Bp3QFSH1.cjs +574 -0
  46. package/dist/format-Bp3QFSH1.cjs.map +1 -0
  47. package/dist/format-Dgg428Kb.js +461 -0
  48. package/dist/format-Dgg428Kb.js.map +1 -0
  49. package/dist/index.cjs +342 -116
  50. package/dist/index.d.cts +2 -2
  51. package/dist/index.d.ts +2 -2
  52. package/dist/index.js +14 -5
  53. package/dist/pageRefs-B3ur7Ckm.cjs +51 -0
  54. package/dist/pageRefs-B3ur7Ckm.cjs.map +1 -0
  55. package/dist/pageRefs-DkbuxSCV.js +40 -0
  56. package/dist/pageRefs-DkbuxSCV.js.map +1 -0
  57. package/dist/public.cjs +59 -0
  58. package/dist/public.d.cts +5 -0
  59. package/dist/public.d.ts +5 -0
  60. package/dist/public.js +9 -0
  61. package/dist/resolveAnnotationDraft-7Ke4nV7F.cjs +3646 -0
  62. package/dist/resolveAnnotationDraft-7Ke4nV7F.cjs.map +1 -0
  63. package/dist/resolveAnnotationDraft-CUpf0SMh.js +3167 -0
  64. package/dist/resolveAnnotationDraft-CUpf0SMh.js.map +1 -0
  65. package/dist/{resolver-inAVzsWt.js → resolver-BBggAxQc.js} +298 -145
  66. package/dist/resolver-BBggAxQc.js.map +1 -0
  67. package/dist/{resolver-CYVNV4hn.cjs → resolver-BWSWSF6R.cjs} +351 -144
  68. package/dist/resolver-BWSWSF6R.cjs.map +1 -0
  69. package/dist/runtime-BaDKjxiu.d.ts +1959 -0
  70. package/dist/runtime-CWEuiwbk.d.cts +1959 -0
  71. package/dist/runtime.cjs +986 -297
  72. package/dist/runtime.cjs.map +1 -1
  73. package/dist/runtime.d.cts +5 -1372
  74. package/dist/runtime.d.ts +5 -1372
  75. package/dist/runtime.js +634 -179
  76. package/dist/runtime.js.map +1 -1
  77. package/dist/schema-6S2VmlAj.js +2087 -0
  78. package/dist/schema-6S2VmlAj.js.map +1 -0
  79. package/dist/schema-miH6tWQC.cjs +3046 -0
  80. package/dist/schema-miH6tWQC.cjs.map +1 -0
  81. package/dist/schemas-BE2QGOit.js +1851 -0
  82. package/dist/schemas-BE2QGOit.js.map +1 -0
  83. package/dist/schemas-DljJR9ut.cjs +2798 -0
  84. package/dist/schemas-DljJR9ut.cjs.map +1 -0
  85. package/dist/subtype-CG4WpIRj.js +129 -0
  86. package/dist/subtype-CG4WpIRj.js.map +1 -0
  87. package/dist/subtype-aDt5TFmK.cjs +158 -0
  88. package/dist/subtype-aDt5TFmK.cjs.map +1 -0
  89. package/dist/validation.cjs +578 -0
  90. package/dist/validation.cjs.map +1 -0
  91. package/dist/validation.d.cts +174 -0
  92. package/dist/validation.d.ts +174 -0
  93. package/dist/validation.js +571 -0
  94. package/dist/validation.js.map +1 -0
  95. package/dist/value-BFS1R8ek.cjs +435 -0
  96. package/dist/value-BFS1R8ek.cjs.map +1 -0
  97. package/dist/value-Dhc8eYcx.js +340 -0
  98. package/dist/value-Dhc8eYcx.js.map +1 -0
  99. package/dist/viewport-CHG9qQUb.cjs +671 -0
  100. package/dist/viewport-CHG9qQUb.cjs.map +1 -0
  101. package/dist/viewport-DQR5LyX3.js +540 -0
  102. package/dist/viewport-DQR5LyX3.js.map +1 -0
  103. package/dist/wire.cjs +1242 -420
  104. package/dist/wire.cjs.map +1 -1
  105. package/dist/wire.d.cts +14840 -830
  106. package/dist/wire.d.ts +14840 -830
  107. package/dist/wire.js +985 -261
  108. package/dist/wire.js.map +1 -1
  109. package/package.json +10 -1
  110. package/dist/AbortError-DwuHPK_I.js +0 -27
  111. package/dist/AbortError-DwuHPK_I.js.map +0 -1
  112. package/dist/AbortError-P0RU0Mgg.cjs +0 -38
  113. package/dist/AbortError-P0RU0Mgg.cjs.map +0 -1
  114. package/dist/AnnotationListSnapshot-D9R5n2Kf.d.cts +0 -7101
  115. package/dist/AnnotationListSnapshot-D9R5n2Kf.d.ts +0 -7101
  116. package/dist/Engine-EWWHhEIi.d.ts +0 -1277
  117. package/dist/Engine-FNaAEjfb.d.cts +0 -1277
  118. package/dist/derive-BbsDk_Kz.cjs +0 -880
  119. package/dist/derive-BbsDk_Kz.cjs.map +0 -1
  120. package/dist/derive-DAFJolWu.js +0 -647
  121. package/dist/derive-DAFJolWu.js.map +0 -1
  122. package/dist/format-Bbphf4zR.js +0 -435
  123. package/dist/format-Bbphf4zR.js.map +0 -1
  124. package/dist/format-D_epWlob.cjs +0 -518
  125. package/dist/format-D_epWlob.cjs.map +0 -1
  126. package/dist/resolver-CYVNV4hn.cjs.map +0 -1
  127. package/dist/resolver-inAVzsWt.js.map +0 -1
  128. package/dist/schemas-CFQGvWiu.js +0 -3243
  129. package/dist/schemas-CFQGvWiu.js.map +0 -1
  130. package/dist/schemas-D0g6tKa9.cjs +0 -4694
  131. package/dist/schemas-D0g6tKa9.cjs.map +0 -1
  132. package/dist/viewport-BWeNHZmb.cjs +0 -3503
  133. package/dist/viewport-BWeNHZmb.cjs.map +0 -1
  134. package/dist/viewport-CvMcadfQ.js +0 -3072
  135. package/dist/viewport-CvMcadfQ.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"calibrate-nQFgCuki.js","names":["isBlob","read","NO_BOX"],"sources":["../src/dto/PdfLinkTarget.ts","../src/geometry/printSize.ts","../src/geometry/renderSize.ts","../src/geometry/pageTransform.ts","../src/geometry/pageSpace.ts","../src/dto/PageGeometrySnapshot.ts","../src/promise/AbortError.ts","../src/identity/OutlineItemRef.ts","../src/resource/BinarySource.ts","../src/resource/binaryMetadata.ts","../src/annotation/resources.ts","../src/transfer/bundleLimits.ts","../src/transfer/codec.ts","../src/transfer/AnnotationBundle.ts","../src/transfer/AnnotationTransfer.ts","../src/dto/Attachment.ts","../src/annotation/appearanceTurn.ts","../src/annotation/resolve/applyAnnotationPatch.ts","../src/annotation/defaults.ts","../src/pageSpace/destinations.ts","../src/pageSpace/measure.ts","../src/pageSpace/annotations.ts","../src/text/layout.ts","../src/pageSpace/text.ts","../src/annotation/drawnPoints.ts","../src/annotation/resolve/annotationOfDraft.ts","../src/pageSpace/helpers.ts","../src/search/fold.ts","../src/measure/units.ts","../src/measure/calibrate.ts"],"sourcesContent":["import type { PdfActionNode, PdfActionTree } from './PdfAction';\nimport type { PageDestination } from './PdfDestination';\n\n/**\n * Where a link annotation points, normalized. A link may carry either a\n * direct `/Dest` or an `/A` action (ISO 32000-1 §12.5.6.5); to a viewer a\n * `/Dest` and a `/A GoTo` are the same intent, so the engine collapses both\n * onto the `goto` arm — clients never see the raw two-shape split (a\n * `target.action.destination` double-wrap). Named destinations are resolved\n * to explicit ones engine-side, the same rule {@link PageDestination}\n * documents.\n *\n * Arm names follow the `PdfActionType` vocabulary (`goto`, `uri`,\n * `goto-remote`, `launch`, `javascript`) so the two action-shaped surfaces\n * never drift.\n *\n * `goto-remote`, `launch`, and `javascript` are read-only in v1: the\n * engine reports them so a client can display/inspect (or, for\n * `javascript`, hand the link to the scripting orchestrator), but never\n * follows or executes them here, and refuses to write them (see\n * {@link PdfLinkTargetWritable}). `javascript` deliberately carries no\n * script payload — the text already rides the base\n * `actions.activate` model, which is the scripting plane's single home\n * for action scripts. `unsupported` preserves round-trip for action\n * types the reader doesn't model. A `goto` goes to a {@link PageDestination};\n * the engine's readers use `PdfLinkTarget<PdfDestination>`.\n */\nexport type PdfLinkTarget<Destination = PageDestination> =\n | { kind: 'goto'; destination: Destination }\n | { kind: 'uri'; uri: string }\n | { kind: 'goto-remote'; file: string }\n | { kind: 'launch'; path: string }\n | { kind: 'javascript' }\n /** `/S /Named` — a viewer verb (`NextPage`, `PrevPage`, `FirstPage`,\n * `LastPage`, …), as the file names it; common in TOC/nav links. */\n | { kind: 'named'; name: string }\n | { kind: 'unsupported' };\n\n/** The page-turning viewer verbs every PDF app knows (ISO 32000 Table 211). */\nexport type PdfStandardNamedAction = 'NextPage' | 'PrevPage' | 'FirstPage' | 'LastPage';\n\n/**\n * The subset of {@link PdfLinkTarget} that drafts/patches may author:\n * in-document destinations, URIs and the four standard page-turning verbs.\n * Keeping `goto-remote`/`launch` out of the write surface is deliberate\n * (executable-shaped actions are a security liability the viewer never\n * needs to author), another app's own named verb is only sent back as read,\n * and `unsupported` carries nothing to write.\n */\nexport type PdfLinkTargetWritable<Destination = PageDestination> =\n | Extract<PdfLinkTarget<Destination>, { kind: 'goto' | 'uri' }>\n | { kind: 'named'; name: PdfStandardNamedAction };\n\n/**\n * The action tree the engine writes for a target a write can make: one URI,\n * GoTo or Named action, as a read of it returns it. Links and outline items\n * both write their targets this way.\n */\nexport function actionTreeOf<Destination>(\n target: PdfLinkTargetWritable<Destination>,\n): PdfActionTree<Destination> {\n const root: PdfActionNode<Destination> =\n target.kind === 'uri'\n ? { type: 'uri', subtype: 'URI', uri: target.uri, isMap: false, next: [] }\n : target.kind === 'goto'\n ? { type: 'goto', subtype: 'GoTo', destination: target.destination, next: [] }\n : { type: 'named', subtype: 'Named', name: target.name, next: [] };\n return { root, incomplete: false, warningFlags: 0, warnings: [] };\n}\n","import type { PrintDpi } from '../dto/PageRender';\n\n/**\n * The paper a print picture is sized for, in points: the larger of A4\n * (595 × 842) and Letter (612 × 792) on each side.\n */\nexport const PRINT_PAPER = { long: 842, short: 612 } as const;\n\n/**\n * The scale (pixels per point) of a print picture of a page `size` points\n * big at `dpi` dots per inch of paper. A page that fits on the paper is\n * drawn at its own size at that DPI; a bigger one gets no more pixels than\n * it needs shrunk to fit, since the printer would throw the rest away. An\n * A0 drawing printed on office paper needs no more; printed at its own\n * size, it needs vectors (the print copy). Portrait or landscape doesn't\n * matter.\n */\nexport function printScale(size: { width: number; height: number }, dpi: PrintDpi): number {\n const long = Math.max(size.width, size.height);\n const short = Math.min(size.width, size.height);\n const fit = Math.min(1, PRINT_PAPER.long / long, PRINT_PAPER.short / short);\n return (dpi / 72) * fit;\n}\n","import type { PdfRotation } from './primitives';\nimport { printScale } from './printSize';\nimport type { PageRenderViewport } from '../dto/PageRender';\nimport { EngineError } from '../errors/EngineError';\nimport { EngineErrorCode } from '../errors/EngineErrorCode';\n\n/**\n * The pixel size of a render: an area of `width` × `height` points, turned\n * by `rotation` (width and height swap on a quarter turn) and sized by\n * `viewport`. A `dpi` viewport sizes a print picture for its paper\n * ({@link printScale}). The local worker allocates exactly this; the cloud\n * client reports it without rendering. `InvalidArg` for a viewport that\n * isn't positive.\n */\nexport function renderSize(\n area: { width: number; height: number },\n rotation: PdfRotation,\n viewport: PageRenderViewport,\n): { width: number; height: number } {\n const swap = rotation === 90 || rotation === 270;\n const baseWidth = swap ? area.height : area.width;\n const baseHeight = swap ? area.width : area.height;\n\n if (viewport.kind === 'width') {\n if (!Number.isFinite(viewport.width) || viewport.width <= 0) {\n throw new EngineError(EngineErrorCode.InvalidArg, 'render viewport width must be positive');\n }\n const width = Math.max(1, Math.round(viewport.width));\n return { width, height: Math.max(1, Math.round((width * baseHeight) / baseWidth)) };\n }\n\n const scale = viewport.kind === 'dpi' ? printScale(area, viewport.dpi) : (viewport.scale ?? 1);\n if (!Number.isFinite(scale) || scale <= 0) {\n throw new EngineError(EngineErrorCode.InvalidArg, 'render viewport scale must be positive');\n }\n return {\n width: Math.max(1, Math.round(baseWidth * scale)),\n height: Math.max(1, Math.round(baseHeight * scale)),\n };\n}\n","import type { PageBox, PagePoint, PageQuad } from './pageSpace';\nimport type { PdfRotation, PdfSize } from './primitives';\nimport { renderSize } from './renderSize';\nimport type { PageRenderTarget, PageRenderViewport } from '../dto/PageRender';\nimport { EngineError } from '../errors/EngineError';\nimport { EngineErrorCode } from '../errors/EngineErrorCode';\n\n/**\n * Page space and the pixels of a render. A render draws an area of the page\n * (the whole page, or a `target` rect), turned clockwise by `rotation`, onto\n * `width` × `height` pixels. The size is rounded to whole pixels and the area\n * is stretched to fill them exactly, so each axis has its own scale. The\n * renderer draws with {@link renderMatrix}, so a transform always matches the\n * pixels.\n */\n\n/**\n * A 2D transform as the six numbers of a CSS `matrix()` or a canvas\n * `setTransform()`: `x' = a·x + c·y + e`, `y' = b·x + d·y + f`.\n */\nexport type PageRenderMatrix = readonly [\n a: number,\n b: number,\n c: number,\n d: number,\n e: number,\n f: number,\n];\n\n/** A point in an image's pixels, from its top-left corner, y down. */\nexport interface PixelPoint {\n x: number;\n y: number;\n}\n\n/** A box in an image's pixels: its top-left corner and its size. */\nexport interface PixelBox {\n x: number;\n y: number;\n width: number;\n height: number;\n}\n\n/** A page-space quad in an image's pixels: each corner keeps its name. */\nexport interface PixelQuad {\n upperLeft: PixelPoint;\n upperRight: PixelPoint;\n lowerLeft: PixelPoint;\n lowerRight: PixelPoint;\n}\n\n/** Converts between page space and the pixels of one render. */\nexport interface PageRenderTransform {\n /** The image's width in pixels. */\n readonly width: number;\n /** The image's height in pixels. */\n readonly height: number;\n /** Page space to pixels. */\n readonly matrix: PageRenderMatrix;\n // Most specific first: a box is also shaped like a point.\n /** Where a point, a box or a quad of the page lands in the image. */\n pageToPixels(quad: PageQuad): PixelQuad;\n pageToPixels(box: PageBox): PixelBox;\n pageToPixels(point: PagePoint): PixelPoint;\n /** The page point or box under a point or a box of the image. */\n pixelsToPage(box: PixelBox): PageBox;\n pixelsToPage(point: PixelPoint): PagePoint;\n}\n\n/** The settings a render is made with that decide where its pixels are. */\nexport interface PageTransformOptions {\n viewport?: PageRenderViewport;\n rotation?: PdfRotation;\n target?: PageRenderTarget;\n}\n\n/**\n * The transform of the image a render with `options` makes of `page`, without\n * rendering: its size, rounding included, and the conversion between page\n * space and its pixels. Takes the page's layout (`doc.pages.list()`).\n * `InvalidArg` for a viewport that isn't positive or a target without area.\n */\nexport function pageTransform(\n page: { size: PdfSize },\n options: PageTransformOptions = {},\n): PageRenderTransform {\n const target = options.target;\n return renderAreaTransform(\n target?.kind === 'rect'\n ? renderTargetArea(target.rect)\n : { x: 0, y: 0, width: page.size.width, height: page.size.height },\n options,\n );\n}\n\n/** The transform of a render of `area` with `options`' turn and size. */\nexport function renderAreaTransform(\n area: PageBox,\n options: Pick<PageTransformOptions, 'viewport' | 'rotation'>,\n): PageRenderTransform {\n const rotation = options.rotation ?? 0;\n const { width, height } = renderSize(area, rotation, options.viewport ?? { kind: 'scale' });\n return renderTransform(area, rotation, width, height);\n}\n\n/**\n * A render target's area with its sides in order, as the renderer takes it.\n * `InvalidArg` for a rect without area, or one that isn't numbers.\n */\nexport function renderTargetArea(rect: PageBox): PageBox {\n const { x, y, width, height } = rect;\n if (![x, y, width, height].every(Number.isFinite) || width === 0 || height === 0) {\n throw new EngineError(EngineErrorCode.InvalidArg, 'render rect must have positive area');\n }\n return {\n x: Math.min(x, x + width),\n y: Math.min(y, y + height),\n width: Math.abs(width),\n height: Math.abs(height),\n };\n}\n\n/**\n * The matrix that draws `area` of the page, turned clockwise by `rotation`,\n * onto `width` × `height` pixels. The renderer draws with it.\n */\nexport function renderMatrix(\n area: PageBox,\n rotation: PdfRotation,\n width: number,\n height: number,\n): PageRenderMatrix {\n const { x, y } = area;\n const w = area.width;\n const h = area.height;\n switch (rotation) {\n case 0:\n return [width / w, 0, 0, height / h, (-width / w) * x, (-height / h) * y];\n case 90:\n return [0, height / w, -width / h, 0, (width / h) * (y + h), (-height / w) * x];\n case 180:\n return [-width / w, 0, 0, -height / h, (width / w) * (x + w), (height / h) * (y + h)];\n case 270:\n return [0, -height / w, width / h, 0, (-width / h) * y, (height / w) * (x + w)];\n }\n}\n\n/** The transform of a render of `area`, turned by `rotation`, drawn onto `width` × `height` pixels. */\nexport function renderTransform(\n area: PageBox,\n rotation: PdfRotation,\n width: number,\n height: number,\n): PageRenderTransform {\n const matrix = renderMatrix(area, rotation, width, height);\n const inverse = inverseOf(matrix);\n return {\n width,\n height,\n matrix,\n pageToPixels: ((value: PagePoint | PageBox | PageQuad) =>\n mapped(matrix, value)) as PageRenderTransform['pageToPixels'],\n pixelsToPage: ((value: PixelPoint | PixelBox) =>\n mapped(inverse, value)) as PageRenderTransform['pixelsToPage'],\n };\n}\n\nfunction inverseOf([a, b, c, d, e, f]: PageRenderMatrix): PageRenderMatrix {\n const det = a * d - b * c;\n return [d / det, -b / det, -c / det, a / det, (c * f - d * e) / det, (b * e - a * f) / det];\n}\n\nfunction mappedPoint(m: PageRenderMatrix, { x, y }: PagePoint): PagePoint {\n return { x: m[0] * x + m[2] * y + m[4], y: m[1] * x + m[3] * y + m[5] };\n}\n\n/** A point, a box or a quad through `m`. A box stays a box: every turn is a quarter turn. */\nfunction mapped(\n m: PageRenderMatrix,\n value: PagePoint | PageBox | PageQuad,\n): PagePoint | PageBox | PageQuad {\n if ('upperLeft' in value) {\n return {\n upperLeft: mappedPoint(m, value.upperLeft),\n upperRight: mappedPoint(m, value.upperRight),\n lowerLeft: mappedPoint(m, value.lowerLeft),\n lowerRight: mappedPoint(m, value.lowerRight),\n };\n }\n if ('width' in value) {\n const from = mappedPoint(m, value);\n const to = mappedPoint(m, { x: value.x + value.width, y: value.y + value.height });\n return {\n x: Math.min(from.x, to.x),\n y: Math.min(from.y, to.y),\n width: Math.abs(to.x - from.x),\n height: Math.abs(to.y - from.y),\n };\n }\n return mappedPoint(m, value);\n}\n","/**\n * Page space: where things are on a page as you see it. x runs right from the\n * left edge of the page's visible box, y runs down from its top edge, in PDF\n * units, on the page as stored: a page's own turn (`/Rotate`) never changes a\n * number. The visible box is the crop box inside the media box\n * (`pageBoxesOf`).\n *\n * The file keeps PDF user space (y up, its origin wherever the file puts it).\n * These convert between the two given the page's visible box in PDF space.\n * The conversion is a shift and a flip, nothing else, so it is exact: a value\n * read from a file (a 32-bit float) converts and converts back to the same\n * number.\n */\n\nimport type { PdfPoint, PdfQuad, PdfRect } from './primitives';\n\n/** A point in page space: x from the visible page's left edge, y down from its top edge. */\nexport interface PagePoint {\n x: number;\n y: number;\n}\n\n/** A box in page space: `x, y` is its top-left corner. */\nexport interface PageBox {\n x: number;\n y: number;\n width: number;\n height: number;\n}\n\n/**\n * A quad in page space, with `PdfQuad`'s corner names. The names belong to\n * the text's frame, so the flip to page space keeps them.\n */\nexport interface PageQuad {\n upperLeft: PagePoint;\n upperRight: PagePoint;\n lowerLeft: PagePoint;\n lowerRight: PagePoint;\n}\n\n/** A point in the file's coordinates, in page space. `visible` is the page's visible box. */\nexport function pagePointOf(point: PdfPoint, visible: PdfRect): PagePoint {\n return { x: point.x - visible.left, y: visible.top - point.y };\n}\n\n/** A page-space point in the file's coordinates. */\nexport function pdfPointOf(point: PagePoint, visible: PdfRect): PdfPoint {\n return { x: point.x + visible.left, y: visible.top - point.y };\n}\n\n/** A normalized rect in the file's coordinates, in page space. */\nexport function pageBoxOf(rect: PdfRect, visible: PdfRect): PageBox {\n return {\n x: rect.left - visible.left,\n y: visible.top - rect.top,\n width: rect.right - rect.left,\n height: rect.top - rect.bottom,\n };\n}\n\n/** A page-space box in the file's coordinates, keys in `normalizePdfRect`'s order. */\nexport function pdfRectOf(box: PageBox, visible: PdfRect): PdfRect {\n const left = box.x + visible.left;\n const top = visible.top - box.y;\n return { left, right: left + box.width, bottom: top - box.height, top };\n}\n\nexport function pageQuadOf(quad: PdfQuad, visible: PdfRect): PageQuad {\n return {\n upperLeft: pagePointOf(quad.upperLeft, visible),\n upperRight: pagePointOf(quad.upperRight, visible),\n lowerLeft: pagePointOf(quad.lowerLeft, visible),\n lowerRight: pagePointOf(quad.lowerRight, visible),\n };\n}\n\nexport function pdfQuadOf(quad: PageQuad, visible: PdfRect): PdfQuad {\n return {\n upperLeft: pdfPointOf(quad.upperLeft, visible),\n upperRight: pdfPointOf(quad.upperRight, visible),\n lowerLeft: pdfPointOf(quad.lowerLeft, visible),\n lowerRight: pdfPointOf(quad.lowerRight, visible),\n };\n}\n\n// ── mirroring ──\n//\n// Math written for the file's coordinates (y up) runs unchanged on page-space\n// values flipped top to bottom: the flip turns page space into the file's\n// coordinates shifted, and none of that math depends on where the origin is.\n// Flipping needs no page box and is exact.\n\n/** A page-space point flipped into y-up coordinates. */\nexport const mirroredPoint = (point: { x: number; y: number }): PdfPoint => ({\n x: point.x,\n y: -point.y,\n});\n\n/** A y-up point flipped back into page space. */\nexport const unmirroredPoint = (point: PdfPoint): PagePoint => ({ x: point.x, y: -point.y });\n\n/** A page-space box flipped into a y-up rect. */\nexport const mirroredRect = (box: PageBox): PdfRect => ({\n left: box.x,\n right: box.x + box.width,\n bottom: -(box.y + box.height),\n top: -box.y,\n});\n\n/** A y-up rect flipped back into a page-space box. */\nexport const unmirroredBox = (rect: PdfRect): PageBox => ({\n x: rect.left,\n y: -rect.top,\n width: rect.right - rect.left,\n height: rect.top - rect.bottom,\n});\n\nexport const mirroredQuad = (quad: PageQuad): PdfQuad => ({\n upperLeft: mirroredPoint(quad.upperLeft),\n upperRight: mirroredPoint(quad.upperRight),\n lowerLeft: mirroredPoint(quad.lowerLeft),\n lowerRight: mirroredPoint(quad.lowerRight),\n});\n\nexport const unmirroredQuad = (quad: PdfQuad): PageQuad => ({\n upperLeft: unmirroredPoint(quad.upperLeft),\n upperRight: unmirroredPoint(quad.upperRight),\n lowerLeft: unmirroredPoint(quad.lowerLeft),\n lowerRight: unmirroredPoint(quad.lowerRight),\n});\n","import { pdfQuadBounds } from '../geometry/convert';\nimport type { PdfQuad, PdfRect } from '../geometry/primitives';\nimport type { Coordinates, PageCoordinates, PdfCoordinates } from '../pageSpace/coordinates';\n\n/**\n * One upright character's geometry: its boxes, in page space.\n *\n * `loose` is the loose char cell (pdfium `FPDFText_GetLooseCharBox`): the\n * font-metric box covering the full glyph cell without regard to the actual\n * glyph shape. Always present (zeroed and `empty` for degenerate glyphs);\n * it's the box selection envelopes are built from.\n *\n * `tight` is the tight char box (pdfium `FPDFText_GetCharBox`): the box\n * hugging the actual glyph shape. Optional — absent for empty/whitespace\n * glyphs that have no real outline.\n *\n * `space` and `empty` are present, and `true`, only for a space and for a\n * character with no box of its own.\n */\nexport interface PageGeometryGlyph<C extends Coordinates = PageCoordinates> {\n loose: C['box'];\n tight?: C['box'];\n space?: true;\n empty?: true;\n}\n\n/**\n * One non-upright character's geometry: the exact oriented cells, in page\n * space (not a local frame). Each cell's corners are named in the glyph's\n * own upright frame, as every quad's are (see `PdfQuad`).\n *\n * Degenerate glyphs carry a zeroed `loose` quad and `empty`, mirroring the\n * upright variant's zeroed-box convention.\n */\nexport interface RotatedGeometryGlyph<C extends Coordinates = PageCoordinates> {\n loose: C['quad'];\n tight?: C['quad'];\n space?: true;\n empty?: true;\n}\n\n/**\n * A run whose char matrix is upright — byte-identical to the wire shape that\n * predates orientation support, so upright documents never pay for it.\n */\nexport interface UprightGeometryRun<C extends Coordinates = PageCoordinates> {\n rect: C['box'];\n /** The run's first character; it covers `glyphs.length` characters from here. */\n start: number;\n glyphs: PageGeometryGlyph<C>[];\n fontSize?: number;\n}\n\n/**\n * A run whose char matrix is not upright (rotated, sheared, or mirrored).\n *\n * `rect` stays a page-space AABB (culling), like every other wire rect.\n * `rotation` is how far the text is turned from upright, in degrees\n * clockwise as the page shows it (0 up to 360), like every other `rotation`:\n * text that reads straight up the page is 270. Note a shear-only run has\n * `rotation === 0` and still uses this variant — its cells are\n * parallelograms an AABB would misrepresent. `ascentFlip` is true when the\n * ascent vector maps opposite the rotated frame's +y (mirrored /\n * negative-determinant content).\n */\nexport interface RotatedGeometryRun<C extends Coordinates = PageCoordinates> {\n rect: C['box'];\n /** The run's first character; it covers `glyphs.length` characters from here. */\n start: number;\n glyphs: RotatedGeometryGlyph<C>[];\n /** Degrees clockwise, 0 up to 360. */\n rotation: number;\n ascentFlip: boolean;\n fontSize?: number;\n}\n\n/**\n * One text run (contiguous glyphs sharing a text object and orientation).\n * A discriminated union so consumers cannot read axis-aligned boxes off\n * rotated text by accident — handling orientation is a compile-time\n * obligation, not a runtime discovery. Narrow with\n * {@link isRotatedGeometryRun}, or use the uniform `pageGlyphLooseQuad` /\n * `pageGlyphLooseBounds` views.\n */\nexport type PageGeometryRun<C extends Coordinates = PageCoordinates> =\n | UprightGeometryRun<C>\n | RotatedGeometryRun<C>;\n\n/**\n * Geometry-only text layout for one page, in page space: points from the\n * top-left of the page's visible box, y down.\n *\n * Pure content, addressed and cached by `contentVersion`.\n */\nexport interface PageGeometrySnapshot<C extends Coordinates = PageCoordinates> {\n runs: PageGeometryRun<C>[];\n}\n\n/** Narrowing guard: is this run the rotated (non-upright) variant? */\nexport function isRotatedGeometryRun<C extends Coordinates>(\n run: PageGeometryRun<C>,\n): run is RotatedGeometryRun<C> {\n return 'rotation' in run;\n}\n\n/**\n * Uniform oriented-cell view over either run variant, in the file's\n * coordinates: the glyph's loose cell as a quad (synthesized from the box\n * corners when the run is upright).\n */\nexport function glyphLooseQuad(run: PageGeometryRun<PdfCoordinates>, index: number): PdfQuad {\n if (isRotatedGeometryRun(run)) return run.glyphs[index].loose;\n const b = run.glyphs[index].loose;\n return {\n upperLeft: { x: b.left, y: b.top },\n upperRight: { x: b.right, y: b.top },\n lowerLeft: { x: b.left, y: b.bottom },\n lowerRight: { x: b.right, y: b.bottom },\n };\n}\n\n/**\n * Uniform AABB view over either run variant, in the file's coordinates: the\n * glyph's loose box, or the\n * enclosing bounds of its oriented cell when the run is rotated. The\n * conservative envelope for consumers that genuinely want a box (culling,\n * scroll targets) — never a substitute for handling orientation in geometry\n * that gets drawn.\n */\nexport function glyphLooseBounds(run: PageGeometryRun<PdfCoordinates>, index: number): PdfRect {\n if (isRotatedGeometryRun(run)) return pdfQuadBounds(run.glyphs[index].loose);\n return run.glyphs[index].loose;\n}\n","import { EngineError } from '../errors/EngineError';\nimport { EngineErrorCode } from '../errors/EngineErrorCode';\n\n/**\n * What a cancelled call rejects with: an `EngineError` with code `Aborted`,\n * named `AbortError` like the DOM's, so both `EngineError.is(err,\n * EngineErrorCode.Aborted)` and `err.name === 'AbortError'` recognise it.\n */\nexport class AbortError extends EngineError {\n override readonly name: string = 'AbortError';\n readonly reason: unknown;\n\n constructor(reason?: unknown) {\n super(EngineErrorCode.Aborted, reasonMessage(reason));\n this.reason = reason;\n }\n}\n\nexport function isAbortError(value: unknown): value is AbortError {\n return value instanceof AbortError || (value as { name?: string } | null)?.name === 'AbortError';\n}\n\nfunction reasonMessage(reason: unknown): string {\n if (reason == null) return 'aborted';\n if (typeof reason === 'string') return reason;\n if (reason instanceof Error) return reason.message || 'aborted';\n try {\n return JSON.stringify(reason);\n } catch {\n return 'aborted';\n }\n}\n","/**\n * How callers address an item of the document's outline — the outline-plane\n * sibling of `PageRef`, `AnnotationRef` and `FormFieldRef`.\n *\n * `objectNumber` is the indirect object number of the outline item\n * dictionary. ISO 32000-2 §12.3.3 requires every item to be an indirect\n * object (its siblings and parent refer to it), the layer runtime never\n * renumbers, and a deleted item's number is never given to anything else —\n * so it is the item's name for the life of the document. A create can name\n * it before the item exists (`doc.objectNumbers`). Like `PageRef`, this is\n * the only kind.\n */\nexport type OutlineItemRef = { kind: 'objectNumber'; objectNumber: number };\n\n/** Build the address for an outline item from its object number. */\nexport function toOutlineItemRef(objectNumber: number): OutlineItemRef {\n return { kind: 'objectNumber', objectNumber };\n}\n\n/** Structural equality for two outline item addresses. */\nexport function outlineItemRefsEqual(a: OutlineItemRef, b: OutlineItemRef): boolean {\n return a.kind === b.kind && a.objectNumber === b.objectNumber;\n}\n","/**\n * Binary payloads of a call: a document attachment's file, a signature's\n * appearance, the pages to insert. Bytes are a call argument, never engine\n * state. On the way out they become a `WireResourceMap` that travels beside\n * the JSON (worker: transferable buffers; cloud: multipart parts). After the\n * call, the only durable home for the bytes is the PDF itself. Annotations\n * take theirs by role, as `AnnotationResources` (`annotation/resources.ts`).\n */\n\n/**\n * Richest accepted input for a binary field. `mimeType` is advisory only —\n * every engine sniffs magic bytes and the sniffed format wins (the server\n * cannot trust a declared type anyway).\n */\nexport type BinarySource = Uint8Array | Blob | BinaryPayload;\n\nexport interface BinaryPayload {\n data: Uint8Array | Blob;\n /** Advisory only — engines always sniff magic bytes. */\n mimeType?: string;\n /** Optional display/file name (multipart `filename`, future /UF). */\n name?: string;\n}\n\n/**\n * A resolved binary payload in wire form: a private copy of the caller's\n * bytes, owned by the call and ready to ship (worker transfer list or\n * multipart part body). Ownership is the whole point: the local engine puts\n * `bytes` on a postMessage transfer list, which detaches the buffer, and a\n * `BinarySource` is a borrowed argument — never the caller's buffer to lose.\n * Blob sources yield fresh bytes by construction; Uint8Array sources are\n * copied here so a full-span view is not silently aliased and killed.\n */\nexport interface WireResource {\n bytes: ArrayBuffer;\n mimeType?: string;\n name?: string;\n}\n\n/** Keyed resources accompanying one mutation. Keys are allocator-generated (`r0`, `r1`, …). */\nexport type WireResourceMap = Record<string, WireResource>;\n\nfunction isBlob(value: unknown): value is Blob {\n return typeof Blob !== 'undefined' && value instanceof Blob;\n}\n\n/**\n * Copy a Uint8Array view into a fresh, exactly-sized ArrayBuffer the call\n * owns. Always copies — even when the view spans its whole buffer — because\n * the result may be transferred to a worker (detaching it), and the view is\n * the caller's. Returning `view.buffer` here would let one transfer zero\n * the caller's bytes (a stamp library's Uint8Array became single-use).\n * Callers wanting a zero-copy hand-off need an explicit \"give\" form, as\n * `pages.insert` has for bare ArrayBuffers; `BinarySource` has none.\n */\nfunction toOwnedArrayBuffer(view: Uint8Array): ArrayBuffer {\n const copy = new ArrayBuffer(view.byteLength);\n new Uint8Array(copy).set(view);\n return copy;\n}\n\n/**\n * Resolve any accepted `BinarySource` form into a `WireResource`.\n * Async because Blob bytes can only be read asynchronously.\n */\nexport async function resolveBinarySource(source: BinarySource): Promise<WireResource> {\n if (source instanceof Uint8Array) {\n return { bytes: toOwnedArrayBuffer(source) };\n }\n if (isBlob(source)) {\n const blobName = blobFileName(source);\n return {\n bytes: await source.arrayBuffer(),\n mimeType: source.type || undefined,\n ...(blobName !== undefined ? { name: blobName } : {}),\n };\n }\n const { data, mimeType, name } = source;\n const inner =\n data instanceof Uint8Array\n ? {\n bytes: toOwnedArrayBuffer(data),\n mimeType: undefined as string | undefined,\n name: undefined as string | undefined,\n }\n : {\n bytes: await data.arrayBuffer(),\n mimeType: data.type || undefined,\n name: blobFileName(data),\n };\n const resolvedName = name ?? inner.name;\n return {\n bytes: inner.bytes,\n ...((mimeType ?? inner.mimeType) ? { mimeType: mimeType ?? inner.mimeType } : {}),\n ...(resolvedName !== undefined ? { name: resolvedName } : {}),\n };\n}\n\n/** A browser `File` is a Blob with a `name` — pick it up so attachment\n * drafts can pass a `File` directly without repeating the file name. */\nexport function blobFileName(blob: Blob): string | undefined {\n const name = (blob as File).name;\n return typeof name === 'string' && name.length > 0 ? name : undefined;\n}\n","/**\n * Magic-byte format detection for inline binary payloads.\n *\n * Declared mime types are never trusted — the sniffed format is canonical\n * on every engine and on the server. Raster formats include intrinsic pixel\n * dimensions (used for aspect-ratio fitting); PDF only identifies the format.\n */\n\nexport type BinaryMimeType = 'image/png' | 'image/jpeg' | 'application/pdf';\n\nexport type BinaryMetadata =\n | { mimeType: 'image/png'; width: number; height: number }\n | { mimeType: 'image/jpeg'; width: number; height: number }\n | { mimeType: 'application/pdf' };\n\n/**\n * Detect format (and intrinsic dimensions for rasters) of a binary buffer.\n *\n * @returns metadata, or `null` for unsupported/corrupt data\n */\nexport function sniffBinaryMetadata(buffer: ArrayBuffer): BinaryMetadata | null {\n if (buffer.byteLength < 4) return null;\n\n const bytes = new Uint8Array(buffer);\n\n if (bytes[0] === 0x89 && bytes[1] === 0x50 && bytes[2] === 0x4e && bytes[3] === 0x47) {\n return parsePng(buffer);\n }\n\n if (bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff) {\n return parseJpeg(buffer);\n }\n\n if (bytes[0] === 0x25 && bytes[1] === 0x50 && bytes[2] === 0x44 && bytes[3] === 0x46) {\n return { mimeType: 'application/pdf' };\n }\n\n return null;\n}\n\nfunction parsePng(buffer: ArrayBuffer): BinaryMetadata | null {\n if (buffer.byteLength < 24) return null;\n const view = new DataView(buffer);\n const width = view.getUint32(16);\n const height = view.getUint32(20);\n if (width === 0 || height === 0) return null;\n return { mimeType: 'image/png', width, height };\n}\n\nfunction parseJpeg(buffer: ArrayBuffer): BinaryMetadata | null {\n const bytes = new Uint8Array(buffer);\n let offset = 2;\n\n while (offset + 4 < bytes.byteLength) {\n if (bytes[offset] !== 0xff) return null;\n\n const marker = bytes[offset + 1];\n\n // SOF0 through SOF3 (baseline, progressive, lossless)\n if (marker >= 0xc0 && marker <= 0xc3) {\n if (offset + 9 > bytes.byteLength) return null;\n const view = new DataView(buffer, offset + 5);\n const height = view.getUint16(0);\n const width = view.getUint16(2);\n if (width === 0 || height === 0) return null;\n return { mimeType: 'image/jpeg', width, height };\n }\n\n // Skip non-SOF markers\n if (marker === 0xd8 || marker === 0xd9) {\n offset += 2;\n } else if (marker === 0xff) {\n offset += 1;\n } else {\n const segLen = (bytes[offset + 2] << 8) | bytes[offset + 3];\n offset += 2 + segLen;\n }\n }\n\n return null;\n}\n","import { ANNOTATION_RESOURCE_ROLES } from './field-names';\nimport type { AnnotationDraft } from './kinds';\nimport type { AnnotationSubtype } from './subtype';\nimport { EngineError } from '../errors/EngineError';\nimport { EngineErrorCode } from '../errors/EngineErrorCode';\nimport { sniffBinaryMetadata } from '../resource/binaryMetadata';\nimport { blobFileName } from '../resource/BinarySource';\n\n/**\n * Bytes travel beside an annotation's data, never inside it:\n * `create(data, resources)` and `update(ref, patch, resources)`. A read\n * returns the data only. Each role names what the bytes are for; a kind\n * declares the roles it takes (`kinds/<kind>/declaration.ts`).\n */\n\n/**\n * What bytes beside an annotation's data can be for:\n *\n * - `appearance`: what the box shows before the rotation the data describes,\n * PNG, JPEG or a one-page PDF, scaled into the box as the data's `fit` says.\n * A stamp requires it; on update it replaces the drawing.\n * - `file`: an attached file's exact bytes; its name, MIME type and\n * description are the data's `file`. A file attachment requires it; on\n * update it replaces the bytes.\n */\nexport const ANNOTATION_RESOURCE_ROLE_NAMES = ['appearance', 'file'] as const;\n\nexport type AnnotationResourceRole = (typeof ANNOTATION_RESOURCE_ROLE_NAMES)[number];\n\n/** Bytes as a caller holds them. */\nexport type ResourceBytes = Uint8Array | Blob;\n\n/** The bytes of one write, by role. */\nexport type AnnotationResources = Partial<Record<AnnotationResourceRole, ResourceBytes>>;\n\n/** The same, owned and ready for a worker transfer list or a multipart part. */\nexport type WireAnnotationResources = Partial<Record<AnnotationResourceRole, ArrayBuffer>>;\n\n/**\n * Copy each resource into bytes the write owns: the local engine transfers\n * them to its worker, which detaches the buffer, and the caller's bytes are\n * only borrowed. An appearance that isn't PNG, JPEG or PDF fails here,\n * before anything is sent; the format comes from the bytes.\n */\nexport async function resolveAnnotationResources(\n resources: AnnotationResources | undefined,\n): Promise<WireAnnotationResources> {\n if (!resources) return {};\n for (const role of Object.keys(resources)) {\n if (!(ANNOTATION_RESOURCE_ROLE_NAMES as readonly string[]).includes(role)) {\n throw new EngineError(\n EngineErrorCode.InvalidArg,\n `unknown annotation resource '${role}'; expected ${ANNOTATION_RESOURCE_ROLE_NAMES.join(' or ')}`,\n );\n }\n }\n const wire: WireAnnotationResources = {};\n for (const role of ANNOTATION_RESOURCE_ROLE_NAMES) {\n const data = resources[role];\n if (data === undefined) continue;\n const bytes = await ownedBytes(data);\n if (role === 'appearance' && !sniffBinaryMetadata(bytes)) {\n throw new EngineError(\n EngineErrorCode.InvalidArg,\n 'the appearance resource must be PNG, JPEG or one-page PDF bytes',\n );\n }\n wire[role] = bytes;\n }\n return wire;\n}\n\n/**\n * A file-attachment create's `file`, completed from its `file` resource when\n * that is a `File` or a `Blob`: the name a `File` brings and the type a\n * `Blob` does, where the data leaves them out. A `Blob` with no type gives\n * none. Other drafts, and bare bytes, pass as they are.\n */\nexport function withFileFromResource(\n draft: AnnotationDraft,\n resources: AnnotationResources | undefined,\n): AnnotationDraft {\n const data = resources?.file;\n if (draft.subtype !== 'file-attachment' || !isBlob(data)) return draft;\n const name = draft.file?.name ?? blobFileName(data);\n if (name === undefined) return draft;\n return {\n ...draft,\n file: {\n ...draft.file,\n name,\n mimeType: draft.file?.mimeType !== undefined ? draft.file.mimeType : data.type || null,\n },\n };\n}\n\nexport function hasAnnotationResources(resources: WireAnnotationResources): boolean {\n return ANNOTATION_RESOURCE_ROLE_NAMES.some((role) => resources[role] !== undefined);\n}\n\n/** The buffers of a write's resources: what a worker transfer list hands over. */\nexport function annotationResourceBuffers(resources: WireAnnotationResources): ArrayBuffer[] {\n return Object.values(resources).filter((bytes): bytes is ArrayBuffer => bytes !== undefined);\n}\n\n/**\n * Check a write's resources against its kind: a role the kind doesn't take\n * is refused, and so is a create without a role the kind requires.\n */\nexport function assertAnnotationResources(\n subtype: AnnotationSubtype,\n resources: WireAnnotationResources | undefined,\n write: 'create' | 'update',\n): void {\n const roles = ANNOTATION_RESOURCE_ROLES[subtype] ?? {};\n for (const role of ANNOTATION_RESOURCE_ROLE_NAMES) {\n const given = resources?.[role] !== undefined;\n if (given && roles[role] === undefined) {\n throw new EngineError(\n EngineErrorCode.InvalidArg,\n `a ${subtype} annotation takes no '${role}' resource`,\n );\n }\n if (!given && write === 'create' && roles[role] === 'required') {\n throw new EngineError(\n EngineErrorCode.InvalidArg,\n `creating a ${subtype} annotation needs its '${role}' resource`,\n );\n }\n }\n}\n\nfunction isBlob(value: unknown): value is Blob {\n return typeof Blob !== 'undefined' && value instanceof Blob;\n}\n\nasync function ownedBytes(data: ResourceBytes): Promise<ArrayBuffer> {\n if (isBlob(data)) return data.arrayBuffer();\n const copy = new ArrayBuffer(data.byteLength);\n new Uint8Array(copy).set(data);\n return copy;\n}\n","import type { BundleKind } from './bundle';\nimport { EngineError } from '../errors/EngineError';\nimport { EngineErrorCode } from '../errors/EngineErrorCode';\n\n/**\n * How large a bundle may be, annotations or a form. One set applies wherever\n * a bundle is made or read, so whatever an export makes, an import accepts.\n * Sizes are measured on the bundle itself, never on a file or request\n * carrying it: the manifest (its pages and rows as JSON) plus each\n * resource's bytes.\n */\nexport interface BundleLimits {\n /** The manifest's bytes plus every resource's bytes. */\n readonly bundleBytes: number;\n /** The pages and rows, as UTF-8 JSON. */\n readonly manifestBytes: number;\n /** The rows: an annotation bundle's items, a form bundle's fields and widgets. */\n readonly items: number;\n readonly pages: number;\n readonly resources: number;\n readonly resourceBytes: number;\n /** Width times height of a PNG or JPEG resource, once decoded. */\n readonly imagePixels: number;\n}\n\nexport const DEFAULT_BUNDLE_LIMITS: BundleLimits = Object.freeze({\n bundleBytes: 50 * 1024 * 1024,\n manifestBytes: 16 * 1024 * 1024,\n items: 10_000,\n pages: 2_000,\n resources: 2_000,\n resourceBytes: 50 * 1024 * 1024,\n imagePixels: 40_000_000,\n});\n\n/** The bytes of a bundle's manifest: its pages and rows (`{ pages, items }`) as UTF-8 JSON. */\nexport function manifestBytesOf(rows: object): number {\n return new TextEncoder().encode(JSON.stringify(rows)).length;\n}\n\n/** Refuse `value` when it is past the limit named `limit`. */\nexport function assertWithinLimit(\n kind: BundleKind,\n limits: BundleLimits,\n limit: keyof BundleLimits,\n value: number,\n): void {\n const max = limits[limit];\n if (value <= max) return;\n throw new EngineError(\n EngineErrorCode.PayloadTooLarge,\n `the ${kind} bundle is past its ${limit} limit: ${value} > ${max}`,\n { details: { limit, max, value } },\n );\n}\n","import { assertResourceIds, type BundleKind, type ResourceId } from './bundle';\nimport { DEFAULT_BUNDLE_LIMITS, type BundleLimits } from './bundleLimits';\nimport { EngineError } from '../errors/EngineError';\nimport { EngineErrorCode } from '../errors/EngineErrorCode';\nimport { decodedLengthOf, fromBase64, toBase64 } from '../resource/base64';\n\nexport interface BundleTransferOptions {\n /** The limits the file is written and read under; the defaults otherwise. */\n readonly limits?: BundleLimits;\n}\n\n/** A bundle as one JSON file, each resource in base64. */\nexport interface BundleCodec<Bundle> {\n /**\n * The file for `bundle`. Its shape, references and limits are checked\n * first, so no file is written that `parse` refuses for them; the\n * resources are checked against their ids by `parse`.\n */\n stringify(bundle: Bundle, options?: BundleTransferOptions): string;\n /**\n * The bundle a file holds, checked whole: `InvalidArg` for anything that\n * isn't a bundle of this family and version, a resource that doesn't match\n * its id, a row naming a resource that isn't there, or a resource no row\n * names; `PayloadTooLarge` past a limit. Limits come first, so a file that\n * is refused is never decoded: the text's length, then the counts and\n * every resource's size from its base64, and only then the resources,\n * decoded and hashed.\n */\n parse(text: string, options?: BundleTransferOptions): Promise<Bundle>;\n}\n\n/** What a family's file is: its kind, its manifest's keys, and their check. */\nexport interface BundleFileSpec<Bundle> {\n readonly kind: BundleKind;\n /** The bundle's keys besides `resources`, in the order the file writes them. */\n readonly keys: readonly Exclude<keyof Bundle & string, 'resources'>[];\n /**\n * Check everything but the resources' bytes, given their sizes by id:\n * format and version, counts and sizes against `limits`, shape and\n * references.\n */\n assertManifest(\n manifest: unknown,\n resourceSizes: ReadonlyMap<string, number>,\n limits: BundleLimits,\n ): void;\n}\n\n/** A resource's entry in the file besides its base64: its id, quotes and separators. */\nconst RESOURCE_ENTRY_CHARACTERS = 81;\n/** The file's own keys and punctuation. */\nconst ENVELOPE_CHARACTERS = 256;\n\nconst A_BUNDLE: Record<BundleKind, string> = {\n annotation: 'an annotation bundle',\n form: 'a form bundle',\n};\n\n/**\n * The JSON file of one family's bundles: a bundle whole, to store or\n * download. HTTP carries bundles as multipart instead, without the third\n * base64 adds.\n */\nexport function bundleCodec<\n Bundle extends { readonly resources: Readonly<Record<ResourceId, Uint8Array>> },\n>(spec: BundleFileSpec<Bundle>): BundleCodec<Bundle> {\n const notABundle = (cause?: unknown) =>\n new EngineError(\n EngineErrorCode.InvalidArg,\n `the file is not ${A_BUNDLE[spec.kind]}`,\n cause === undefined ? undefined : { cause },\n );\n\n return {\n stringify(bundle, options) {\n const limits = options?.limits ?? DEFAULT_BUNDLE_LIMITS;\n const sizes = new Map<string, number>();\n for (const [id, bytes] of Object.entries(bundle.resources)) sizes.set(id, bytes.length);\n spec.assertManifest(bundle, sizes, limits);\n const file: Record<string, unknown> = {};\n for (const key of spec.keys) file[key] = bundle[key];\n const resources: Record<string, string> = {};\n for (const [id, bytes] of Object.entries(bundle.resources)) resources[id] = toBase64(bytes);\n file.resources = resources;\n return JSON.stringify(file);\n },\n\n async parse(text, options) {\n const limits = options?.limits ?? DEFAULT_BUNDLE_LIMITS;\n const maxLength =\n Math.ceil((limits.bundleBytes * 4) / 3) +\n limits.resources * RESOURCE_ENTRY_CHARACTERS +\n ENVELOPE_CHARACTERS;\n if (text.length > maxLength) {\n throw new EngineError(\n EngineErrorCode.PayloadTooLarge,\n `the file is ${text.length} characters, more than a bundle within ` +\n `${limits.bundleBytes} bytes can be`,\n { details: { limit: 'bundleBytes', max: limits.bundleBytes, fileLength: text.length } },\n );\n }\n\n let file: unknown;\n try {\n file = JSON.parse(text);\n } catch (error) {\n throw notABundle(error);\n }\n const encoded =\n typeof file === 'object' && file !== null\n ? (file as { resources?: unknown }).resources\n : null;\n if (typeof encoded !== 'object' || encoded === null || Array.isArray(encoded)) {\n throw notABundle();\n }\n\n const sizes = new Map<string, number>();\n for (const [id, value] of Object.entries(encoded)) {\n const size = typeof value === 'string' ? decodedLengthOf(value) : null;\n if (size === null) {\n throw new EngineError(EngineErrorCode.InvalidArg, `resource ${id} is not base64`);\n }\n sizes.set(id, size);\n }\n spec.assertManifest(file, sizes, limits);\n\n const resources: Record<ResourceId, Uint8Array> = {};\n for (const [id, value] of Object.entries(encoded as Record<ResourceId, string>)) {\n try {\n resources[id as ResourceId] = fromBase64(value);\n } catch (error) {\n throw new EngineError(EngineErrorCode.InvalidArg, `resource ${id} is not base64`, {\n cause: error,\n });\n }\n }\n await assertResourceIds(spec.kind, resources);\n const bundle: Record<string, unknown> = {};\n for (const key of spec.keys) bundle[key] = (file as Record<string, unknown>)[key];\n bundle.resources = resources;\n return bundle as unknown as Bundle;\n },\n };\n}\n","import {\n assertBundlePages,\n assertKnownFields,\n assertResourceIds,\n assertResourcesNamed,\n assertRowResources,\n invalidBundle,\n isBundlePageRef,\n isRecord,\n type BundlePage,\n type ResourceId,\n} from './bundle';\nimport {\n assertWithinLimit,\n DEFAULT_BUNDLE_LIMITS,\n manifestBytesOf,\n type BundleLimits,\n} from './bundleLimits';\nimport type { Annotation } from '../annotation/kinds';\nimport {\n ANNOTATION_RESOURCE_ROLE_NAMES,\n type AnnotationResourceRole,\n} from '../annotation/resources';\nimport { encodePageKey } from '../identity/PageRef';\nimport type { Coordinates, PageCoordinates } from '../pageSpace/coordinates';\n\n/**\n * Annotations and the bytes beside them, taken out of a document to go into\n * this one or another. Each item is a row: its data, exactly what a read\n * returns, and the resources it names by id. Each resource is here once,\n * however many items name it, under the SHA-256 of its bytes, so a receiver\n * can check it and a host can store it once. Any set of rows and the\n * resources they name is a bundle.\n */\nexport interface AnnotationBundle<C extends Coordinates = PageCoordinates> {\n readonly format: 'embedpdf/annotations';\n readonly version: 1;\n /** Every page an item is on or points at, in document order. */\n readonly pages: readonly BundlePage[];\n /** In page order, then in each page's annotation order. */\n readonly items: readonly AnnotationBundleItem<C>[];\n readonly resources: Readonly<Record<ResourceId, Uint8Array>>;\n}\n\nexport interface AnnotationBundleItem<C extends Coordinates = PageCoordinates> {\n readonly data: Annotation<C>;\n readonly resources: Readonly<Partial<Record<AnnotationResourceRole, ResourceId>>>;\n}\n\n/** A bundle as a worker returns it: each resource an `ArrayBuffer` on the transfer list. */\nexport interface WireAnnotationBundle<C extends Coordinates = PageCoordinates> extends Omit<\n AnnotationBundle<C>,\n 'resources'\n> {\n readonly resources: Readonly<Record<ResourceId, ArrayBuffer>>;\n}\n\nexport const ANNOTATION_BUNDLE_FORMAT = 'embedpdf/annotations';\nexport const ANNOTATION_BUNDLE_VERSION = 1;\n\n/** The manifest's keys, in the order a file writes them. */\nexport const ANNOTATION_BUNDLE_KEYS = ['format', 'version', 'pages', 'items'] as const;\n\nconst BUNDLE_FIELDS = [...ANNOTATION_BUNDLE_KEYS, 'resources'] as const;\nconst ITEM_FIELDS = ['data', 'resources'] as const;\n\n/**\n * Check a bundle before anything uses it, the checks cheapest first: its\n * format, its counts and sizes against `limits` (`PayloadTooLarge`), its\n * shape and references (`InvalidArg`), then every resource against its id.\n */\nexport async function assertAnnotationBundle(\n bundle: AnnotationBundle,\n limits: BundleLimits = DEFAULT_BUNDLE_LIMITS,\n): Promise<void> {\n const resources = isRecord(bundle?.resources)\n ? bundle.resources\n : invalidBundle('annotation', 'no resources');\n const sizes = new Map<string, number>();\n for (const [id, bytes] of Object.entries(resources)) {\n if (!(bytes instanceof Uint8Array)) invalidBundle('annotation', `resource ${id} is not bytes`);\n sizes.set(id, bytes.length);\n }\n assertAnnotationBundleManifest(bundle, sizes, limits);\n await assertResourceIds('annotation', resources);\n}\n\n/**\n * The checks that need no resource bytes, only their sizes by id: format\n * and version, counts, sizes, the shape of pages and items, and that items\n * and resources name each other exactly.\n */\nexport function assertAnnotationBundleManifest(\n manifest: unknown,\n resourceSizes: ReadonlyMap<string, number>,\n limits: BundleLimits,\n): asserts manifest is Omit<AnnotationBundle, 'resources'> {\n if (!isRecord(manifest)) invalidBundle('annotation', 'not an annotation bundle');\n assertKnownFields('annotation', 'the bundle', manifest, BUNDLE_FIELDS);\n if (manifest.format !== ANNOTATION_BUNDLE_FORMAT) {\n invalidBundle('annotation', `unknown format ${JSON.stringify(manifest.format)}`);\n }\n if (manifest.version !== ANNOTATION_BUNDLE_VERSION) {\n invalidBundle('annotation', `unknown version ${JSON.stringify(manifest.version)}`);\n }\n const { pages, items } = manifest;\n if (!Array.isArray(pages)) invalidBundle('annotation', 'pages is not a list');\n if (!Array.isArray(items)) invalidBundle('annotation', 'items is not a list');\n\n assertWithinLimit('annotation', limits, 'items', items.length);\n assertWithinLimit('annotation', limits, 'pages', pages.length);\n assertWithinLimit('annotation', limits, 'resources', resourceSizes.size);\n let bundleBytes = manifestBytesOf({ pages, items });\n assertWithinLimit('annotation', limits, 'manifestBytes', bundleBytes);\n for (const size of resourceSizes.values()) {\n assertWithinLimit('annotation', limits, 'resourceBytes', size);\n bundleBytes += size;\n }\n assertWithinLimit('annotation', limits, 'bundleBytes', bundleBytes);\n\n const pageKeys = assertBundlePages('annotation', pages);\n const named = new Set<string>();\n items.forEach((item, index) => {\n if (!isRecord(item) || !isRecord(item.data) || typeof item.data.subtype !== 'string') {\n invalidBundle('annotation', `item ${index} has no annotation data`);\n }\n assertKnownFields('annotation', `item ${index}`, item, ITEM_FIELDS);\n const ref = item.data.ref;\n const page = isRecord(ref) ? ref.page : undefined;\n if (!isBundlePageRef(page) || !pageKeys.has(encodePageKey(page))) {\n invalidBundle('annotation', `item ${index} is on a page the bundle doesn't list`);\n }\n assertRowResources(\n 'annotation',\n `item ${index}`,\n item.resources,\n ANNOTATION_RESOURCE_ROLE_NAMES,\n resourceSizes,\n named,\n );\n });\n assertResourcesNamed('annotation', 'item', resourceSizes, named);\n}\n","import {\n ANNOTATION_BUNDLE_KEYS,\n assertAnnotationBundleManifest,\n type AnnotationBundle,\n} from './AnnotationBundle';\nimport { bundleCodec } from './codec';\n\n/**\n * An annotation bundle as one JSON file, each resource in base64: a bundle\n * whole, to store or download. HTTP carries bundles as multipart instead,\n * without the third base64 adds.\n */\nexport const AnnotationTransfer = bundleCodec<AnnotationBundle>({\n kind: 'annotation',\n keys: ANNOTATION_BUNDLE_KEYS,\n assertManifest: assertAnnotationBundleManifest,\n});\n","import type { IsoDateTime } from './IsoDateTime';\n\n/**\n * One vocabulary for \"a file living inside a PDF\", shared by the\n * file-attachment annotation kind and the document-level EmbeddedFiles\n * service:\n *\n * write -> the document service takes {@link AttachmentFileSource}: the\n * metadata fields plus the bytes. A file attachment annotation\n * takes the metadata as its `file` data and the bytes as its\n * `file` resource.\n * read -> {@link AttachmentFileInfo}: the same metadata fields plus\n * engine-derived facts (size, checksum, dates) and never\n * the bytes — listings stay cheap; bytes leave the engine only\n * through an explicit download call.\n *\n * A file has exactly two possible homes: the document catalog's\n * `/EmbeddedFiles` name tree (addressed by {@link Attachment.ref}), and a\n * FileAttachment annotation's `/FS` (addressed by the annotation ref).\n */\n\n/** The metadata fields a write takes. */\nexport interface AttachmentFileBase {\n /** File name — `/UF` (and `/F`) on the filespec. */\n name: string;\n /** MIME type — `/Subtype` of the embedded file stream. */\n mimeType?: string;\n /** Human-readable description — `/Desc` on the filespec. */\n description?: string;\n}\n\n/**\n * What callers pass to create an attachment. `name` may be omitted only\n * when `data` carries one itself (a browser `File`); normalization throws\n * `InvalidArg` when no name is resolvable — a PDF filespec requires one.\n * `mimeType` is stored as declared (attachment types cannot be reliably\n * sniffed); it falls back to the Blob's type, and without either the file\n * has none (a read says `null`).\n */\nexport interface AttachmentFileSource {\n data: Uint8Array | ArrayBuffer | Blob;\n name?: string;\n mimeType?: string;\n description?: string;\n}\n\n/** An {@link AttachmentFileSource} ready to ship: its metadata, and the key of its bytes. */\nexport interface WireAttachmentFile {\n /** The file's key: its bytes are the part `resource:<key>`. */\n resources: { file: string };\n name: string;\n mimeType?: string;\n description?: string;\n}\n\n/**\n * Read-side projection of an embedded file stream (`/EF` + `/Params`). Every\n * field is present, `null` when the PDF has no value for it.\n */\nexport interface AttachmentFileInfo {\n /** File name — `/UF` (and `/F`) on the filespec. */\n name: string;\n /** MIME type — `/Subtype` of the embedded file stream. */\n mimeType: string | null;\n /** Human-readable description — `/Desc` on the filespec. */\n description: string | null;\n /** `/Params /Size` — decoded size in bytes. */\n size: number | null;\n /** `/Params /CheckSum` — MD5 of the decoded bytes, lowercase hex. */\n checksum: string | null;\n /** `/Params /CreationDate`. */\n createdAt: IsoDateTime | null;\n /** `/Params /ModDate`. */\n modifiedAt: IsoDateTime | null;\n}\n\n/**\n * Durable address of a document-level attachment: its name-tree key.\n * Keys are unique within the tree by construction (ISO 32000 §7.9.6). A\n * discriminated union so future ref kinds can be added without a breaking\n * change (the `AnnotationRef` pattern).\n *\n * The key usually equals the file's display `name` (`/UF`) — always, for\n * engine-created attachments — but foreign PDFs may diverge, and `/UF`\n * values may collide while keys cannot. Address by `key`; display `name`.\n */\nexport type AttachmentRef = { kind: 'key'; key: string };\n\n/**\n * How much of a file the local engine decodes: a download of a larger file,\n * from either home, is refused with `PayloadTooLarge`, before a small stream\n * that inflates to gigabytes takes the tab down. A file's declared size\n * can't be trusted. The cloud engine has its server's limit.\n */\nexport const ATTACHMENT_LIMITS = { decodedBytes: 256 * 1024 * 1024 } as const;\n\n/** The ref of an attachment whose name-tree key you already hold. */\nexport function toAttachmentRef(key: string): AttachmentRef {\n return { kind: 'key', key };\n}\n\n/** One entry of the document-level `/EmbeddedFiles` name tree. */\nexport interface Attachment extends AttachmentFileInfo {\n /** The attachment's address, for download and delete. */\n ref: AttachmentRef;\n /**\n * Position in name-tree (sorted) order — display metadata, not an\n * address: both create and delete shift indices. Address by `ref`.\n */\n index: number;\n}\n\n/** What `attachments.list()` returns: the attachments in name-tree order. */\nexport interface AttachmentList {\n attachments: Attachment[];\n}\n\n/**\n * A downloaded attachment: the payload symmetric counterpart of\n * {@link AttachmentFileSource} — what you put in is what you get out.\n */\nexport interface AttachmentContent {\n bytes: Uint8Array;\n name: string;\n /** The declared type; `null` when the file has none (the engine never guesses one). */\n mimeType: string | null;\n}\n","import { isSamePdfRect, pdfRectTurnedBounds } from '../geometry/convert';\nimport type { PdfRect } from '../geometry/primitives';\n\n/** The kinds drawn about a box that can turn. */\nconst BOX_KINDS: ReadonlySet<string> = new Set(['square', 'circle', 'free-text', 'stamp', 'caret']);\n\n/**\n * The turn an annotation's appearance raster is drawn without, degrees\n * clockwise, or `null` when the raster is drawn as the page shows it. A box\n * kind drawn turned whose drawing stays inside the turned box (its `rect` is\n * the upright box around it) renders upright over its `box`, for the\n * consumer to turn about the middle of `box`: a new turn needs no new\n * raster. A callout (its line isn't turned) and a drawing that reaches past\n * its box (a cloudy border's bumps) render as the page shows them, placed by\n * `rect`.\n */\nexport function pdfAppearanceTurnOf(annotation: {\n subtype: string;\n rect: PdfRect;\n box?: PdfRect | null;\n rotation?: number | null;\n intent?: string | null;\n}): number | null {\n const { subtype, rect, box, rotation, intent } = annotation;\n if (!BOX_KINDS.has(subtype) || !box || !rotation) return null;\n if (subtype === 'free-text' && intent === 'free-text-callout') return null;\n return isSamePdfRect(pdfRectTurnedBounds(box, rotation), rect) ? rotation : null;\n}\n","import type { AttachmentFileInfo } from '../../dto/Attachment';\nimport type { PdfAnnotationActions } from '../../dto/PdfAction';\nimport { actionTreeOf } from '../../dto/PdfLinkTarget';\nimport {\n DEFAULT_RICH_TEXT_BODY,\n type RichTextDocument,\n type RichTextDocumentInput,\n} from '../../dto/RichText';\nimport type { Coordinates } from '../../pageSpace/coordinates';\nimport { kindFactsOf } from '../kind-facts';\nimport type { Annotation, AnnotationPatch } from '../kinds';\n\n/**\n * A resolved patch's fields as a read spells them. Most fields read as they\n * are written; these take a different shape on the way in.\n */\nexport function readValueOf(name: string, value: unknown, current: unknown): unknown {\n if (value === null) return null;\n switch (name) {\n case 'reply': {\n const reply = value as { to: unknown; type?: 'reply' | 'group' };\n return { to: reply.to, type: reply.type ?? 'reply' };\n }\n case 'richText': {\n const input = value as RichTextDocumentInput;\n const read = current as RichTextDocument | undefined;\n const body = input.body\n ? { ...DEFAULT_RICH_TEXT_BODY, ...input.body }\n : (read?.body ?? DEFAULT_RICH_TEXT_BODY);\n // A read spells every rich color in lowercase, and keeps no empty run.\n return {\n body: { ...body, color: body.color.toLowerCase() },\n paragraphs: input.paragraphs.map((paragraph) => ({\n ...paragraph,\n runs: paragraph.runs\n .filter((run) => run.text !== '')\n .map((run) =>\n run.style?.color\n ? { ...run, style: { ...run.style, color: run.style.color.toLowerCase() } }\n : run,\n ),\n })),\n } satisfies RichTextDocument;\n }\n case 'file': {\n const written = value as {\n name: string;\n mimeType?: string | null;\n description?: string | null;\n };\n const read = current as AttachmentFileInfo | null;\n // The name, type and description are one value, replaced whole; what\n // the bytes say (size, checksum, dates) stays until new bytes come.\n return {\n ...(read ?? { size: null, checksum: null, createdAt: null, modifiedAt: null }),\n name: written.name,\n mimeType: written.mimeType ?? null,\n description: written.description ?? null,\n } satisfies AttachmentFileInfo;\n }\n default:\n return value;\n }\n}\n\n/**\n * `current` with a resolved patch's data fields in place, each as a read\n * spells it. Fields the engine works out or stamps itself (a drawn kind's\n * `rect`, the modified date and author) keep\n * the value `current` has: the engine's answer brings the new one. Works in\n * either space: it only moves values by field name.\n */\nexport function applyResolvedPatch<A extends Annotation<Coordinates>>(\n current: A,\n resolved: AnnotationPatch<Coordinates>,\n): A {\n const owners = kindFactsOf(current.subtype)?.owners ?? {};\n const read = current as unknown as Record<string, unknown>;\n const next: Record<string, unknown> = { ...read };\n for (const [name, value] of Object.entries(resolved)) {\n if (name === 'subtype' || value === undefined) continue;\n // Fields the engine owns, stamps or keeps as found are accepted and ignored.\n if (owners[name] !== 'data') continue;\n next[name] = readValueOf(name, value, read[name]);\n }\n return { ...next, ...followingReads(current, resolved) } as unknown as A;\n}\n\n/**\n * Fields the engine keeps as found, but rewrites when a data field they\n * mirror changes: a link's `target` is the root of its `/A`, so a new target\n * is a new `actions.activate` (and no target, none).\n */\nfunction followingReads(\n current: Annotation<Coordinates>,\n resolved: AnnotationPatch<Coordinates>,\n): Record<string, unknown> {\n if (current.subtype !== 'link' || resolved.subtype !== 'link') return {};\n const target = resolved.target;\n // A target a write can't make moves no action: sent back unchanged it is\n // kept, and the engine refuses a changed one.\n if (target === undefined || (target !== null && target.kind !== 'uri' && target.kind !== 'goto'))\n return {};\n const { activate: _replaced, ...others } = current.actions ?? {};\n const actions: PdfAnnotationActions<unknown> =\n target === null ? others : { ...others, activate: actionTreeOf(target) };\n return { actions: Object.keys(actions).length > 0 ? actions : null };\n}\n","/**\n * What a create that leaves out a data field reads back, kind by kind: the\n * engine's defaults, in one table. The writers take their values from here,\n * and a viewer draws an annotation it is still creating with them, in the\n * colors the engine will write.\n *\n * The type asks for a value for every optional field a read never shows as\n * `null` (a color, a flag, an icon); a field that reads `null` when left out\n * needs none. `test/annotation/defaults.test.ts` checks each value against the\n * field's schema, and the prediction conformance suite checks the table\n * against what both engines create.\n */\nimport type { Color } from './primitives';\nimport type { DefaultsOf } from './declaration';\nimport type { WritableAnnotationDeclaration } from './kinds/declarations';\nimport type { AnnotationSubtype } from './subtype';\n\n/** A kind's defaults, from its declaration. */\nexport type AnnotationDefaults<Subtype extends WritableSubtype> = DefaultsOf<\n Extract<WritableAnnotationDeclaration, { subtype: Subtype }>\n>;\n\ntype WritableSubtype = WritableAnnotationDeclaration['subtype'];\n\nconst RED: Color = '#ff0000';\nconst BLACK: Color = '#000000';\nconst YELLOW: Color = '#ffff00';\n\n/** Every kind: printed (as Acrobat creates them), no other flag set, normal blending. A popup doesn't print. */\nconst BASE = {\n invisible: false,\n hidden: false,\n print: true,\n noZoom: false,\n noRotate: false,\n noView: false,\n readOnly: false,\n locked: false,\n toggleNoView: false,\n lockedContents: false,\n blendMode: 'normal',\n} as const;\n\n/** Shapes and lines: a solid red line, one point wide. */\nconst STROKE = {\n ...BASE,\n color: RED,\n opacity: 1,\n strokeWidth: 1,\n borderStyle: 'solid',\n} as const;\n\nconst NO_ENDINGS = { start: 'none', end: 'none' } as const;\n\n/** Text markup other than a highlight: black. */\nconst MARKUP = { ...BASE, color: BLACK, opacity: 1 } as const;\n\nexport const ANNOTATION_DEFAULTS = {\n square: STROKE,\n circle: STROKE,\n line: { ...STROKE, lineEndings: NO_ENDINGS, captionPosition: 'inline' },\n polygon: STROKE,\n polyline: { ...STROKE, lineEndings: NO_ENDINGS },\n ink: STROKE,\n // A highlight multiplies, so the text shows through its yellow.\n highlight: { ...BASE, blendMode: 'multiply', color: YELLOW, opacity: 1 },\n underline: MARKUP,\n squiggly: MARKUP,\n strikeout: MARKUP,\n caret: { ...BASE, color: RED, opacity: 1 },\n 'free-text': {\n ...BASE,\n contents: '',\n intent: 'free-text',\n fontFamily: 'helvetica',\n fontSize: 12,\n textAlign: 'left',\n verticalAlign: 'top',\n color: BLACK,\n fontColor: BLACK,\n opacity: 1,\n strokeWidth: 1,\n borderStyle: 'solid',\n },\n text: { ...BASE, icon: 'note', open: false, color: YELLOW, opacity: 1 },\n 'file-attachment': { ...BASE, icon: 'paperclip', color: YELLOW, opacity: 1 },\n link: BASE,\n redact: {\n ...BASE,\n quadPoints: [],\n color: RED,\n opacity: 1,\n repeat: false,\n fontFamily: 'helvetica',\n fontSize: 12,\n fontColor: BLACK,\n textAlign: 'left',\n },\n // A stamp another tool made reads `fit: null`; one the engine creates records its fit.\n stamp: { ...BASE, fit: 'contain', opacity: 1 },\n widget: { ...BASE, strokeWidth: 1, borderStyle: 'solid', textAlign: 'left' },\n popup: { ...BASE, print: false, open: false },\n} satisfies { readonly [S in WritableSubtype]: AnnotationDefaults<S> };\n\n/** What a create of `subtype` reads back for each data field it leaves out. */\nexport function annotationDefaultsOf(\n subtype: AnnotationSubtype,\n): Readonly<Record<string, unknown>> {\n return subtype === 'unsupported' ? {} : ANNOTATION_DEFAULTS[subtype];\n}\n","import type {\n DocumentActionsSnapshot,\n NamedJavaScriptAction,\n PdfActionNode,\n PdfActionTree,\n PdfActionWrite,\n PdfAnnotationActions,\n PdfFieldActions,\n PdfPageActions,\n} from '../dto/PdfAction';\nimport type { PageDestination, PdfDestination } from '../dto/PdfDestination';\nimport type { PdfLinkTarget } from '../dto/PdfLinkTarget';\nimport type { PdfRect } from '../geometry/primitives';\nimport type { PageRef } from '../identity/PageRef';\n\n/**\n * The visible box of any page of the document, in the file's coordinates. A\n * destination is measured on the page it goes to, so converting one needs\n * that page's box, not the box of the page it sits on.\n */\nexport type VisibleBoxOf = (page: PageRef) => PdfRect;\n\n/**\n * The visible box a destination is measured on: the `pdfCropBox` of the page\n * it goes to, or a function that gives any page's.\n */\nexport type DestinationBox = PdfRect | VisibleBoxOf;\n\nconst boxFor = (page: PageRef, box: DestinationBox): PdfRect =>\n typeof box === 'function' ? box(page) : box;\n\ntype Axis = number | null | undefined;\n\n/** An axis value that may keep the current one (`null`) or be left out. */\nconst across = (value: Axis, convert: (value: number) => number): Axis =>\n value == null ? value : convert(value);\n\n/**\n * A destination in the file's coordinates, in page space: for one read by\n * another PDF tool, before handing it to the viewer. `box` is the `pdfCropBox`\n * of the page it goes to.\n */\nexport function pageDestinationOf(\n destination: PdfDestination,\n box: DestinationBox,\n): PageDestination {\n const { left: boxLeft, top: boxTop } = boxFor(destination.page, box);\n const x = (left: Axis) => across(left, (value) => value - boxLeft);\n const y = (top: Axis) => across(top, (value) => boxTop - value);\n switch (destination.kind) {\n case 'xyz': {\n const { left, top, ...rest } = destination;\n return {\n ...rest,\n ...('left' in destination ? { x: x(left) } : {}),\n ...('top' in destination ? { y: y(top) } : {}),\n };\n }\n case 'fitH':\n case 'fitBH': {\n const { top, ...rest } = destination;\n return { ...rest, ...('top' in destination ? { y: y(top) } : {}) };\n }\n case 'fitV':\n case 'fitBV': {\n const { left, ...rest } = destination;\n return { ...rest, ...('left' in destination ? { x: x(left) } : {}) };\n }\n case 'fitR': {\n const { left, bottom, right, top, ...rest } = destination;\n const lower = Math.min(bottom, top);\n const upper = Math.max(bottom, top);\n return {\n ...rest,\n x: Math.min(left, right) - boxLeft,\n y: boxTop - upper,\n width: Math.abs(right - left),\n height: upper - lower,\n };\n }\n case 'fit':\n case 'fitB':\n return destination;\n }\n}\n\n/**\n * A page-space destination in the file's coordinates: for handing one to\n * another PDF tool. `box` is the `pdfCropBox` of the page it goes to.\n */\nexport function pdfDestinationOf(\n destination: PageDestination,\n box: DestinationBox,\n): PdfDestination {\n const { left: boxLeft, top: boxTop } = boxFor(destination.page, box);\n const left = (x: Axis) => across(x, (value) => value + boxLeft);\n const top = (y: Axis) => across(y, (value) => boxTop - value);\n switch (destination.kind) {\n case 'xyz': {\n const { x, y, ...rest } = destination;\n return {\n ...rest,\n ...('x' in destination ? { left: left(x) } : {}),\n ...('y' in destination ? { top: top(y) } : {}),\n };\n }\n case 'fitH':\n case 'fitBH': {\n const { y, ...rest } = destination;\n return { ...rest, ...('y' in destination ? { top: top(y) } : {}) };\n }\n case 'fitV':\n case 'fitBV': {\n const { x, ...rest } = destination;\n return { ...rest, ...('x' in destination ? { left: left(x) } : {}) };\n }\n case 'fitR': {\n const { x, y, width, height, ...rest } = destination;\n const upper = boxTop - y;\n return {\n ...rest,\n left: x + boxLeft,\n bottom: upper - height,\n right: x + boxLeft + width,\n top: upper,\n };\n }\n case 'fit':\n case 'fitB':\n return destination;\n }\n}\n\n// ── the values that carry destinations ──\n\n/** Converts the destinations inside a value; everything else is kept. */\ntype Convert<From, To> = (destination: From) => To;\n\nexport function mapLinkTarget<From, To>(\n target: PdfLinkTarget<From>,\n convert: Convert<From, To>,\n): PdfLinkTarget<To> {\n return target.kind === 'goto' ? { ...target, destination: convert(target.destination) } : target;\n}\n\nexport function mapActionNode<From, To>(\n node: PdfActionNode<From>,\n convert: Convert<From, To>,\n): PdfActionNode<To> {\n const next = node.next.map((child) => mapActionNode(child, convert));\n return (\n node.type === 'goto'\n ? { ...node, next, destination: convert(node.destination) }\n : { ...node, next }\n ) as PdfActionNode<To>;\n}\n\nexport function mapActionTree<From, To>(\n tree: PdfActionTree<From>,\n convert: Convert<From, To>,\n): PdfActionTree<To> {\n return { ...tree, root: tree.root ? mapActionNode(tree.root, convert) : null };\n}\n\n/** An action to write, its destinations converted. */\nexport function mapActionWrite<From, To>(\n action: PdfActionWrite<From>,\n convert: Convert<From, To>,\n): PdfActionWrite<To> {\n const next = action.next?.map((child) => mapActionWrite(child, convert));\n const converted =\n action.type === 'goto' ? { ...action, destination: convert(action.destination) } : action;\n return (next ? { ...converted, next } : converted) as PdfActionWrite<To>;\n}\n\n/**\n * A record of triggers as a read has them (trees) or a write takes them\n * (actions to write, `null` to remove one), its destinations converted.\n */\nexport function mapTriggerActions<From, To>(\n triggers: object,\n convert: Convert<From, To>,\n): Record<string, unknown> {\n return Object.fromEntries(\n Object.entries(triggers as Record<string, unknown>).map(([trigger, value]) => {\n if (value == null) return [trigger, value];\n return [\n trigger,\n 'root' in (value as object)\n ? mapActionTree(value as PdfActionTree<From>, convert)\n : mapActionWrite(value as PdfActionWrite<From>, convert),\n ];\n }),\n );\n}\n\n/** Every action tree in a record of triggers (an annotation's, a page's or a field's). */\nfunction mapTriggers<From, To>(\n triggers: object,\n convert: Convert<From, To>,\n): Record<string, PdfActionTree<To> | undefined> {\n return Object.fromEntries(\n Object.entries(triggers as Record<string, PdfActionTree<From> | undefined>).map(\n ([trigger, tree]) => [trigger, tree ? mapActionTree(tree, convert) : tree],\n ),\n );\n}\n\nexport function mapAnnotationActions<From, To>(\n actions: PdfAnnotationActions<From>,\n convert: Convert<From, To>,\n): PdfAnnotationActions<To> {\n return mapTriggers(actions, convert);\n}\n\nexport function mapPageActions<From, To>(\n actions: PdfPageActions<From>,\n convert: Convert<From, To>,\n): PdfPageActions<To> {\n return mapTriggers(actions, convert);\n}\n\nexport function mapFieldActions<From, To>(\n actions: PdfFieldActions<From>,\n convert: Convert<From, To>,\n): PdfFieldActions<To> {\n return mapTriggers(actions, convert);\n}\n\nexport function mapDocumentActions<From, To>(\n snapshot: DocumentActionsSnapshot<From>,\n convert: Convert<From, To>,\n): DocumentActionsSnapshot<To> {\n const { nameTreeScripts, openAction, openDestination, ...triggers } = snapshot;\n return {\n ...mapTriggers(triggers, convert),\n nameTreeScripts: nameTreeScripts.map(\n (script): NamedJavaScriptAction<To> => ({\n ...script,\n action: mapActionTree(script.action, convert),\n }),\n ),\n openAction: openAction ? mapActionTree(openAction, convert) : null,\n ...('openDestination' in snapshot\n ? { openDestination: openDestination ? convert(openDestination) : openDestination }\n : {}),\n } as DocumentActionsSnapshot<To>;\n}\n","import type { PageCoordinates, PdfCoordinates } from './coordinates';\nimport type { PdfMeasurement, PageMeasurementViewport } from '../dto/Measure';\nimport { pageBoxOf, pagePointOf, pdfPointOf, type PagePoint } from '../geometry/pageSpace';\nimport type { PdfPoint, PdfRect } from '../geometry/primitives';\n\nconst withOrigin = <Measure extends PdfMeasurement>(\n measure: Measure,\n convert: (origin: PdfPoint) => PdfPoint,\n): Measure =>\n measure.subtype === 'rectilinear' && measure.origin\n ? { ...measure, origin: convert(measure.origin) }\n : measure;\n\n/** A scale in page space: its origin (`/O`) is a place on the page. */\nexport function pageMeasureOf<Measure extends PdfMeasurement>(\n measure: Measure,\n visible: PdfRect,\n): Measure {\n return withOrigin(measure, (origin) => pagePointOf(origin, visible));\n}\n\n/** A page-space scale in the file's coordinates. */\nexport function pdfMeasureOf<Measure extends PdfMeasurement>(\n measure: Measure,\n visible: PdfRect,\n): Measure {\n return withOrigin(measure, (origin) => pdfPointOf(origin as PagePoint, visible));\n}\n\n/** A page's measurement viewports in page space. */\nexport function pageViewportsOf(\n viewports: readonly PageMeasurementViewport<PdfCoordinates>[],\n visible: PdfRect,\n): PageMeasurementViewport<PageCoordinates>[] {\n return viewports.map((viewport) => ({\n ...viewport,\n bbox: pageBoxOf(viewport.bbox, visible),\n measure: viewport.measure ? pageMeasureOf(viewport.measure, visible) : null,\n }));\n}\n","import {\n mapLinkTarget,\n mapTriggerActions,\n pageDestinationOf,\n pdfDestinationOf,\n type VisibleBoxOf,\n} from './destinations';\nimport { pageMeasureOf, pdfMeasureOf } from './measure';\nimport type { PdfCoordinates } from './coordinates';\nimport {\n ANNOTATION_FIELD_SPACES,\n ANNOTATION_FIELD_SPACES_BY_NAME,\n type MeasuredFieldSpace,\n} from '../annotation/field-spaces';\nimport type { Annotation, AnnotationDraft, AnnotationPatch } from '../annotation/kinds';\nimport type { AnnotationSubtype } from '../annotation/subtype';\nimport type { PdfMeasurement } from '../dto/Measure';\nimport type { PageDestination, PdfDestination } from '../dto/PdfDestination';\nimport type { PdfLinkTarget } from '../dto/PdfLinkTarget';\nimport {\n pageBoxOf,\n pagePointOf,\n pageQuadOf,\n pdfPointOf,\n pdfQuadOf,\n pdfRectOf,\n type PageBox,\n type PagePoint,\n type PageQuad,\n} from '../geometry/pageSpace';\nimport type { PdfPoint, PdfQuad, PdfRect } from '../geometry/primitives';\nimport { EngineError } from '../errors/EngineError';\nimport { EngineErrorCode } from '../errors/EngineErrorCode';\n\n/**\n * Annotation values between the file's coordinates and page space, field by\n * field, by what each field holds (`ANNOTATION_FIELD_SPACES`, kept equal to\n * the declarations). Places on the annotation's page are measured from that\n * page's visible box; a destination from the box of the page it goes to.\n */\ninterface Frame {\n /** The visible box of the annotation's page, in the file's coordinates. */\n visible: PdfRect;\n boxOf: VisibleBoxOf;\n}\n\ntype Converter = (value: never, frame: Frame) => unknown;\n\nconst TO_PAGE: Record<MeasuredFieldSpace, Converter> = {\n length: (value) => value,\n point: (point: PdfPoint, { visible }) => pagePointOf(point, visible),\n points: (points: PdfPoint[], { visible }) => points.map((point) => pagePointOf(point, visible)),\n strokes: (strokes: PdfPoint[][], { visible }) =>\n strokes.map((stroke) => stroke.map((point) => pagePointOf(point, visible))),\n box: (rect: PdfRect, { visible }) => pageBoxOf(rect, visible),\n quads: (quads: PdfQuad[], { visible }) => quads.map((quad) => pageQuadOf(quad, visible)),\n linePoints: (line: { start: PdfPoint; end: PdfPoint }, { visible }) => ({\n start: pagePointOf(line.start, visible),\n end: pagePointOf(line.end, visible),\n }),\n calloutLine: (points: PdfPoint[], { visible }) =>\n points.map((point) => pagePointOf(point, visible)),\n measure: (measure: PdfMeasurement, { visible }) => pageMeasureOf(measure, visible),\n linkTarget: (target: PdfLinkTarget<PdfDestination>, { boxOf }) =>\n mapLinkTarget(target, (destination) => pageDestinationOf(destination, boxOf)),\n actions: (actions: object, { boxOf }) =>\n mapTriggerActions(actions, (destination: PdfDestination) =>\n pageDestinationOf(destination, boxOf),\n ),\n};\n\nconst TO_PDF: Record<MeasuredFieldSpace, Converter> = {\n length: (value) => value,\n point: (point: PagePoint, { visible }) => pdfPointOf(point, visible),\n points: (points: PagePoint[], { visible }) => points.map((point) => pdfPointOf(point, visible)),\n strokes: (strokes: PagePoint[][], { visible }) =>\n strokes.map((stroke) => stroke.map((point) => pdfPointOf(point, visible))),\n box: (box: PageBox, { visible }) => pdfRectOf(box, visible),\n quads: (quads: PageQuad[], { visible }) => quads.map((quad) => pdfQuadOf(quad, visible)),\n linePoints: (line: { start: PagePoint; end: PagePoint }, { visible }) => ({\n start: pdfPointOf(line.start, visible),\n end: pdfPointOf(line.end, visible),\n }),\n calloutLine: (points: PagePoint[], { visible }) =>\n points.map((point) => pdfPointOf(point, visible)),\n measure: (measure: PdfMeasurement, { visible }) => pdfMeasureOf(measure, visible),\n linkTarget: (target: PdfLinkTarget<PageDestination>, { boxOf }) =>\n mapLinkTarget(target, (destination) => pdfDestinationOf(destination, boxOf)),\n actions: (actions: object, { boxOf }) =>\n mapTriggerActions(actions, (destination: PageDestination) =>\n pdfDestinationOf(destination, boxOf),\n ),\n};\n\n/**\n * The measured fields of a kind; a kind the engine doesn't know has the base\n * fields. An update may leave out its kind: a field's name says what it\n * holds, the same in every kind.\n */\nconst spacesOf = (subtype: string | undefined): Readonly<Record<string, MeasuredFieldSpace>> =>\n subtype === undefined\n ? ANNOTATION_FIELD_SPACES_BY_NAME\n : (ANNOTATION_FIELD_SPACES[subtype as AnnotationSubtype] ??\n ANNOTATION_FIELD_SPACES.unsupported);\n\nfunction convertFields(\n subtype: string | undefined,\n value: object,\n frame: Frame,\n converters: Record<MeasuredFieldSpace, Converter>,\n): Record<string, unknown> {\n const spaces = spacesOf(subtype);\n return Object.fromEntries(\n Object.entries(value).map(([name, field]) => {\n const space = spaces[name];\n if (!space || field == null) return [name, field];\n const converted = converters[space](field as never, frame);\n if (converters === TO_PDF && hasNaN(converted)) throw notInPageSpace(name, space);\n return [name, converted];\n }),\n );\n}\n\n/** Whether a converted value has a number that isn't one: a place not given in page space. */\nfunction hasNaN(value: unknown): boolean {\n if (typeof value === 'number') return Number.isNaN(value);\n if (typeof value !== 'object' || value === null) return false;\n return Object.values(value).some(hasNaN);\n}\n\nfunction notInPageSpace(name: string, space: MeasuredFieldSpace): EngineError {\n const shape = space === 'box' ? '{ x, y, width, height }' : 'points as { x, y }';\n return new EngineError(\n EngineErrorCode.InvalidArg,\n `field '${name}': expected page space, ${shape} from the page's top-left`,\n { details: { field: name } },\n );\n}\n\n/** A read in page space. `visible` is its page's visible box, in the file's coordinates. */\nexport function pageAnnotationOf(\n annotation: Annotation<PdfCoordinates>,\n visible: PdfRect,\n boxOf: VisibleBoxOf,\n): Annotation {\n return convertFields(annotation.subtype, annotation, { visible, boxOf }, TO_PAGE) as Annotation;\n}\n\n/** A page-space read in the file's coordinates. */\nexport function pdfAnnotationOf(\n annotation: Annotation,\n visible: PdfRect,\n boxOf: VisibleBoxOf,\n): Annotation<PdfCoordinates> {\n return convertFields(\n annotation.subtype,\n annotation,\n { visible, boxOf },\n TO_PDF,\n ) as Annotation<PdfCoordinates>;\n}\n\n/** A page-space create in the file's coordinates. */\nexport function pdfAnnotationDraftOf(\n draft: AnnotationDraft,\n visible: PdfRect,\n boxOf: VisibleBoxOf,\n): AnnotationDraft<PdfCoordinates> {\n return convertFields(\n draft.subtype,\n draft,\n { visible, boxOf },\n TO_PDF,\n ) as AnnotationDraft<PdfCoordinates>;\n}\n\n/** A create in the file's coordinates, in page space. */\nexport function pageAnnotationDraftOf(\n draft: AnnotationDraft<PdfCoordinates>,\n visible: PdfRect,\n boxOf: VisibleBoxOf,\n): AnnotationDraft {\n return convertFields(draft.subtype, draft, { visible, boxOf }, TO_PAGE) as AnnotationDraft;\n}\n\n/**\n * A page-space update in the file's coordinates. An update may leave out its\n * `subtype`; its fields' names say what they hold.\n */\nexport function pdfAnnotationPatchOf(\n patch: AnnotationPatch,\n visible: PdfRect,\n boxOf: VisibleBoxOf,\n): AnnotationPatch<PdfCoordinates> {\n return convertFields(\n patch.subtype,\n patch,\n { visible, boxOf },\n TO_PDF,\n ) as AnnotationPatch<PdfCoordinates>;\n}\n\n/** An update in the file's coordinates, in page space. */\nexport function pageAnnotationPatchOf(\n patch: AnnotationPatch<PdfCoordinates>,\n visible: PdfRect,\n boxOf: VisibleBoxOf,\n): AnnotationPatch {\n return convertFields(patch.subtype, patch, { visible, boxOf }, TO_PAGE) as AnnotationPatch;\n}\n","import type { TextRange } from './TextRange';\nimport {\n isRotatedGeometryRun,\n type PageGeometryRun,\n type PageGeometrySnapshot,\n type RotatedGeometryRun,\n} from '../dto/PageGeometrySnapshot';\nimport type { PdfPoint, PdfQuad, PdfRect } from '../geometry/primitives';\nimport type { Coordinates, PageCoordinates, PdfCoordinates } from '../pageSpace/coordinates';\n\n/**\n * The canonical text-interaction layout — the one place glyph geometry\n * becomes hit targets, word/line ranges, and visual-line segments.\n *\n * Selection owns gestures and state; search owns matching and cursors;\n * neither owns segmentation. Both consume this module, so a text range has\n * exactly one canonical segmentation regardless of how it was produced.\n *\n * Everything here works in the file's coordinates (y up), as the engine reads\n * them. The public layout (`createTextLayout`, `pageSpace/text.ts`) runs this\n * one on page-space geometry flipped top to bottom and flips its answers\n * back. The line-merge is adapted from Chromium's\n * pdf/pdfium/pdfium_range.cc `MergeAdjacentRects` (BSD-licensed, Copyright\n * 2010 The Chromium Authors); hit-testing mirrors PDFium `GetIndexAtPos`\n * (exact tight box first, then a tolerance pass).\n *\n * Orientation model — frames. Every run belongs to a frame: frame 0 is page\n * space itself (all upright runs — the dominant case takes a byte-identical\n * fast path), and each rotated orientation cluster gets an orthonormal frame\n * in which its text reads upright (baseline +x, ascent +y). Frames are\n * derived from the semantic edges of the first classifiable glyph's quad —\n * never from advisory wire fields — and keyed by (baseline direction,\n * ascent handedness):\n *\n * - Rotated and mirrored text become upright inside their frame.\n * - Shear (fake italic) is deliberately not part of the frame key or the\n * basis: a sheared run shares the frame of its unsheared neighbours, so\n * a mixed roman/italic line merges into one segment (Acrobat parity),\n * and the shear is absorbed as a small in-frame AABB residue. This is\n * the deterministic, order-independent contract — an affine\n * (shear-preserving) basis would either fragment mixed lines or make\n * the roman body's geometry depend on whether an italic run came first.\n * - Runs of different frames never merge into one line.\n *\n * All algorithms run on frame-local boxes; every participating run of a\n * cluster is transformed through the same frame, so merged coordinates are\n * always commensurable. Only the output maps back to page space, as\n * oriented quads.\n */\n\n/** A space or a character with no box ends a word. */\nconst isBoundary = (g: { space?: boolean; empty?: boolean }): boolean => !!(g.space || g.empty);\nconst isEmpty = (g: { empty?: boolean }): boolean => !!g.empty;\n\nconst CHAR_DISTANCE_FACTOR = 2.5;\nconst FONT_SIZE_RATIO_THRESHOLD = 1.5;\nconst VERTICAL_OVERLAP_THRESHOLD = 0.8;\nconst LINE_OVERLAP_THRESHOLD = 0.5;\n/** Baseline directions within ~0.5° share a frame. */\nconst FRAME_DOT_TOLERANCE = Math.cos(0.0087);\nconst EDGE_EPSILON = 1e-6;\n\n/**\n * One merged visual line of a text range, in page space. `quad` is the\n * geometric authority (corners named in the line's own frame, not in reading\n * order);\n * `rect` is its axis-aligned bounds, produced by the same constructor.\n * `advance` is the reading direction along the baseline, derived from the\n * glyph sequence (+1 = the frame's +x), never inferred from geometry.\n */\nexport interface PdfTextSegment<C extends Coordinates = PageCoordinates> {\n quad: C['quad'];\n rect: C['box'];\n advance: 1 | -1;\n}\n\n/** One glyph in its frame's space. `loose` builds segments; `tight` hit-tests. */\ninterface TextLayoutGlyph {\n loose: PdfRect;\n tight?: PdfRect;\n space?: boolean;\n empty?: boolean;\n}\n\n/** A contiguous run of glyphs (a text object) in one frame. */\ninterface TextLayoutRun {\n /** First char index — identical to the flat glyph index (runs tile the page). */\n start: number;\n count: number;\n /** Frame-local loose box (page space itself in frame 0). */\n rect: PdfRect;\n fontSize?: number;\n /** Index into {@link PageTextLayout.frames}; 0 = page space (upright). */\n frame: number;\n}\n\n/** An orientation cluster's orthonormal basis in page space. */\ninterface TextLayoutFrame {\n /** Unit vector along the reading baseline (+x of the frame). */\n baseline: PdfPoint;\n /** Unit vector toward the ascent side (+y of the frame), ⟂ baseline. */\n ascent: PdfPoint;\n}\n\n/**\n * A page's text laid out per-frame: a flat glyph list (index = text-page\n * char index), the run structure, and the orientation frames.\n */\ninterface PageTextLayout {\n glyphs: TextLayoutGlyph[];\n runs: TextLayoutRun[];\n frames: TextLayoutFrame[];\n}\n\n/**\n * Where a page's text is, as `page.text.layout()` returns it: read it once\n * per page and keep it, every method answers right away. Positions are in\n * page space: points from the top-left of the page, y down. Characters are\n * numbered as the page's character space, the\n * space every {@link TextRange} is in.\n */\nexport interface TextLayout<C extends Coordinates = PageCoordinates> {\n /** How many characters the page has: they are numbered 0 to `charCount - 1`. */\n readonly charCount: number;\n /** The raw geometry: characters grouped by line and font, with their boxes. */\n readonly runs: readonly PageGeometryRun<C>[];\n /**\n * The character at a point, or `null` when there's no text near it. The\n * tight box is tried first, then a near miss within 1.5 times the average\n * line height.\n */\n charAt(point: C['point']): number | null;\n /** The word at a point or around a character, or `null` when there is none. */\n wordAt(at: C['point'] | number): TextRange | null;\n /** The visual line at a point or around a character, or `null` when there is none. */\n lineAt(at: C['point'] | number): TextRange | null;\n /** One segment per visual line the range covers: what to draw, or to highlight. */\n segments(range: TextRange): PdfTextSegment<C>[];\n /** One character's loose cell, as a quad, or `null` for a character with no box. */\n charQuad(index: number): C['quad'] | null;\n}\n\n/**\n * The layout of a page's geometry in the file's coordinates, for the engine's\n * own readers. Everything else uses `createTextLayout`, in page space.\n */\nexport function createPdfTextLayout(\n snapshot: PageGeometrySnapshot<PdfCoordinates>,\n): TextLayout<PdfCoordinates> {\n const layout = buildPageTextLayout(snapshot);\n const charCount = layout.glyphs.length;\n const indexOf = (at: PdfPoint | number): number | null => {\n if (typeof at !== 'number') return textGlyphAt(layout, at);\n return Number.isInteger(at) && at >= 0 && at < charCount ? at : null;\n };\n const rangeOf = ([from, to]: [number, number]): TextRange => ({\n start: from,\n count: to - from + 1,\n });\n return {\n charCount,\n runs: snapshot.runs,\n charAt: (point) => textGlyphAt(layout, point),\n wordAt: (at) => {\n const index = indexOf(at);\n return index === null ? null : rangeOf(expandTextRangeToWord(layout, index));\n },\n lineAt: (at) => {\n const index = indexOf(at);\n return index === null ? null : rangeOf(expandTextRangeToLine(layout, index));\n },\n segments: (range) => textSegmentsForRange(layout, range.start, range.count),\n charQuad: (index) => textGlyphQuad(layout, index),\n };\n}\n\nconst IDENTITY_FRAME: TextLayoutFrame = { baseline: { x: 1, y: 0 }, ascent: { x: 0, y: 1 } };\n\nconst toFrame = (f: TextLayoutFrame, p: PdfPoint): PdfPoint => ({\n x: p.x * f.baseline.x + p.y * f.baseline.y,\n y: p.x * f.ascent.x + p.y * f.ascent.y,\n});\n\nconst fromFrame = (f: TextLayoutFrame, p: PdfPoint): PdfPoint => ({\n x: f.baseline.x * p.x + f.ascent.x * p.y,\n y: f.baseline.y * p.x + f.ascent.y * p.y,\n});\n\nconst ZERO_RECT: PdfRect = { left: 0, bottom: 0, right: 0, top: 0 };\n\n/** Frame-local AABB of a page-space cell (exact under the frame's rotation;\n * shear residue is the documented in-frame envelope). */\nfunction frameBoxOfQuad(f: TextLayoutFrame, q: PdfQuad): PdfRect {\n const pts = [q.upperLeft, q.upperRight, q.lowerLeft, q.lowerRight].map((p) => toFrame(f, p));\n const xs = pts.map((p) => p.x);\n const ys = pts.map((p) => p.y);\n return {\n left: Math.min(...xs),\n bottom: Math.min(...ys),\n right: Math.max(...xs),\n top: Math.max(...ys),\n };\n}\n\n/** Find-or-create the frame for a rotated run, keyed by the baseline\n * direction + ascent handedness of its first classifiable glyph's edges. */\nfunction frameForRun(frames: TextLayoutFrame[], run: RotatedGeometryRun<PdfCoordinates>): number {\n const seed = run.glyphs.find((g) => !isEmpty(g));\n if (!seed) return 0;\n const q = seed.loose;\n const bx = q.upperRight.x - q.upperLeft.x;\n const by = q.upperRight.y - q.upperLeft.y;\n const len = Math.hypot(bx, by);\n if (len <= EDGE_EPSILON) return 0;\n const baseline: PdfPoint = { x: bx / len, y: by / len };\n // Handedness from the actual ascent edge (lower-left → upper-left), so\n // mirrored text gets its own frame with \"up\" on its true ascent side.\n const ax = q.upperLeft.x - q.lowerLeft.x;\n const ay = q.upperLeft.y - q.lowerLeft.y;\n const sign = baseline.x * ay - baseline.y * ax >= 0 ? 1 : -1;\n const ascent: PdfPoint = { x: -baseline.y * sign, y: baseline.x * sign };\n\n for (let i = 0; i < frames.length; i++) {\n const f = frames[i];\n const dot = f.baseline.x * baseline.x + f.baseline.y * baseline.y;\n const sameHandedness = f.ascent.x * ascent.x + f.ascent.y * ascent.y > 0;\n if (dot >= FRAME_DOT_TOLERANCE && sameHandedness) return i;\n }\n frames.push({ baseline, ascent });\n return frames.length - 1;\n}\n\n/**\n * Flatten a page's geometry snapshot into the canonical layout. Upright runs\n * copy their wire boxes verbatim (frame 0, wire run rects included); rotated\n * runs project their glyph cells into their cluster's frame.\n */\nfunction buildPageTextLayout(snapshot: PageGeometrySnapshot<PdfCoordinates>): PageTextLayout {\n const glyphs: TextLayoutGlyph[] = [];\n const runs: TextLayoutRun[] = [];\n const frames: TextLayoutFrame[] = [IDENTITY_FRAME];\n\n for (const run of snapshot.runs) {\n if (!isRotatedGeometryRun(run)) {\n for (const g of run.glyphs) {\n glyphs.push({ loose: g.loose, tight: g.tight, space: g.space, empty: g.empty });\n }\n runs.push({\n start: run.start,\n count: run.glyphs.length,\n rect: run.rect,\n fontSize: run.fontSize,\n frame: 0,\n });\n continue;\n }\n\n const frame = frameForRun(frames, run);\n const f = frames[frame];\n let runBox: PdfRect | null = null;\n for (const g of run.glyphs) {\n if (isEmpty(g)) {\n glyphs.push({ loose: ZERO_RECT, space: g.space, empty: true });\n continue;\n }\n const loose = frameBoxOfQuad(f, g.loose);\n const tight = g.tight ? frameBoxOfQuad(f, g.tight) : undefined;\n glyphs.push({ loose, tight, space: g.space });\n runBox = runBox\n ? {\n left: Math.min(runBox.left, loose.left),\n bottom: Math.min(runBox.bottom, loose.bottom),\n right: Math.max(runBox.right, loose.right),\n top: Math.max(runBox.top, loose.top),\n }\n : loose;\n }\n runs.push({\n start: run.start,\n count: run.glyphs.length,\n rect: runBox ?? ZERO_RECT,\n fontSize: run.fontSize,\n frame,\n });\n }\n return { glyphs, runs, frames };\n}\n\nconst inRect = (r: PdfRect, p: PdfPoint): boolean =>\n p.x >= r.left && p.x <= r.right && p.y >= r.bottom && p.y <= r.top;\n\nfunction avgGlyphHeight(layout: PageTextLayout): number {\n let total = 0;\n let count = 0;\n for (const g of layout.glyphs) {\n if (isEmpty(g)) continue;\n total += g.loose.top - g.loose.bottom;\n count++;\n }\n return count === 0 ? 0 : total / count;\n}\n\n/** The point expressed in every frame (index-aligned with `layout.frames`).\n * Frame 0 returns the point itself — no float round-trip on the fast path. */\nfunction pointPerFrame(layout: PageTextLayout, p: PdfPoint): PdfPoint[] {\n return layout.frames.map((f, i) => (i === 0 ? p : toFrame(f, p)));\n}\n\n/**\n * The glyph (char) index at a page-space point, or null when nothing is near\n * (so callers can show the pointer cursor off-text). PDFium `GetIndexAtPos`:\n * exact tight-box containment first, then a tolerance pass (closest by\n * Manhattan distance within `toleranceFactor × average glyph height`). Each\n * run tests the point in its own frame, so rotated text hit-tests exactly.\n */\nfunction textGlyphAt(\n layout: PageTextLayout,\n point: PdfPoint,\n toleranceFactor = 1.5,\n): number | null {\n const pts = pointPerFrame(layout, point);\n for (const run of layout.runs) {\n const q = pts[run.frame];\n if (!inRect(run.rect, q)) continue;\n for (let i = 0; i < run.count; i++) {\n const g = layout.glyphs[run.start + i];\n if (inRect(g.tight ?? g.loose, q)) return run.start + i;\n }\n }\n if (toleranceFactor <= 0) return null;\n\n const half = (avgGlyphHeight(layout) * toleranceFactor) / 2;\n let best = -1;\n let bestDist = Infinity;\n for (const run of layout.runs) {\n const q = pts[run.frame];\n const r = run.rect;\n if (\n q.x < r.left - half ||\n q.x > r.right + half ||\n q.y < r.bottom - half ||\n q.y > r.top + half\n ) {\n continue;\n }\n for (let i = 0; i < run.count; i++) {\n const g = layout.glyphs[run.start + i];\n if (isEmpty(g)) continue;\n const b = g.tight ?? g.loose;\n if (\n q.x < b.left - half ||\n q.x > b.right + half ||\n q.y < b.bottom - half ||\n q.y > b.top + half\n ) {\n continue;\n }\n const dx = Math.min(Math.abs(q.x - b.left), Math.abs(q.x - b.right));\n const dy = Math.min(Math.abs(q.y - b.bottom), Math.abs(q.y - b.top));\n // Neighbours share an edge, so a point nearest to it is as near to both:\n // the first one wins, whatever the last bit of rounding says.\n if (dx + dy < bestDist - EDGE_EPSILON) {\n bestDist = dx + dy;\n best = run.start + i;\n }\n }\n }\n return best >= 0 ? best : null;\n}\n\n/** Double-click: the word around `glyph` (walk to space/empty glyphs both ways). */\nfunction expandTextRangeToWord(layout: PageTextLayout, glyph: number): [number, number] {\n const n = layout.glyphs.length;\n if (glyph < 0 || glyph >= n) return [glyph, glyph];\n let from = glyph;\n while (from > 0 && !isBoundary(layout.glyphs[from - 1])) from--;\n let to = glyph;\n while (to < n - 1 && !isBoundary(layout.glyphs[to + 1])) to++;\n return [from, to];\n}\n\n/** Triple-click: the full visual line — same-frame runs whose vertical extent\n * overlaps the anchor run's. A differently-oriented run is a line boundary. */\nfunction expandTextRangeToLine(layout: PageTextLayout, glyph: number): [number, number] {\n const ri = layout.runs.findIndex((r) => glyph >= r.start && glyph < r.start + r.count);\n if (ri < 0) return [glyph, glyph];\n const anchor = layout.runs[ri];\n const bottom = anchor.rect.bottom;\n const top = anchor.rect.top;\n let from = anchor.start;\n let to = anchor.start + anchor.count - 1;\n for (let r = ri - 1; r >= 0; r--) {\n const run = layout.runs[r];\n if (isZero(run.rect)) continue;\n if (run.frame !== anchor.frame) break;\n if (!overlapV(run.rect.bottom, run.rect.top, bottom, top)) break;\n from = run.start;\n }\n for (let r = ri + 1; r < layout.runs.length; r++) {\n const run = layout.runs[r];\n if (isZero(run.rect)) continue;\n if (run.frame !== anchor.frame) break;\n if (!overlapV(run.rect.bottom, run.rect.top, bottom, top)) break;\n to = run.start + run.count - 1;\n }\n return [from, to];\n}\n\n/**\n * A single glyph's oriented cell in page space, or null for degenerate\n * glyphs — the anchor for caret placement at a selection boundary.\n */\nfunction textGlyphQuad(layout: PageTextLayout, glyph: number): PdfQuad | null {\n const g = layout.glyphs[glyph];\n if (!g || isEmpty(g)) return null;\n const b = g.loose;\n if (b.right <= b.left || b.top <= b.bottom) return null;\n const run = layout.runs.find((r) => glyph >= r.start && glyph < r.start + r.count);\n const f = layout.frames[run?.frame ?? 0];\n return quadOfFrameRect(f, run?.frame ?? 0, b);\n}\n\ninterface SubRun {\n rect: PdfRect;\n charCount: number;\n fontSize?: number;\n frame: number;\n /** Baseline x of the first/last glyph in sequence order (frame space) —\n * the reading-direction signal. */\n firstX: number;\n lastX: number;\n}\n\n/**\n * Merged visual-line segments for the half-open char range\n * `[start, start + count)` — the canonical segmentation. Chars\n * outside the layout are ignored.\n */\nfunction textSegmentsForRange(\n layout: PageTextLayout,\n start: number,\n count: number,\n): PdfTextSegment<PdfCoordinates>[] {\n if (count <= 0 || layout.glyphs.length === 0) return [];\n const lo = Math.max(0, start);\n const hi = Math.min(layout.glyphs.length - 1, start + count - 1);\n if (hi < lo) return [];\n const subRuns: SubRun[] = [];\n\n for (const run of layout.runs) {\n const runEnd = run.start + run.count - 1;\n if (runEnd < lo || run.start > hi) continue;\n const s = Math.max(lo, run.start);\n const e = Math.min(hi, runEnd);\n\n let left = Infinity;\n let right = -Infinity;\n let bottom = Infinity;\n let top = -Infinity;\n let charCountAcc = 0;\n let widthSum = 0;\n let prevRight = -Infinity;\n let firstX = 0;\n let lastX = 0;\n const flush = () => {\n if (charCountAcc > 0 && left !== Infinity) {\n subRuns.push({\n rect: { left, bottom, right, top },\n charCount: charCountAcc,\n fontSize: run.fontSize,\n frame: run.frame,\n firstX,\n lastX,\n });\n }\n left = Infinity;\n right = -Infinity;\n bottom = Infinity;\n top = -Infinity;\n charCountAcc = 0;\n widthSum = 0;\n prevRight = -Infinity;\n };\n\n for (let ci = s; ci <= e; ci++) {\n const g = layout.glyphs[ci];\n if (isEmpty(g)) continue;\n const b = g.loose;\n if (charCountAcc > 0 && prevRight > -Infinity) {\n const avg = widthSum / charCountAcc;\n if (avg > 0 && Math.abs(b.left - prevRight) > CHAR_DISTANCE_FACTOR * avg) flush();\n }\n const centerX = (b.left + b.right) / 2;\n if (charCountAcc === 0) firstX = centerX;\n lastX = centerX;\n left = Math.min(left, b.left);\n right = Math.max(right, b.right);\n bottom = Math.min(bottom, b.bottom);\n top = Math.max(top, b.top);\n charCountAcc++;\n widthSum += b.right - b.left;\n prevRight = b.right;\n }\n flush();\n }\n\n return mergeAdjacentSubRuns(subRuns).map((m) => materializeSegment(layout, m));\n}\n\ninterface MergedSubRun {\n rect: PdfRect;\n frame: number;\n firstX: number;\n lastX: number;\n}\n\nfunction mergeAdjacentSubRuns(runs: SubRun[]): MergedSubRun[] {\n const out: MergedSubRun[] = [];\n let prev: SubRun | null = null;\n let cur: MergedSubRun | null = null;\n for (const run of runs) {\n // Frames are canonical per cluster, so index equality is the \"same\n // orientation\" test — every participant was projected through the same\n // frame, keeping merged coordinates commensurable.\n if (prev && cur && prev.frame === run.frame && shouldMerge(prev, run)) {\n cur = {\n rect: {\n left: Math.min(cur.rect.left, run.rect.left),\n bottom: Math.min(cur.rect.bottom, run.rect.bottom),\n right: Math.max(cur.rect.right, run.rect.right),\n top: Math.max(cur.rect.top, run.rect.top),\n },\n frame: cur.frame,\n firstX: cur.firstX,\n lastX: run.lastX,\n };\n } else {\n if (cur) out.push(cur);\n cur = { rect: run.rect, frame: run.frame, firstX: run.firstX, lastX: run.lastX };\n }\n prev = run;\n }\n if (cur && cur.rect.right > cur.rect.left && cur.rect.top > cur.rect.bottom) out.push(cur);\n return out;\n}\n\n/** Segment quad for a frame-local rect (frame 0: the rect's own corners,\n * no float round-trip). The frame is y-up, so the upper corners sit at the\n * frame top. */\nfunction quadOfFrameRect(f: TextLayoutFrame, frameIndex: number, r: PdfRect): PdfQuad {\n if (frameIndex === 0) {\n return {\n upperLeft: { x: r.left, y: r.top },\n upperRight: { x: r.right, y: r.top },\n lowerLeft: { x: r.left, y: r.bottom },\n lowerRight: { x: r.right, y: r.bottom },\n };\n }\n return {\n upperLeft: fromFrame(f, { x: r.left, y: r.top }),\n upperRight: fromFrame(f, { x: r.right, y: r.top }),\n lowerLeft: fromFrame(f, { x: r.left, y: r.bottom }),\n lowerRight: fromFrame(f, { x: r.right, y: r.bottom }),\n };\n}\n\nfunction materializeSegment(\n layout: PageTextLayout,\n m: MergedSubRun,\n): PdfTextSegment<PdfCoordinates> {\n const frame = layout.frames[m.frame];\n const quad = quadOfFrameRect(frame, m.frame, m.rect);\n const rect =\n m.frame === 0\n ? m.rect\n : {\n left: Math.min(quad.upperLeft.x, quad.upperRight.x, quad.lowerLeft.x, quad.lowerRight.x),\n bottom: Math.min(\n quad.upperLeft.y,\n quad.upperRight.y,\n quad.lowerLeft.y,\n quad.lowerRight.y,\n ),\n right: Math.max(quad.upperLeft.x, quad.upperRight.x, quad.lowerLeft.x, quad.lowerRight.x),\n top: Math.max(quad.upperLeft.y, quad.upperRight.y, quad.lowerLeft.y, quad.lowerRight.y),\n };\n return { quad, rect, advance: m.lastX >= m.firstX ? 1 : -1 };\n}\n\nfunction shouldMerge(a: SubRun, b: SubRun): boolean {\n if (a.fontSize != null && b.fontSize != null && a.fontSize > 0 && b.fontSize > 0) {\n const ratio = Math.max(a.fontSize, b.fontSize) / Math.min(a.fontSize, b.fontSize);\n if (ratio > FONT_SIZE_RATIO_THRESHOLD) return false;\n }\n if (verticalOverlap(a.rect, b.rect) < VERTICAL_OVERLAP_THRESHOLD) return false;\n const aw = (a.rect.right - a.rect.left) / a.charCount;\n const bw = (b.rect.right - b.rect.left) / b.charCount;\n const aL = a.rect.left - aw;\n const aR = a.rect.right + aw;\n const bL = b.rect.left - bw;\n const bR = b.rect.right + bw;\n return aL < bR && aR > bL;\n}\n\nfunction verticalOverlap(a: PdfRect, b: PdfRect): number {\n const ah = a.top - a.bottom;\n const bh = b.top - b.bottom;\n if (ah <= 0 || bh <= 0) return 0;\n const u = Math.max(a.top, b.top) - Math.min(a.bottom, b.bottom);\n if (u === ah || u === bh) return 1;\n const i = Math.max(0, Math.min(a.top, b.top) - Math.max(a.bottom, b.bottom));\n return i / u;\n}\n\nconst isZero = (r: PdfRect): boolean => r.right === r.left && r.top === r.bottom;\n\nfunction overlapV(bottom1: number, top1: number, bottom2: number, top2: number): boolean {\n const u = Math.max(top1, top2) - Math.min(bottom1, bottom2);\n if (u === 0) return false;\n const i = Math.max(0, Math.min(top1, top2) - Math.max(bottom1, bottom2));\n return i / u >= LINE_OVERLAP_THRESHOLD;\n}\n","import type { PageCoordinates, PdfCoordinates } from './coordinates';\nimport type { VisibleBoxOf } from './destinations';\nimport {\n isRotatedGeometryRun,\n type PageGeometryRun,\n type PageGeometrySnapshot,\n} from '../dto/PageGeometrySnapshot';\nimport {\n mirroredPoint,\n mirroredQuad,\n mirroredRect,\n pageBoxOf,\n pageQuadOf,\n unmirroredBox,\n unmirroredQuad,\n type PageBox,\n} from '../geometry/pageSpace';\nimport type { PdfRect } from '../geometry/primitives';\nimport type { SearchMatch, SearchSlice } from '../search/types';\nimport { createPdfTextLayout, type PdfTextSegment, type TextLayout } from '../text/layout';\n\n/**\n * A character with no box of its own (`empty`) carries a zeroed box or quad\n * that says so, in either space, and so does a run of nothing but such\n * characters; it is not a place, so it never converts.\n */\nconst NO_BOX: PageBox = { x: 0, y: 0, width: 0, height: 0 };\nconst NO_RECT: PdfRect = { left: 0, bottom: 0, right: 0, top: 0 };\nconst NO_QUAD = {\n upperLeft: { x: 0, y: 0 },\n upperRight: { x: 0, y: 0 },\n lowerLeft: { x: 0, y: 0 },\n lowerRight: { x: 0, y: 0 },\n};\n\n/** Whether a run has a character with a box of its own. */\nconst hasBox = (run: { glyphs: readonly { empty?: true }[] }): boolean =>\n run.glyphs.some((glyph) => !glyph.empty);\n\n/** A page's text geometry in page space. `visible` is the page's visible box. */\nexport function pageGeometryOf(\n snapshot: PageGeometrySnapshot<PdfCoordinates>,\n visible: PdfRect,\n): PageGeometrySnapshot<PageCoordinates> {\n return {\n ...snapshot,\n runs: snapshot.runs.map((run): PageGeometryRun<PageCoordinates> => {\n const rect = hasBox(run) ? pageBoxOf(run.rect, visible) : NO_BOX;\n if (isRotatedGeometryRun(run)) {\n return {\n ...run,\n rect,\n glyphs: run.glyphs.map(({ loose, tight, ...glyph }) => ({\n ...glyph,\n loose: glyph.empty ? NO_QUAD : pageQuadOf(loose, visible),\n ...(tight ? { tight: pageQuadOf(tight, visible) } : {}),\n })),\n };\n }\n return {\n ...run,\n rect,\n glyphs: run.glyphs.map(({ loose, tight, ...glyph }) => ({\n ...glyph,\n loose: glyph.empty ? NO_BOX : pageBoxOf(loose, visible),\n ...(tight ? { tight: pageBoxOf(tight, visible) } : {}),\n })),\n };\n }),\n };\n}\n\n/** A page-space run flipped top to bottom, for the y-up math of the text layout and its helpers. */\nexport function mirroredRun(\n run: PageGeometryRun<PageCoordinates>,\n): PageGeometryRun<PdfCoordinates> {\n const rect = hasBox(run) ? mirroredRect(run.rect) : NO_RECT;\n if (isRotatedGeometryRun(run)) {\n return {\n ...run,\n rect,\n glyphs: run.glyphs.map(({ loose, tight, ...glyph }) => ({\n ...glyph,\n loose: glyph.empty ? NO_QUAD : mirroredQuad(loose),\n ...(tight ? { tight: mirroredQuad(tight) } : {}),\n })),\n };\n }\n return {\n ...run,\n rect,\n glyphs: run.glyphs.map(({ loose, tight, ...glyph }) => ({\n ...glyph,\n loose: glyph.empty ? NO_RECT : mirroredRect(loose),\n ...(tight ? { tight: mirroredRect(tight) } : {}),\n })),\n };\n}\n\nexport function pageTextSegmentOf(\n segment: PdfTextSegment<PdfCoordinates>,\n visible: PdfRect,\n): PdfTextSegment<PageCoordinates> {\n return {\n ...segment,\n quad: pageQuadOf(segment.quad, visible),\n rect: pageBoxOf(segment.rect, visible),\n };\n}\n\n/** A search batch in page space: each match measured on its own page. */\nexport function pageSearchSliceOf(\n slice: SearchSlice<PdfCoordinates>,\n boxOf: VisibleBoxOf,\n): SearchSlice<PageCoordinates> {\n return {\n ...slice,\n matches: slice.matches.map((match): SearchMatch<PageCoordinates> => {\n const visible = boxOf(match.page);\n return {\n ...match,\n segments: match.segments.map((segment) => pageTextSegmentOf(segment, visible)),\n };\n }),\n };\n}\n\n/**\n * The layout of a page's text geometry in page space. It runs the same\n * layout as the file's coordinates do, on the geometry flipped top to bottom,\n * and flips each answer back: the flip is exact and the layout doesn't depend\n * on where the origin is.\n */\nexport function createTextLayout(snapshot: PageGeometrySnapshot): TextLayout {\n const layout = createPdfTextLayout({ ...snapshot, runs: snapshot.runs.map(mirroredRun) });\n const at = (value: { x: number; y: number } | number) =>\n typeof value === 'number' ? value : mirroredPoint(value);\n return {\n charCount: layout.charCount,\n runs: snapshot.runs,\n charAt: (point) => layout.charAt(mirroredPoint(point)),\n wordAt: (value) => layout.wordAt(at(value)),\n lineAt: (value) => layout.lineAt(at(value)),\n segments: (range) =>\n layout.segments(range).map((segment) => ({\n ...segment,\n quad: unmirroredQuad(segment.quad),\n rect: unmirroredBox(segment.rect),\n })),\n charQuad: (index) => {\n const quad = layout.charQuad(index);\n return quad ? unmirroredQuad(quad) : null;\n },\n };\n}\n","import type { Annotation } from './kinds';\nimport type { PdfCoordinates } from '../pageSpace/coordinates';\nimport { pdfPointTurned, pdfTurnOfUpright } from '../geometry/pointTurn';\nimport type { PdfPoint } from '../geometry/primitives';\n\n/**\n * The points of a line, polyline, polygon or ink as the page shows them: the\n * upright points a read gives, turned by `rotation` about the middle of their\n * box. One list for a line (its two ends) or a polygon, one per ink stroke;\n * `null` for any other kind.\n */\nexport function pdfDrawnPointsOf(annotation: Annotation<PdfCoordinates>): PdfPoint[][] | null {\n let sets: PdfPoint[][];\n switch (annotation.subtype) {\n case 'line':\n sets = [[annotation.linePoints.start, annotation.linePoints.end]];\n break;\n case 'polyline':\n case 'polygon':\n sets = [annotation.vertices];\n break;\n case 'ink':\n sets = annotation.inkList.map((stroke) => [...stroke]);\n break;\n default:\n return null;\n }\n if (!annotation.rotation) return sets.map((set) => set.map((point) => ({ ...point })));\n const turn = pdfTurnOfUpright(sets.flat(), annotation.rotation);\n return sets.map((set) => set.map((point) => pdfPointTurned(point, turn)));\n}\n","import { actionTreeOf } from '../../dto/PdfLinkTarget';\nimport {\n DEFAULT_RICH_TEXT_BODY,\n type RichTextBody,\n type RichTextDocument,\n} from '../../dto/RichText';\nimport type { AnnotationRef } from '../../identity/AnnotationRef';\nimport type { Coordinates } from '../../pageSpace/coordinates';\nimport { UNBAKED_KINDS } from '../appearance';\nimport { annotationDefaultsOf } from '../defaults';\nimport type { DescribeFont } from '../fontFaces';\nimport { kindFactsOf } from '../kind-facts';\nimport type { AnnotationDraft, Annotation } from '../kinds';\nimport { readValueOf } from './applyAnnotationPatch';\n\n/** Who the engine stamps as creating an annotation, and when. */\nexport type DraftAttribution = Readonly<\n Partial<\n Record<'author' | 'userId' | 'createdBy' | 'modifiedBy' | 'createdAt' | 'modifiedAt', string>\n >\n>;\n\n/**\n * What a draft alone doesn't say about the annotation it creates: its name,\n * who creates it, and what the engine works out from its drawing.\n */\nexport interface DraftContext<Box = unknown> {\n /** The ref the read names it by. */\n readonly ref: AnnotationRef;\n /**\n * The name the engine gives it when the draft has no `nm`: a fresh UUIDv7\n * the engine mints. Left out, the prediction says `null` until the engine\n * answers.\n */\n readonly nm?: string;\n /** Who creates it and when, as the engine stamps it. Left out, a read says `null`. */\n readonly attribution?: DraftAttribution;\n /**\n * The upright box around what it draws, for a kind whose `rect` the engine\n * works out (a shape, a line, text markup). Left out: its `box`.\n */\n readonly rect?: Box;\n /** Looks up a registered font, for a free text in one. */\n readonly describeFont?: DescribeFont;\n}\n\nconst NO_BOX = { x: 0, y: 0, width: 0, height: 0 };\n\n/**\n * A free text's rich text as a read spells it, and the text style it reads\n * back with: the resolved body over the engine's defaults, and its size,\n * text color and alignment beside it. The font keeps the name the draft\n * gave, or the default.\n */\nfunction freeTextReadOf(given: Record<string, unknown>, read: Record<string, unknown>) {\n const richText = given.richText as { body?: Partial<RichTextBody> } | undefined;\n const body = { ...DEFAULT_RICH_TEXT_BODY, ...richText?.body };\n body.color = body.color.toLowerCase();\n read.richText = { ...(read.richText as RichTextDocument), body };\n read.fontSize = body.size;\n read.fontColor = body.color;\n read.textAlign = body.align;\n}\n\n/**\n * The annotation a resolved draft creates, as a read spells it: the draft's\n * data fields, the kind's defaults for those it leaves out, and what\n * `context` says for the fields the engine owns or stamps. Works in either\n * space: it only moves values by field name.\n */\nexport function annotationOfResolvedDraft<C extends Coordinates>(\n resolved: AnnotationDraft<C>,\n context: DraftContext,\n): Annotation<C> {\n const subtype = resolved.subtype;\n const owners = kindFactsOf(subtype)?.owners ?? {};\n const defaults = annotationDefaultsOf(subtype);\n const given = resolved as unknown as Record<string, unknown>;\n const read: Record<string, unknown> = { subtype };\n for (const [name, owner] of Object.entries(owners)) {\n if (owner === 'data' && given[name] !== undefined) {\n read[name] = readValueOf(name, given[name], undefined);\n } else if (owner === 'data') {\n read[name] = defaults[name] ?? null;\n } else if (owner === 'attribution') {\n read[name] = context.attribution?.[name as keyof DraftAttribution] ?? null;\n } else {\n read[name] = null;\n }\n }\n if (read.nm === null && context.nm !== undefined) read.nm = context.nm;\n read.ref = context.ref;\n read.page = context.ref.page;\n read.hasAppearance = !UNBAKED_KINDS.has(subtype);\n if (read.rect === null) read.rect = context.rect ?? given.rect ?? given.box ?? NO_BOX;\n\n if (subtype === 'free-text') freeTextReadOf(given, read);\n if (subtype === 'link') {\n const target = given.target as { kind: string } | null | undefined;\n read.actions =\n target && (target.kind === 'uri' || target.kind === 'goto')\n ? { activate: actionTreeOf(target as Parameters<typeof actionTreeOf>[0]) }\n : null;\n }\n if (subtype === 'widget') {\n // A widget created on its own belongs to no field (`field: null`) until a form adopts it.\n read.fieldFamily = 'unknown';\n }\n return read as unknown as Annotation<C>;\n}\n","/**\n * The engine's geometry helpers, for page-space values. Each flips its\n * values top to bottom, runs the helper written for the file's coordinates\n * (y up), and flips the answer back: exact, and needing no page box, since\n * none of that math depends on where the origin is.\n */\n\nimport {\n pageAnnotationDraftOf,\n pageAnnotationPatchOf,\n pdfAnnotationDraftOf,\n pdfAnnotationOf,\n pdfAnnotationPatchOf,\n} from './annotations';\nimport type { PageCoordinates, PdfCoordinates } from './coordinates';\nimport type { VisibleBoxOf } from './destinations';\nimport { mirroredRun } from './text';\nimport { pdfAppearanceTurnOf } from '../annotation/appearanceTurn';\nimport { pdfDrawnPointsOf } from '../annotation/drawnPoints';\nimport { semanticEqual } from '../annotation/appearance';\nimport type { AnnotationDraft, Annotation, AnnotationPatch } from '../annotation/kinds';\nimport {\n annotationOfResolvedDraft,\n type DraftContext,\n} from '../annotation/resolve/annotationOfDraft';\nimport {\n pdfPredictAnnotationDraft,\n type DraftResolveOptions,\n} from '../annotation/resolve/resolveAnnotationDraft';\nimport { pdfResolveRectCommand } from '../annotation/resolve/rectCommand';\nimport { applyResolvedPatch } from '../annotation/resolve/applyAnnotationPatch';\nimport {\n pdfPredictAnnotationPatch,\n type ResolveOptions,\n} from '../annotation/resolve/resolveAnnotationPatch';\nimport { DRAWN_RECT_KINDS, pdfShapeForRect, shapeFieldsOf } from '../annotation/shapeForRect';\nimport {\n glyphLooseBounds,\n glyphLooseQuad,\n type PageGeometryRun,\n} from '../dto/PageGeometrySnapshot';\nimport { isRotatedGeometryRun } from '../dto/PageGeometrySnapshot';\nimport { pdfQuadBounds } from '../geometry/convert';\nimport {\n mirroredPoint,\n mirroredQuad,\n mirroredRect,\n unmirroredBox,\n unmirroredPoint,\n unmirroredQuad,\n type PageBox,\n type PagePoint,\n type PageQuad,\n} from '../geometry/pageSpace';\nimport {\n pdfPointsBounds,\n pdfPointTurned,\n pdfPointUnturned,\n pdfTurnOfDrawn,\n pdfTurnOfUpright,\n type PdfPointTurn,\n} from '../geometry/pointTurn';\nimport type { PdfRect } from '../geometry/primitives';\n\n/** A turn in page space: degrees clockwise, as the page shows it, about `center`. */\nexport interface PagePointTurn {\n degrees: number;\n center: PagePoint;\n}\n\nconst mirroredTurn = (turn: PagePointTurn): PdfPointTurn => ({\n degrees: turn.degrees,\n center: mirroredPoint(turn.center),\n});\n\nconst unmirroredTurn = (turn: PdfPointTurn): PagePointTurn => ({\n degrees: turn.degrees,\n center: unmirroredPoint(turn.center),\n});\n\n/** The box around `points`; a zero box at the origin when there are none. */\nexport const pagePointsBounds = (points: readonly PagePoint[]): PageBox =>\n unmirroredBox(pdfPointsBounds(points.map(mirroredPoint)));\n\n/** `point` turned by `turn`; a negative angle turns it back. */\nexport const pagePointTurned = (point: PagePoint, turn: PagePointTurn): PagePoint =>\n unmirroredPoint(pdfPointTurned(mirroredPoint(point), mirroredTurn(turn)));\n\n/** `point` turned back by `turn`. */\nexport const pagePointUnturned = (point: PagePoint, turn: PagePointTurn): PagePoint =>\n unmirroredPoint(pdfPointUnturned(mirroredPoint(point), mirroredTurn(turn)));\n\n/** The turn that draws upright `points`: `degrees` about the middle of their box. */\nexport const pageTurnOfUpright = (points: readonly PagePoint[], degrees: number): PagePointTurn =>\n unmirroredTurn(pdfTurnOfUpright(points.map(mirroredPoint), degrees));\n\n/** The turn drawn `points` were made with: `degrees` about the middle of their upright box. */\nexport const pageTurnOfDrawn = (points: readonly PagePoint[], degrees: number): PagePointTurn =>\n unmirroredTurn(pdfTurnOfDrawn(points.map(mirroredPoint), degrees));\n\n/** The upright box around a quad, whatever its turn or skew. */\nexport const pageQuadBounds = (quad: PageQuad): PageBox =>\n unmirroredBox(pdfQuadBounds(mirroredQuad(quad)));\n\n/** A glyph's loose cell as a quad. */\nexport const pageGlyphLooseQuad = (\n run: PageGeometryRun<PageCoordinates>,\n index: number,\n): PageQuad => unmirroredQuad(glyphLooseQuad(mirroredRun(run), index));\n\n/** A glyph's loose cell as an upright box. */\nexport const pageGlyphLooseBounds = (\n run: PageGeometryRun<PageCoordinates>,\n index: number,\n): PageBox => unmirroredBox(glyphLooseBounds(mirroredRun(run), index));\n\n/**\n * The points of a line, polyline, polygon or ink as the page shows them: the\n * upright points a read gives, turned by `rotation` about the middle of their\n * box. One list for a line (its two ends) or a polygon, one per ink stroke;\n * `null` for any other kind.\n */\nexport function drawnPointsOf(annotation: Annotation): PagePoint[][] | null {\n const flip = (points: readonly PagePoint[]) => points.map(mirroredPoint);\n let mirrored: object;\n switch (annotation.subtype) {\n case 'line':\n mirrored = {\n subtype: 'line',\n rotation: annotation.rotation,\n linePoints: {\n start: mirroredPoint(annotation.linePoints.start),\n end: mirroredPoint(annotation.linePoints.end),\n },\n };\n break;\n case 'polyline':\n case 'polygon':\n mirrored = {\n subtype: annotation.subtype,\n rotation: annotation.rotation,\n vertices: flip(annotation.vertices),\n };\n break;\n case 'ink':\n mirrored = {\n subtype: 'ink',\n rotation: annotation.rotation,\n inkList: annotation.inkList.map(flip),\n };\n break;\n default:\n return null;\n }\n const sets = pdfDrawnPointsOf(mirrored as Annotation<PdfCoordinates>);\n return sets && sets.map((set) => set.map(unmirroredPoint));\n}\n\n/**\n * The turn an annotation's appearance raster is drawn without, degrees\n * clockwise, or `null` when the raster is drawn as the page shows it. A box\n * kind drawn turned whose drawing stays inside the turned box (its `rect` is\n * the upright box around it) renders upright over its `box`, for the\n * consumer to turn about the middle of `box`: a new turn needs no new\n * raster. A callout (its line isn't turned) and a drawing that reaches past\n * its box (a cloudy border's bumps) render as the page shows them, placed by\n * `rect`.\n */\nexport function appearanceTurnOf(annotation: {\n subtype: string;\n rect: PageBox;\n box?: PageBox | null;\n rotation?: number | null;\n intent?: string | null;\n}): number | null {\n return pdfAppearanceTurnOf({\n ...annotation,\n rect: mirroredRect(annotation.rect),\n box: annotation.box ? mirroredRect(annotation.box) : annotation.box,\n });\n}\n\n/** Page space with its origin as the file's: turning one into the other is the mirror. */\nconst MIRROR: PdfRect = { left: 0, bottom: 0, right: 0, top: 0 };\n\n/** Shape fields hold no destinations, so nothing asks for another page's box. */\nconst noOtherPage: VisibleBoxOf = () => {\n throw new Error('a shape field holds no destination');\n};\n\n/**\n * The shape fields that put `annotation` at `rect`, the rule an update's\n * `rect` follows (`create({ ...copy, ...shapeForRect(copy, target) })` puts a\n * copy there).\n *\n * - A kind whose shape is its rect (note, file attachment, link, popup,\n * redaction) takes `rect` as it is.\n * - A drawn kind has every place it holds mapped from its current `rect` onto\n * `rect`, each axis on its own, as Acrobat does when a script sets\n * `annot.rect`: a rect of the same size moves the shape, a bigger one\n * stretches it. The engine then works out the rect from the shape, so it\n * can differ a little from `rect` (a stroke keeps its width). A box at a\n * quarter turn stretches along its own sides, as it stands on the page.\n *\n * A drawn kind refuses a rect that would squash it to no width or height, a\n * rect of another size when it's turned (it can only move) unless it is a\n * box at a quarter turn, and one when its own rect has no width or height to\n * stretch. Each refusal is `InvalidArg` on `rect`.\n */\nexport function shapeForRect<A extends Annotation>(annotation: A, rect: PageBox): Partial<A> {\n if (!DRAWN_RECT_KINDS.has(annotation.subtype)) return { rect } as Partial<A>;\n const read = annotation as unknown as Record<string, unknown>;\n const shape = Object.fromEntries(\n ['subtype', 'rect', ...shapeFieldsOf(annotation.subtype)]\n .filter((name) => read[name] !== undefined)\n .map((name) => [name, read[name]]),\n );\n const mirrored = pdfAnnotationOf(shape as Annotation, MIRROR, noOtherPage);\n const placed = pdfShapeForRect(mirrored, mirroredRect(rect));\n // The kind picks what each field holds; the answer is only the shape.\n const { subtype: _kind, ...fields } = pageAnnotationPatchOf(\n { subtype: annotation.subtype, ...placed } as never,\n MIRROR,\n noOtherPage,\n );\n return fields as unknown as Partial<A>;\n}\n\n/**\n * `patch` with its `rect` resolved as the engine resolves it on update (the\n * same step, `pdfResolveRectCommand`):\n *\n * - the rect the annotation reads, sent back, is dropped: nothing moves;\n * - on a drawn kind, another rect becomes the shape fields that put the\n * drawing there (`shapeForRect`);\n * - a new rect with a changed shape field is refused (`InvalidArg` on\n * `rect`): which of the two to follow would be a guess.\n *\n * A kind whose shape is its rect keeps it as a plain field. A viewer runs\n * this before it merges fields it writes itself, so a `rect` behaves the same\n * from every door. Values `patch` gives come back as given.\n */\nexport function resolveRectCommand(\n annotation: Annotation,\n patch: AnnotationPatch,\n): AnnotationPatch {\n const given = patch as Record<string, unknown>;\n if (given.rect === undefined || !DRAWN_RECT_KINDS.has(annotation.subtype)) return patch;\n const read = annotation as unknown as Record<string, unknown>;\n const shapeNames = shapeFieldsOf(annotation.subtype);\n const pick = (from: Record<string, unknown>, names: readonly string[]) =>\n Object.fromEntries(\n names.filter((name) => from[name] !== undefined).map((name) => [name, from[name]]),\n );\n const current = pdfAnnotationOf(\n { subtype: annotation.subtype, ...pick(read, ['rect', ...shapeNames]) } as Annotation,\n MIRROR,\n noOtherPage,\n );\n const command = pdfAnnotationPatchOf(\n { subtype: annotation.subtype, ...pick(given, ['rect', ...shapeNames]) } as AnnotationPatch,\n MIRROR,\n noOtherPage,\n );\n const { subtype: _kind, ...placed } = pageAnnotationPatchOf(\n pdfResolveRectCommand(current, command),\n MIRROR,\n noOtherPage,\n ) as Record<string, unknown>;\n const { rect: _rect, ...rest } = given;\n const out: Record<string, unknown> = { ...rest };\n for (const [name, value] of Object.entries(placed)) {\n // The round trip through the file's edges can move a last digit: a value\n // the caller gave, that the command didn't change, is the caller's own.\n out[name] =\n given[name] !== undefined && semanticEqual(value, given[name]) ? given[name] : value;\n }\n return out as AnnotationPatch;\n}\n\n/**\n * Every page's box is the mirror, so a link's destination makes the round\n * trip into the file's coordinates and back unchanged, with no real page.\n */\nconst mirrorEveryPage: VisibleBoxOf = () => MIRROR;\n\n/**\n * The patch the engine writes for `patch` on `current`, as a viewer predicts\n * it: its subtype filled in, and every field that follows from it stated. A\n * drawn kind's new `rect` becomes the shape fields that put it there, values\n * sent back as read are dropped, a note's standard review state brings its\n * state model, a free text's contents and rich text follow each other, a\n * callout's line stays attached to its moved box, and a measurement's label\n * follows its points and scale. Values `patch` gives come back as given.\n *\n * Throws `InvalidArg` for what the engine refuses without its schemas: a\n * field the kind doesn't declare, a changed subtype or name, a rect with a\n * new shape or that isn't finite, and where nothing can follow. The engine\n * checks the values against the kind's schema when the update reaches it,\n * and refuses there what this lets through.\n */\nexport function resolveAnnotationPatch(\n current: Annotation,\n patch: AnnotationPatch,\n options: ResolveOptions = {},\n): AnnotationPatch {\n const resolved = pdfPredictAnnotationPatch(\n pdfAnnotationOf(current, MIRROR, mirrorEveryPage),\n pdfAnnotationPatchOf(\n { ...patch, subtype: patch.subtype ?? current.subtype } as AnnotationPatch,\n MIRROR,\n mirrorEveryPage,\n ),\n options,\n );\n const back = pageAnnotationPatchOf(resolved, MIRROR, mirrorEveryPage) as Record<string, unknown>;\n // The round trip through the file's edges can move a box's last digit: a\n // value the caller gave, that no rule changed, is the caller's own.\n const given = patch as Record<string, unknown>;\n for (const name of Object.keys(back)) {\n if (given[name] !== undefined && semanticEqual(back[name], given[name]))\n back[name] = given[name];\n }\n return back as AnnotationPatch;\n}\n\n/**\n * `current` as the engine will read it after `patch`: what a viewer shows\n * while the write is on its way. Fields the engine works out or stamps itself\n * (a drawn kind's `rect`, the modified date and author) keep their current\n * value until the engine's answer brings the new one. A field `patch` leaves\n * alone keeps its very value.\n */\nexport function applyAnnotationPatch<A extends Annotation>(\n current: A,\n patch: AnnotationPatch,\n options: ResolveOptions = {},\n): A {\n return applyResolvedPatch(current, resolveAnnotationPatch(current, patch, options));\n}\n\n/**\n * The draft the engine writes for `draft`, as a viewer predicts it: every\n * field that follows from it stated. A box kind placed by its `rect` states\n * its `box`, a note's standard review state brings its state model, a free\n * text's rich text and contents follow each other, and a measurement's label\n * follows its points and scale. Fields left out stay out: the kind's\n * defaults (`ANNOTATION_DEFAULTS`) say what they read back. Values `draft`\n * gives come back as given.\n *\n * Throws `InvalidArg` for what the engine refuses without its schemas: a\n * field the kind doesn't declare, a box kind it can't place, and where\n * nothing can follow. The engine checks the values against the kind's schema\n * when the create reaches it, and refuses there what this lets through.\n */\nexport function resolveAnnotationDraft(\n draft: AnnotationDraft,\n options: DraftResolveOptions = {},\n): AnnotationDraft {\n const resolved = pdfPredictAnnotationDraft(\n pdfAnnotationDraftOf(draft, MIRROR, mirrorEveryPage),\n options,\n );\n const back = pageAnnotationDraftOf(resolved, MIRROR, mirrorEveryPage) as Record<string, unknown>;\n const given = draft as Record<string, unknown>;\n for (const name of Object.keys(back)) {\n if (given[name] !== undefined && semanticEqual(back[name], given[name]))\n back[name] = given[name];\n }\n return back as AnnotationDraft;\n}\n\n/**\n * The annotation the engine will read back after creating `draft`: what a\n * viewer shows while the create is on its way. `context` says what the draft\n * doesn't: the ref and place it will have, who creates it, and, for a kind\n * whose `rect` the engine works out from its drawing, that box. The draft is\n * resolved as `resolveAnnotationDraft` does it, without the engine's schema\n * check: a create the engine refuses leaves the view when it answers.\n */\nexport function annotationOfDraft(\n draft: AnnotationDraft,\n context: DraftContext<PageBox>,\n): Annotation {\n return annotationOfResolvedDraft(\n resolveAnnotationDraft(draft, { describeFont: context.describeFont }),\n context,\n );\n}\n","import type { TextRange } from '../text/TextRange';\n\n/**\n * Text folding for literal search: the deterministic normalization applied\n * to both the page text and the needle so that \"Café\" finds \"cafe\" and a\n * line-wrapped \"hello\\n world\" finds \"hello world\".\n *\n * Fold version 1:\n * - whitespace runs collapse to a single space (any `\\s`, including the\n * spaces some compatibility decompositions emit) — or are dropped\n * entirely with `dropWhitespace` (ignoreWhitespace),\n * - each code point is NFKD-decomposed (ligatures split: \"fi\" → \"fi\",\n * \"²\" → \"2\"),\n * - combining marks are stripped unless `keepMarks`,\n * - case is folded via upper→lower round-trip unless `keepCase` (this\n * poor-man's full fold catches \"ß\"→\"ss\" and \"ς\"→\"σ\", which a plain\n * `toLowerCase` misses).\n *\n * Every folded code unit remembers which original code point produced it\n * (`map`), so match ranges found in folded space translate back to exact\n * original-text ranges — the property the whole anchor stage rests on.\n *\n * Pre-folded corpus artifacts store this fold's output; bump\n * `SEARCH_FOLD_VERSION` on any semantic change so stored corpora are\n * rebuilt instead of silently mismatching fresh needles.\n */\n\n/** Version stamp for persisted pre-folded corpus artifacts. */\nexport const SEARCH_FOLD_VERSION = 1;\n\nexport interface FoldOptions {\n /** Preserve case (matchCase). */\n keepCase?: boolean;\n /** Preserve combining marks (matchDiacritics). */\n keepMarks?: boolean;\n /** Drop whitespace instead of collapsing it to one space (ignoreWhitespace). */\n dropWhitespace?: boolean;\n}\n\nexport interface FoldedText {\n folded: string;\n /** Folded code unit i → code-unit index of the original code point it came from. */\n map: Uint32Array;\n original: string;\n}\n\nconst WHITESPACE = /\\s/;\nconst MARKS = /\\p{M}/gu;\n\nexport function foldText(original: string, options: FoldOptions = {}): FoldedText {\n const units: string[] = [];\n const map: number[] = [];\n let lastWasSpace = false;\n\n let index = 0;\n for (const cp of original) {\n let piece: string;\n if (WHITESPACE.test(cp)) {\n piece = ' ';\n } else {\n piece = cp.normalize('NFKD');\n if (!options.keepMarks) piece = piece.replace(MARKS, '');\n if (!options.keepCase) piece = piece.toUpperCase().toLowerCase();\n }\n // A decomposition can itself contain whitespace (U+00A8 → space +\n // combining diaeresis), so collapse (or drop) runs at the unit level,\n // not just for source whitespace.\n for (let u = 0; u < piece.length; u++) {\n const unit = piece[u];\n if (WHITESPACE.test(unit)) {\n if (options.dropWhitespace || lastWasSpace) continue;\n units.push(' ');\n map.push(index);\n lastWasSpace = true;\n } else {\n units.push(unit);\n map.push(index);\n lastWasSpace = false;\n }\n }\n index += cp.length;\n }\n\n return { folded: units.join(''), map: Uint32Array.from(map), original };\n}\n\n/** Code-unit length of the code point starting at `index` (1 or 2). */\nfunction codePointLengthAt(text: string, index: number): number {\n const unit = text.charCodeAt(index);\n if (unit >= 0xd800 && unit <= 0xdbff && index + 1 < text.length) {\n const next = text.charCodeAt(index + 1);\n if (next >= 0xdc00 && next <= 0xdfff) return 2;\n }\n return 1;\n}\n\n/**\n * Translate a match found in folded space back to a range of the original\n * text (code units).\n * The range covers whole original code points: a hit on either folded\n * half of \"fi\" spans the full ligature, and a hit ending on a collapsed\n * space extends only through the first whitespace char of the run (the\n * remainder is presentation, not match).\n */\nexport function toOriginalRange(\n folded: FoldedText,\n foldedStart: number,\n foldedLength: number,\n): TextRange {\n const start = folded.map[foldedStart];\n const lastOriginal = folded.map[foldedStart + foldedLength - 1];\n const end = lastOriginal + codePointLengthAt(folded.original, lastOriginal);\n return { start, count: end - start };\n}\n","export const METRES = {\n pt: 0.0254 / 72,\n mm: 0.001,\n cm: 0.01,\n m: 1,\n km: 1000,\n in: 0.0254,\n ft: 0.3048,\n yd: 0.9144,\n mi: 1609.344,\n} as const;\nexport type LengthUnit = keyof typeof METRES;\nexport type AreaUnit = `${LengthUnit}2` | 'ha' | 'acre';\nexport const squareOf = (unit: LengthUnit): AreaUnit => `${unit}2`;\nexport function squareMetres(unit: AreaUnit): number {\n return unit === 'ha'\n ? 10000\n : unit === 'acre'\n ? 4046.8564224\n : METRES[unit.slice(0, -1) as LengthUnit] ** 2;\n}\nexport const areaUnitLabel = (unit: AreaUnit): string =>\n unit.endsWith('2') ? unit.slice(0, -1) + '²' : unit;\n","import { assertWritableMeasure } from './validate';\nimport type { PdfMeasure, PdfNumberFormat } from '../dto/Measure';\nimport { EngineError } from '../errors/EngineError';\nimport { EngineErrorCode } from '../errors/EngineErrorCode';\nimport {\n areaUnitLabel,\n METRES,\n squareMetres,\n squareOf,\n type AreaUnit,\n type LengthUnit,\n} from './units';\n\nexport interface MeasurementFormatOptions {\n /** Decimals, as 1, 10, 100, …: 100 shows two. Default 100. */\n precision?: number;\n fixed?: boolean;\n areaUnit?: AreaUnit;\n imperialFeetInches?: boolean;\n /** Inch fraction denominator when imperialFeetInches is true. Default 16. */\n fractionalPrecision?: number;\n}\n/** {@link measureFromRatio}'s options: how values are shown, and the page's user unit. */\nexport interface MeasureFromRatioOptions extends MeasurementFormatOptions {\n /** The page's `/UserUnit`: a point is this many 1/72 inch. Default 1. */\n userUnit?: number;\n}\n\nfunction invalid(message: string): EngineError {\n return new EngineError(EngineErrorCode.InvalidArg, message);\n}\n\nfunction positive(value: number): void {\n if (!Number.isFinite(value) || value <= 0) {\n throw invalid('Calibration requires finite positive lengths and scales');\n }\n}\nfunction build(\n perPoint: number,\n unit: LengthUnit,\n ratio: string,\n format: MeasurementFormatOptions,\n): PdfMeasure {\n positive(Math.fround(perPoint));\n const precision = format.precision ?? 100;\n if (!Number.isInteger(Math.log10(precision)) || precision < 1 || precision > 1e9) {\n throw invalid('Invalid decimal precision');\n }\n const areaUnit = format.areaUnit ?? squareOf(unit);\n const common = {\n precision,\n ...(format.fixed === undefined ? {} : { fixed: format.fixed }),\n };\n const distance: PdfNumberFormat[] = format.imperialFeetInches\n ? [\n { unit: 'ft', conversion: Math.fround(METRES[unit] / METRES.ft) },\n {\n unit: 'in',\n conversion: 12,\n fraction: 'fraction',\n precision: format.fractionalPrecision ?? 16,\n ...('fixed' in common ? { fixed: common.fixed } : {}),\n },\n ]\n : [{ unit, conversion: 1, ...common }];\n if (\n format.imperialFeetInches &&\n (!Number.isInteger(distance[1].precision) ||\n distance[1].precision! < 1 ||\n distance[1].precision! > 2147483647)\n )\n throw invalid('Invalid fraction denominator');\n const measure: PdfMeasure = {\n subtype: 'rectilinear',\n ratio,\n x: [{ unit, conversion: Math.fround(perPoint), ...common }],\n distance,\n area: [\n {\n unit: areaUnitLabel(areaUnit),\n conversion: Math.fround(METRES[unit] ** 2 / squareMetres(areaUnit)),\n ...common,\n },\n ],\n };\n assertWritableMeasure(measure);\n return measure;\n}\nexport function measureFromKnownLength(\n userSpaceLength: number,\n real: { value: number; unit: LengthUnit },\n format: MeasurementFormatOptions = {},\n): PdfMeasure {\n positive(userSpaceLength);\n positive(real.value);\n const perPoint = real.value / userSpaceLength;\n return build(\n perPoint,\n real.unit,\n `1 in = ${Number((perPoint * 72).toPrecision(8))} ${real.unit}`,\n format,\n );\n}\nexport function measureFromRatio(\n paper: number,\n real: number,\n unit: LengthUnit,\n options: MeasureFromRatioOptions = {},\n): PdfMeasure {\n const { userUnit = 1, ...format } = options;\n positive(paper);\n positive(real);\n positive(userUnit);\n return build(\n ((userUnit / 72) * 0.0254 * (real / pa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