@embedpdf/engine-core 3.0.0-next.13 → 3.0.0-next.15

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-CkijRHet.d.cts +27163 -0
  2. package/dist/AnnotationList-CkijRHet.d.ts +27163 -0
  3. package/dist/Change-CKoxfTNY.js +889 -0
  4. package/dist/Change-CKoxfTNY.js.map +1 -0
  5. package/dist/Change-CjImsrN0.cjs +1020 -0
  6. package/dist/Change-CjImsrN0.cjs.map +1 -0
  7. package/dist/DocumentRenderService-BfFdFSwI.cjs +120 -0
  8. package/dist/DocumentRenderService-BfFdFSwI.cjs.map +1 -0
  9. package/dist/DocumentRenderService-DV3J9lMz.js +85 -0
  10. package/dist/DocumentRenderService-DV3J9lMz.js.map +1 -0
  11. package/dist/{DocumentSecurityService-_JRjqvoI.d.ts → DocumentSecurityService-CU1M6Q7m.d.ts} +100 -112
  12. package/dist/{DocumentSecurityService-ClTZc0zO.d.cts → DocumentSecurityService-e6vp2de8.d.cts} +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-DFoBm4B3.d.cts +1565 -0
  18. package/dist/LocalEngine-DPriFujS.d.ts +1565 -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-B3BklsB4.js +2239 -0
  24. package/dist/authority-B3BklsB4.js.map +1 -0
  25. package/dist/authority-DLMNR7ff.cjs +2676 -0
  26. package/dist/authority-DLMNR7ff.cjs.map +1 -0
  27. package/dist/builders-CNj0POeY.js +161 -0
  28. package/dist/builders-CNj0POeY.js.map +1 -0
  29. package/dist/builders-Cgdp_YCn.cjs +184 -0
  30. package/dist/builders-Cgdp_YCn.cjs.map +1 -0
  31. package/dist/calibrate-7T3fnP8-.js +2404 -0
  32. package/dist/calibrate-7T3fnP8-.js.map +1 -0
  33. package/dist/calibrate-DJBXnhLE.cjs +2919 -0
  34. package/dist/calibrate-DJBXnhLE.cjs.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 +16753 -5247
  40. package/dist/conformance.cjs.map +1 -1
  41. package/dist/conformance.d.cts +928 -165
  42. package/dist/conformance.d.ts +928 -165
  43. package/dist/conformance.js +16731 -5268
  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 +330 -103
  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 +57 -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-CzxmD9Ck.js} +294 -144
  66. package/dist/resolver-CzxmD9Ck.js.map +1 -0
  67. package/dist/{resolver-CYVNV4hn.cjs → resolver-D2OCtE8F.cjs} +347 -143
  68. package/dist/resolver-D2OCtE8F.cjs.map +1 -0
  69. package/dist/runtime-Cl0v56mm.d.ts +2032 -0
  70. package/dist/runtime-p1WDzDo4.d.cts +2032 -0
  71. package/dist/runtime.cjs +733 -284
  72. package/dist/runtime.cjs.map +1 -1
  73. package/dist/runtime.d.cts +5 -1348
  74. package/dist/runtime.d.ts +5 -1348
  75. package/dist/runtime.js +396 -179
  76. package/dist/runtime.js.map +1 -1
  77. package/dist/schema-C-gU4vj7.cjs +3034 -0
  78. package/dist/schema-C-gU4vj7.cjs.map +1 -0
  79. package/dist/schema-DzlUNk38.js +2081 -0
  80. package/dist/schema-DzlUNk38.js.map +1 -0
  81. package/dist/schemas-Berf1swF.cjs +2481 -0
  82. package/dist/schemas-Berf1swF.cjs.map +1 -0
  83. package/dist/schemas-D6xOGjqg.js +1654 -0
  84. package/dist/schemas-D6xOGjqg.js.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-BJW13EGZ.js +540 -0
  100. package/dist/viewport-BJW13EGZ.js.map +1 -0
  101. package/dist/viewport-DlL5Bxbg.cjs +671 -0
  102. package/dist/viewport-DlL5Bxbg.cjs.map +1 -0
  103. package/dist/wire.cjs +1056 -379
  104. package/dist/wire.cjs.map +1 -1
  105. package/dist/wire.d.cts +15069 -725
  106. package/dist/wire.d.ts +15069 -725
  107. package/dist/wire.js +825 -239
  108. package/dist/wire.js.map +1 -1
  109. package/package.json +10 -1
  110. package/dist/AbortError-Cq2igpZ6.cjs +0 -38
  111. package/dist/AbortError-Cq2igpZ6.cjs.map +0 -1
  112. package/dist/AbortError-DHqPBnYc.js +0 -27
  113. package/dist/AbortError-DHqPBnYc.js.map +0 -1
  114. package/dist/AnnotationListSnapshot-D3mFut1e.d.cts +0 -6871
  115. package/dist/AnnotationListSnapshot-D3mFut1e.d.ts +0 -6871
  116. package/dist/Engine-Bx0NOfmd.d.cts +0 -1264
  117. package/dist/Engine-DxtpCYcP.d.ts +0 -1264
  118. package/dist/PageInsertBlankInput-CqXBmFhN.cjs +0 -449
  119. package/dist/PageInsertBlankInput-CqXBmFhN.cjs.map +0 -1
  120. package/dist/PageInsertBlankInput-cHq9-i-z.js +0 -378
  121. package/dist/PageInsertBlankInput-cHq9-i-z.js.map +0 -1
  122. package/dist/builders-Bqm8yTpi.cjs +0 -3564
  123. package/dist/builders-Bqm8yTpi.cjs.map +0 -1
  124. package/dist/builders-Dqo2X-dt.js +0 -3121
  125. package/dist/builders-Dqo2X-dt.js.map +0 -1
  126. package/dist/fold-2V29cxCV.cjs +0 -447
  127. package/dist/fold-2V29cxCV.cjs.map +0 -1
  128. package/dist/fold-CdEJTBTn.js +0 -334
  129. package/dist/fold-CdEJTBTn.js.map +0 -1
  130. package/dist/resolver-CYVNV4hn.cjs.map +0 -1
  131. package/dist/resolver-inAVzsWt.js.map +0 -1
  132. package/dist/schemas-BLARNCgx.js +0 -3113
  133. package/dist/schemas-BLARNCgx.js.map +0 -1
  134. package/dist/schemas-DIqFMmrC.cjs +0 -4468
  135. package/dist/schemas-DIqFMmrC.cjs.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"resolveAnnotationDraft-7Ke4nV7F.cjs","names":["encodePageKey","EngineError","EngineErrorCode","annotationKey","annotationKey","EngineError","EngineErrorCode","validNumberFormat","formatMeasurement","EngineError","EngineErrorCode","validNumberFormat","EngineError","EngineErrorCode","STANDARD_FONTS","EngineError","EngineErrorCode","EngineError","EngineErrorCode","EngineError","EngineErrorCode","EngineError","EngineErrorCode","EngineError","EngineErrorCode"],"sources":["../src/geometry/convert.ts","../src/geometry/pointTurn.ts","../src/dto/RichText.ts","../src/annotation/color.ts","../src/annotation/kind-facts.generated.ts","../src/annotation/kind-facts.ts","../src/annotation/field-names.ts","../src/annotation/field-spaces.ts","../src/dto/IsoDateTime.ts","../src/transfer/bundle.ts","../src/annotation/relationships.ts","../src/annotation/comments.ts","../src/annotation/appearance.ts","../src/annotation/shapeForRect.ts","../src/measure/compute.ts","../src/measure/derive.ts","../src/measure/validate.ts","../src/annotation/resolve/measurement.ts","../src/annotation/calloutEnd.ts","../src/annotation/fontFaces.ts","../src/annotation/resolve/freeText.ts","../src/annotation/resolve/rectCommand.ts","../src/annotation/resolve/sentBack.ts","../src/annotation/resolve/text.ts","../src/annotation/resolve/resolveAnnotationPatch.ts","../src/annotation/resolve/box.ts","../src/annotation/resolve/redact.ts","../src/annotation/resolve/resolveAnnotationDraft.ts"],"sourcesContent":["/**\n * PDF-space-internal geometry helpers.\n *\n * These operate entirely within PDF user space (y-up, edges). They never\n * produce viewer-local (y-down) geometry — that conversion needs the crop box\n * plus rotation/scale and lives in the viewer layer (the `Mat2D` matrix\n * model), never here.\n */\n\nimport type { PdfPoint, PdfQuad, PdfRect, PdfRotation, PdfSize } from './primitives';\n\n/** Origin + size form of a `PdfRect`, still y-up (origin = bottom-left). */\nexport interface PdfOriginSize {\n x: number;\n y: number;\n width: number;\n height: number;\n}\n\n/**\n * Whether `value` is a rect: `left`, `bottom`, `right` and `top`, each a finite number. A rect\n * with `Infinity` or `NaN` in it places nothing, so every write refuses one: here on the page,\n * and by `PdfRectSchema` and `PageBoxSchema` in the engine and on the wire.\n */\nexport function isFinitePdfRect(value: unknown): value is PdfRect {\n if (typeof value !== 'object' || value === null) return false;\n const { left, bottom, right, top } = value as Record<string, unknown>;\n return [left, bottom, right, top].every(\n (edge) => typeof edge === 'number' && Number.isFinite(edge),\n );\n}\n\n/**\n * Normalize a `PdfRect` to the y-up invariant (`left <= right`, `bottom <= top`),\n * regardless of how the PDF ordered the corners (a `/Rect` array or `FS_RECTF`\n * may carry them in any order). The enforcement point for the \"PdfRect is always\n * normalized\" rule: every producer that reads a raw box from PDFium passes it\n * through here, so the invariant holds once, centrally — downstream `width =\n * right - left` is never negative.\n */\nexport function normalizePdfRect(r: PdfRect): PdfRect {\n return {\n left: Math.min(r.left, r.right),\n right: Math.max(r.left, r.right),\n bottom: Math.min(r.top, r.bottom),\n top: Math.max(r.top, r.bottom),\n };\n}\n\nexport function pdfRectWidth(r: PdfRect): number {\n return r.right - r.left;\n}\n\nexport function pdfRectHeight(r: PdfRect): number {\n return r.top - r.bottom;\n}\n\nexport function pdfRectSize(r: PdfRect): PdfSize {\n return { width: r.right - r.left, height: r.top - r.bottom };\n}\n\n/** Convert edges -> origin+size, staying y-up (origin at bottom-left). */\nexport function pdfRectToOriginSize(r: PdfRect): PdfOriginSize {\n return { x: r.left, y: r.bottom, width: r.right - r.left, height: r.top - r.bottom };\n}\n\n/** Convert y-up origin+size back to edges. */\nexport function pdfRectFromOriginSize(o: PdfOriginSize): PdfRect {\n return { left: o.x, bottom: o.y, right: o.x + o.width, top: o.y + o.height };\n}\n\n/**\n * Enclosing axis-aligned box of a quad, in PDF user space. Orientation\n * agnostic (correct for rotated/skewed quads) — this is what highlight\n * rendering and hit-testing want.\n */\nexport function pdfQuadBounds(q: PdfQuad): PdfRect {\n const xs = [q.upperLeft.x, q.upperRight.x, q.lowerLeft.x, q.lowerRight.x];\n const ys = [q.upperLeft.y, q.upperRight.y, q.lowerLeft.y, q.lowerRight.y];\n return {\n left: Math.min(...xs),\n right: Math.max(...xs),\n bottom: Math.min(...ys),\n top: Math.max(...ys),\n };\n}\n\n/** A `/QuadPoints` entry's four points, in the order the file gives them. */\nexport type PdfQuadPoints = readonly [PdfPoint, PdfPoint, PdfPoint, PdfPoint];\n\nconst QUAD_EPSILON = 1e-6;\n\nconst isFinitePoint = (point: PdfPoint) => Number.isFinite(point.x) && Number.isFinite(point.y);\n\n/** Whether the four points, read as upper-left, upper-right, lower-left, lower-right, make a quad. */\nfunction isZigzagQuad([ul, ur, ll, lr]: PdfQuadPoints): boolean {\n if (![ul, ur, ll, lr].every(isFinitePoint)) return false;\n const upper = { x: ur.x - ul.x, y: ur.y - ul.y };\n const lower = { x: lr.x - ll.x, y: lr.y - ll.y };\n const left = { x: ll.x - ul.x, y: ll.y - ul.y };\n const right = { x: lr.x - ur.x, y: lr.y - ur.y };\n const lengths = [upper, lower, left, right].map((edge) => Math.hypot(edge.x, edge.y));\n if (lengths.some((length) => length <= QUAD_EPSILON)) return false;\n // Opposite edges run the same way: a crossed or reversed order fails here.\n if (upper.x * lower.x + upper.y * lower.y <= 0) return false;\n if (left.x * right.x + left.y * right.y <= 0) return false;\n // Both ends have area and turn the same way.\n const leftArea = upper.x * left.y - upper.y * left.x;\n const rightArea = lower.x * right.y - lower.y * right.x;\n if (Math.abs(leftArea) <= QUAD_EPSILON * lengths[0] * lengths[2]) return false;\n if (Math.abs(rightArea) <= QUAD_EPSILON * lengths[1] * lengths[3]) return false;\n return Math.sign(leftArea) === Math.sign(rightArea);\n}\n\n/**\n * Name the corners of a `/QuadPoints` entry. Writers disagree on the order,\n * so every quad read from a file passes through here, and the corner names\n * hold once, centrally:\n *\n * 1. the order Acrobat writes and reads (upper-left, upper-right,\n * lower-left, lower-right) is kept, turned quads included;\n * 2. the ring order some writers use (upper-left, upper-right, lower-right,\n * lower-left) is repaired;\n * 3. anything else is named from its shape: the corners go round their\n * middle, the edge highest on the page (largest y) is the upper one, and\n * its end with the smaller x is the left. Which side of a quad is up\n * cannot be told from four points alone; this rule decides it.\n *\n * A misnamed quad can move an underline to the wrong edge, never cross it.\n */\nexport function normalizePdfQuad(points: PdfQuadPoints): PdfQuad {\n const [first, second, third, fourth] = points;\n if (isZigzagQuad(points)) {\n return { upperLeft: first, upperRight: second, lowerLeft: third, lowerRight: fourth };\n }\n if (isZigzagQuad([first, second, fourth, third])) {\n return { upperLeft: first, upperRight: second, lowerLeft: fourth, lowerRight: third };\n }\n\n const finite = points.map((point) => (isFinitePoint(point) ? point : { x: 0, y: 0 }));\n const cx = finite.reduce((sum, point) => sum + point.x, 0) / 4;\n const cy = finite.reduce((sum, point) => sum + point.y, 0) / 4;\n const ring = [...finite].sort(\n (a, b) => Math.atan2(a.y - cy, a.x - cx) - Math.atan2(b.y - cy, b.x - cx),\n );\n let upper = 0;\n for (let i = 1; i < 4; i++) {\n if (ring[i].y + ring[(i + 1) % 4].y > ring[upper].y + ring[(upper + 1) % 4].y) upper = i;\n }\n // Round the ring: upperEnds[0], upperEnds[1], lowerEnds[1], lowerEnds[0].\n const upperEnds = [ring[upper], ring[(upper + 1) % 4]];\n const lowerEnds = [ring[(upper + 3) % 4], ring[(upper + 2) % 4]];\n const leftFirst = upperEnds[0].x <= upperEnds[1].x;\n return leftFirst\n ? {\n upperLeft: upperEnds[0],\n upperRight: upperEnds[1],\n lowerLeft: lowerEnds[0],\n lowerRight: lowerEnds[1],\n }\n : {\n upperLeft: upperEnds[1],\n upperRight: upperEnds[0],\n lowerLeft: lowerEnds[1],\n lowerRight: lowerEnds[0],\n };\n}\n\n/**\n * The upright box around `rect` turned by `degrees` about its middle, either\n * way: the `/Rect` of a turned box. A quarter turn is exact: the sides swap.\n */\nexport function pdfRectTurnedBounds(rect: PdfRect, degrees: number): PdfRect {\n const quarterTurn = quarterTurnOf(degrees);\n if (quarterTurn !== null) return pdfQuarterTurnBox(rect, quarterTurn);\n const radians = (degrees * Math.PI) / 180;\n const cos = Math.abs(Math.cos(radians));\n const sin = Math.abs(Math.sin(radians));\n const width = rect.right - rect.left;\n const height = rect.top - rect.bottom;\n const halfAcross = (width * cos + height * sin) / 2;\n const halfUp = (width * sin + height * cos) / 2;\n const x = (rect.left + rect.right) / 2;\n const y = (rect.bottom + rect.top) / 2;\n return { left: x - halfAcross, bottom: y - halfUp, right: x + halfAcross, top: y + halfUp };\n}\n\n/**\n * `degrees` as a quarter turn (clockwise, 0 to 270), or `null` when it isn't\n * one. A negative turn, or one past a whole turn, is the same turn.\n */\nexport function quarterTurnOf(degrees: number): PdfRotation | null {\n const turn = ((degrees % 360) + 360) % 360;\n return turn % 90 === 0 ? (turn as PdfRotation) : null;\n}\n\n/**\n * The box that, turned `rotation` about its middle, stands upright in\n * `rect`: `rect` itself, its sides swapped under 90 and 270. The inverse of\n * {@link pdfRectTurnedBounds} for a quarter turn, which is the one turn a\n * rect pins a box down for.\n */\nexport function pdfQuarterTurnBox(rect: PdfRect, rotation: PdfRotation): PdfRect {\n if (rotation === 0 || rotation === 180) return rect;\n const x = (rect.left + rect.right) / 2;\n const y = (rect.bottom + rect.top) / 2;\n const halfWidth = (rect.top - rect.bottom) / 2;\n const halfHeight = (rect.right - rect.left) / 2;\n return { left: x - halfWidth, bottom: y - halfHeight, right: x + halfWidth, top: y + halfHeight };\n}\n\n/**\n * The area two normalized rects share, or `null` when they share none. Keys\n * in `normalizePdfRect`'s order, so a rect reads the same whichever made it.\n */\nexport function pdfRectIntersection(rect: PdfRect, other: PdfRect): PdfRect | null {\n const left = Math.max(rect.left, other.left);\n const right = Math.min(rect.right, other.right);\n const bottom = Math.max(rect.bottom, other.bottom);\n const top = Math.min(rect.top, other.top);\n return left < right && bottom < top ? { left, right, bottom, top } : null;\n}\n\n/**\n * Whether two rects are the same within what a file's numbers hold: Acrobat\n * writes three decimals, and a rect the engine writes is floats.\n */\nexport function isSamePdfRect(rect: PdfRect, other: PdfRect): boolean {\n const size = Math.max(\n rect.right - rect.left,\n rect.top - rect.bottom,\n other.right - other.left,\n other.top - other.bottom,\n );\n const tolerance = 0.01 + 1e-4 * size;\n return (\n Math.abs(rect.left - other.left) <= tolerance &&\n Math.abs(rect.bottom - other.bottom) <= tolerance &&\n Math.abs(rect.right - other.right) <= tolerance &&\n Math.abs(rect.top - other.top) <= tolerance\n );\n}\n","/**\n * Turning points about a middle, in PDF user space (y up). A line's,\n * polyline's, polygon's or ink's points turn about the middle of the box\n * around them before the turn, as a square turns about its box.\n */\n\nimport type { PdfPoint, PdfRect } from './primitives';\n\n/** A turn: degrees clockwise, as the page shows it, about `center`. */\nexport interface PdfPointTurn {\n degrees: number;\n center: PdfPoint;\n}\n\n/** The box around `points`; a zero box at the origin when there are none. */\nexport function pdfPointsBounds(points: readonly PdfPoint[]): PdfRect {\n if (points.length === 0) return { left: 0, bottom: 0, right: 0, top: 0 };\n let left = Infinity;\n let bottom = Infinity;\n let right = -Infinity;\n let top = -Infinity;\n for (const { x, y } of points) {\n left = Math.min(left, x);\n bottom = Math.min(bottom, y);\n right = Math.max(right, x);\n top = Math.max(top, y);\n }\n return { left, bottom, right, top };\n}\n\n/** `point` turned by `turn`; a negative angle turns it back. */\nexport function pdfPointTurned(point: PdfPoint, turn: PdfPointTurn): PdfPoint {\n const radians = (turn.degrees * Math.PI) / 180;\n const cos = Math.cos(radians);\n const sin = Math.sin(radians);\n const dx = point.x - turn.center.x;\n const dy = point.y - turn.center.y;\n // Clockwise on the page is negative in y-up space.\n return {\n x: turn.center.x + dx * cos + dy * sin,\n y: turn.center.y - dx * sin + dy * cos,\n };\n}\n\n/** `point` turned back by `turn`. */\nexport function pdfPointUnturned(point: PdfPoint, turn: PdfPointTurn): PdfPoint {\n return pdfPointTurned(point, { degrees: -turn.degrees, center: turn.center });\n}\n\nconst middleOf = (rect: PdfRect): PdfPoint => ({\n x: (rect.left + rect.right) / 2,\n y: (rect.bottom + rect.top) / 2,\n});\n\n/** The turn that draws upright `points`: `degrees` about the middle of their box. */\nexport function pdfTurnOfUpright(points: readonly PdfPoint[], degrees: number): PdfPointTurn {\n return { degrees, center: middleOf(pdfPointsBounds(points)) };\n}\n\n/**\n * The turn drawn `points` were made with: `degrees` about the middle of the\n * box around the upright points they came from. That middle is where the turn\n * leaves it, so it follows from the drawing: turned back about the origin, the\n * points are the upright ones moved, and turning their middle forward again\n * about the origin gives it.\n */\nexport function pdfTurnOfDrawn(points: readonly PdfPoint[], degrees: number): PdfPointTurn {\n const origin = { x: 0, y: 0 };\n const back = points.map((point) => pdfPointTurned(point, { degrees: -degrees, center: origin }));\n const middle = middleOf(pdfPointsBounds(back));\n return { degrees, center: pdfPointTurned(middle, { degrees, center: origin }) };\n}\n","import type { TextAlignment } from '../annotation/primitives';\n\n/**\n * Rich text of a FreeText annotation (`/RC` + `/DS`), the model the engine\n * lays out and writes. Runs carry only the style they override (deltas\n * against the body), exactly as the XHTML spans do, so changing the body\n * style moves every run that did not override that property.\n *\n * Families name faces the way a PDF does: a standard-14 family\n * (`\"Helvetica\"`), a font registered through `engine.fonts` (its family, or\n * its `key` — the engine resolves either), or a family already embedded in\n * the document. A family that resolves nowhere substitutes Helvetica; the\n * appearance still renders and the box still edits.\n */\nexport type RichTextDecoration = 'underline' | 'line-through' | 'word';\nexport type RichTextScript = 'normal' | 'sub' | 'super';\nexport type RichTextAlign = TextAlignment | 'justify';\nexport type RichTextDirection = 'ltr' | 'rtl';\n\nexport interface RichTextRunStyle {\n family: string;\n /** 100..900. */\n weight: number;\n italic: boolean;\n /** Points. */\n size: number;\n /** `#RRGGBB`. */\n color: string;\n decoration: RichTextDecoration[];\n script: RichTextScript;\n /** Points, added after every glyph. */\n letterSpacing: number;\n /** 1 = normal (`xfa-font-horizontal-scale` / 100). */\n horizontalScale: number;\n /** CSS declarations the engine does not model, kept verbatim. */\n unknown?: string;\n}\n\nexport interface RichTextMargins {\n top: number;\n bottom: number;\n left: number;\n right: number;\n}\n\nexport interface RichTextParagraphProps {\n align: RichTextAlign;\n dir: RichTextDirection;\n /** Points; absent = the normal line box. */\n lineHeight?: number;\n margins?: RichTextMargins;\n textIndent?: number;\n unknown?: string;\n}\n\nexport interface RichTextRun {\n /** May contain `\\r`: a hard line break inside the paragraph. */\n text: string;\n /** The properties this run overrides. Absent = the body style. */\n style?: Partial<RichTextRunStyle>;\n}\n\n/** A paragraph: its own alignment/direction when they differ from the body's. */\nexport interface RichTextParagraph extends Partial<RichTextParagraphProps> {\n runs: RichTextRun[];\n}\n\nexport type RichTextBody = RichTextRunStyle & RichTextParagraphProps;\n\n/**\n * The body a partial input body completes itself from: Helvetica 12 pt\n * black, left-aligned, ltr, nothing else set.\n */\nexport const DEFAULT_RICH_TEXT_BODY: Readonly<RichTextBody> = {\n family: 'Helvetica',\n weight: 400,\n italic: false,\n size: 12,\n color: '#000000',\n decoration: [],\n script: 'normal',\n letterSpacing: 0,\n horizontalScale: 1,\n align: 'left',\n dir: 'ltr',\n};\n\n/** What an annotation reads back: a complete body, every paragraph resolved. */\nexport interface RichTextDocument {\n body: RichTextBody;\n paragraphs: RichTextParagraph[];\n}\n\n/**\n * What a draft or patch writes. `body` may be omitted (the annotation's\n * current body style stays — the \"plain text replacement\" of the patch\n * table) or partial (missing properties take the engine's defaults:\n * Helvetica 12 pt black, left-aligned, ltr).\n */\nexport interface RichTextDocumentInput {\n body?: Partial<RichTextBody>;\n paragraphs: RichTextParagraph[];\n}\n\n/** The plain-text projection of a rich document: paragraphs joined by `\\r`,\n * runs concatenated — what the engine writes to `/Contents`. */\nexport function richTextPlainText(doc: { paragraphs: readonly RichTextParagraph[] }): string {\n return doc.paragraphs.map((p) => p.runs.map((r) => r.text).join('')).join('\\r');\n}\n\n/** Plain text as rich paragraphs: one per line break, one run each, no\n * overrides (the engine's own `/Contents` fallback shape). */\nexport function richTextParagraphsFromPlainText(text: string): RichTextParagraph[] {\n return text.split(/\\r\\n|\\r|\\n/).map((line) => ({ runs: [{ text: line }] }));\n}\n","import type { Color } from './primitives';\n\n/** One 0..255 component as two lowercase hex digits. */\nconst hex2 = (component: number): string =>\n Math.max(0, Math.min(255, Math.round(component)))\n .toString(16)\n .padStart(2, '0');\n\n/** A color from its 0..255 sRGB components, as the engine gives colors. */\nexport function colorOf(r: number, g: number, b: number): Color {\n return `#${hex2(r)}${hex2(g)}${hex2(b)}`;\n}\n\n/** The 0..255 sRGB components of a `'#rrggbb'` color, in either case. */\nexport function rgbOf(color: Color): { r: number; g: number; b: number } {\n const value = Number.parseInt(color.slice(1), 16);\n return { r: (value >> 16) & 0xff, g: (value >> 8) & 0xff, b: value & 0xff };\n}\n\n/** Whether two colors are the same, whatever the case of their digits. */\nexport function sameColor(a: Color, b: Color): boolean {\n return a.toLowerCase() === b.toLowerCase();\n}\n","// Generated from the annotation kind declarations (`kinds/<kind>/declaration.ts`) by\n// `scripts/generate-kind-facts.ts`; `test/annotation/kind-facts.test.ts` fails when this file\n// is out of date. Not edited by hand: `pnpm --filter @embedpdf/engine-core generate` writes it.\n\nimport type { KindFacts } from './kind-facts';\nimport type { AnnotationSubtype } from './subtype';\n\n/** Each annotation kind's {@link KindFacts}, in the engine's catalog order. */\nexport const ANNOTATION_KIND_FACTS: Readonly<Record<AnnotationSubtype, KindFacts>> = {\n highlight: {\n owners: {\n ref: 'engine',\n page: 'engine',\n hasAppearance: 'engine',\n appearanceState: 'engine',\n nm: 'data',\n rect: 'engine',\n contents: 'data',\n subject: 'data',\n blendMode: 'data',\n invisible: 'data',\n hidden: 'data',\n print: 'data',\n noZoom: 'data',\n noRotate: 'data',\n noView: 'data',\n readOnly: 'data',\n locked: 'data',\n toggleNoView: 'data',\n lockedContents: 'data',\n reply: 'data',\n popup: 'engine',\n groupId: 'data',\n author: 'attribution',\n createdAt: 'attribution',\n modifiedAt: 'attribution',\n userId: 'attribution',\n createdBy: 'attribution',\n modifiedBy: 'attribution',\n importedBy: 'engine',\n actions: 'preserved',\n color: 'data',\n opacity: 'data',\n quadPoints: 'data',\n },\n readBack: ['rect'],\n colors: ['color'],\n spaces: {\n rect: 'box',\n actions: 'actions',\n quadPoints: 'quads',\n },\n resources: {},\n },\n underline: {\n owners: {\n ref: 'engine',\n page: 'engine',\n hasAppearance: 'engine',\n appearanceState: 'engine',\n nm: 'data',\n rect: 'engine',\n contents: 'data',\n subject: 'data',\n blendMode: 'data',\n invisible: 'data',\n hidden: 'data',\n print: 'data',\n noZoom: 'data',\n noRotate: 'data',\n noView: 'data',\n readOnly: 'data',\n locked: 'data',\n toggleNoView: 'data',\n lockedContents: 'data',\n reply: 'data',\n popup: 'engine',\n groupId: 'data',\n author: 'attribution',\n createdAt: 'attribution',\n modifiedAt: 'attribution',\n userId: 'attribution',\n createdBy: 'attribution',\n modifiedBy: 'attribution',\n importedBy: 'engine',\n actions: 'preserved',\n color: 'data',\n opacity: 'data',\n quadPoints: 'data',\n },\n readBack: ['rect'],\n colors: ['color'],\n spaces: {\n rect: 'box',\n actions: 'actions',\n quadPoints: 'quads',\n },\n resources: {},\n },\n squiggly: {\n owners: {\n ref: 'engine',\n page: 'engine',\n hasAppearance: 'engine',\n appearanceState: 'engine',\n nm: 'data',\n rect: 'engine',\n contents: 'data',\n subject: 'data',\n blendMode: 'data',\n invisible: 'data',\n hidden: 'data',\n print: 'data',\n noZoom: 'data',\n noRotate: 'data',\n noView: 'data',\n readOnly: 'data',\n locked: 'data',\n toggleNoView: 'data',\n lockedContents: 'data',\n reply: 'data',\n popup: 'engine',\n groupId: 'data',\n author: 'attribution',\n createdAt: 'attribution',\n modifiedAt: 'attribution',\n userId: 'attribution',\n createdBy: 'attribution',\n modifiedBy: 'attribution',\n importedBy: 'engine',\n actions: 'preserved',\n color: 'data',\n opacity: 'data',\n quadPoints: 'data',\n },\n readBack: ['rect'],\n colors: ['color'],\n spaces: {\n rect: 'box',\n actions: 'actions',\n quadPoints: 'quads',\n },\n resources: {},\n },\n strikeout: {\n owners: {\n ref: 'engine',\n page: 'engine',\n hasAppearance: 'engine',\n appearanceState: 'engine',\n nm: 'data',\n rect: 'engine',\n contents: 'data',\n subject: 'data',\n blendMode: 'data',\n invisible: 'data',\n hidden: 'data',\n print: 'data',\n noZoom: 'data',\n noRotate: 'data',\n noView: 'data',\n readOnly: 'data',\n locked: 'data',\n toggleNoView: 'data',\n lockedContents: 'data',\n reply: 'data',\n popup: 'engine',\n groupId: 'data',\n author: 'attribution',\n createdAt: 'attribution',\n modifiedAt: 'attribution',\n userId: 'attribution',\n createdBy: 'attribution',\n modifiedBy: 'attribution',\n importedBy: 'engine',\n actions: 'preserved',\n color: 'data',\n opacity: 'data',\n quadPoints: 'data',\n intent: 'data',\n },\n readBack: ['rect'],\n colors: ['color'],\n spaces: {\n rect: 'box',\n actions: 'actions',\n quadPoints: 'quads',\n },\n resources: {},\n },\n circle: {\n owners: {\n ref: 'engine',\n page: 'engine',\n hasAppearance: 'engine',\n appearanceState: 'engine',\n nm: 'data',\n rect: 'engine',\n contents: 'data',\n subject: 'data',\n blendMode: 'data',\n invisible: 'data',\n hidden: 'data',\n print: 'data',\n noZoom: 'data',\n noRotate: 'data',\n noView: 'data',\n readOnly: 'data',\n locked: 'data',\n toggleNoView: 'data',\n lockedContents: 'data',\n reply: 'data',\n popup: 'engine',\n groupId: 'data',\n author: 'attribution',\n createdAt: 'attribution',\n modifiedAt: 'attribution',\n userId: 'attribution',\n createdBy: 'attribution',\n modifiedBy: 'attribution',\n importedBy: 'engine',\n actions: 'preserved',\n color: 'data',\n opacity: 'data',\n strokeWidth: 'data',\n borderStyle: 'data',\n dashArray: 'data',\n interiorColor: 'data',\n box: 'data',\n rotation: 'data',\n cloudyIntensity: 'data',\n },\n readBack: ['rect', 'borderStyle'],\n colors: ['color', 'interiorColor'],\n spaces: {\n rect: 'box',\n actions: 'actions',\n box: 'box',\n },\n resources: {},\n },\n square: {\n owners: {\n ref: 'engine',\n page: 'engine',\n hasAppearance: 'engine',\n appearanceState: 'engine',\n nm: 'data',\n rect: 'engine',\n contents: 'data',\n subject: 'data',\n blendMode: 'data',\n invisible: 'data',\n hidden: 'data',\n print: 'data',\n noZoom: 'data',\n noRotate: 'data',\n noView: 'data',\n readOnly: 'data',\n locked: 'data',\n toggleNoView: 'data',\n lockedContents: 'data',\n reply: 'data',\n popup: 'engine',\n groupId: 'data',\n author: 'attribution',\n createdAt: 'attribution',\n modifiedAt: 'attribution',\n userId: 'attribution',\n createdBy: 'attribution',\n modifiedBy: 'attribution',\n importedBy: 'engine',\n actions: 'preserved',\n color: 'data',\n opacity: 'data',\n strokeWidth: 'data',\n borderStyle: 'data',\n dashArray: 'data',\n interiorColor: 'data',\n box: 'data',\n rotation: 'data',\n cloudyIntensity: 'data',\n },\n readBack: ['rect', 'borderStyle'],\n colors: ['color', 'interiorColor'],\n spaces: {\n rect: 'box',\n actions: 'actions',\n box: 'box',\n },\n resources: {},\n },\n polygon: {\n owners: {\n ref: 'engine',\n page: 'engine',\n hasAppearance: 'engine',\n appearanceState: 'engine',\n nm: 'data',\n rect: 'engine',\n contents: 'data',\n subject: 'data',\n blendMode: 'data',\n invisible: 'data',\n hidden: 'data',\n print: 'data',\n noZoom: 'data',\n noRotate: 'data',\n noView: 'data',\n readOnly: 'data',\n locked: 'data',\n toggleNoView: 'data',\n lockedContents: 'data',\n reply: 'data',\n popup: 'engine',\n groupId: 'data',\n author: 'attribution',\n createdAt: 'attribution',\n modifiedAt: 'attribution',\n userId: 'attribution',\n createdBy: 'attribution',\n modifiedBy: 'attribution',\n importedBy: 'engine',\n actions: 'preserved',\n color: 'data',\n opacity: 'data',\n strokeWidth: 'data',\n borderStyle: 'data',\n dashArray: 'data',\n interiorColor: 'data',\n vertices: 'data',\n rotation: 'data',\n captionEnabled: 'data',\n captionCenter: 'data',\n intent: 'data',\n measure: 'data',\n cloudyIntensity: 'data',\n },\n readBack: ['rect', 'borderStyle', 'vertices'],\n colors: ['color', 'interiorColor'],\n spaces: {\n rect: 'box',\n actions: 'actions',\n vertices: 'points',\n captionCenter: 'point',\n measure: 'measure',\n },\n resources: {},\n },\n polyline: {\n owners: {\n ref: 'engine',\n page: 'engine',\n hasAppearance: 'engine',\n appearanceState: 'engine',\n nm: 'data',\n rect: 'engine',\n contents: 'data',\n subject: 'data',\n blendMode: 'data',\n invisible: 'data',\n hidden: 'data',\n print: 'data',\n noZoom: 'data',\n noRotate: 'data',\n noView: 'data',\n readOnly: 'data',\n locked: 'data',\n toggleNoView: 'data',\n lockedContents: 'data',\n reply: 'data',\n popup: 'engine',\n groupId: 'data',\n author: 'attribution',\n createdAt: 'attribution',\n modifiedAt: 'attribution',\n userId: 'attribution',\n createdBy: 'attribution',\n modifiedBy: 'attribution',\n importedBy: 'engine',\n actions: 'preserved',\n color: 'data',\n opacity: 'data',\n strokeWidth: 'data',\n borderStyle: 'data',\n dashArray: 'data',\n interiorColor: 'data',\n vertices: 'data',\n rotation: 'data',\n captionEnabled: 'data',\n captionCenter: 'data',\n intent: 'data',\n measure: 'data',\n lineEndings: 'data',\n },\n readBack: ['rect', 'borderStyle', 'vertices'],\n colors: ['color', 'interiorColor'],\n spaces: {\n rect: 'box',\n actions: 'actions',\n vertices: 'points',\n captionCenter: 'point',\n measure: 'measure',\n },\n resources: {},\n },\n line: {\n owners: {\n ref: 'engine',\n page: 'engine',\n hasAppearance: 'engine',\n appearanceState: 'engine',\n nm: 'data',\n rect: 'engine',\n contents: 'data',\n subject: 'data',\n blendMode: 'data',\n invisible: 'data',\n hidden: 'data',\n print: 'data',\n noZoom: 'data',\n noRotate: 'data',\n noView: 'data',\n readOnly: 'data',\n locked: 'data',\n toggleNoView: 'data',\n lockedContents: 'data',\n reply: 'data',\n popup: 'engine',\n groupId: 'data',\n author: 'attribution',\n createdAt: 'attribution',\n modifiedAt: 'attribution',\n userId: 'attribution',\n createdBy: 'attribution',\n modifiedBy: 'attribution',\n importedBy: 'engine',\n actions: 'preserved',\n color: 'data',\n opacity: 'data',\n strokeWidth: 'data',\n borderStyle: 'data',\n dashArray: 'data',\n interiorColor: 'data',\n linePoints: 'data',\n lineEndings: 'data',\n rotation: 'data',\n intent: 'data',\n measure: 'data',\n captionEnabled: 'data',\n captionPosition: 'data',\n captionOffset: 'data',\n leader: 'data',\n },\n readBack: ['rect', 'borderStyle'],\n colors: ['color', 'interiorColor'],\n spaces: {\n rect: 'box',\n actions: 'actions',\n linePoints: 'linePoints',\n measure: 'measure',\n },\n resources: {},\n },\n link: {\n owners: {\n ref: 'engine',\n page: 'engine',\n hasAppearance: 'engine',\n appearanceState: 'engine',\n nm: 'data',\n rect: 'data',\n contents: 'data',\n subject: 'data',\n blendMode: 'data',\n invisible: 'data',\n hidden: 'data',\n print: 'data',\n noZoom: 'data',\n noRotate: 'data',\n noView: 'data',\n readOnly: 'data',\n locked: 'data',\n toggleNoView: 'data',\n lockedContents: 'data',\n reply: 'data',\n popup: 'engine',\n groupId: 'data',\n author: 'attribution',\n createdAt: 'attribution',\n modifiedAt: 'attribution',\n userId: 'attribution',\n createdBy: 'attribution',\n modifiedBy: 'attribution',\n importedBy: 'engine',\n actions: 'preserved',\n target: 'data',\n },\n readBack: ['target'],\n colors: [],\n spaces: {\n rect: 'box',\n actions: 'actions',\n target: 'linkTarget',\n },\n resources: {},\n },\n ink: {\n owners: {\n ref: 'engine',\n page: 'engine',\n hasAppearance: 'engine',\n appearanceState: 'engine',\n nm: 'data',\n rect: 'engine',\n contents: 'data',\n subject: 'data',\n blendMode: 'data',\n invisible: 'data',\n hidden: 'data',\n print: 'data',\n noZoom: 'data',\n noRotate: 'data',\n noView: 'data',\n readOnly: 'data',\n locked: 'data',\n toggleNoView: 'data',\n lockedContents: 'data',\n reply: 'data',\n popup: 'engine',\n groupId: 'data',\n author: 'attribution',\n createdAt: 'attribution',\n modifiedAt: 'attribution',\n userId: 'attribution',\n createdBy: 'attribution',\n modifiedBy: 'attribution',\n importedBy: 'engine',\n actions: 'preserved',\n color: 'data',\n opacity: 'data',\n strokeWidth: 'data',\n borderStyle: 'data',\n dashArray: 'data',\n inkList: 'data',\n intent: 'data',\n rotation: 'data',\n },\n readBack: ['rect', 'strokeWidth', 'borderStyle', 'inkList'],\n colors: ['color'],\n spaces: {\n rect: 'box',\n actions: 'actions',\n inkList: 'strokes',\n },\n resources: {},\n },\n 'free-text': {\n owners: {\n ref: 'engine',\n page: 'engine',\n hasAppearance: 'engine',\n appearanceState: 'engine',\n nm: 'data',\n rect: 'engine',\n contents: 'data',\n subject: 'data',\n blendMode: 'data',\n invisible: 'data',\n hidden: 'data',\n print: 'data',\n noZoom: 'data',\n noRotate: 'data',\n noView: 'data',\n readOnly: 'data',\n locked: 'data',\n toggleNoView: 'data',\n lockedContents: 'data',\n reply: 'data',\n popup: 'engine',\n groupId: 'data',\n author: 'attribution',\n createdAt: 'attribution',\n modifiedAt: 'attribution',\n userId: 'attribution',\n createdBy: 'attribution',\n modifiedBy: 'attribution',\n importedBy: 'engine',\n actions: 'preserved',\n box: 'data',\n rotation: 'data',\n intent: 'data',\n fontFamily: 'data',\n fontSize: 'data',\n textAlign: 'data',\n verticalAlign: 'data',\n richText: 'data',\n color: 'data',\n fontColor: 'data',\n interiorColor: 'data',\n opacity: 'data',\n strokeWidth: 'data',\n borderStyle: 'data',\n dashArray: 'data',\n cloudyIntensity: 'data',\n calloutLine: 'data',\n lineEnding: 'data',\n },\n readBack: ['rect', 'intent', 'borderStyle'],\n colors: ['color', 'fontColor', 'interiorColor'],\n spaces: {\n rect: 'box',\n actions: 'actions',\n box: 'box',\n richText: 'length',\n calloutLine: 'calloutLine',\n },\n resources: {},\n },\n caret: {\n owners: {\n ref: 'engine',\n page: 'engine',\n hasAppearance: 'engine',\n appearanceState: 'engine',\n nm: 'data',\n rect: 'engine',\n contents: 'data',\n subject: 'data',\n blendMode: 'data',\n invisible: 'data',\n hidden: 'data',\n print: 'data',\n noZoom: 'data',\n noRotate: 'data',\n noView: 'data',\n readOnly: 'data',\n locked: 'data',\n toggleNoView: 'data',\n lockedContents: 'data',\n reply: 'data',\n popup: 'engine',\n groupId: 'data',\n author: 'attribution',\n createdAt: 'attribution',\n modifiedAt: 'attribution',\n userId: 'attribution',\n createdBy: 'attribution',\n modifiedBy: 'attribution',\n importedBy: 'engine',\n actions: 'preserved',\n color: 'data',\n opacity: 'data',\n box: 'data',\n rotation: 'data',\n intent: 'data',\n },\n readBack: ['rect'],\n colors: ['color'],\n spaces: {\n rect: 'box',\n actions: 'actions',\n box: 'box',\n },\n resources: {},\n },\n text: {\n owners: {\n ref: 'engine',\n page: 'engine',\n hasAppearance: 'engine',\n appearanceState: 'engine',\n nm: 'data',\n rect: 'data',\n contents: 'data',\n subject: 'data',\n blendMode: 'data',\n invisible: 'data',\n hidden: 'data',\n print: 'data',\n noZoom: 'data',\n noRotate: 'data',\n noView: 'data',\n readOnly: 'data',\n locked: 'data',\n toggleNoView: 'data',\n lockedContents: 'data',\n reply: 'data',\n popup: 'engine',\n groupId: 'data',\n author: 'attribution',\n createdAt: 'attribution',\n modifiedAt: 'attribution',\n userId: 'attribution',\n createdBy: 'attribution',\n modifiedBy: 'attribution',\n importedBy: 'engine',\n actions: 'preserved',\n color: 'data',\n opacity: 'data',\n icon: 'data',\n open: 'data',\n state: 'data',\n stateModel: 'data',\n },\n readBack: [],\n colors: ['color'],\n spaces: {\n rect: 'box',\n actions: 'actions',\n },\n resources: {},\n },\n stamp: {\n owners: {\n ref: 'engine',\n page: 'engine',\n hasAppearance: 'engine',\n appearanceState: 'engine',\n nm: 'data',\n rect: 'engine',\n contents: 'data',\n subject: 'data',\n blendMode: 'data',\n invisible: 'data',\n hidden: 'data',\n print: 'data',\n noZoom: 'data',\n noRotate: 'data',\n noView: 'data',\n readOnly: 'data',\n locked: 'data',\n toggleNoView: 'data',\n lockedContents: 'data',\n reply: 'data',\n popup: 'engine',\n groupId: 'data',\n author: 'attribution',\n createdAt: 'attribution',\n modifiedAt: 'attribution',\n userId: 'attribution',\n createdBy: 'attribution',\n modifiedBy: 'attribution',\n importedBy: 'engine',\n actions: 'preserved',\n box: 'data',\n rotation: 'data',\n name: 'data',\n fit: 'data',\n opacity: 'data',\n },\n readBack: ['rect'],\n colors: [],\n spaces: {\n rect: 'box',\n actions: 'actions',\n box: 'box',\n },\n resources: {\n appearance: 'required',\n },\n },\n 'file-attachment': {\n owners: {\n ref: 'engine',\n page: 'engine',\n hasAppearance: 'engine',\n appearanceState: 'engine',\n nm: 'data',\n rect: 'data',\n contents: 'data',\n subject: 'data',\n blendMode: 'data',\n invisible: 'data',\n hidden: 'data',\n print: 'data',\n noZoom: 'data',\n noRotate: 'data',\n noView: 'data',\n readOnly: 'data',\n locked: 'data',\n toggleNoView: 'data',\n lockedContents: 'data',\n reply: 'data',\n popup: 'engine',\n groupId: 'data',\n author: 'attribution',\n createdAt: 'attribution',\n modifiedAt: 'attribution',\n userId: 'attribution',\n createdBy: 'attribution',\n modifiedBy: 'attribution',\n importedBy: 'engine',\n actions: 'preserved',\n color: 'data',\n opacity: 'data',\n icon: 'data',\n file: 'data',\n },\n readBack: [],\n colors: ['color'],\n spaces: {\n rect: 'box',\n actions: 'actions',\n },\n resources: {\n file: 'required',\n },\n },\n widget: {\n owners: {\n ref: 'engine',\n page: 'engine',\n hasAppearance: 'engine',\n appearanceState: 'engine',\n nm: 'data',\n rect: 'engine',\n contents: 'data',\n subject: 'data',\n blendMode: 'data',\n invisible: 'data',\n hidden: 'data',\n print: 'data',\n noZoom: 'data',\n noRotate: 'data',\n noView: 'data',\n readOnly: 'data',\n locked: 'data',\n toggleNoView: 'data',\n lockedContents: 'data',\n reply: 'data',\n popup: 'engine',\n groupId: 'data',\n author: 'attribution',\n createdAt: 'attribution',\n modifiedAt: 'attribution',\n userId: 'attribution',\n createdBy: 'attribution',\n modifiedBy: 'attribution',\n importedBy: 'engine',\n actions: 'data',\n box: 'data',\n rotation: 'data',\n color: 'data',\n interiorColor: 'data',\n strokeWidth: 'data',\n borderStyle: 'data',\n dashArray: 'data',\n fontFamily: 'data',\n fontSize: 'data',\n fontColor: 'data',\n textAlign: 'data',\n caption: 'data',\n checkStyle: 'data',\n field: 'engine',\n fieldFamily: 'engine',\n },\n readBack: ['rect', 'actions'],\n colors: ['color', 'interiorColor', 'fontColor'],\n spaces: {\n rect: 'box',\n actions: 'actions',\n box: 'box',\n },\n resources: {},\n },\n redact: {\n owners: {\n ref: 'engine',\n page: 'engine',\n hasAppearance: 'engine',\n appearanceState: 'engine',\n nm: 'data',\n rect: 'data',\n contents: 'data',\n subject: 'data',\n blendMode: 'data',\n invisible: 'data',\n hidden: 'data',\n print: 'data',\n noZoom: 'data',\n noRotate: 'data',\n noView: 'data',\n readOnly: 'data',\n locked: 'data',\n toggleNoView: 'data',\n lockedContents: 'data',\n reply: 'data',\n popup: 'engine',\n groupId: 'data',\n author: 'attribution',\n createdAt: 'attribution',\n modifiedAt: 'attribution',\n userId: 'attribution',\n createdBy: 'attribution',\n modifiedBy: 'attribution',\n importedBy: 'engine',\n actions: 'preserved',\n color: 'data',\n opacity: 'data',\n quadPoints: 'data',\n interiorColor: 'data',\n overlayText: 'data',\n repeat: 'data',\n fontFamily: 'data',\n fontSize: 'data',\n fontColor: 'data',\n textAlign: 'data',\n },\n readBack: [],\n colors: ['color', 'interiorColor', 'fontColor'],\n spaces: {\n rect: 'box',\n actions: 'actions',\n quadPoints: 'quads',\n },\n resources: {},\n },\n popup: {\n owners: {\n ref: 'engine',\n page: 'engine',\n hasAppearance: 'engine',\n appearanceState: 'engine',\n nm: 'data',\n rect: 'data',\n contents: 'data',\n subject: 'data',\n blendMode: 'data',\n invisible: 'data',\n hidden: 'data',\n print: 'data',\n noZoom: 'data',\n noRotate: 'data',\n noView: 'data',\n readOnly: 'data',\n locked: 'data',\n toggleNoView: 'data',\n lockedContents: 'data',\n reply: 'data',\n popup: 'engine',\n groupId: 'data',\n author: 'attribution',\n createdAt: 'attribution',\n modifiedAt: 'attribution',\n userId: 'attribution',\n createdBy: 'attribution',\n modifiedBy: 'attribution',\n importedBy: 'engine',\n actions: 'preserved',\n parent: 'data',\n open: 'data',\n },\n readBack: ['parent'],\n colors: [],\n spaces: {\n rect: 'box',\n actions: 'actions',\n },\n resources: {},\n },\n unsupported: {\n owners: {\n ref: 'engine',\n page: 'engine',\n hasAppearance: 'engine',\n appearanceState: 'engine',\n nm: 'data',\n rect: 'data',\n contents: 'data',\n subject: 'data',\n blendMode: 'data',\n invisible: 'data',\n hidden: 'data',\n print: 'data',\n noZoom: 'data',\n noRotate: 'data',\n noView: 'data',\n readOnly: 'data',\n locked: 'data',\n toggleNoView: 'data',\n lockedContents: 'data',\n reply: 'data',\n popup: 'engine',\n groupId: 'data',\n author: 'attribution',\n createdAt: 'attribution',\n modifiedAt: 'attribution',\n userId: 'attribution',\n createdBy: 'attribution',\n modifiedBy: 'attribution',\n importedBy: 'engine',\n actions: 'preserved',\n rawSubtypeCode: 'engine',\n rawSubtypeName: 'engine',\n },\n readBack: [],\n colors: [],\n spaces: {\n rect: 'box',\n actions: 'actions',\n },\n resources: {},\n },\n};\n","import type { FieldOwner, KindResources } from './declaration';\nimport type { MeasuredFieldSpace } from './field-spaces';\nimport { ANNOTATION_KIND_FACTS } from './kind-facts.generated';\nimport type { AnnotationSubtype } from './subtype';\n\n/**\n * What one annotation kind declares about its fields, without zod, for the code that predicts\n * a write on the page. Written from the kind's declaration (`kinds/<kind>/declaration.ts`), the\n * one source of each kind's fields, into `kind-facts.generated.ts`.\n */\nexport interface KindFacts {\n /** Every field the kind declares, in declaration order, and who writes it. */\n readonly owners: Readonly<Record<string, FieldOwner>>;\n /** The fields an update may send back as a read returned them (`readBack()`). */\n readonly readBack: readonly string[];\n /** The fields that hold a color (`'#rrggbb'`). */\n readonly colors: readonly string[];\n /** The fields that hold something measured on the page, and what. */\n readonly spaces: Readonly<Record<string, MeasuredFieldSpace>>;\n /** The resources the kind takes beside its data, by role. */\n readonly resources: KindResources;\n}\n\n/** A table with an entry for every kind, worked out from the kind's facts. */\nexport function mapKindFacts<Value>(\n of: (facts: KindFacts) => Value,\n): Readonly<Record<AnnotationSubtype, Value>> {\n const table = {} as Record<AnnotationSubtype, Value>;\n for (const subtype of Object.keys(ANNOTATION_KIND_FACTS) as AnnotationSubtype[]) {\n table[subtype] = of(ANNOTATION_KIND_FACTS[subtype]);\n }\n return table;\n}\n\n/** The facts of the kind `subtype` names, or `null` when no kind has that subtype. */\nexport function kindFactsOf(subtype: string): KindFacts | null {\n return Object.prototype.hasOwnProperty.call(ANNOTATION_KIND_FACTS, subtype)\n ? ANNOTATION_KIND_FACTS[subtype as AnnotationSubtype]\n : null;\n}\n","import type { KindResources } from './declaration';\nimport { mapKindFacts } from './kind-facts';\nimport type { AnnotationSubtype } from './subtype';\n\n/**\n * Every field each annotation kind declares, in declaration order, without zod, for code that\n * checks the keys of a write but can't load the schemas (the engines, their workers, the\n * viewer). From `kind-facts.generated.ts`.\n */\nexport const ANNOTATION_FIELD_NAMES: Readonly<Record<AnnotationSubtype, readonly string[]>> =\n mapKindFacts((facts) => Object.keys(facts.owners));\n\n/** The resources each kind takes (`create(data, resources)`), without zod. */\nexport const ANNOTATION_RESOURCE_ROLES: Readonly<Record<AnnotationSubtype, KindResources>> =\n mapKindFacts((facts) => facts.resources);\n","import type { FieldSpace } from './declaration';\nimport { mapKindFacts } from './kind-facts';\nimport type { AnnotationSubtype } from './subtype';\n\n/** A field kind that holds something measured on the page (every kind but `none`). */\nexport type MeasuredFieldSpace = Exclude<FieldSpace, 'none'>;\n\n/**\n * The fields of each annotation kind that hold something measured on the page, and what they\n * hold (`FieldSpace`), without zod, for the code that converts values between the file's\n * coordinates and page space in the engines and their workers. From\n * `kind-facts.generated.ts`; `test/annotation/field-spaces.test.ts` checks that no declared\n * field holds a place on the page without saying so.\n */\nexport const ANNOTATION_FIELD_SPACES: Readonly<\n Record<AnnotationSubtype, Readonly<Record<string, MeasuredFieldSpace>>>\n> = mapKindFacts((facts) => facts.spaces);\n\n/**\n * Every measured field by its name, whatever its kind: a name holds the same\n * thing in every kind (`test/annotation/field-spaces.test.ts` keeps it so).\n * An update that leaves out its kind converts by this.\n */\nexport const ANNOTATION_FIELD_SPACES_BY_NAME: Readonly<Record<string, MeasuredFieldSpace>> =\n Object.assign({}, ...Object.values(ANNOTATION_FIELD_SPACES));\n","/**\n * A moment, as an ISO 8601 string: `2017-07-12T21:44:38-07:00`.\n *\n * Every date in the engine's data has this type. A date read from the PDF\n * keeps the offset it was written with (a PDF date without an offset reads\n * without one); a date the engine makes itself is UTC (`…Z`). A date the PDF\n * writes in a form that can't be parsed reads as `null`. PDF dates have whole\n * seconds, so a fraction is dropped on write.\n *\n * Reads are strings, never `Date` objects: a read must go back into a write\n * as it is, including through JSON, and a `Date` would also drop the offset.\n */\nexport type IsoDateTime = string;\n\n/** A moment as a write takes it: the same string, or a `Date`, which becomes that string. */\nexport type DateInput = IsoDateTime | Date;\n\n/**\n * Order two moments by the instant they name. Their text doesn't order them:\n * `2017-07-12T21:44:38-07:00` is later than `2017-07-13T01:00:00Z`.\n */\nexport function compareIsoDateTime(a: IsoDateTime, b: IsoDateTime): number {\n const difference = Date.parse(a) - Date.parse(b);\n return Number.isNaN(difference) ? 0 : difference;\n}\n","/**\n * What every bundle shares, whichever family it carries: resources named by\n * the SHA-256 of their bytes, the table of pages its rows are on, the checks\n * of that shape, and where an import puts each page.\n */\nimport { EngineError } from '../errors/EngineError';\nimport { EngineErrorCode } from '../errors/EngineErrorCode';\nimport type { PdfSize } from '../geometry/primitives';\nimport { encodePageKey, type PageRef } from '../identity/PageRef';\n\n/** What a bundle holds: annotations, or form fields with their widgets. Messages name it. */\nexport type BundleKind = 'annotation' | 'form';\n\n/** A resource's name in a bundle: `sha256-` and the SHA-256 of its bytes, lowercase hex. */\nexport type ResourceId = `sha256-${string}`;\n\n/** A page a bundle's rows are on or point at. */\nexport interface BundlePage {\n readonly page: PageRef;\n /** Where the page is in its document, for mapping pages by position; never a reference. */\n readonly position: number;\n /**\n * The page's size, as its layout reports it. Positions are measured from\n * the page's top-left, so an import puts each row at the same spot from\n * the top-left of the page it goes to.\n */\n readonly size: PdfSize;\n}\n\n/**\n * Where an import puts each page of the bundle:\n *\n * - `'same'` (the default): each page ref as it is;\n * - `'by-position'`: a bundle page to the page at its `position`;\n * - a list: exactly the pairs given.\n */\nexport type BundleImportPages =\n | 'same'\n | 'by-position'\n | ReadonlyArray<{ readonly from: PageRef; readonly to: PageRef }>;\n\n/** A page of the document an import goes into: its ref and where it is. */\nexport interface BundleImportTarget {\n readonly page: PageRef;\n readonly position: number;\n}\n\nconst RESOURCE_ID_PATTERN = /^sha256-[0-9a-f]{64}$/;\nconst PAGE_FIELDS = ['page', 'position', 'size'] as const;\n\n/** The id of a resource: the SHA-256 of its bytes. */\nexport async function resourceIdOf(bytes: Uint8Array): Promise<ResourceId> {\n const digest = new Uint8Array(\n await crypto.subtle.digest('SHA-256', bytes as Uint8Array<ArrayBuffer>),\n );\n let hex = '';\n for (const byte of digest) hex += byte.toString(16).padStart(2, '0');\n return `sha256-${hex}`;\n}\n\n/** Every resource's bytes hash to its id. */\nexport async function assertResourceIds(\n kind: BundleKind,\n resources: Readonly<Record<string, Uint8Array>>,\n): Promise<void> {\n for (const [id, bytes] of Object.entries(resources)) {\n if ((await resourceIdOf(bytes)) !== id) {\n invalidBundle(kind, `resource ${id} doesn't match its id`);\n }\n }\n}\n\n/**\n * Check a bundle's page table: each entry a page ref, a position and a\n * size, no page or position listed twice. Returns the listed pages' keys,\n * for the rows to be checked against.\n */\nexport function assertBundlePages(kind: BundleKind, pages: readonly unknown[]): Set<string> {\n const pageKeys = new Set<string>();\n const positions = new Set<number>();\n for (const entry of pages) {\n if (!isRecord(entry) || !isBundlePageRef(entry.page) || !isSize(entry.size)) {\n invalidBundle(kind, 'a page needs a page ref, a position and a size');\n }\n assertKnownFields(kind, 'a page', entry, PAGE_FIELDS);\n const { position } = entry;\n if (!Number.isInteger(position) || (position as number) < 0) {\n invalidBundle(kind, `page position ${JSON.stringify(position)} is not a position`);\n }\n const key = encodePageKey(entry.page);\n if (pageKeys.has(key)) invalidBundle(kind, `page ${key} is listed twice`);\n if (positions.has(position as number)) {\n invalidBundle(kind, `position ${position} is listed twice`);\n }\n pageKeys.add(key);\n positions.add(position as number);\n }\n return pageKeys;\n}\n\n/**\n * Check the resources a row names, by role: each role one of `roles`, each\n * id a resource id the bundle holds. Each id is added to `named`.\n */\nexport function assertRowResources(\n kind: BundleKind,\n row: string,\n resources: unknown,\n roles: readonly string[],\n resourceSizes: ReadonlyMap<string, number>,\n named: Set<string>,\n): void {\n if (!isRecord(resources)) invalidBundle(kind, `${row} has no resources`);\n for (const [role, id] of Object.entries(resources)) {\n if (!roles.includes(role))\n invalidBundle(kind, `${row} names an unknown resource role '${role}'`);\n if (typeof id !== 'string' || !RESOURCE_ID_PATTERN.test(id)) {\n invalidBundle(kind, `${row} names ${JSON.stringify(id)}, which is not a resource id`);\n }\n if (!resourceSizes.has(id))\n invalidBundle(kind, `${row} names ${id}, which the bundle doesn't hold`);\n named.add(id);\n }\n}\n\n/**\n * Every resource the bundle holds has a resource id and is named by one of\n * its `rows` (`'item'`, `'widget'`).\n */\nexport function assertResourcesNamed(\n kind: BundleKind,\n rows: string,\n resourceSizes: ReadonlyMap<string, number>,\n named: ReadonlySet<string>,\n): void {\n for (const id of resourceSizes.keys()) {\n if (!RESOURCE_ID_PATTERN.test(id))\n invalidBundle(kind, `${JSON.stringify(id)} is not a resource id`);\n if (!named.has(id)) invalidBundle(kind, `resource ${id} is named by no ${rows}`);\n }\n}\n\n/** `value` has no field outside `fields`. */\nexport function assertKnownFields(\n kind: BundleKind,\n what: string,\n value: Record<string, unknown>,\n fields: readonly string[],\n): void {\n for (const field of Object.keys(value)) {\n if (!fields.includes(field)) invalidBundle(kind, `${what} has an unknown field '${field}'`);\n }\n}\n\n/** Refuse a bundle that isn't one: `InvalidArg`, naming its kind. */\nexport function invalidBundle(kind: BundleKind, message: string): never {\n throw new EngineError(EngineErrorCode.InvalidArg, `${kind} bundle: ${message}`);\n}\n\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n/** A page ref as a bundle holds one: by object number. */\nexport function isBundlePageRef(value: unknown): value is PageRef {\n return (\n isRecord(value) &&\n value.kind === 'objectNumber' &&\n Number.isInteger(value.objectNumber) &&\n (value.objectNumber as number) > 0\n );\n}\n\nfunction isSize(value: unknown): value is PdfSize {\n return (\n isRecord(value) &&\n [value.width, value.height].every(\n (length) => typeof length === 'number' && Number.isFinite(length) && length >= 0,\n )\n );\n}\n\n/**\n * Where an import puts each page of a bundle, as `pages` says, among the\n * `target` document's pages. Every page in `named` (the pages the rows are\n * on or point at) must map somewhere: `InvalidArg` names those that don't,\n * and a list that maps to a page the target doesn't have is `NotFound`.\n * Nothing here touches a document, so an import refuses before its first\n * write.\n */\nexport function bundlePageMapping(input: {\n readonly bundlePages: readonly BundlePage[];\n readonly pages: BundleImportPages;\n readonly target: readonly BundleImportTarget[];\n readonly named: Iterable<PageRef>;\n}): (page: PageRef) => PageRef {\n const table = pageTable(input.bundlePages, input.pages, input.target);\n const unmapped = new Set<string>();\n for (const page of input.named) {\n if (!table.has(encodePageKey(page))) unmapped.add(encodePageKey(page));\n }\n if (unmapped.size > 0) {\n const pages = [...unmapped];\n throw new EngineError(\n EngineErrorCode.InvalidArg,\n `import: ${pages.length === 1 ? 'page' : 'pages'} ${pages.join(', ')} map to no page of this document`,\n { details: { pages } },\n );\n }\n return (page) => table.get(encodePageKey(page))!;\n}\n\n/** Bundle page key → target page. */\nfunction pageTable(\n bundlePages: readonly BundlePage[],\n pages: BundleImportPages,\n target: readonly BundleImportTarget[],\n): Map<string, PageRef> {\n const targetByKey = new Map(target.map((entry) => [encodePageKey(entry.page), entry.page]));\n const table = new Map<string, PageRef>();\n if (pages === 'same') {\n for (const entry of bundlePages) {\n const to = targetByKey.get(encodePageKey(entry.page));\n if (to) table.set(encodePageKey(entry.page), to);\n }\n } else if (pages === 'by-position') {\n const byPosition = new Map(target.map((entry) => [entry.position, entry.page]));\n for (const entry of bundlePages) {\n const to = byPosition.get(entry.position);\n if (to) table.set(encodePageKey(entry.page), to);\n }\n } else {\n for (const { from, to } of pages) {\n const key = encodePageKey(from);\n if (table.has(key)) {\n throw new EngineError(EngineErrorCode.InvalidArg, `import: page ${key} is mapped twice`);\n }\n const found = targetByKey.get(encodePageKey(to));\n if (!found) {\n throw new EngineError(\n EngineErrorCode.NotFound,\n `import: the document has no page ${encodePageKey(to)}`,\n );\n }\n table.set(key, found);\n }\n }\n return table;\n}\n","/**\n * Pure, dependency-free composition of the flat annotation list into\n * reply/group threads. No PDFium, no browser, no zod — safe to import from\n * the cloud SDK, the local engine, and any UI plugin.\n *\n * The engine surfaces `/IRT` + `/RT` as a flat edge on every DTO\n * ({@link AnnotationBase.reply}); it\n * deliberately does not nest replies/group members, because each of those\n * is itself a first-class annotation in the page list. This module turns\n * those edges into the shape a comments sidebar wants.\n *\n * See ISO 32000 §12.5.6.2:\n * - `/RT /R` -> a comment-thread reply (default when `/RT` is absent)\n * - `/RT /Group` -> a subordinate part of one logical annotation group\n */\n\nimport type { AnnotationBase } from './base';\nimport type { Annotation } from './kinds';\nimport type { PdfCoordinates } from '../pageSpace/coordinates';\nimport type { AnnotationRef } from '../identity/AnnotationRef';\nimport { annotationKey } from '../identity/annotationKey';\n\n/**\n * Where a single annotation sits in the reply/group taxonomy.\n *\n * 'top-level' no `/IRT` — a primary annotation / thread root.\n * 'reply' `/IRT` + `/RT /R` (or `/RT` absent) — a comment.\n * 'grouped-subordinate' `/IRT` + `/RT /Group` — a visual part of a group.\n */\nexport type AnnotationRelationKind = 'top-level' | 'reply' | 'grouped-subordinate';\n\n/**\n * Classify one annotation by its relationship edge alone. Mirrors the\n * spec's \"practical parser rule\": no `/IRT` is top-level; `/RT /Group` is\n * a grouped subordinate; anything else with an `/IRT` is a reply (the\n * engine has already normalized a missing `/RT` to `'reply'`).\n */\nexport function classifyRelation(a: Pick<AnnotationBase, 'reply'>): AnnotationRelationKind {\n if (!a.reply) return 'top-level';\n return a.reply.type === 'group' ? 'grouped-subordinate' : 'reply';\n}\n\n/**\n * One composed thread: a primary annotation plus the annotations that\n * point at it.\n *\n * - `groupedParts` (`/RT /Group`) are visual/helper parts of one logical\n * annotation — a sidebar should fold them into the primary, not list\n * them as separate comments. Group-level fields (Contents, T, Subj, …)\n * come from the primary; the subordinate's copies are ignored.\n * - `replies` (`/RT /R`) are real comment-thread entries shown threaded\n * under the primary.\n *\n * A primary may legitimately have both (e.g. a replace-text Caret with its\n * StrikeOut group part and a Text reply).\n */\nexport interface AnnotationThread<T extends Annotation = Annotation> {\n primary: T;\n /** `/RT /Group` children — merge into the primary, don't list separately. */\n groupedParts: T[];\n /** `/RT /R` (or default) children — show as threaded comments. */\n replies: T[];\n}\n\n/**\n * Compose a flat annotation list (one page, or a whole document from\n * `annotations.list()`) into {@link AnnotationThread}s in primary\n * order.\n *\n * Rules (ISO 32000 §12.5.6.2 + the spec's UI rule):\n * - Annotations with no `/IRT` become thread primaries, in input order.\n * - A `/RT /Group` child is attached to its primary's `groupedParts`.\n * - A `/RT /R` (or default) child is attached to its primary's `replies`.\n * - A child whose parent is not in the input set is treated as an\n * orphan primary (defensive — e.g. a partial/filtered page slice).\n *\n * Limitations (v1, matches the legacy stack): threading is one level deep\n * — a reply-to-a-reply is keyed to its direct parent, so it only appears\n * nested if that direct parent is itself a primary. Callers that want a\n * sidebar of \"most annotations, not widgets/popups\" should pre-filter the\n * input; this helper is intentionally unopinionated about eligibility.\n */\nexport function buildThreads(annotations: readonly Annotation[]): AnnotationThread[] {\n const byKey = new Map(annotations.map((a) => [annotationKey(a.ref), a]));\n\n const threads: AnnotationThread[] = [];\n const threadByPrimaryKey = new Map<string, AnnotationThread>();\n\n const primaryThread = (primary: Annotation): AnnotationThread => {\n const key = annotationKey(primary.ref);\n let thread = threadByPrimaryKey.get(key);\n if (!thread) {\n thread = { primary, groupedParts: [], replies: [] };\n threadByPrimaryKey.set(key, thread);\n threads.push(thread);\n }\n return thread;\n };\n\n // Pass 1: every top-level annotation seeds a thread, preserving order.\n for (const a of annotations) {\n if (!a.reply) primaryThread(a);\n }\n\n // Pass 2: attach children to their primary; orphans become primaries.\n for (const a of annotations) {\n if (!a.reply) continue;\n const parent = byKey.get(annotationKey(a.reply.to));\n if (!parent || parent.reply) {\n // Parent missing from the set, or itself a child (one-level-deep\n // limitation): surface the annotation as its own primary so it is\n // never silently dropped.\n primaryThread(a);\n continue;\n }\n const thread = primaryThread(parent);\n if (a.reply.type === 'group') thread.groupedParts.push(a);\n else thread.replies.push(a);\n }\n\n return threads;\n}\n\n/**\n * An annotation and everything deleted with it: every annotation whose\n * `reply.to` leads to it (replies, their replies, grouped parts, review\n * states) and every popup of these. A reply left behind would point at\n * nothing and show as a note of its own in other viewers; a popup left\n * behind would show nobody's text. Children come before their parent and a\n * popup before the annotation it shows, so the annotation itself is last.\n * Empty when `ref` names nothing in `annotations`.\n */\nexport function deletedWith<A extends Annotation | Annotation<PdfCoordinates>>(\n annotations: readonly A[],\n ref: AnnotationRef,\n): A[] {\n const byKey = new Map(\n annotations.map((annotation) => [annotationKey(annotation.ref), annotation]),\n );\n const target = byKey.get(annotationKey(ref));\n if (!target) return [];\n\n const children = new Map<A, A[]>();\n const popups = new Map<A, A[]>();\n const add = (map: Map<A, A[]>, key: A, value: A) =>\n map.set(key, [...(map.get(key) ?? []), value]);\n for (const annotation of annotations) {\n const parent = annotation.reply ? byKey.get(annotationKey(annotation.reply.to)) : undefined;\n if (parent && parent !== annotation) add(children, parent, annotation);\n // A popup belongs to the annotation it shows, by its `/Parent` or by\n // that annotation's `/Popup`.\n const shows =\n annotation.subtype === 'popup' && annotation.parent\n ? byKey.get(annotationKey(annotation.parent))\n : undefined;\n if (shows && shows !== annotation) add(popups, shows, annotation);\n const own = annotation.popup ? byKey.get(annotationKey(annotation.popup)) : undefined;\n if (own && own !== annotation && own.subtype === 'popup') add(popups, annotation, own);\n }\n\n const members: A[] = [];\n const seen = new Set<A>();\n const visit = (annotation: A): void => {\n if (seen.has(annotation)) return;\n seen.add(annotation);\n for (const child of children.get(annotation) ?? []) visit(child);\n for (const popup of popups.get(annotation) ?? []) {\n if (seen.has(popup)) continue;\n seen.add(popup);\n members.push(popup);\n }\n members.push(annotation);\n };\n visit(target);\n return members;\n}\n","/**\n * Comment-thread composition — the conversation-plane view over the flat\n * annotation list.\n *\n * Where `buildThreads()` (relationships.ts) is the minimal, unopinionated\n * one-level composer, `buildCommentThreads()` is the opinionated one a\n * comments sidebar wants:\n *\n * - the whole `/IRT` subtree of a root is walked (cycle-safe), and its\n * non-state members flatten into one chronological reply list;\n * - ISO 32000 §12.5.6.3 state annotations (review status) are extracted\n * into `review` instead of appearing as replies;\n * - widgets, links, popups (a note's window, not a comment) and\n * unsupported blobs are excluded entirely;\n * - `/RT /Group` subordinates anywhere in the subtree fold into\n * `groupedParts`, never into `replies`.\n *\n * Tolerant-reader rules (foreign files are messy; none of this throws):\n * - empty-string `state` / `stateModel` count as absent — the engine\n * DTO is faithful (`''` = present-but-empty), tolerance lives here;\n * - a state annotation whose target cannot be resolved is dropped\n * (status metadata with no anchor has no meaning);\n * - an orphaned non-state reply is promoted to a thread root (matching\n * `buildThreads`), as is the first input-order member of an `/IRT`\n * cycle — the visited set breaks the loop, nothing is lost or hangs;\n * - a `/State` with no `/StateModel` infers its model from the known\n * vocabulary; a custom model with no derivable state is skipped.\n *\n * Ordering: threads appear in the input order of their roots; the\n * composer never sorts by page (display order is a layout concern —\n * callers join `pages.list()`). Replies sort chronologically by\n * `createdAt ?? modifiedAt`, entries without a date last, page z-order\n * (their place in `annotations`, bottom to top) as the final deterministic\n * tiebreak.\n */\n\nimport type { Annotation } from './kinds';\nimport type { KnownAnnotationState, KnownAnnotationStateModel } from './primitives';\nimport { classifyRelation } from './relationships';\nimport { annotationKey } from '../identity/annotationKey';\nimport type { AnnotationRef } from '../identity/AnnotationRef';\nimport type { PageRef } from '../identity/PageRef';\nimport { compareIsoDateTime, type IsoDateTime } from '../dto/IsoDateTime';\n\n/** One reviewer's status, derived from an ISO §12.5.6.3 state annotation. */\nexport interface ReviewStatus {\n /** Wire-normalized when known (`'accepted'`, …); verbatim when custom. */\n state: string;\n /** `'review'`, `'marked'`, or a custom model verbatim. */\n stateModel: string;\n /** Reviewer key: `/EMBD_Metadata` userId, else `/T`, else null. */\n by: string | null;\n /** `/M` ?? `/CreationDate` of the state annotation. */\n at: IsoDateTime | null;\n /** The state annotation itself — for auditing or deletion. */\n ref: AnnotationRef;\n}\n\n/**\n * Review state of one thread. The two ISO state models are independent\n * axes: `byReviewer` / `lastChange` cover review status (the standard\n * `Review` model plus custom models), while the personal-checkmark\n * `Marked` axis lives solely in `markedBy`.\n */\nexport interface CommentThreadReview {\n /** Latest review-axis status per reviewer key (unattributed skipped). */\n byReviewer: Record<string, ReviewStatus>;\n /** Latest review-axis change overall — a convenience, not a verdict. */\n lastChange: ReviewStatus | null;\n /** Reviewer keys whose latest Marked-model status is `'marked'`. */\n markedBy: string[];\n /**\n * Every state annotation in the thread's subtree (both axes, all\n * reviewers, chronological) — thread membership, not status history:\n * deleting a whole thread must delete its state annotations too, and\n * the classified summaries above deliberately drop superseded refs.\n */\n statusRefs: AnnotationRef[];\n /** `byReviewer[currentUserId]`; only set when the option was given. */\n mine?: ReviewStatus | null;\n}\n\nexport interface CommentThread<T extends Annotation = Annotation> {\n root: T;\n page: PageRef;\n /** Whole-subtree replies, flattened chronologically; states excluded. */\n replies: T[];\n /** Every `/RT /Group` subordinate found in the subtree. */\n groupedParts: T[];\n review: CommentThreadReview;\n}\n\nexport interface BuildCommentThreadsOptions {\n /** Compute `review.mine` against this reviewer key. */\n currentUserId?: string;\n}\n\n/** Subtypes that never participate in comment threads: a popup is its\n * parent's window and an unsupported blob is unreadable, so neither makes\n * a comment card. */\nconst EXCLUDED_SUBTYPES: ReadonlySet<string> = new Set(['widget', 'link', 'popup', 'unsupported']);\n\nconst REVIEW_STATES: ReadonlySet<KnownAnnotationState> = new Set([\n 'accepted',\n 'rejected',\n 'cancelled',\n 'completed',\n 'none',\n]);\nconst MARKED_STATES: ReadonlySet<KnownAnnotationState> = new Set(['marked', 'unmarked']);\n\n/**\n * The model a standard state belongs to (ISO 32000 §12.5.6.3, Table 174):\n * `'review'` for accepted, rejected, cancelled, completed and none,\n * `'marked'` for marked and unmarked; `null` for a custom state.\n */\nexport function standardStateModelOf(state: string): KnownAnnotationStateModel | null {\n if (REVIEW_STATES.has(state as KnownAnnotationState)) return 'review';\n if (MARKED_STATES.has(state as KnownAnnotationState)) return 'marked';\n return null;\n}\n\nconst nonEmpty = (v: string | null | undefined): v is string => typeof v === 'string' && v !== '';\n\n/**\n * An ISO 32000 §12.5.6.3 state annotation: a text annotation carrying a\n * non-empty `/State` or `/StateModel`. Classification never relies on\n * flags — producers disagree on how state annotations are flagged.\n */\nexport function isStateAnnotation(a: Annotation): boolean {\n return a.subtype === 'text' && (nonEmpty(a.state) || nonEmpty(a.stateModel));\n}\n\nexport function buildCommentThreads(\n annotations: readonly Annotation[],\n opts: BuildCommentThreadsOptions = {},\n): CommentThread[] {\n const eligible = annotations.filter((a) => !EXCLUDED_SUBTYPES.has(a.subtype));\n\n const byKey = new Map(eligible.map((a) => [annotationKey(a.ref), a]));\n const zOrder = new Map(eligible.map((a, at) => [annotationKey(a.ref), at]));\n const chronological = chronologicalIn(zOrder);\n\n // Children adjacency over resolvable /IRT edges.\n const children = new Map<string, Annotation[]>();\n for (const a of eligible) {\n if (!a.reply) continue;\n const parent = byKey.get(annotationKey(a.reply.to));\n if (!parent) continue; // orphan — handled in the promotion pass\n const parentKey = annotationKey(parent.ref);\n const list = children.get(parentKey);\n if (list) list.push(a);\n else children.set(parentKey, [a]);\n }\n\n const visited = new Set<string>();\n const threads: CommentThread[] = [];\n\n const walk = (root: Annotation): void => {\n const replies: Annotation[] = [];\n const groupedParts: Annotation[] = [];\n const states: Annotation[] = [];\n\n visited.add(annotationKey(root.ref));\n const stack = [...(children.get(annotationKey(root.ref)) ?? [])];\n while (stack.length > 0) {\n const a = stack.pop()!;\n const key = annotationKey(a.ref);\n if (visited.has(key)) continue; // cycle back-edge — skip\n visited.add(key);\n if (isStateAnnotation(a)) states.push(a);\n else if (classifyRelation(a) === 'grouped-subordinate') groupedParts.push(a);\n else replies.push(a);\n stack.push(...(children.get(key) ?? []));\n }\n\n replies.sort(chronological);\n // Chronological order makes latest-wins deterministic for equal or\n // missing dates (the comparator's z-order tiebreak applies).\n states.sort(chronological);\n threads.push({\n root,\n page: root.page,\n replies,\n groupedParts,\n review: computeReview(states, opts),\n });\n };\n\n // Pass 1: real roots, in input order.\n for (const a of eligible) {\n if (!a.reply && !isStateAnnotation(a)) walk(a);\n }\n\n // Pass 2: promotion. Anything not reached from a root — an orphan whose\n // parent is missing, or a member of an /IRT cycle — promotes to its own\n // root in input order. State annotations never promote: a status with no\n // reachable target is dropped.\n for (const a of eligible) {\n if (visited.has(annotationKey(a.ref))) continue;\n if (isStateAnnotation(a)) continue;\n walk(a);\n }\n\n return threads;\n}\n\n/** `createdAt ?? modifiedAt` ascending; undated last; z-order tiebreak. */\nfunction chronologicalIn(zOrder: ReadonlyMap<string, number>) {\n return (a: Annotation, b: Annotation): number => {\n const at = a.createdAt ?? a.modifiedAt;\n const bt = b.createdAt ?? b.modifiedAt;\n const order = at !== null && bt !== null ? compareIsoDateTime(at, bt) : 0;\n if (order !== 0) return order;\n if (at !== null && bt === null) return -1;\n if (at === null && bt !== null) return 1;\n return zOrder.get(annotationKey(a.ref))! - zOrder.get(annotationKey(b.ref))!;\n };\n}\n\nfunction computeReview(\n states: readonly Annotation[],\n opts: BuildCommentThreadsOptions,\n): CommentThreadReview {\n const byReviewer: Record<string, ReviewStatus> = {};\n const markedLatest: Record<string, ReviewStatus> = {};\n let lastChange: ReviewStatus | null = null;\n\n for (const a of states) {\n const status = toReviewStatus(a);\n if (!status) continue;\n if (status.stateModel === 'marked') {\n if (status.by !== null && isNewer(status, markedLatest[status.by])) {\n markedLatest[status.by] = status;\n }\n continue; // the Marked axis never feeds byReviewer / lastChange\n }\n if (status.by !== null && isNewer(status, byReviewer[status.by])) {\n byReviewer[status.by] = status;\n }\n if (isNewer(status, lastChange)) lastChange = status;\n }\n\n const markedBy = Object.keys(markedLatest)\n .filter((key) => markedLatest[key]!.state === 'marked')\n .sort();\n\n const review: CommentThreadReview = {\n byReviewer,\n lastChange,\n markedBy,\n statusRefs: states.map((a) => a.ref),\n };\n if (opts.currentUserId !== undefined) {\n review.mine = byReviewer[opts.currentUserId] ?? null;\n }\n return review;\n}\n\n/**\n * Derive a `ReviewStatus` from one state annotation, or null when nothing\n * classifiable can be derived. ISO defaulting happens here, not in the\n * engine reader: a known model with an absent state means `none` /\n * `unmarked`; an absent model infers from a known state; a custom model\n * with no state has no derivable status.\n */\nfunction toReviewStatus(a: Annotation): ReviewStatus | null {\n if (a.subtype !== 'text') return null;\n const rawState = nonEmpty(a.state) ? a.state : null;\n const rawModel = nonEmpty(a.stateModel) ? a.stateModel : null;\n\n let stateModel = rawModel;\n if (stateModel === null && rawState !== null) {\n stateModel = standardStateModelOf(rawState);\n if (stateModel === null) return null; // custom state without a model: unclassifiable\n }\n let state = rawState;\n if (state === null) {\n if (stateModel === 'review') state = 'none';\n else if (stateModel === 'marked') state = 'unmarked';\n else return null; // custom model without a state: no default exists\n }\n if (stateModel === null) return null; // unreachable, kept for narrowing\n\n return {\n state,\n stateModel,\n by: a.userId ?? (nonEmpty(a.author) ? a.author : null),\n at: a.modifiedAt ?? a.createdAt ?? null,\n ref: a.ref,\n };\n}\n\n/** `a` newer than (or supersedes) `b`. `at` decides; dated beats undated.\n * States arrive pre-sorted by `chronological` (date, then z-order), so on\n * equal or missing dates the later entry wins via `>=` / `true`. */\nfunction isNewer(a: ReviewStatus, b: ReviewStatus | null | undefined): boolean {\n if (!b) return true;\n if (a.at !== null && b.at !== null) return compareIsoDateTime(a.at, b.at) >= 0;\n if (a.at !== null) return true;\n if (b.at !== null) return false;\n return true; // both undated: input order — later entry wins\n}\n","import type { Annotation, AnnotationPatch } from './kinds';\nimport type { AnnotationSubtype } from './subtype';\nimport type { Coordinates, PdfCoordinates } from '../pageSpace/coordinates';\n\n/**\n * Appearance-impact classification: the shared, pure decision for whether an\n * update patch requires re-baking the `/AP` normal appearance stream.\n *\n * An `/AP` stream is content, not cache — a foreign producer's appearance\n * (Acrobat's rich `/AP`, an image-backed stamp) generally cannot be\n * recomputed, so destroying it is only acceptable as the explicit consequence\n * of a semantic edit. Per ISO 32000 §12.5.5 a form XObject's `BBox` is\n * algorithmically fitted into `/Rect`, so a same-size `/Rect` change\n * translates the painted pixels verbatim: preservation on a verified rigid\n * translation is a theorem, not a policy. The engine therefore never trusts a\n * caller's claim of \"this is just a move\" — it checks the geometric fact that\n * licenses preservation.\n *\n * The classifier compares in DTO space on both sides (the patch vocabulary is\n * the DTO vocabulary, produced by the same readers), so value-diffing drops\n * no-op keys even from clients that send full-object patches. Unknown keys\n * and unknown subtypes classify as `regenerate` — conservative by default.\n * It reads positions by their axis names only (`x`/`left`/`right`,\n * `y`/`bottom`/`top`), so it classifies the file's values and page-space\n * values alike: a viewer asks the same question the engine does.\n */\nexport type AppearanceImpact =\n /** Nothing appearance-affecting changed value — never touch `/AP`. */\n | 'inert'\n /** A verified rigid translation — pixels identical up to translation. */\n | 'translation'\n /** A semantic appearance edit — the owner re-bakes `/AP`. */\n | 'regenerate';\n\n/**\n * An update's appearance impact, with the distance a `translation` moves the\n * drawing by, in the coordinates of the values classified.\n */\nexport type AppearanceChange =\n | { readonly impact: 'inert' }\n | { readonly impact: 'translation'; readonly by: { readonly x: number; readonly y: number } }\n | { readonly impact: 'regenerate' };\n\n/**\n * The kinds a write gives no appearance of the engine's: a link, which the\n * engine writes with no border to draw, and a form widget, which its form\n * field draws (one on its own has nothing to draw). A write leaves whether\n * the file holds one as it was, and a new one has none. Every other kind's\n * create bakes one, and so does every change to it that is visible and not a\n * pure move.\n */\nexport const UNBAKED_KINDS: ReadonlySet<AnnotationSubtype> = new Set(['link', 'widget']);\n\n/**\n * What actually happened to `/AP` during an update (the engine's echo):\n * kept, drawn again, not drawable for the kind, or, in an undo, put back as\n * it was before the change being undone.\n */\nexport type AppearanceAction = 'preserved' | 'regenerated' | 'generation-unavailable' | 'restored';\n\n/**\n * The appearance verdict every `AnnotationUpdateResult` carries. `changed`\n * (not `action`) is the raster-invalidation signal: `true` iff the document's\n * appearance definition changed — a regenerated `/AP`, or appearance-affecting\n * dictionary writes on a subtype the generic generator cannot re-bake.\n */\nexport interface AppearanceOutcome {\n action: AppearanceAction;\n changed: boolean;\n}\n\n/**\n * Coordinate tolerance in PDF user-space points. PDF numbers round-trip\n * through f32 (~7 significant digits) and client-side space conversions, so\n * exact float equality would misclassify no-op writes; 1e-3 pt is far below\n * anything visible while far above accumulated f32 drift at page magnitudes.\n */\nconst EPSILON = 1e-3;\n\n/**\n * Keys that never affect `/AP` on any kind: the discriminator, the `/F`\n * flags, the name, relationships and grouping, the conversation-plane\n * entries (`/Subj` subject line, `/State` + `/StateModel` review status —\n * dictionary-only per ISO 32000 §12.5.6.3, never painted), and the fields a\n * write accepts but never applies (addresses, attribution, `/A` and `/AA`).\n */\nconst INERT_KEYS: ReadonlySet<string> = new Set([\n 'subtype',\n 'invisible',\n 'hidden',\n 'print',\n 'noZoom',\n 'noRotate',\n 'noView',\n 'readOnly',\n 'locked',\n 'toggleNoView',\n 'lockedContents',\n 'nm',\n 'reply',\n 'popup',\n 'parent',\n // Whether a comment window shows open: the window's state, never painted.\n 'open',\n 'groupId',\n 'subject',\n 'state',\n 'stateModel',\n 'ref',\n 'page',\n 'hasAppearance',\n // Which state shows: picked among the pictures the annotation has.\n 'appearanceState',\n 'author',\n 'createdAt',\n 'modifiedAt',\n 'userId',\n 'createdBy',\n 'modifiedBy',\n 'importedBy',\n 'actions',\n // A file attachment's icon is drawn from `/Name` and `/C`, never from its file.\n 'file',\n // The field a widget belongs to, as the form reads it.\n 'field',\n 'fieldFamily',\n]);\n\n/**\n * Kinds whose `/AP` paints `/Contents`. Everywhere else `contents` is popup\n * note text — editing a comment must never re-bake (or destroy) the shape's\n * appearance.\n */\nconst CONTENTS_PAINTED: ReadonlySet<string> = new Set(['free-text', 'redact']);\n\n/**\n * The kinds that turn by `rotation`: a box kind about the middle of its\n * `box`, a point kind about the middle of its points' box. Tri-state on\n * writes: an omitted rotation is kept, `null` (or `0`) clears it. Translation\n * verification therefore compares the after-state —\n * `patch.rotation ?? current.rotation` — not the patch keys.\n */\nconst TURNING_KINDS: ReadonlySet<string> = new Set([\n 'square',\n 'circle',\n 'free-text',\n 'stamp',\n 'caret',\n 'widget',\n 'line',\n 'polyline',\n 'polygon',\n 'ink',\n]);\n\n/**\n * Per-kind absolute-geometry fields (PDF user space) that a rigid translation\n * shifts together. A kind absent from this table never takes the translation\n * route. The first is where a move shows: the field the caller gives the\n * shape in (a `box`, the points, the quads), or `rect` where that is the\n * shape. A `rect` the engine works out moves with it.\n */\nconst TRANSLATABLE_GEOMETRY: Record<string, readonly string[]> = {\n square: ['box'],\n circle: ['box'],\n 'free-text': ['box', 'calloutLine'],\n line: ['linePoints'],\n polygon: ['vertices'],\n polyline: ['vertices'],\n ink: ['inkList'],\n highlight: ['quadPoints'],\n underline: ['quadPoints'],\n squiggly: ['quadPoints'],\n strikeout: ['quadPoints'],\n redact: ['rect', 'quadPoints'],\n caret: ['box'],\n text: ['rect'],\n stamp: ['box'],\n 'file-attachment': ['rect'],\n link: ['rect'],\n widget: ['box'],\n};\n\nconst numEq = (a: number, b: number): boolean => Math.abs(a - b) <= EPSILON;\n\n/** Degrees normalized to [0,360); absent reads as 0 (no rotation). */\nconst normDeg = (v: unknown): number => {\n const n = typeof v === 'number' ? ((v % 360) + 360) % 360 : 0;\n return n;\n};\n\n/**\n * Semantic equality between a patch value and the current DTO value.\n * Numbers compare within {@link epsilon}; `null` and `undefined` both mean\n * \"entry absent\" (the tri-state clear of an absent entry is a no-op); arrays\n * and objects compare structurally.\n */\nexport function semanticEqual(a: unknown, b: unknown): boolean {\n if (a == null || b == null) return a == null && b == null;\n if (typeof a === 'number' && typeof b === 'number') return numEq(a, b);\n if (Array.isArray(a) || Array.isArray(b)) {\n if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) return false;\n return a.every((v, i) => semanticEqual(v, b[i]));\n }\n if (typeof a === 'object' && typeof b === 'object') {\n const keys = new Set([...Object.keys(a), ...Object.keys(b as object)]);\n for (const k of keys) {\n if (!semanticEqual((a as Record<string, unknown>)[k], (b as Record<string, unknown>)[k])) {\n return false;\n }\n }\n return true;\n }\n return a === b;\n}\n\n/**\n * Is `next` exactly `cur` shifted by `(dx, dy)`? Walks the value structurally:\n * numeric leaves under x-axis keys (`left`/`right`/`x`) must shift by `dx`,\n * y-axis keys (`bottom`/`top`/`y`) by `dy`, and any other numeric leaf must be\n * unchanged. Arrays walk elementwise (same length required).\n */\nfunction shiftedBy(cur: unknown, next: unknown, dx: number, dy: number): boolean {\n if (cur == null || next == null) return cur == null && next == null;\n if (Array.isArray(cur) || Array.isArray(next)) {\n if (!Array.isArray(cur) || !Array.isArray(next) || cur.length !== next.length) return false;\n return cur.every((v, i) => shiftedBy(v, next[i], dx, dy));\n }\n if (typeof cur === 'object' && typeof next === 'object') {\n const keys = new Set([...Object.keys(cur), ...Object.keys(next as object)]);\n for (const k of keys) {\n const c = (cur as Record<string, unknown>)[k];\n const n = (next as Record<string, unknown>)[k];\n if (typeof c === 'number' && typeof n === 'number') {\n const delta =\n k === 'left' || k === 'right' || k === 'x'\n ? dx\n : k === 'bottom' || k === 'top' || k === 'y'\n ? dy\n : 0;\n if (!numEq(c + delta, n)) return false;\n } else if (!shiftedBy(c, n, dx, dy)) {\n return false;\n }\n }\n return true;\n }\n return cur === next;\n}\n\n/**\n * The first point a geometry value holds: a rect's bottom-left, a point, a\n * line's start, a quad's first corner, the first of a list.\n */\nfunction firstPoint(value: unknown): { x: number; y: number } | undefined {\n if (value == null || typeof value !== 'object') return undefined;\n if (Array.isArray(value)) return value.length > 0 ? firstPoint(value[0]) : undefined;\n const record = value as Record<string, unknown>;\n if (typeof record.x === 'number' && typeof record.y === 'number') {\n return { x: record.x, y: record.y };\n }\n if (typeof record.left === 'number' && typeof record.bottom === 'number') {\n return { x: record.left, y: record.bottom };\n }\n return firstPoint(record.start ?? record.upperLeft);\n}\n\n/**\n * The distance the touched geometry moves by, when it is one rigid\n * translation of the current state; `null` when it isn't. Requires the kind's\n * first geometry field in the patch; it and every other geometry field\n * present on the annotation must ride along shifted by the same delta — a box\n * resized, or a leader left behind by a moved text box, is not a translation\n * (the dictionary would desync from the pixels). For the kinds that turn, the\n * turn is checked as an after-state: an omitted rotation keeps the current\n * one.\n */\nfunction rigidTranslationOf(\n cur: Record<string, unknown>,\n pat: Record<string, unknown>,\n subtype: string,\n geometryKeys: readonly string[],\n): { x: number; y: number } | null {\n const [anchor] = geometryKeys;\n const from = firstPoint(cur[anchor!]);\n const to = firstPoint(pat[anchor!]);\n if (!from || !to) return null;\n const dx = to.x - from.x;\n const dy = to.y - from.y;\n\n if (TURNING_KINDS.has(subtype)) {\n // Tri-state writes: an omitted rotation preserves the current one; `null`\n // clears (≡ 0). Compare the resulting after-state.\n const rotAfter = pat.rotation === undefined ? cur.rotation : pat.rotation;\n if (!numEq(normDeg(cur.rotation), normDeg(rotAfter))) return null;\n }\n\n for (const key of geometryKeys) {\n const c = cur[key];\n const p = pat[key];\n if (c == null && p == null) continue; // absent on both — nothing to shift\n if (c == null || p == null) return null; // geometry appearing/vanishing\n if (!shiftedBy(c, p, dx, dy)) return null;\n }\n return { x: dx, y: dy };\n}\n\nconst INERT: AppearanceChange = { impact: 'inert' };\nconst REGENERATE: AppearanceChange = { impact: 'regenerate' };\n\n/**\n * Classify an update patch against the annotation's current read, in either\n * space, with the distance a translation moves the drawing by.\n *\n * 1. Value-diff: drop keys whose value semantically equals the current one,\n * plus the always-inert metadata keys (and per-kind inert keys: `contents`\n * where it isn't painted).\n * Nothing left → `'inert'`.\n * 2. If every remaining key is translatable geometry for this kind and the\n * values are one rigid translation → `'translation'`, by how far.\n * 3. Anything else — style, text, unknown keys, unknown kinds → `'regenerate'`.\n */\nexport function appearanceChangeOf<C extends Coordinates>(\n current: Annotation<C>,\n patch: AnnotationPatch<C>,\n): AppearanceChange {\n if (patch.subtype !== undefined && patch.subtype !== current.subtype) return REGENERATE;\n\n const cur = current as unknown as Record<string, unknown>;\n const pat = patch as unknown as Record<string, unknown>;\n const subtype = current.subtype;\n const captionEnabled = pat.captionEnabled === undefined ? cur.captionEnabled : pat.captionEnabled;\n const contentsPainted =\n CONTENTS_PAINTED.has(subtype) ||\n (['line', 'polygon', 'polyline'].includes(subtype) && captionEnabled === true);\n\n const touched: string[] = [];\n for (const [key, value] of Object.entries(pat)) {\n if (value === undefined || INERT_KEYS.has(key)) continue;\n if (key === 'contents' && !contentsPainted) continue;\n if (!semanticEqual(value, cur[key])) touched.push(key);\n }\n if (touched.length === 0) return INERT;\n\n const baseGeometryKeys = TRANSLATABLE_GEOMETRY[subtype];\n // A manual shape caption is page-space geometry and must ride with a rigid\n // move. Automatic centers follow the vertices without an explicit patch.\n const geometryKeys =\n baseGeometryKeys && (subtype === 'polygon' || subtype === 'polyline') && cur.captionCenter\n ? [...baseGeometryKeys, 'captionCenter']\n : baseGeometryKeys;\n if (!geometryKeys) return REGENERATE;\n if (!touched.every((k) => geometryKeys.includes(k))) return REGENERATE;\n const by = rigidTranslationOf(cur, pat, subtype, geometryKeys);\n return by ? { impact: 'translation', by } : REGENERATE;\n}\n\n/** {@link appearanceChangeOf}'s verdict alone, on the file's values: what the engine's update decides. */\nexport function appearanceImpactOf(\n current: Annotation<PdfCoordinates>,\n patch: AnnotationPatch<PdfCoordinates>,\n): AppearanceImpact {\n return appearanceChangeOf(current, patch).impact;\n}\n","import { semanticEqual } from './appearance';\nimport { ANNOTATION_FIELD_SPACES, type MeasuredFieldSpace } from './field-spaces';\nimport type { Annotation } from './kinds';\nimport type { AnnotationSubtype } from './subtype';\nimport { EngineError } from '../errors/EngineError';\nimport { EngineErrorCode } from '../errors/EngineErrorCode';\nimport {\n normalizePdfRect,\n pdfQuarterTurnBox,\n pdfRectTurnedBounds,\n quarterTurnOf,\n} from '../geometry/convert';\nimport type { PdfPoint, PdfQuad, PdfRect } from '../geometry/primitives';\nimport type { PdfCoordinates } from '../pageSpace/coordinates';\n\n/**\n * The kinds whose `rect` the engine works out from their shape: a box, points\n * or quads (`drawnRectFields`). `test/annotation/shapeForRect.test.ts` keeps\n * it equal to the declarations.\n */\nexport const DRAWN_RECT_KINDS: ReadonlySet<AnnotationSubtype> = new Set([\n 'highlight',\n 'underline',\n 'squiggly',\n 'strikeout',\n 'square',\n 'circle',\n 'free-text',\n 'stamp',\n 'caret',\n 'widget',\n 'line',\n 'polyline',\n 'polygon',\n 'ink',\n]);\n\n/**\n * The places that make up a drawing. A measurement's origin isn't one: it's\n * where the scale's coordinates start, so it stays when the drawing moves.\n */\nconst DRAWING_SPACES: ReadonlySet<MeasuredFieldSpace> = new Set([\n 'box',\n 'point',\n 'points',\n 'strokes',\n 'quads',\n 'linePoints',\n 'calloutLine',\n]);\n\n/** The fields that hold a drawn kind's shape: its places, and its turn. */\nexport function shapeFieldsOf(subtype: AnnotationSubtype): string[] {\n const places = Object.entries(ANNOTATION_FIELD_SPACES[subtype])\n .filter(([name, space]) => name !== 'rect' && DRAWING_SPACES.has(space))\n .map(([name]) => name);\n return [...places, 'rotation'];\n}\n\n/**\n * The shape fields that put `annotation` at `rect`, in the file's\n * coordinates: the rule an update's `rect` follows. The public\n * `shapeForRect` runs it on page-space values.\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 pdfShapeForRect<A extends Annotation<PdfCoordinates>>(\n annotation: A,\n rect: PdfRect,\n): Partial<A> {\n const subtype = annotation.subtype;\n if (!DRAWN_RECT_KINDS.has(subtype)) return { rect } as Partial<A>;\n\n const to = normalizePdfRect(rect);\n const from = normalizePdfRect(annotation.rect);\n const toWidth = to.right - to.left;\n const toHeight = to.top - to.bottom;\n const fromWidth = from.right - from.left;\n const fromHeight = from.top - from.bottom;\n const sameWidth = semanticEqual(toWidth, fromWidth);\n const sameHeight = semanticEqual(toHeight, fromHeight);\n if ((!sameWidth && toWidth <= 0) || (!sameHeight && toHeight <= 0)) {\n throw refused(subtype, 'a rect needs a width and a height');\n }\n const rotation = (annotation as { rotation?: number | null }).rotation ?? 0;\n const spaces = ANNOTATION_FIELD_SPACES[subtype];\n // A box at a quarter turn stands upright on the page: a rect pins it down.\n const quarterTurn = spaces.box === 'box' ? quarterTurnOf(rotation) : null;\n if (!semanticEqual(((rotation % 360) + 360) % 360, 0) && quarterTurn === null) {\n if (!sameWidth || !sameHeight) {\n throw refused(subtype, \"a turned drawing's rect can only move; resize its shape instead\");\n }\n }\n if ((!sameWidth && fromWidth <= 0) || (!sameHeight && fromHeight <= 0)) {\n throw refused(subtype, 'its rect has no width or height to stretch; it can only move');\n }\n\n const scaleX = sameWidth ? 1 : toWidth / fromWidth;\n const scaleY = sameHeight ? 1 : toHeight / fromHeight;\n const point = (p: PdfPoint): PdfPoint => ({\n x: to.left + (p.x - from.left) * scaleX,\n y: to.bottom + (p.y - from.bottom) * scaleY,\n });\n const placeRect = (rect: PdfRect): PdfRect => {\n const corner = point({ x: rect.left, y: rect.bottom });\n const opposite = point({ x: rect.right, y: rect.top });\n return normalizePdfRect({\n left: corner.x,\n bottom: corner.y,\n right: opposite.x,\n top: opposite.y,\n });\n };\n const place: Partial<Record<MeasuredFieldSpace, (value: never) => unknown>> = {\n // A quarter-turned box is placed as it stands on the page, then turned back.\n box: (box: PdfRect) =>\n quarterTurn === null || quarterTurn === 0 || quarterTurn === 180\n ? placeRect(box)\n : pdfQuarterTurnBox(placeRect(pdfRectTurnedBounds(box, quarterTurn)), quarterTurn),\n point,\n points: (points: PdfPoint[]) => points.map(point),\n strokes: (strokes: PdfPoint[][]) => strokes.map((stroke) => stroke.map(point)),\n quads: (quads: PdfQuad[]) =>\n quads.map((quad) => ({\n upperLeft: point(quad.upperLeft),\n upperRight: point(quad.upperRight),\n lowerLeft: point(quad.lowerLeft),\n lowerRight: point(quad.lowerRight),\n })),\n linePoints: (line: { start: PdfPoint; end: PdfPoint }) => ({\n start: point(line.start),\n end: point(line.end),\n }),\n calloutLine: (points: PdfPoint[]) => points.map(point),\n };\n\n const shape: Record<string, unknown> = {};\n for (const name of shapeFieldsOf(subtype)) {\n const value = (annotation as unknown as Record<string, unknown>)[name];\n const space = spaces[name];\n if (value != null && space) shape[name] = place[space]!(value as never);\n }\n return shape as Partial<A>;\n}\n\nfunction refused(subtype: string, reason: string): EngineError {\n return new EngineError(EngineErrorCode.InvalidArg, `${subtype} field 'rect': ${reason}`, {\n details: { field: 'rect' },\n });\n}\n","import type { PdfMeasure } from '../dto/Measure';\nimport type { PdfPoint } from '../geometry/primitives';\n\nexport interface MeasuredScale {\n sx: number;\n sy: number;\n}\nconst positive = (n: number): boolean => Number.isFinite(n) && n > 0;\nexport function scaleOf(measure: PdfMeasure): MeasuredScale | null {\n const sx = Math.fround(measure.x[0]?.conversion ?? NaN);\n if (!positive(sx)) return null;\n if (!measure.y) return { sx, sy: sx };\n const cy = Math.fround(measure.y[0]?.conversion ?? NaN);\n const cyx = Math.fround(measure.cyx ?? NaN);\n const sy = cy * cyx;\n return positive(cy) && positive(cyx) && positive(sy) ? { sx, sy } : null;\n}\n\nexport const measurementPoint = (p: PdfPoint): PdfPoint => ({\n x: Math.fround(p.x),\n y: Math.fround(p.y),\n});\n\nexport function pathLength(\n points: readonly PdfPoint[],\n closed: boolean,\n scale: MeasuredScale,\n): number {\n let total = 0;\n const normalized = points.map(measurementPoint);\n for (let i = 0; i < (closed ? normalized.length : normalized.length - 1); i++) {\n const a = normalized[i],\n b = normalized[(i + 1) % normalized.length];\n total += Math.hypot((b.x - a.x) * scale.sx, (b.y - a.y) * scale.sy);\n }\n return total;\n}\n\nexport function polygonArea(points: readonly PdfPoint[], scale: MeasuredScale): number {\n if (points.length < 3) return 0;\n const normalized = points.map(measurementPoint);\n const origin = normalized[0];\n let twice = 0;\n // Relative coordinates avoid cancellation at a large nonzero page origin.\n for (let i = 1; i < normalized.length - 1; i++) {\n const a = normalized[i],\n b = normalized[i + 1];\n twice += (a.x - origin.x) * (b.y - origin.y) - (b.x - origin.x) * (a.y - origin.y);\n }\n return Math.abs(twice * scale.sx * scale.sy) / 2;\n}\n\n/** A measured area must have one simple, nonzero boundary. Repeated closing\n * vertices are allowed in imported PDFs; crossings and overlapping edges are not. */\nexport function validAreaBoundary(points: readonly PdfPoint[]): boolean {\n const boundary = points.map(measurementPoint);\n const same = (a: PdfPoint, b: PdfPoint) => a.x === b.x && a.y === b.y;\n if (boundary.length > 1 && same(boundary[0], boundary[boundary.length - 1])) {\n boundary.pop();\n }\n if (boundary.length < 3 || polygonArea(boundary, { sx: 1, sy: 1 }) === 0) return false;\n\n const cross = (a: PdfPoint, b: PdfPoint, c: PdfPoint) =>\n (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x);\n const onSegment = (a: PdfPoint, b: PdfPoint, p: PdfPoint) =>\n cross(a, b, p) === 0 &&\n p.x >= Math.min(a.x, b.x) &&\n p.x <= Math.max(a.x, b.x) &&\n p.y >= Math.min(a.y, b.y) &&\n p.y <= Math.max(a.y, b.y);\n\n for (let i = 0; i < boundary.length; i++) {\n const a = boundary[i];\n const b = boundary[(i + 1) % boundary.length];\n if (same(a, b)) return false;\n const next = boundary[(i + 2) % boundary.length];\n // Adjacent collinear edges may continue forward, but must not double back.\n const doublesBack = (b.x - a.x) * (next.x - b.x) + (b.y - a.y) * (next.y - b.y) < 0;\n if (cross(a, b, next) === 0 && doublesBack) {\n return false;\n }\n\n for (let j = i + 1; j < boundary.length; j++) {\n if (j === i + 1 || (i === 0 && j === boundary.length - 1)) continue;\n const c = boundary[j];\n const d = boundary[(j + 1) % boundary.length];\n if (onSegment(a, b, c) || onSegment(a, b, d) || onSegment(c, d, a) || onSegment(c, d, b)) {\n return false;\n }\n if (\n Math.sign(cross(a, b, c)) !== Math.sign(cross(a, b, d)) &&\n Math.sign(cross(c, d, a)) !== Math.sign(cross(c, d, b))\n ) {\n return false;\n }\n }\n }\n return true;\n}\n","import type { PdfMeasurement } from '../dto/Measure';\nimport type { LinePoints, PdfPoint } from '../geometry/primitives';\nimport { pathLength, polygonArea, scaleOf, validAreaBoundary } from './compute';\nimport { formatMeasurement, validNumberFormat } from './format';\n\nexport interface DimensionInput {\n subtype: string;\n intent?: string | null;\n measure?: PdfMeasurement | null;\n linePoints?: LinePoints;\n vertices?: PdfPoint[];\n contents?: string | null;\n}\nexport interface MeasurementReadout {\n kind: 'distance' | 'perimeter' | 'area';\n label: string;\n /** Value in the first display format's unit. */\n value: number;\n perimeter?: string;\n}\nexport interface MeasurementUnavailable {\n unavailable:\n | 'not-dimension'\n | 'no-measure'\n | 'foreign-measure'\n | 'no-scale'\n | 'no-distance-format'\n | 'no-area-format'\n | 'invalid-format'\n | 'invalid-geometry';\n}\nexport function isDimension(dto: { subtype: string; intent?: string | null }): boolean {\n return (\n (dto.subtype === 'line' && dto.intent === 'line-dimension') ||\n (dto.subtype === 'polyline' && dto.intent === 'polyline-dimension') ||\n (dto.subtype === 'polygon' && dto.intent === 'polygon-dimension')\n );\n}\nexport const isReadout = (\n r: MeasurementReadout | MeasurementUnavailable,\n): r is MeasurementReadout => !('unavailable' in r);\n\nexport function measurementReadout(\n dto: DimensionInput,\n): MeasurementReadout | MeasurementUnavailable {\n if (!isDimension(dto)) return { unavailable: 'not-dimension' };\n if (!dto.measure) return { unavailable: 'no-measure' };\n if (dto.measure.subtype !== 'rectilinear') return { unavailable: 'foreign-measure' };\n const m = dto.measure,\n scale = scaleOf(m);\n if (!scale) return { unavailable: 'no-scale' };\n const points =\n dto.subtype === 'line'\n ? dto.linePoints\n ? [dto.linePoints.start, dto.linePoints.end]\n : []\n : (dto.vertices ?? []);\n if (\n points.length < (dto.subtype === 'polygon' ? 3 : 2) ||\n points.some((p) => !Number.isFinite(Math.fround(p.x)) || !Number.isFinite(Math.fround(p.y)))\n ) {\n return { unavailable: 'invalid-geometry' };\n }\n const area = dto.subtype === 'polygon';\n if (area && !validAreaBoundary(points)) return { unavailable: 'invalid-geometry' };\n const formats = area ? m.area : m.distance;\n if (!formats.length) return { unavailable: area ? 'no-area-format' : 'no-distance-format' };\n if (!formats.every(validNumberFormat)) return { unavailable: 'invalid-format' };\n const value = area ? polygonArea(points, scale) : pathLength(points, false, scale);\n try {\n return {\n kind: area ? 'area' : dto.subtype === 'line' ? 'distance' : 'perimeter',\n value: value * Math.fround(formats[0].conversion!),\n label: formatMeasurement(value, formats),\n ...(area && m.distance.length && m.distance.every(validNumberFormat)\n ? { perimeter: formatMeasurement(pathLength(points, true, scale), m.distance) }\n : {}),\n };\n } catch {\n return { unavailable: 'invalid-format' };\n }\n}\n\nexport function deriveMeasurementLabel<T extends DimensionInput>(dto: T): T {\n const readout = measurementReadout(dto);\n return isReadout(readout) && dto.contents !== readout.label\n ? { ...dto, contents: readout.label }\n : dto;\n}\n","import type { PdfMeasure } from '../dto/Measure';\nimport { EngineError } from '../errors/EngineError';\nimport { EngineErrorCode } from '../errors/EngineErrorCode';\nimport { validNumberFormat } from './format';\n\n/** Shared preflight for HTTP, workers and calibration helpers. Does not write. */\nexport function assertWritableMeasure(value: PdfMeasure): void {\n if (value.subtype !== 'rectilinear')\n throw new EngineError(EngineErrorCode.InvalidArg, 'Only rectilinear measures can be authored');\n if (value.ratio !== undefined && (typeof value.ratio !== 'string' || value.ratio.includes('\\0')))\n throw new EngineError(EngineErrorCode.InvalidArg, 'Invalid scale ratio');\n for (const key of ['x', 'y', 'distance', 'area', 'angle', 'slope'] as const) {\n const list = value[key];\n if (list === undefined && (key === 'y' || key === 'angle' || key === 'slope')) continue;\n if (!Array.isArray(list))\n throw new EngineError(EngineErrorCode.InvalidArg, `Missing ${key} formats`);\n for (const nf of list) {\n if (!nf || typeof nf.unit !== 'string' || !validNumberFormat(nf))\n throw new EngineError(EngineErrorCode.InvalidArg, 'Invalid number format');\n if (\n nf.fraction !== undefined &&\n !['decimal', 'fraction', 'round', 'truncate'].includes(nf.fraction)\n )\n throw new EngineError(EngineErrorCode.InvalidArg, 'Invalid fraction mode');\n if (nf.labelPosition !== undefined && !['prefix', 'suffix'].includes(nf.labelPosition))\n throw new EngineError(EngineErrorCode.InvalidArg, 'Invalid label position');\n if (nf.fixed !== undefined && typeof nf.fixed !== 'boolean')\n throw new EngineError(EngineErrorCode.InvalidArg, 'Invalid fixed precision');\n for (const key of [\n 'unit',\n 'thousands',\n 'decimal',\n 'prefixSpacing',\n 'suffixSpacing',\n ] as const) {\n const text = nf[key];\n if (text !== undefined && (typeof text !== 'string' || text.includes('\\0')))\n throw new EngineError(EngineErrorCode.InvalidArg, 'Invalid measurement text');\n }\n }\n }\n if (value.origin !== undefined)\n for (const n of [value.origin.x, value.origin.y]) assertPdfFloat(n);\n if (value.cyx !== undefined) {\n assertPdfFloat(value.cyx);\n if (Math.fround(value.cyx) <= 0)\n throw new EngineError(EngineErrorCode.InvalidArg, 'Invalid CYX');\n }\n}\nexport function assertPdfFloat(n: number): void {\n if (typeof n !== 'number' || !Number.isFinite(Math.fround(n)))\n throw new EngineError(EngineErrorCode.InvalidArg, 'Value is outside PDF float range');\n}\n","import { EngineError } from '../../errors/EngineError';\nimport { EngineErrorCode } from '../../errors/EngineErrorCode';\nimport type { PdfPoint } from '../../geometry/primitives';\nimport { deriveMeasurementLabel, isReadout, measurementReadout } from '../../measure/derive';\nimport { assertPdfFloat, assertWritableMeasure } from '../../measure/validate';\nimport type { PdfCoordinates } from '../../pageSpace/coordinates';\nimport type { AnnotationDraft, Annotation, AnnotationPatch } from '../kinds';\n\ntype DimensionKind = 'line' | 'polygon' | 'polyline';\ntype DimensionWrite = Extract<\n AnnotationDraft<PdfCoordinates> | AnnotationPatch<PdfCoordinates>,\n { subtype?: DimensionKind }\n>;\n\n/** The fields a measurement's label is worked out from. */\nconst LABEL_INPUTS = ['linePoints', 'vertices', 'measure', 'intent', 'contents'] as const;\n\nconst CAPTION_FIELDS = ['captionEnabled', 'captionPosition', 'captionOffset', 'captionCenter'];\n\nconst isDimensionKind = (subtype: string | undefined): subtype is DimensionKind =>\n subtype === 'line' || subtype === 'polygon' || subtype === 'polyline';\n\n/** Whether a write names any of the caption's fields. */\nexport const touchesCaption = (value: object): boolean =>\n CAPTION_FIELDS.some((name) => (value as Record<string, unknown>)[name] !== undefined);\n\nfunction validate(subtype: DimensionKind, write: DimensionWrite): void {\n try {\n if (write.measure != null && write.measure.subtype === 'rectilinear')\n assertWritableMeasure(write.measure);\n if (\n subtype === 'line' &&\n 'leader' in write &&\n write.leader != null &&\n (typeof write.leader !== 'object' || Array.isArray(write.leader))\n )\n throw new EngineError(EngineErrorCode.InvalidArg, 'Invalid line leader');\n const intents =\n subtype === 'line'\n ? ['line-dimension', 'line-arrow']\n : subtype === 'polygon'\n ? ['polygon-dimension', 'polygon-cloud']\n : ['polyline-dimension'];\n if (write.intent != null && !intents.includes(write.intent))\n throw new EngineError(EngineErrorCode.InvalidArg, 'Invalid measurement intent');\n if (write.captionEnabled != null && typeof write.captionEnabled !== 'boolean')\n throw new EngineError(EngineErrorCode.InvalidArg, 'Invalid caption visibility');\n if ('captionPosition' in write && write.captionPosition != null) {\n if (!['inline', 'top'].includes(write.captionPosition))\n throw new EngineError(EngineErrorCode.InvalidArg, 'Invalid caption position');\n }\n if ('captionOffset' in write && write.captionOffset) {\n assertPdfFloat(write.captionOffset.along);\n assertPdfFloat(write.captionOffset.perpendicular);\n }\n if ('captionCenter' in write && write.captionCenter) {\n assertPdfFloat(write.captionCenter.x);\n assertPdfFloat(write.captionCenter.y);\n }\n if ('leader' in write && write.leader) {\n for (const length of [\n write.leader.length,\n write.leader.extension ?? 0,\n write.leader.offset ?? 0,\n ])\n assertPdfFloat(length);\n if ((write.leader.extension ?? 0) < 0 || (write.leader.offset ?? 0) < 0)\n throw new EngineError(\n EngineErrorCode.InvalidArg,\n 'Leader extension and offset must be nonnegative',\n );\n }\n const points =\n 'linePoints' in write\n ? write.linePoints\n ? [write.linePoints.start, write.linePoints.end]\n : []\n : 'vertices' in write\n ? (write.vertices ?? [])\n : [];\n for (const point of points) {\n assertPdfFloat(point.x);\n assertPdfFloat(point.y);\n }\n } catch (error) {\n throw new EngineError(EngineErrorCode.InvalidArg, (error as Error).message);\n }\n}\n\n/** Infer a rigid transform only when all corresponding vertices agree. Vertex edits leave a manual center fixed. */\nfunction moveCenter(\n before: readonly PdfPoint[],\n after: readonly PdfPoint[],\n center: PdfPoint,\n): PdfPoint | undefined {\n if (before.length !== after.length || before.length < 2) return undefined;\n const origin = before[0]!;\n const moved = after[0]!;\n const index = before.findIndex(\n (point) => Math.hypot(point.x - origin.x, point.y - origin.y) > 1e-6,\n );\n if (index < 0) return undefined;\n const from = { x: before[index]!.x - origin.x, y: before[index]!.y - origin.y };\n const to = { x: after[index]!.x - moved.x, y: after[index]!.y - moved.y };\n const length = from.x * from.x + from.y * from.y;\n const cos = (from.x * to.x + from.y * to.y) / length;\n const sin = (from.x * to.y - from.y * to.x) / length;\n if (Math.abs(cos * cos + sin * sin - 1) > 1e-5) return undefined;\n const transform = (point: PdfPoint): PdfPoint => ({\n x: moved.x + cos * (point.x - origin.x) - sin * (point.y - origin.y),\n y: moved.y + sin * (point.x - origin.x) + cos * (point.y - origin.y),\n });\n if (\n !before.every((point, i) => {\n const placed = transform(point);\n return Math.hypot(placed.x - after[i]!.x, placed.y - after[i]!.y) <= 1e-3;\n })\n )\n return undefined;\n return transform(center);\n}\n\n/**\n * A dimension draft ready for the writer: validated, its label worked out,\n * and its caption fields complete, since the native caption setters write\n * the whole caption at once.\n */\nexport function resolveMeasurementDraft(\n draft: AnnotationDraft<PdfCoordinates>,\n): AnnotationDraft<PdfCoordinates> {\n if (!isDimensionKind(draft.subtype)) return draft;\n const dimension = draft as DimensionWrite;\n validate(draft.subtype, dimension);\n if (dimension.measure != null && dimension.measure.subtype !== 'rectilinear') {\n throw new EngineError(\n EngineErrorCode.InvalidArg,\n `A ${dimension.measure.subtype === 'geospatial' ? 'geospatial' : 'foreign'} measure can't be written; leave measure out`,\n );\n }\n let resolved = draft;\n if (touchesCaption(draft)) {\n if (draft.subtype === 'line') {\n resolved = {\n ...draft,\n // `null` is a line without a caption flag, as a read says.\n captionEnabled: draft.captionEnabled === undefined ? false : draft.captionEnabled,\n captionPosition: draft.captionPosition ?? 'inline',\n captionOffset: draft.captionOffset ?? null,\n };\n } else if (draft.subtype === 'polygon' || draft.subtype === 'polyline') {\n resolved = {\n ...draft,\n captionEnabled: draft.captionEnabled ?? (draft.captionCenter != null ? false : null),\n captionCenter: draft.captionCenter ?? null,\n };\n }\n }\n return deriveMeasurementLabel(resolved as never) as AnnotationDraft<PdfCoordinates>;\n}\n\n/**\n * A dimension patch with what follows from it. The patch's subtype is the\n * target's. Caption fields merge with the current caption into a complete\n * caption; a whole-shape move carries a manual caption center along; a\n * foreign measure marker sent back keeps the measure as it is; and the label\n * is worked out from the resulting geometry and scale.\n */\nexport function measurementFollows(\n current: Annotation<PdfCoordinates>,\n patch: AnnotationPatch<PdfCoordinates>,\n): AnnotationPatch<PdfCoordinates> {\n if (current.subtype !== 'line' && current.subtype !== 'polygon' && current.subtype !== 'polyline')\n return patch;\n const subtype = current.subtype;\n let next = { ...patch, subtype } as DimensionWrite & { subtype: DimensionKind };\n validate(subtype, next);\n\n if (next.measure != null && next.measure.subtype !== 'rectilinear') {\n if (current.measure?.subtype !== next.measure.subtype) {\n throw new EngineError(\n EngineErrorCode.InvalidArg,\n `A ${next.measure.subtype === 'geospatial' ? 'geospatial' : 'foreign'} measure can't be written; leave measure out`,\n );\n }\n // The marker a read returned, sent back: the measure stays as it is.\n next = { ...next, measure: undefined };\n }\n\n if (current.subtype === 'line' && next.subtype === 'line') {\n if (touchesCaption(next)) {\n next = {\n ...next,\n captionEnabled:\n next.captionEnabled === undefined ? current.captionEnabled : next.captionEnabled,\n captionPosition: next.captionPosition ?? current.captionPosition,\n captionOffset:\n next.captionOffset === undefined ? current.captionOffset : next.captionOffset,\n };\n }\n } else if (current.subtype !== 'line' && next.subtype !== 'line') {\n if (\n next.vertices &&\n next.captionEnabled !== null &&\n next.captionCenter === undefined &&\n current.captionCenter\n ) {\n const center = moveCenter(current.vertices, next.vertices, current.captionCenter);\n if (center) next = { ...next, captionCenter: center };\n }\n if (touchesCaption(next)) {\n next =\n next.captionEnabled === null\n ? // No caption flag: the caption and its placement go together.\n { ...next, captionEnabled: null, captionCenter: null }\n : {\n ...next,\n captionEnabled: next.captionEnabled ?? current.captionEnabled ?? false,\n captionCenter:\n next.captionCenter === undefined ? current.captionCenter : next.captionCenter,\n };\n }\n }\n\n if (LABEL_INPUTS.some((key) => (next as Record<string, unknown>)[key] !== undefined)) {\n const readout = measurementReadout({ ...current, ...next } as never);\n if (isReadout(readout)) next = { ...next, contents: readout.label };\n }\n validate(subtype, next);\n return next as AnnotationPatch<PdfCoordinates>;\n}\n","import { pdfPointTurned, pdfPointUnturned } from '../geometry/pointTurn';\nimport type { PdfPoint, PdfRect } from '../geometry/primitives';\n\n/**\n * Where a callout's line meets its text box: the middle of the side `toward`\n * (the knee, else the tip) lies beyond, chosen by which way it is farther\n * from the box's middle, across or up and down. A turned box decides in its\n * own frame, and the point lands on the turned side, the one the page shows.\n * In the file's coordinates.\n */\nexport function pdfCalloutEnd(box: PdfRect, toward: PdfPoint, rotation: number): PdfPoint {\n const center = { x: (box.left + box.right) / 2, y: (box.bottom + box.top) / 2 };\n const turn = { degrees: rotation, center };\n const local = rotation ? pdfPointUnturned(toward, turn) : toward;\n const dx = local.x - center.x;\n const dy = local.y - center.y;\n const end =\n Math.abs(dx) >= Math.abs(dy)\n ? { x: dx >= 0 ? box.right : box.left, y: center.y }\n : { x: center.x, y: dy > 0 ? box.top : box.bottom };\n return rotation ? pdfPointTurned(end, turn) : end;\n}\n","/**\n * Font names and faces. A free text's or a widget's `fontFamily` names a\n * face the way the host does (a standard font's kebab name, a registered\n * font's `key`, or a family the document has); rich text and the engine name\n * it the way a PDF does (family, weight, italic). Both directions map here.\n */\nimport type { FontIdentityInfo } from '../dto/FontSpec';\nimport { STANDARD_FONTS, type FreeTextFont, type StandardFont } from './primitives';\n\n/** The face a font name asks for; weight and italic when the name implies them. */\nexport interface FaceRequest {\n family: string;\n weight?: number;\n italic?: boolean;\n}\n\ninterface StandardFace {\n family: 'Helvetica' | 'Times' | 'Courier' | 'Symbol' | 'ZapfDingbats';\n weight: number;\n italic: boolean;\n}\n\n/** Looks up a registered font by its key: what `engine.fonts` knows about it. */\nexport type DescribeFont = (fontKey: string) => FontIdentityInfo | undefined;\n\nexport const STANDARD_FACES: Readonly<Record<StandardFont, StandardFace>> = {\n courier: { family: 'Courier', weight: 400, italic: false },\n 'courier-bold': { family: 'Courier', weight: 700, italic: false },\n 'courier-bold-oblique': { family: 'Courier', weight: 700, italic: true },\n 'courier-oblique': { family: 'Courier', weight: 400, italic: true },\n helvetica: { family: 'Helvetica', weight: 400, italic: false },\n 'helvetica-bold': { family: 'Helvetica', weight: 700, italic: false },\n 'helvetica-bold-oblique': { family: 'Helvetica', weight: 700, italic: true },\n 'helvetica-oblique': { family: 'Helvetica', weight: 400, italic: true },\n 'times-roman': { family: 'Times', weight: 400, italic: false },\n 'times-bold': { family: 'Times', weight: 700, italic: false },\n 'times-bold-italic': { family: 'Times', weight: 700, italic: true },\n 'times-italic': { family: 'Times', weight: 400, italic: true },\n symbol: { family: 'Symbol', weight: 400, italic: false },\n 'zapf-dingbats': { family: 'ZapfDingbats', weight: 400, italic: false },\n};\n\n/** One of the 14 standard names. The names are reserved: a registered font keyed `'helvetica'` resolves as the standard one. */\nexport const isStandardFontName = (font: string): font is StandardFont =>\n (STANDARD_FONTS as readonly string[]).includes(font);\n\n/**\n * The face a free text's `fontFamily` (or a rich run's `family`) asks for: a\n * standard font's family, weight and italic; a registered key's identity; or,\n * for anything else, the string itself as a family name (a face the document\n * embeds, or one the engine will substitute).\n */\nexport function faceForFreeTextFont(font: FreeTextFont, describe?: DescribeFont): FaceRequest {\n if (isStandardFontName(font)) {\n const face = STANDARD_FACES[font];\n return { family: face.family, weight: face.weight, italic: face.italic };\n }\n const registered = describe?.(font);\n if (registered) {\n return { family: registered.familyName, weight: registered.weight, italic: registered.italic };\n }\n return { family: font };\n}\n\n/** Family names compare without case, spaces, hyphens and underscores\n * (the engine's own rule): \"Noto Sans\" == \"NotoSans\" == \"noto-sans\". */\nexport function familyKey(family: string): string {\n return family.toLowerCase().replace(/[\\s\\-_'\"]/g, '');\n}\n\n/** Families that are a standard font's, by `familyKey`. */\nconst STANDARD_FAMILY_KEYS: Record<string, StandardFace['family']> = {\n helvetica: 'Helvetica',\n arial: 'Helvetica',\n arialmt: 'Helvetica',\n sansserif: 'Helvetica',\n times: 'Times',\n timesroman: 'Times',\n timesnewroman: 'Times',\n timesnewromanpsmt: 'Times',\n serif: 'Times',\n courier: 'Courier',\n couriernew: 'Courier',\n couriernewpsmt: 'Courier',\n monospace: 'Courier',\n symbol: 'Symbol',\n zapfdingbats: 'ZapfDingbats',\n dingbats: 'ZapfDingbats',\n};\n\n/** Looks up the registered font a face is: its `key`, or undefined. */\nexport type KeyForFace = (family: string, weight: number, italic: boolean) => string | undefined;\n\n/**\n * The `fontFamily` that names a face (the other direction of\n * {@link faceForFreeTextFont}): the registered `key` whose identity matches,\n * else the standard font's kebab name, else the family itself.\n */\nexport function freeTextFontForFace(\n face: { family: string; weight: number; italic: boolean },\n keyForFace?: KeyForFace,\n): FreeTextFont {\n const key = keyForFace?.(face.family, face.weight, face.italic);\n if (key !== undefined) return key;\n const standard = STANDARD_FAMILY_KEYS[familyKey(face.family)];\n if (standard) {\n const faces = Object.entries(STANDARD_FACES) as [StandardFont, StandardFace][];\n const bold = face.weight >= 600;\n const exact = faces.find(\n ([, spec]) =>\n spec.family === standard && spec.weight >= 600 === bold && spec.italic === face.italic,\n );\n // Symbol and ZapfDingbats have no bold or italic faces.\n const any = exact ?? faces.find(([, spec]) => spec.family === standard);\n if (any) return any[0];\n }\n return face.family;\n}\n","import { EngineError } from '../../errors/EngineError';\nimport { EngineErrorCode } from '../../errors/EngineErrorCode';\nimport {\n richTextParagraphsFromPlainText,\n richTextPlainText,\n type RichTextBody,\n} from '../../dto/RichText';\nimport type { PdfCoordinates } from '../../pageSpace/coordinates';\nimport { pdfCalloutEnd } from '../calloutEnd';\nimport { faceForFreeTextFont, type DescribeFont } from '../fontFaces';\nimport type { AnnotationDraft, Annotation, AnnotationPatch } from '../kinds';\nimport type { FreeTextIntent } from '../primitives';\n\ntype FreeTextPatch = Extract<AnnotationPatch<PdfCoordinates>, { subtype?: 'free-text' }>;\ntype FreeTextRead = Extract<Annotation<PdfCoordinates>, { subtype: 'free-text' }>;\n\n/** A free text's text style: the four fields that are its rich body's. */\ntype TextStyle = Pick<FreeTextPatch, 'fontFamily' | 'fontSize' | 'fontColor' | 'textAlign'>;\n\n/**\n * `base` with a free text's text style over it. The font, size, text color\n * and alignment are the rich body's (runs are deltas over it, so every run\n * that didn't set one follows), and a style given by itself wins over the\n * body's.\n */\nexport function bodyWithStyle(\n base: Partial<RichTextBody>,\n style: TextStyle,\n describe?: DescribeFont,\n): Partial<RichTextBody> {\n const body = { ...base };\n if (style.fontFamily !== undefined) {\n const face = faceForFreeTextFont(style.fontFamily, describe);\n body.family = face.family;\n if (face.weight !== undefined) body.weight = face.weight;\n if (face.italic !== undefined) body.italic = face.italic;\n }\n if (style.fontSize !== undefined) body.size = style.fontSize;\n if (style.fontColor != null) body.color = style.fontColor;\n if (style.textAlign !== undefined) body.align = style.textAlign;\n return body;\n}\n\n/** A callout line goes only with the callout intent: another box would draw without it. */\nfunction assertCalloutIntent(intent: FreeTextIntent, calloutLine: unknown): void {\n if (calloutLine != null && intent !== 'free-text-callout') {\n throw new EngineError(\n EngineErrorCode.InvalidArg,\n `free-text: a callout line needs intent 'free-text-callout', not '${intent}'`,\n { details: { field: 'intent' } },\n );\n }\n}\n\n/**\n * The text style fields a new body brings, beside it: a free text reads its\n * size, text color and alignment off its body, so they change with it. Only\n * the ones that differ from `current`, and never over one the patch states.\n */\nfunction styleOfBody(\n body: Partial<RichTextBody>,\n current: FreeTextRead,\n text: FreeTextPatch,\n): TextStyle {\n const style: TextStyle = {};\n if (text.fontSize === undefined && body.size !== undefined && body.size !== current.fontSize) {\n style.fontSize = body.size;\n }\n if (\n text.fontColor === undefined &&\n body.color !== undefined &&\n body.color.toLowerCase() !== current.fontColor?.toLowerCase()\n ) {\n style.fontColor = body.color.toLowerCase();\n }\n if (\n text.textAlign === undefined &&\n body.align !== undefined &&\n body.align !== current.textAlign\n ) {\n style.textAlign = body.align;\n }\n return style;\n}\n\n/**\n * A free text's text lives in its rich text: `contents` is its plain\n * projection, and the font, size, text color and alignment are its body.\n *\n * - New `richText` brings its `contents`; a partial body merges over the\n * current one.\n * - New `contents` becomes body-style paragraphs, one per line break (run\n * formatting goes: a plain-text writer can't keep what it can't see).\n * - A new font, size, text color or alignment moves the body.\n * - Whatever moves the body states the complete rich text to write, and the\n * size, text color and alignment it reads back with.\n * - A callout line needs the callout intent.\n */\nexport function freeTextFollows(\n current: Annotation<PdfCoordinates>,\n patch: AnnotationPatch<PdfCoordinates>,\n describe?: DescribeFont,\n): AnnotationPatch<PdfCoordinates> {\n if (current.subtype !== 'free-text' || patch.subtype !== 'free-text') return patch;\n const text = patch as FreeTextPatch;\n if (text.intent !== undefined || text.calloutLine !== undefined) {\n assertCalloutIntent(\n text.intent ?? current.intent,\n text.calloutLine !== undefined ? text.calloutLine : current.calloutLine,\n );\n }\n const changes = bodyWithStyle({}, text, describe);\n const textChanged = text.richText !== undefined || text.contents !== undefined;\n if (!textChanged && Object.keys(changes).length === 0) return text;\n const body = { ...current.richText.body, ...text.richText?.body, ...changes };\n const paragraphs =\n text.richText?.paragraphs ??\n (text.contents !== undefined\n ? richTextParagraphsFromPlainText(text.contents ?? '')\n : current.richText.paragraphs);\n const richText = { body, paragraphs };\n return {\n ...text,\n ...styleOfBody(body, current, text),\n richText,\n // The engine writes `/Contents` from the rich text: a line break reads back as `\\r`.\n ...(textChanged ? { contents: richTextPlainText(richText) } : {}),\n };\n}\n\n/**\n * A callout's line stays attached: when its box moves or turns and the\n * patch doesn't state its own `calloutLine`, the line's end moves to where\n * the line now meets the box (the side its knee, else its tip, lies beyond).\n * A stated `calloutLine` is kept as given; a patch that moves neither the box\n * nor its turn keeps the stored end.\n */\nexport function calloutEndFollows(\n current: Annotation<PdfCoordinates>,\n patch: AnnotationPatch<PdfCoordinates>,\n): AnnotationPatch<PdfCoordinates> {\n if (current.subtype !== 'free-text' || patch.subtype !== 'free-text') return patch;\n const text = patch as FreeTextPatch;\n const line = current.calloutLine;\n if (!line || text.calloutLine !== undefined) return text;\n if (text.box === undefined && text.rotation === undefined) return text;\n const box = text.box ?? current.box;\n const rotation = (text.rotation === undefined ? current.rotation : text.rotation) ?? 0;\n const knee = line.length === 3 ? line[1] : undefined;\n const end = pdfCalloutEnd(box, knee ?? line[0], rotation);\n return { ...text, calloutLine: knee ? [line[0], knee, end] : [line[0], end] };\n}\n\n/**\n * A free text draft, stated whole:\n *\n * - its intent: the callout intent when it has a callout line, else a plain\n * box (a callout line needs the callout intent);\n * - its text as rich text: the draft's rich text, else body-style paragraphs\n * from its `contents` (one per line break, an empty box without any), with\n * the text style over the body (a style given by itself wins over the\n * body's; what neither gives is the engine's default);\n * - `contents` as the rich text's plain projection.\n */\nexport function freeTextDraftFollows(\n draft: AnnotationDraft<PdfCoordinates>,\n describe?: DescribeFont,\n): AnnotationDraft<PdfCoordinates> {\n if (draft.subtype !== 'free-text') return draft;\n const intent = draft.intent ?? (draft.calloutLine != null ? 'free-text-callout' : 'free-text');\n assertCalloutIntent(intent, draft.calloutLine);\n const richText = {\n body: bodyWithStyle(draft.richText?.body ?? {}, draft, describe),\n paragraphs: draft.richText?.paragraphs ?? richTextParagraphsFromPlainText(draft.contents ?? ''),\n };\n // The engine writes `/Contents` from the rich text: a line break reads back as `\\r`.\n return { ...draft, intent, richText, contents: richTextPlainText(richText) };\n}\n","import { EngineError } from '../../errors/EngineError';\nimport { EngineErrorCode } from '../../errors/EngineErrorCode';\nimport { isFinitePdfRect, normalizePdfRect } from '../../geometry/convert';\nimport type { PdfCoordinates } from '../../pageSpace/coordinates';\nimport { semanticEqual } from '../appearance';\nimport type { Annotation, AnnotationPatch } from '../kinds';\nimport { DRAWN_RECT_KINDS, pdfShapeForRect, shapeFieldsOf } from '../shapeForRect';\n\n/**\n * An update's `rect` on a drawn kind, resolved as a command: the rect it\n * read, sent back, is dropped (nothing moves); another rect becomes the shape\n * fields that put the drawing there. It can't come with a change to the shape\n * itself: which of the two to follow would be a guess, so it is refused\n * (`InvalidArg` on `rect`), as is a rect that isn't four finite numbers. A\n * kind whose shape is its rect keeps it as a plain field. The page-space\n * `resolveRectCommand` runs it on page-space values.\n */\nexport function pdfResolveRectCommand(\n current: Annotation<PdfCoordinates>,\n patch: AnnotationPatch<PdfCoordinates>,\n): AnnotationPatch<PdfCoordinates> {\n const { rect, ...rest } = patch as AnnotationPatch<PdfCoordinates> & { rect?: unknown };\n if (rect === undefined || !DRAWN_RECT_KINDS.has(current.subtype)) return patch;\n if (!isFinitePdfRect(rect)) {\n throw new EngineError(\n EngineErrorCode.InvalidArg,\n `${current.subtype} update field 'rect': not a rect of finite numbers`,\n { details: { field: 'rect' } },\n );\n }\n // The rect it read, sent back: nothing moves.\n if (semanticEqual(normalizePdfRect(rect), current.rect)) {\n return rest as AnnotationPatch<PdfCoordinates>;\n }\n const read = current as unknown as Record<string, unknown>;\n const changed = shapeFieldsOf(current.subtype).find((name) => {\n const value = (patch as unknown as Record<string, unknown>)[name];\n return value !== undefined && !semanticEqual(value, read[name]);\n });\n if (changed) {\n throw new EngineError(\n EngineErrorCode.InvalidArg,\n `${current.subtype} update field 'rect': a new rect moves the shape, so it can't come with a new '${changed}'`,\n { details: { field: 'rect' } },\n );\n }\n const { left, bottom, right, top } = rect;\n return {\n ...rest,\n ...pdfShapeForRect(current, { left, bottom, right, top }),\n } as AnnotationPatch<PdfCoordinates>;\n}\n","import type { Coordinates } from '../../pageSpace/coordinates';\nimport { semanticEqual } from '../appearance';\nimport { sameColor } from '../color';\nimport { kindFactsOf } from '../kind-facts';\nimport type { Annotation, AnnotationPatch } from '../kinds';\n\n/** `patch` without the fields `drop` names. `subtype` always stays. */\nfunction without<C extends Coordinates>(\n patch: AnnotationPatch<C>,\n drop: (name: string, value: unknown) => boolean,\n): AnnotationPatch<C> {\n const kept = Object.entries(patch).filter(\n ([name, value]) => name === 'subtype' || !drop(name, value),\n );\n return Object.fromEntries(kept) as AnnotationPatch<C>;\n}\n\n/**\n * The patch without the colors it sends back as they read. A gray or CMYK\n * color in the file reads as its sRGB equivalent; writing that back would\n * store it as sRGB, so leaving it out keeps the file as it is.\n */\nexport function withoutUnchangedColors<C extends Coordinates>(\n current: Annotation<C>,\n patch: AnnotationPatch<C>,\n): AnnotationPatch<C> {\n const colors = kindFactsOf(current.subtype)?.colors ?? [];\n const read = current as unknown as Record<string, unknown>;\n return without(patch, (name, value) => {\n const was = read[name];\n return (\n colors.includes(name) &&\n typeof value === 'string' &&\n typeof was === 'string' &&\n sameColor(value, was)\n );\n });\n}\n\n/**\n * The patch without the fields it sends back as they read: a field equal to\n * the read is not a change, so the annotation keeps it and nothing follows\n * from it. Equal as `semanticEqual` judges it: `null` and a field left out\n * are the same, and numbers within the precision a round trip through page\n * space keeps, so a read sent back from page space is the read. A changed\n * value stays, whatever it is; the engine's check refuses one its kind can't\n * write.\n */\nexport function withoutUnchangedFields<C extends Coordinates>(\n current: Annotation<C>,\n patch: AnnotationPatch<C>,\n): AnnotationPatch<C> {\n const read = current as unknown as Record<string, unknown>;\n return without(patch, (name, value) => value !== undefined && semanticEqual(value, read[name]));\n}\n","import { EngineError } from '../../errors/EngineError';\nimport { EngineErrorCode } from '../../errors/EngineErrorCode';\nimport { richTextPlainText, type RichTextDocumentInput } from '../../dto/RichText';\nimport type { PdfCoordinates } from '../../pageSpace/coordinates';\nimport { standardStateModelOf } from '../comments';\nimport type { AnnotationDraft, Annotation, AnnotationPatch } from '../kinds';\n\n/**\n * A review state needs its model (ISO 32000 §12.5.6.3): a standard state\n * brings its own, so only a custom state with none is refused.\n */\nfunction stateNeedsModel(state: string): EngineError {\n return new EngineError(\n EngineErrorCode.InvalidArg,\n `text: the custom state '${state}' needs a stateModel`,\n { details: { field: 'stateModel' } },\n );\n}\n\n/**\n * A note draft's state with its model filled in: a standard state brings its\n * own; a custom state without one is refused, before the first write.\n */\nexport function noteDraftStateFollows(\n draft: AnnotationDraft<PdfCoordinates>,\n): AnnotationDraft<PdfCoordinates> {\n if (draft.subtype !== 'text' || draft.state == null || draft.stateModel != null) return draft;\n const model = standardStateModelOf(draft.state);\n if (!model) throw stateNeedsModel(draft.state);\n return { ...draft, stateModel: model };\n}\n\n/**\n * A note's new state with its model filled in: a standard state sets its\n * own; a custom one keeps the annotation's, and needs one.\n */\nexport function noteStateFollows(\n current: Annotation<PdfCoordinates>,\n patch: AnnotationPatch<PdfCoordinates>,\n): AnnotationPatch<PdfCoordinates> {\n if (current.subtype !== 'text' || patch.subtype !== 'text') return patch;\n if (patch.state == null || patch.stateModel !== undefined) return patch;\n const model = standardStateModelOf(patch.state);\n if (model) return { ...patch, stateModel: model };\n if (!current.stateModel) throw stateNeedsModel(patch.state);\n return patch;\n}\n\n/**\n * A draft or patch that carries both `contents` and `richText` must agree:\n * `contents` is the plain projection of the rich text. A stale read sent back\n * fails loud here instead of quietly restoring old text.\n */\nexport function assertRichTextAgreement(input: {\n subtype?: string;\n contents?: string | null;\n richText?: RichTextDocumentInput;\n}): void {\n if (input.subtype !== 'free-text' || input.richText === undefined) return;\n if (input.contents === undefined || input.contents === null) return;\n if (input.contents !== richTextPlainText(input.richText)) {\n throw new EngineError(\n EngineErrorCode.InvalidArg,\n 'free-text: `contents` must equal the plain projection of `richText` when both are given',\n );\n }\n}\n","/**\n * What a patch means: the one place the engine decides which fields an\n * update changes. An update is prepared (`pdfPrepareAnnotationPatch`), then\n * what follows from it is derived (`pdfDeriveAnnotationPatch`). The engine\n * checks the prepared patch against its kind's schema between the two\n * (`pdfResolveAnnotationPatch`, from `@embedpdf/engine-core/validation`), a\n * check that only accepts or refuses; a viewer shows a pending change by\n * running the same two steps without schema validation (`applyAnnotationPatch`),\n * so the two can't disagree. The writers write what this resolves and nothing\n * more.\n */\nimport { EngineError } from '../../errors/EngineError';\nimport { EngineErrorCode } from '../../errors/EngineErrorCode';\nimport type { PdfCoordinates } from '../../pageSpace/coordinates';\nimport { ANNOTATION_FIELD_NAMES } from '../field-names';\nimport type { Annotation, AnnotationPatch } from '../kinds';\nimport type { AnnotationSubtype } from '../subtype';\nimport type { DescribeFont } from '../fontFaces';\nimport { calloutEndFollows, freeTextFollows } from './freeText';\nimport { measurementFollows } from './measurement';\nimport { pdfResolveRectCommand } from './rectCommand';\nimport { withoutUnchangedColors, withoutUnchangedFields } from './sentBack';\nimport { assertRichTextAgreement, noteStateFollows } from './text';\n\n/** A write names only fields its kind declares: a misspelled or foreign field is refused, never ignored. */\nexport function assertDeclaredFields(subtype: AnnotationSubtype, write: object): void {\n const known = ANNOTATION_FIELD_NAMES[subtype];\n const unknown = Object.keys(write).filter((name) => name !== 'subtype' && !known.includes(name));\n if (unknown.length > 0) {\n throw new EngineError(\n EngineErrorCode.InvalidArg,\n `${subtype} has no field ${unknown.map((name) => `'${name}'`).join(', ')}`,\n );\n }\n}\n\n/**\n * The patch as the target's kind: its subtype filled in from the target, which\n * a caller may leave out. A different subtype, a changed name, a field the\n * kind doesn't declare, or any change to an annotation of a type the engine\n * doesn't model is refused.\n */\nfunction annotationPatchForTarget(\n current: Annotation<PdfCoordinates>,\n patch: AnnotationPatch<PdfCoordinates>,\n): AnnotationPatch<PdfCoordinates> {\n if (patch.subtype !== undefined && patch.subtype !== current.subtype) {\n throw new EngineError(EngineErrorCode.InvalidArg, 'Annotation subtype cannot change');\n }\n if (current.subtype === 'unsupported') {\n throw new EngineError(\n EngineErrorCode.InvalidArg,\n \"an annotation of a type the engine doesn't model can't be updated\",\n );\n }\n if (patch.nm !== undefined && patch.nm !== current.nm) {\n throw new EngineError(\n EngineErrorCode.InvalidArg,\n \"an annotation's nm can't change after create\",\n );\n }\n assertDeclaredFields(current.subtype, patch);\n return { ...patch, subtype: current.subtype } as AnnotationPatch<PdfCoordinates>;\n}\n\n/**\n * The patch an update writes before anything follows from it, in the file's\n * coordinates, the same on the page and in the engine:\n *\n * - its subtype filled in from `current` (a different one is refused, as is\n * a field the kind doesn't declare and a changed `nm`);\n * - a drawn kind's `rect`: the rect it reads, sent back, dropped; another one\n * the shape fields that put the drawing there (`pdfResolveRectCommand`);\n * - a color sent back as it reads dropped, so the file keeps it as it has it;\n * - every other field sent back as it reads dropped: it is not a change\n * (`withoutUnchangedFields`).\n *\n * A changed value stays whatever it is: whether the kind can write it is the\n * engine's check, which never adds, drops or changes a field.\n */\nexport function pdfPrepareAnnotationPatch(\n current: Annotation<PdfCoordinates>,\n patch: AnnotationPatch<PdfCoordinates>,\n): AnnotationPatch<PdfCoordinates> {\n const targeted = annotationPatchForTarget(current, patch);\n return withoutUnchangedFields(\n current,\n withoutUnchangedColors(current, pdfResolveRectCommand(current, targeted)),\n );\n}\n\n/**\n * A prepared patch with every field that follows from it stated, in the\n * file's coordinates:\n *\n * - a note's standard review state brings its state model;\n * - a free text's `contents` and rich text follow each other, and its font,\n * size, text color and alignment move its rich body;\n * - a callout's line stays attached to its box when the box moves or turns;\n * - a measurement's label follows its points and scale, and a polygon's\n * caption follows its vertices.\n *\n * Throws `InvalidArg` where nothing can follow. Pure: it reads nothing but its\n * arguments.\n */\nexport function pdfDeriveAnnotationPatch(\n current: Annotation<PdfCoordinates>,\n prepared: AnnotationPatch<PdfCoordinates>,\n options: ResolveOptions = {},\n): AnnotationPatch<PdfCoordinates> {\n const resolved = noteStateFollows(current, prepared);\n assertRichTextAgreement(resolved);\n const text = calloutEndFollows(current, freeTextFollows(current, resolved, options.describeFont));\n return measurementFollows(current, text);\n}\n\n/**\n * The patch the engine writes for `patch` on `current`, as a viewer predicts\n * it, in the file's coordinates: prepared and derived as the engine does\n * (`pdfPrepareAnnotationPatch`, `pdfDeriveAnnotationPatch`), without schema\n * validation. A patch the engine's schema check refuses\n * (`pdfResolveAnnotationPatch`, from `@embedpdf/engine-core/validation`) is\n * refused when the update reaches it.\n *\n * Throws `InvalidArg` for what preparation and derivation refuse: a field the\n * kind doesn't declare, a changed subtype or name, a rect with a new shape or\n * that isn't finite, and where nothing can follow.\n */\nexport function pdfPredictAnnotationPatch(\n current: Annotation<PdfCoordinates>,\n patch: AnnotationPatch<PdfCoordinates>,\n options: ResolveOptions = {},\n): AnnotationPatch<PdfCoordinates> {\n return pdfDeriveAnnotationPatch(current, pdfPrepareAnnotationPatch(current, patch), options);\n}\n\nexport interface ResolveOptions {\n /**\n * Looks up a registered font by its key, so a free text's new `fontFamily`\n * moves its rich body to that face. Without it a registered key names the\n * family as it is; the standard 14 need no lookup.\n */\n describeFont?: DescribeFont;\n}\n","import { EngineError } from '../../errors/EngineError';\nimport { EngineErrorCode } from '../../errors/EngineErrorCode';\nimport {\n isFinitePdfRect,\n normalizePdfRect,\n pdfQuarterTurnBox,\n quarterTurnOf,\n} from '../../geometry/convert';\nimport type { PdfCoordinates } from '../../pageSpace/coordinates';\nimport { ANNOTATION_FIELD_SPACES } from '../field-spaces';\nimport type { AnnotationDraft } from '../kinds';\n\n/**\n * A create once resolved (`pdfResolveAnnotationDraft`): a box kind states\n * its `box`, whether the caller gave it or placed the kind by its `rect`.\n * What the writers take.\n */\nexport type PlacedDraft<Draft> = Draft extends { box?: infer Box }\n ? Omit<Draft, 'box'> & { box: NonNullable<Box> }\n : Draft;\n\n/**\n * A box kind's create placed by where it stands: a `rect` with a quarter\n * turn pins the box down, `rect` itself or its sides swapped under 90 and\n * 270 (`pdfQuarterTurnBox`). A create that gives `box` keeps it, and its\n * `rect` is worked out from it as ever, so a read sent back as a create\n * places the copy by its box.\n *\n * Refused with `InvalidArg`: a create with neither, a `rect` that isn't four\n * finite numbers, and a `rect` at another angle, where many boxes stand in\n * the same rect.\n */\nexport function boxDraftFollows(\n draft: AnnotationDraft<PdfCoordinates>,\n): AnnotationDraft<PdfCoordinates> {\n if (ANNOTATION_FIELD_SPACES[draft.subtype]?.box !== 'box') return draft;\n const given = draft as { box?: unknown; rect?: unknown; rotation?: number | null };\n if (given.box !== undefined) return draft;\n if (given.rect === undefined) {\n throw new EngineError(\n EngineErrorCode.InvalidArg,\n `${draft.subtype} create: give its \\`box\\`, or its \\`rect\\` with a quarter turn`,\n { details: { field: 'box' } },\n );\n }\n if (!isFinitePdfRect(given.rect)) {\n throw new EngineError(\n EngineErrorCode.InvalidArg,\n `${draft.subtype} create field 'rect': not a rect of finite numbers`,\n { details: { field: 'rect' } },\n );\n }\n const rotation = given.rotation ?? 0;\n const turn = quarterTurnOf(rotation);\n if (turn === null) {\n throw new EngineError(\n EngineErrorCode.InvalidArg,\n `${draft.subtype} create field 'rect': a rect places a box at a quarter turn; at ${rotation}° give its \\`box\\``,\n { details: { field: 'rect' } },\n );\n }\n const { rect: _placed, ...rest } = draft as AnnotationDraft<PdfCoordinates> & { rect?: unknown };\n return {\n ...rest,\n box: pdfQuarterTurnBox(normalizePdfRect(given.rect), turn),\n } as AnnotationDraft<PdfCoordinates>;\n}\n","import { pdfPointsBounds } from '../../geometry/pointTurn';\nimport type { PdfCoordinates } from '../../pageSpace/coordinates';\nimport type { AnnotationDraft } from '../kinds';\n\n/**\n * A redaction over text that names no `rect` covers its quads: the box\n * around them is its region.\n */\nexport function redactDraftFollows(\n draft: AnnotationDraft<PdfCoordinates>,\n): AnnotationDraft<PdfCoordinates> {\n if (draft.subtype !== 'redact' || draft.rect != null) return draft;\n const quads = draft.quadPoints ?? [];\n if (quads.length === 0) return draft;\n const rect = pdfPointsBounds(\n quads.flatMap((quad) => [quad.upperLeft, quad.upperRight, quad.lowerLeft, quad.lowerRight]),\n );\n return { ...draft, rect };\n}\n","import type { PdfCoordinates } from '../../pageSpace/coordinates';\nimport type { DescribeFont } from '../fontFaces';\nimport type { AnnotationDraft } from '../kinds';\nimport { boxDraftFollows } from './box';\nimport { freeTextDraftFollows } from './freeText';\nimport { resolveMeasurementDraft } from './measurement';\nimport { redactDraftFollows } from './redact';\nimport { assertDeclaredFields } from './resolveAnnotationPatch';\nimport { assertRichTextAgreement, noteDraftStateFollows } from './text';\n\nexport interface DraftResolveOptions {\n /**\n * Link fields the caller takes out and links itself (a change set's `reply`\n * and a popup's `parent`); the engine's schema check leaves them out.\n */\n linked?: readonly string[];\n /**\n * Looks up a registered font by its key, so a free text in one takes that\n * face in its rich body. The standard 14 need no lookup.\n */\n describeFont?: DescribeFont;\n}\n\n/**\n * The draft a create writes before anything follows from it, in the file's\n * coordinates, the same on the page and in the engine: its fields named by\n * its kind, and a box kind placed by its `rect` at a quarter turn stating its\n * `box` (`boxDraftFollows`). The engine checks the prepared draft against its\n * kind's schema before deriving the rest (`pdfResolveAnnotationDraft`), a\n * check that only accepts or refuses.\n *\n * Throws `InvalidArg` for a field the kind doesn't declare, and for a box\n * kind it can't place.\n */\nexport function pdfPrepareAnnotationDraft(\n draft: AnnotationDraft<PdfCoordinates>,\n): AnnotationDraft<PdfCoordinates> {\n assertDeclaredFields(draft.subtype, draft);\n return boxDraftFollows(draft);\n}\n\n/**\n * A prepared draft with every field that follows from it stated, in the\n * file's coordinates:\n *\n * - a note's standard review state brings its state model;\n * - a free text states its intent, and its text as rich text carrying its\n * text style, with `contents` its plain projection;\n * - a redaction over text without a `rect` covers its quads;\n * - a measurement's label follows its points and scale, and its caption is\n * stated whole.\n *\n * Throws `InvalidArg` where nothing can follow: a custom review state with no\n * model, contents that disagree with the rich text, a callout line without\n * the callout intent, a measurement it can't label. Pure: it reads nothing\n * but its arguments. Defaults stay out of the draft: a field left out reads\n * back as `annotation/defaults.ts` says.\n */\nexport function pdfDeriveAnnotationDraft(\n prepared: AnnotationDraft<PdfCoordinates>,\n options: DraftResolveOptions = {},\n): AnnotationDraft<PdfCoordinates> {\n assertRichTextAgreement(prepared);\n const followed = redactDraftFollows(\n freeTextDraftFollows(noteDraftStateFollows(prepared), options.describeFont),\n );\n return resolveMeasurementDraft(followed);\n}\n\n/**\n * The draft the engine writes for `draft`, as a viewer predicts it: prepared\n * and derived as the engine does (`pdfPrepareAnnotationDraft`,\n * `pdfDeriveAnnotationDraft`), without schema validation. A draft the\n * engine's schema check refuses (`pdfResolveAnnotationDraft`, from\n * `@embedpdf/engine-core/validation`) is refused when the create reaches it.\n */\nexport function pdfPredictAnnotationDraft(\n draft: AnnotationDraft<PdfCoordinates>,\n options: DraftResolveOptions = {},\n): AnnotationDraft<PdfCoordinates> {\n return pdfDeriveAnnotationDraft(pdfPrepareAnnotationDraft(draft), options);\n}\n"],"mappings":";;;;;;;AAwBA,SAAgB,gBAAgB,OAAkC;CAChE,IAAI,OAAO,UAAU,YAAY,UAAU,MAAM,OAAO;CACxD,MAAM,EAAE,MAAM,QAAQ,OAAO,QAAQ;CACrC,OAAO;EAAC;EAAM;EAAQ;EAAO;CAAG,CAAC,CAAC,OAC/B,SAAS,OAAO,SAAS,YAAY,OAAO,SAAS,IAAI,CAC5D;AACF;;;;;;;;;AAUA,SAAgB,iBAAiB,GAAqB;CACpD,OAAO;EACL,MAAM,KAAK,IAAI,EAAE,MAAM,EAAE,KAAK;EAC9B,OAAO,KAAK,IAAI,EAAE,MAAM,EAAE,KAAK;EAC/B,QAAQ,KAAK,IAAI,EAAE,KAAK,EAAE,MAAM;EAChC,KAAK,KAAK,IAAI,E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