@inkbar/core 0.11.0 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sign-BSP7H3b7.mjs","names":["isWhite","latin1","numbers","dictOf","PDF_NAME","GlossFringe","GlossLineEnding","GlossFreeTextStyle","PDF_NAME","targetOf","sameValue","scriptAction","sameValue","GLOSS_FORMAT","GLOSS_VERSION","uuidv7","sameValue","uuidv7","copy","uuidv7"],"sources":["../src/model/errors.ts","../src/model/events.ts","../src/model/geometry.ts","../src/model/readable.ts","../src/model/records.ts","../src/model/selection.ts","../src/model/annotations/pdf-names.ts","../src/pdf/lexer.ts","../src/pdf/annotation-fields.ts","../src/pdf/form-fields.ts","../src/pdf/stream.ts","../src/pdf/xref.ts","../src/pdf/objects.ts","../src/pdfjs/destinations.ts","../src/pdfjs/glyphs.ts","../src/pdfjs/load.ts","../src/model/pdf-date.ts","../src/model/annotations/defaults.ts","../src/model/annotations/callout.ts","../src/model/annotations/types.ts","../src/model/annotations/embedded.ts","../src/model/destination.ts","../src/model/form/url.ts","../src/model/links.ts","../src/model/map-in-order.ts","../src/pdfjs/outline.ts","../src/model/form/values.ts","../src/model/form/gloss.ts","../src/model/form/submit.ts","../src/pdfjs/sandbox-patch.ts","../src/pdfjs/scripting.ts","../src/pdfjs/structure.ts","../src/model/annotations/embedded-fields.ts","../src/model/env.ts","../src/model/annotations/history.ts","../src/model/annotations/gloss-mapping.ts","../src/model/annotations/json.ts","../src/model/annotations/store.ts","../src/model/form/controller.ts","../src/model/form/structure.ts","../src/model/measure-char.ts","../src/model/page-cache.ts","../src/model/pages.ts","../src/model/search-text.ts","../src/model/search.ts","../src/model/source.ts","../src/model/glyph-advances.ts","../src/model/text.ts","../src/model/document.ts","../src/model/annotations/edit.ts","../src/model/annotations/style-map.ts","../src/model/annotations/tool-style.ts","../src/model/annotations/threads.ts","../src/model/annotations/shape-geometry.ts","../src/model/recognise.ts","../src/model/storage.ts","../src/model/signatures.ts","../src/model/form/sign.ts"],"sourcesContent":["export type InkErrorCode =\n | 'PasswordRequired'\n | 'InvalidPdf'\n | 'SourceFetchFailed'\n | 'AssetConfigMissing'\n | 'AssetLoadFailed'\n | 'EngineUnavailable'\n | 'ControlledMutationIgnored'\n | 'DocumentDestroyed'\n | 'PageOutOfRange'\n | 'DuplicateId'\n | 'DuplicatePlugin'\n | 'InvalidPluginId'\n | 'InvalidCommandLabel'\n | 'UnknownCommand'\n | 'UnknownTool'\n | 'FormScriptError'\n | 'UnknownField'\n | 'NotSignatureField'\n | 'FieldReadOnly'\n | 'FieldSigned'\n\nexport class InkError extends Error {\n override readonly name = 'InkError'\n readonly code: InkErrorCode\n readonly details: Readonly<Record<string, unknown>>\n\n constructor(\n code: InkErrorCode,\n message: string,\n details: Record<string, unknown> = {},\n cause?: unknown\n ) {\n super(message, cause === undefined ? undefined : { cause })\n this.code = code\n this.details = details\n }\n}\n\nexport function isInkError(value: unknown): value is InkError {\n return (\n value instanceof InkError ||\n (typeof value === 'object' &&\n value !== null &&\n (value as { name?: unknown }).name === 'InkError')\n )\n}\n","export type Listener<T> = (payload: T) => void\n\nexport class Emitter<Events extends Record<string, unknown>> {\n private listeners = new Map<keyof Events, Set<Listener<never>>>()\n\n on<K extends keyof Events>(event: K, fn: Listener<Events[K]>): () => void {\n let set = this.listeners.get(event)\n if (!set) {\n set = new Set()\n this.listeners.set(event, set)\n }\n set.add(fn)\n return () => {\n set?.delete(fn)\n }\n }\n\n emit<K extends keyof Events>(event: K, payload: Events[K]): void {\n const set = this.listeners.get(event)\n if (!set) return\n for (const fn of [...set]) (fn as Listener<Events[K]>)(payload)\n }\n\n clear(): void {\n this.listeners.clear()\n }\n}\n","/**\n * All geometry in this module is PDF default user space: points, origin at the\n * lower-left of the page, before /Rotate. Pixel conversions live in dom/transform.ts.\n */\nexport interface Point {\n x: number\n y: number\n}\n\n/** Axis-aligned box. `x`,`y` is the lower-left corner. */\nexport interface Rect {\n x: number\n y: number\n width: number\n height: number\n}\n\n/** Four corners in PDF.js's normalised QuadPoints order: upper-left, upper-right, lower-left, lower-right. */\nexport interface Quad {\n p1: Point\n p2: Point\n p3: Point\n p4: Point\n}\n\n/** PDF transformation matrix [a b c d e f]: x' = a·x + c·y + e, y' = b·x + d·y + f. */\nexport type Matrix = readonly [number, number, number, number, number, number]\n\nexport function approxEqual(a: number, b: number, eps = 0.01): boolean {\n return Math.abs(a - b) <= eps\n}\n\nexport function rectFromPoints(a: Point, b: Point): Rect {\n const x = Math.min(a.x, b.x)\n const y = Math.min(a.y, b.y)\n return { x, y, width: Math.abs(a.x - b.x), height: Math.abs(a.y - b.y) }\n}\n\nexport function rectFromQuad(q: Quad): Rect {\n const xs = [q.p1.x, q.p2.x, q.p3.x, q.p4.x]\n const ys = [q.p1.y, q.p2.y, q.p3.y, q.p4.y]\n const x = Math.min(...xs)\n const y = Math.min(...ys)\n return { x, y, width: Math.max(...xs) - x, height: Math.max(...ys) - y }\n}\n\nexport function quadFromRect(r: Rect): Quad {\n const top = r.y + r.height\n const right = r.x + r.width\n return {\n p1: { x: r.x, y: top },\n p2: { x: right, y: top },\n p3: { x: r.x, y: r.y },\n p4: { x: right, y: r.y },\n }\n}\n\n/** One quad covering `r`, in the corner order of `quadFromRect`. */\nexport function quadsFromRect(r: Rect): Quad[] {\n return [quadFromRect(r)]\n}\n\n/** The bounding box of every corner of `quads`. */\nexport function rectFromQuads(quads: readonly Quad[]): Rect {\n if (quads.length === 0) throw new RangeError('rectFromQuads needs at least one quad')\n return unionRects(quads.map(rectFromQuad))\n}\n\nexport function unionRects(rects: readonly Rect[]): Rect {\n if (rects.length === 0) throw new RangeError('unionRects needs at least one rect')\n let x1 = Infinity\n let y1 = Infinity\n let x2 = -Infinity\n let y2 = -Infinity\n for (const r of rects) {\n x1 = Math.min(x1, r.x)\n y1 = Math.min(y1, r.y)\n x2 = Math.max(x2, r.x + r.width)\n y2 = Math.max(y2, r.y + r.height)\n }\n return { x: x1, y: y1, width: x2 - x1, height: y2 - y1 }\n}\n\nexport function rectsIntersect(a: Rect, b: Rect): boolean {\n return (\n a.x < b.x + b.width &&\n b.x < a.x + a.width &&\n a.y < b.y + b.height &&\n b.y < a.y + a.height\n )\n}\n\nexport function rectContainsPoint(r: Rect, p: Point): boolean {\n return p.x >= r.x && p.x <= r.x + r.width && p.y >= r.y && p.y <= r.y + r.height\n}\n\n/**\n * Whether `p` is inside `q` or on its edge. A quad's corners run top-left, top-right,\n * bottom-left, bottom-right (PDF QuadPoints order), so its outline is p1, p2, p4, p3. Works for\n * any convex quad, whichever way round it winds. A quad with no area (a point or a line, as a\n * malformed file may give) contains nothing.\n */\nexport function quadContainsPoint(q: Quad, p: Point): boolean {\n const ring = [q.p1, q.p2, q.p4, q.p3]\n let area = 0\n for (let i = 0; i < 4; i++) {\n const a = ring[i]!\n const b = ring[(i + 1) % 4]!\n area += a.x * b.y - b.x * a.y\n }\n if (area === 0) return false\n let sign = 0\n for (let i = 0; i < 4; i++) {\n const a = ring[i]!\n const b = ring[(i + 1) % 4]!\n const cross = (b.x - a.x) * (p.y - a.y) - (b.y - a.y) * (p.x - a.x)\n if (cross === 0) continue\n const s = Math.sign(cross)\n if (sign === 0) sign = s\n else if (s !== sign) return false\n }\n return true\n}\n\nexport function translateRect(r: Rect, dx: number, dy: number): Rect {\n return { x: r.x + dx, y: r.y + dy, width: r.width, height: r.height }\n}\n\nexport function translateQuad(q: Quad, dx: number, dy: number): Quad {\n const t = (p: Point): Point => ({ x: p.x + dx, y: p.y + dy })\n return { p1: t(q.p1), p2: t(q.p2), p3: t(q.p3), p4: t(q.p4) }\n}\n\nexport function applyMatrix(m: Matrix, p: Point): Point {\n return { x: m[0] * p.x + m[2] * p.y + m[4], y: m[1] * p.x + m[3] * p.y + m[5] }\n}\n\nexport function invertMatrix(m: Matrix): Matrix {\n const det = m[0] * m[3] - m[1] * m[2]\n if (det === 0) throw new RangeError('matrix is not invertible')\n return [\n m[3] / det,\n -m[1] / det,\n -m[2] / det,\n m[0] / det,\n (m[2] * m[5] - m[3] * m[4]) / det,\n (m[1] * m[4] - m[0] * m[5]) / det,\n ]\n}\n\n/** Returns the matrix that applies `a` first, then `b`. */\nexport function multiplyMatrix(a: Matrix, b: Matrix): Matrix {\n return [\n a[0] * b[0] + a[1] * b[2],\n a[0] * b[1] + a[1] * b[3],\n a[2] * b[0] + a[3] * b[2],\n a[2] * b[1] + a[3] * b[3],\n a[4] * b[0] + a[5] * b[2] + b[4],\n a[4] * b[1] + a[5] * b[3] + b[5],\n ]\n}\n\nexport function pointsFromFlat(flat: ArrayLike<number>): Point[] {\n const out: Point[] = []\n for (let i = 0; i + 1 < flat.length; i += 2) out.push({ x: flat[i]!, y: flat[i + 1]! })\n return out\n}\n\n/** Eight numbers per quad, in PDF.js's normalised order. Trailing partial quads are dropped. */\nexport function quadsFromFlat(flat: ArrayLike<number>): Quad[] {\n const pts = pointsFromFlat(flat)\n const out: Quad[] = []\n for (let i = 0; i + 3 < pts.length; i += 4) {\n out.push({ p1: pts[i]!, p2: pts[i + 1]!, p3: pts[i + 2]!, p4: pts[i + 3]! })\n }\n return out\n}\n","export interface Readable<T> {\n get(): T\n subscribe(fn: (value: T) => void): () => void\n}\n\nexport interface Writable<T> extends Readable<T> {\n set(this: void, value: T): void\n /** Safe to call detached (`const { update } = store`). */\n update(this: void, fn: (value: T) => T): void\n}\n\nexport function writable<T>(initial: T): Writable<T> {\n let value = initial\n const subs = new Set<(v: T) => void>()\n // Not `this.set`: `update` must work detached, e.g. `const { update } = store`.\n const set = (next: T): void => {\n if (Object.is(next, value)) return\n value = next\n for (const fn of [...subs]) fn(value)\n }\n return {\n get: () => value,\n set,\n update(fn) {\n set(fn(value))\n },\n subscribe(fn) {\n subs.add(fn)\n return () => {\n subs.delete(fn)\n }\n },\n }\n}\n\n/**\n * A readable computed from `source`. It subscribes to the source only while it has\n * subscribers of its own, so an unobserved derived value holds no reference to the source.\n */\nexport function derived<T, U>(source: Readable<T>, fn: (value: T) => U): Readable<U> {\n const subs = new Set<(v: U) => void>()\n let cached: U\n let stopSource: (() => void) | undefined\n\n const onSource = (v: T): void => {\n const next = fn(v)\n if (Object.is(next, cached)) return\n cached = next\n for (const sub of [...subs]) sub(next)\n }\n\n return {\n get: () => (stopSource ? cached : fn(source.get())),\n subscribe(sub) {\n if (!stopSource) {\n cached = fn(source.get())\n stopSource = source.subscribe(onSource)\n }\n subs.add(sub)\n return () => {\n if (!subs.delete(sub) || subs.size > 0) return\n stopSource?.()\n stopSource = undefined\n }\n },\n }\n}\n\nexport function readonly<T>(w: Writable<T>): Readable<T> {\n return { get: () => w.get(), subscribe: (fn) => w.subscribe(fn) }\n}\n","import { InkError } from './errors'\nimport { Emitter } from './events'\nimport { readonly, writable, type Readable } from './readable'\n\nexport interface RecordBase {\n readonly id: string\n}\n\nexport type RecordChange<T> =\n | { kind: 'add'; record: T }\n | { kind: 'update'; id: string; before: T; after: T }\n | { kind: 'remove'; record: T }\n | {\n kind: 'replace'\n reason: 'history' | 'reset'\n /** Ids of the records the replace added, changed and dropped, in list order. */\n added: string[]\n updated: string[]\n removed: string[]\n }\n\nexport interface RecordStore<T extends RecordBase> {\n /** The slot name the store is registered under. */\n readonly key: string\n readonly list: Readable<readonly T[]>\n get(id: string): T | undefined\n /** Returns the stored (frozen) record. Throws `InkError('DuplicateId')` when the id is taken. */\n add(record: T): T\n /** `id` cannot be patched. Returns `undefined`, emitting nothing, for an unknown id. */\n update(id: string, patch: Partial<Omit<T, 'id'>>): T | undefined\n /** Returns the removed record, or `undefined`, emitting nothing, for an unknown id. */\n remove(id: string): T | undefined\n replaceAll(list: readonly T[], reason: 'history' | 'reset'): void\n on(event: 'change', fn: (change: RecordChange<T>) => void): () => void\n /** Drops the listeners. Writes after it change nothing and emit nothing. */\n destroy(): void\n}\n\nexport interface RecordStoreOptions<T extends RecordBase> {\n initial?: readonly T[]\n /** Called after every change, `replace` included, with the list as it now stands. */\n onChange?: (list: readonly T[], change: RecordChange<T>) => void\n}\n\n/**\n * A keyed list of plain records. Records are stored as frozen copies, so a change's `before` and `after` can be\n * kept as history entries without copying.\n */\nexport function createRecordStore<T extends RecordBase>(\n key: string,\n opts: RecordStoreOptions<T> = {}\n): RecordStore<T> {\n const list = writable<readonly T[]>((opts.initial ?? []).map(frozen))\n const emitter = new Emitter<{ change: RecordChange<T> }>()\n let destroyed = false\n\n function commit(next: readonly T[], change: RecordChange<T>): void {\n if (destroyed) return\n list.set(next)\n emitter.emit('change', change)\n opts.onChange?.(next, change)\n }\n\n return {\n key,\n list: readonly(list),\n get: (id) => list.get().find((r) => r.id === id),\n add(record) {\n if (list.get().some((r) => r.id === record.id))\n throw new InkError(\n 'DuplicateId',\n `A record with id ${record.id} already exists`,\n {\n key,\n id: record.id,\n }\n )\n const stored = frozen(record)\n commit([...list.get(), stored], { kind: 'add', record: stored })\n return stored\n },\n update(id, patch) {\n const before = list.get().find((r) => r.id === id)\n if (destroyed || !before) return undefined\n const after = Object.freeze({ ...before, ...patch, id: before.id }) as T\n commit(\n list.get().map((r) => (r.id === id ? after : r)),\n { kind: 'update', id, before, after }\n )\n return after\n },\n remove(id) {\n const record = list.get().find((r) => r.id === id)\n if (destroyed || !record) return undefined\n commit(\n list.get().filter((r) => r.id !== id),\n { kind: 'remove', record }\n )\n return record\n },\n replaceAll(incoming, reason) {\n const prev = new Map(list.get().map((r) => [r.id, r]))\n const added: string[] = []\n const updated: string[] = []\n // A record whose fields all equal (===) the stored one's keeps the stored object, so a\n // history step reports only the records it really changed, and `updated` means \"the\n // stored object changed\".\n const next = incoming.map((r) => {\n const old = prev.get(r.id)\n if (!old) {\n added.push(r.id)\n return frozen(r)\n }\n if (shallowEqual(old, r)) return old\n updated.push(r.id)\n return frozen(r)\n })\n const kept = new Set(next.map((r) => r.id))\n const removed = [...prev.keys()].filter((id) => !kept.has(id))\n commit(next, { kind: 'replace', reason, added, updated, removed })\n },\n on: (event, fn) => emitter.on(event, fn),\n destroy() {\n destroyed = true\n emitter.clear()\n },\n }\n}\n\n/** Freezes a copy, so the caller's object stays theirs; an already frozen record is kept. */\nfunction frozen<T extends RecordBase>(record: T): T {\n return Object.isFrozen(record) ? record : Object.freeze({ ...record })\n}\n\nfunction shallowEqual(a: object, b: object): boolean {\n const ka = Object.keys(a)\n const kb = Object.keys(b)\n return (\n ka.length === kb.length &&\n ka.every(\n (k) =>\n Object.hasOwn(b, k) &&\n (a as Record<string, unknown>)[k] === (b as Record<string, unknown>)[k]\n )\n )\n}\n","import { quadFromRect, type Quad, type Rect } from './geometry'\n\nconst union = (a: Rect, b: Rect): Rect => {\n const x = Math.min(a.x, b.x)\n const y = Math.min(a.y, b.y)\n return {\n x,\n y,\n width: Math.max(a.x + a.width, b.x + b.width) - x,\n height: Math.max(a.y + a.height, b.y + b.height) - y,\n }\n}\n\nconst centreY = (r: Rect): number => r.y + r.height / 2\n\nfunction median(values: number[]): number {\n const sorted = [...values].sort((a, b) => a - b)\n const mid = sorted.length >> 1\n return sorted.length % 2 ? sorted[mid]! : (sorted[mid - 1]! + sorted[mid]!) / 2\n}\n\n/**\n * Merges glyph boxes that share a line into one quad per run, ordered top to bottom (by\n * vertical centre) then left to right. Boxes whose vertical centres are within `tolerance`\n * points count as the same line; boxes with no area are dropped. Within a line, a horizontal\n * gap wider than `gap` points (default 1.5 × the line's median box height) starts a new run,\n * so text selected across a column gutter yields one quad per column. Pure user-space maths.\n */\nexport function mergeLineRects(\n rects: readonly Rect[],\n tolerance = 2,\n gap?: number\n): Quad[] {\n const lines: { bounds: Rect; boxes: Rect[] }[] = []\n for (const r of rects) {\n if (!(r.width > 0 && r.height > 0)) continue\n const line = lines.find((l) => Math.abs(centreY(l.bounds) - centreY(r)) <= tolerance)\n if (!line) {\n lines.push({ bounds: { ...r }, boxes: [r] })\n continue\n }\n line.bounds = union(line.bounds, r)\n line.boxes.push(r)\n }\n const runs: Rect[] = []\n for (const line of lines) {\n const maxGap = gap ?? 1.5 * median(line.boxes.map((b) => b.height))\n const boxes = [...line.boxes].sort((a, b) => a.x - b.x)\n let run = { ...boxes[0]! }\n for (const b of boxes.slice(1)) {\n if (b.x - (run.x + run.width) > maxGap) {\n runs.push(run)\n run = { ...b }\n } else {\n run = union(run, b)\n }\n }\n runs.push(run)\n }\n runs.sort((a, b) => centreY(b) - centreY(a) || a.x - b.x)\n return runs.map(quadFromRect)\n}\n","import { PDF_NAME } from 'gloss-format'\nimport { z } from 'zod'\n\nexport { INTENTS, LINE_ENDINGS, NOTE_ICONS, PDF_NAME } from 'gloss-format'\n\n/**\n * A set of PDF names Inkbar knows that stays open: any other valid PDF name loads, is kept and\n * is written back unchanged. The output type keeps autocomplete for the known values.\n */\nexport function pdfNameSet<const K extends readonly [string, ...string[]]>(known: K) {\n return z\n .union([z.enum(known), z.string().regex(PDF_NAME, 'expected a PDF name')])\n .describe(\n `One of ${known.join(', ')}. Any other PDF name is allowed and kept unchanged.`\n ) as z.ZodType<K[number] | (string & {}), K[number] | (string & {})>\n}\n\n/** True when `v` is one of the values in `list`. */\nexport function isKnown<K extends readonly string[]>(list: K, v: string): v is K[number] {\n return (list as readonly string[]).includes(v)\n}\n","/** A PDF name object, with `#xx` escapes decoded. */\nexport interface PdfName {\n kind: 'name'\n name: string\n}\n\n/** An indirect reference such as `12 0 R`. */\nexport interface PdfRef {\n kind: 'ref'\n num: number\n gen: number\n}\n\n/** A string object: its bytes after escapes and hex are decoded. See `textString` for text. */\nexport interface PdfString {\n kind: 'string'\n bytes: Uint8Array\n}\n\n/** A dictionary object. */\nexport interface PdfDict {\n kind: 'dict'\n entries: Map<string, PdfValue>\n}\n\n/** Any PDF object this reader understands. */\nexport type PdfValue =\n number | boolean | null | PdfName | PdfRef | PdfString | PdfDict | PdfValue[]\n\n/** Thrown when the bytes are not valid PDF object syntax. */\nexport class PdfSyntaxError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'PdfSyntaxError'\n }\n}\n\nconst isWhite = (c: number): boolean =>\n c === 0 || c === 9 || c === 10 || c === 12 || c === 13 || c === 32\n\nconst isDelimiter = (c: number): boolean =>\n c === 0x28 || // (\n c === 0x29 || // )\n c === 0x3c || // <\n c === 0x3e || // >\n c === 0x5b || // [\n c === 0x5d || // ]\n c === 0x7b || // {\n c === 0x7d || // }\n c === 0x2f || // /\n c === 0x25 // %\n\nconst isRegular = (c: number): boolean => !isWhite(c) && !isDelimiter(c)\nconst isDigit = (c: number): boolean => c >= 0x30 && c <= 0x39\n\nconst latin1 = (bytes: Uint8Array, from: number, to: number): string => {\n let out = ''\n for (let i = from; i < to; i++) out += String.fromCharCode(bytes[i]!)\n return out\n}\n\nfunction skipSpace(bytes: Uint8Array, offset: number): number {\n let i = offset\n while (i < bytes.length) {\n const c = bytes[i]!\n if (isWhite(c)) {\n i++\n } else if (c === 0x25) {\n while (i < bytes.length && bytes[i] !== 10 && bytes[i] !== 13) i++\n } else {\n break\n }\n }\n return i\n}\n\nfunction tokenEnd(bytes: Uint8Array, offset: number): number {\n let i = offset\n while (i < bytes.length && isRegular(bytes[i]!)) i++\n return i\n}\n\nconst hexValue = (c: number | undefined): number => {\n if (c === undefined) return -1\n if (c >= 0x30 && c <= 0x39) return c - 0x30\n if (c >= 0x41 && c <= 0x46) return c - 0x41 + 10\n if (c >= 0x61 && c <= 0x66) return c - 0x61 + 10\n return -1\n}\n\nfunction parseName(bytes: Uint8Array, offset: number): { value: PdfName; end: number } {\n const end = tokenEnd(bytes, offset + 1)\n let name = ''\n for (let i = offset + 1; i < end; i++) {\n const c = bytes[i]!\n const hi = c === 0x23 ? hexValue(bytes[i + 1]) : -1\n const lo = hi >= 0 ? hexValue(bytes[i + 2]) : -1\n if (hi >= 0 && lo >= 0 && i + 2 < end) {\n name += String.fromCharCode(hi * 16 + lo)\n i += 2\n } else {\n name += String.fromCharCode(c)\n }\n }\n return { value: { kind: 'name', name }, end }\n}\n\nconst ESCAPES: Record<number, number> = {\n 0x6e: 10, // n\n 0x72: 13, // r\n 0x74: 9, // t\n 0x62: 8, // b\n 0x66: 12, // f\n}\n\nconst isOctal = (c: number | undefined): c is number =>\n c !== undefined && c >= 0x30 && c <= 0x37\n\nfunction parseLiteralString(\n bytes: Uint8Array,\n offset: number\n): { value: PdfString; end: number } {\n const out: number[] = []\n let depth = 0\n for (let i = offset; i < bytes.length; i++) {\n const c = bytes[i]!\n if (c === 0x5c) {\n const e = bytes[++i]\n if (e === undefined) break\n if (isOctal(e)) {\n let n = e - 0x30\n for (let k = 0; k < 2 && isOctal(bytes[i + 1]); k++)\n n = n * 8 + bytes[++i]! - 0x30\n out.push(n & 0xff)\n } else if (e === 13) {\n // A backslash before an end of line continues the string on the next line.\n if (bytes[i + 1] === 10) i++\n } else if (e !== 10) {\n out.push(ESCAPES[e] ?? e)\n }\n continue\n }\n if (c === 0x28 && depth++ === 0) continue\n if (c === 0x29 && --depth === 0) {\n return { value: { kind: 'string', bytes: Uint8Array.from(out) }, end: i + 1 }\n }\n if (c === 13) {\n // An unescaped CR or CRLF in a literal string reads as a single LF.\n if (bytes[i + 1] === 10) i++\n out.push(10)\n continue\n }\n out.push(c)\n }\n throw new PdfSyntaxError('Unterminated string')\n}\n\nfunction parseHexString(\n bytes: Uint8Array,\n offset: number\n): { value: PdfString; end: number } {\n const out: number[] = []\n let hi = -1\n for (let i = offset + 1; i < bytes.length; i++) {\n const c = bytes[i]!\n if (c === 0x3e) {\n // An odd final digit is read as if followed by 0.\n if (hi >= 0) out.push(hi * 16)\n return { value: { kind: 'string', bytes: Uint8Array.from(out) }, end: i + 1 }\n }\n const v = hexValue(c)\n if (v < 0) continue\n if (hi < 0) {\n hi = v\n } else {\n out.push(hi * 16 + v)\n hi = -1\n }\n }\n throw new PdfSyntaxError('Unterminated hex string')\n}\n\n/** After a non-negative integer ending at `end`, looks for `gen R`. */\nfunction tryReference(\n bytes: Uint8Array,\n num: number,\n end: number\n): { value: PdfRef; end: number } | undefined {\n let i = end\n if (i >= bytes.length || !isWhite(bytes[i]!)) return undefined\n i = skipSpace(bytes, i)\n const genStart = i\n while (i < bytes.length && isDigit(bytes[i]!)) i++\n if (i === genStart || i >= bytes.length || !isWhite(bytes[i]!)) return undefined\n const gen = Number(latin1(bytes, genStart, i))\n i = skipSpace(bytes, i)\n if (bytes[i] !== 0x52 || (i + 1 < bytes.length && isRegular(bytes[i + 1]!))) {\n return undefined\n }\n return { value: { kind: 'ref', num, gen }, end: i + 1 }\n}\n\nfunction parseNumberOrKeyword(\n bytes: Uint8Array,\n offset: number\n): { value: PdfValue; end: number } {\n const end = tokenEnd(bytes, offset)\n const token = latin1(bytes, offset, end)\n if (token === 'true') return { value: true, end }\n if (token === 'false') return { value: false, end }\n if (token === 'null') return { value: null, end }\n if (/^[+-]?(\\d+\\.?\\d*|\\.\\d+)$/.test(token)) {\n const n = Number(token)\n if (/^\\d+$/.test(token)) {\n const ref = tryReference(bytes, n, end)\n if (ref) return ref\n }\n return { value: n, end }\n }\n throw new PdfSyntaxError(`Unexpected token \"${token}\" at ${offset}`)\n}\n\n/** Parses one value at `offset`, skipping whitespace and comments first. */\nexport function parseValue(\n bytes: Uint8Array,\n offset: number\n): { value: PdfValue; end: number } {\n const i = skipSpace(bytes, offset)\n if (i >= bytes.length) throw new PdfSyntaxError('Unexpected end of data')\n const c = bytes[i]!\n if (c === 0x2f) return parseName(bytes, i)\n if (c === 0x28) return parseLiteralString(bytes, i)\n if (c === 0x3c && bytes[i + 1] === 0x3c) return parseDict(bytes, i + 2)\n if (c === 0x3c) return parseHexString(bytes, i)\n if (c === 0x5b) return parseArray(bytes, i + 1)\n if (isRegular(c)) return parseNumberOrKeyword(bytes, i)\n throw new PdfSyntaxError(`Unexpected \"${String.fromCharCode(c)}\" at ${i}`)\n}\n\nfunction parseArray(\n bytes: Uint8Array,\n offset: number\n): { value: PdfValue[]; end: number } {\n const items: PdfValue[] = []\n let i = offset\n for (;;) {\n i = skipSpace(bytes, i)\n if (i >= bytes.length) throw new PdfSyntaxError('Unterminated array')\n if (bytes[i] === 0x5d) return { value: items, end: i + 1 }\n const item = parseValue(bytes, i)\n items.push(item.value)\n i = item.end\n }\n}\n\nfunction parseDict(bytes: Uint8Array, offset: number): { value: PdfDict; end: number } {\n const entries = new Map<string, PdfValue>()\n let i = offset\n for (;;) {\n i = skipSpace(bytes, i)\n if (i >= bytes.length) throw new PdfSyntaxError('Unterminated dictionary')\n if (bytes[i] === 0x3e && bytes[i + 1] === 0x3e) {\n return { value: { kind: 'dict', entries }, end: i + 2 }\n }\n if (bytes[i] !== 0x2f) throw new PdfSyntaxError(`Expected a name key at ${i}`)\n const key = parseName(bytes, i)\n const val = parseValue(bytes, key.end)\n entries.set(key.value.name, val.value)\n i = val.end\n }\n}\n\nfunction readInteger(bytes: Uint8Array, offset: number): { n: number; end: number } {\n const i = skipSpace(bytes, offset)\n let end = i\n while (end < bytes.length && isDigit(bytes[end]!)) end++\n if (end === i) throw new PdfSyntaxError(`Expected an integer at ${i}`)\n return { n: Number(latin1(bytes, i, end)), end }\n}\n\n/** Parses `num gen obj <value> [stream]` at `offset`. `streamStart` is the first data byte after `stream` and its EOL. */\nexport function parseIndirect(\n bytes: Uint8Array,\n offset: number\n): { num: number; gen: number; value: PdfValue; streamStart?: number } {\n const num = readInteger(bytes, offset)\n const gen = readInteger(bytes, num.end)\n const kw = skipSpace(bytes, gen.end)\n if (latin1(bytes, kw, tokenEnd(bytes, kw)) !== 'obj') {\n throw new PdfSyntaxError(`Expected \"obj\" at ${kw}`)\n }\n const { value, end } = parseValue(bytes, kw + 3)\n const result: { num: number; gen: number; value: PdfValue; streamStart?: number } = {\n num: num.n,\n gen: gen.n,\n value,\n }\n const next = skipSpace(bytes, end)\n if (latin1(bytes, next, next + 6) === 'stream' && !isRegular(bytes[next + 6] ?? 32)) {\n let start = next + 6\n if (bytes[start] === 13 && bytes[start + 1] === 10) start += 2\n else if (bytes[start] === 10 || bytes[start] === 13) start += 1\n result.streamStart = start\n }\n return result\n}\n\n/** Reads a dictionary entry. */\nexport const dictGet = (d: PdfDict, key: string): PdfValue | undefined =>\n d.entries.get(key)\n\n/** True for a name object, optionally one with the given spelling. */\nexport const isName = (v: unknown, name?: string): v is PdfName =>\n typeof v === 'object' &&\n v !== null &&\n (v as PdfName).kind === 'name' &&\n (name === undefined || (v as PdfName).name === name)\n\n/** True for a dictionary object. */\nexport const isDict = (v: PdfValue | undefined): v is PdfDict =>\n typeof v === 'object' && v !== null && !Array.isArray(v) && v.kind === 'dict'\n\n/** True for an indirect reference. */\nexport const isRef = (v: PdfValue | undefined): v is PdfRef =>\n typeof v === 'object' && v !== null && !Array.isArray(v) && v.kind === 'ref'\n\n/** PDFDocEncoding where it differs from Latin-1: 0x18–0x1f, 0x80–0x9e and 0xa0 (the euro sign). */\nconst PDF_DOC_18 = '\\u02d8\\u02c7\\u02c6\\u02d9\\u02dd\\u02db\\u02da\\u02dc'\nconst PDF_DOC_80 = '•†‡…—–ƒ⁄‹›−‰„“”‘’‚™fiflŁŒŠŸŽıłœšž'\n\n/**\n * A string object read as a text string: UTF-16BE or UTF-8 after a byte-order mark, else\n * PDFDocEncoding. Undefined for anything that is not a string.\n */\nexport function textString(v: PdfValue | undefined): string | undefined {\n if (typeof v !== 'object' || v === null || Array.isArray(v) || v.kind !== 'string')\n return undefined\n const b = v.bytes\n if (b[0] === 0xfe && b[1] === 0xff)\n return new TextDecoder('utf-16be').decode(b.subarray(2))\n if (b[0] === 0xef && b[1] === 0xbb && b[2] === 0xbf)\n return new TextDecoder().decode(b.subarray(3))\n let out = ''\n for (const c of b) {\n if (c >= 0x18 && c <= 0x1f) out += PDF_DOC_18[c - 0x18]\n else if (c >= 0x80 && c <= 0x9e) out += PDF_DOC_80[c - 0x80]\n else if (c === 0xa0) out += '€'\n else out += String.fromCharCode(c)\n }\n return out\n}\n","import { PDF_NAME } from '../model/annotations/pdf-names'\n\nimport {\n dictGet,\n isDict,\n isName,\n type PdfDict,\n type PdfRef,\n type PdfValue,\n} from './lexer'\n\nimport type { PdfObjects } from './objects'\n\nexport interface FontFields {\n fontFamily?: string\n fontWeight?: 'bold'\n fontStyle?: 'italic'\n}\n\nexport interface FreeTextFields {\n /** Two or three points, tip first. */\n callout?: { x: number; y: number }[]\n fringe?: { left: number; top: number; right: number; bottom: number }\n head?: string\n font?: FontFields\n}\n\n/** `12R` → {num:12,gen:0}, `12R3` → {num:12,gen:3}; anything else undefined. */\nexport function refOfPdfjsId(id: string): PdfRef | undefined {\n const m = /^(\\d+)R(\\d+)?$/.exec(id)\n if (!m) return undefined\n return { kind: 'ref', num: Number(m[1]), gen: m[2] === undefined ? 0 : Number(m[2]) }\n}\n\nconst FAMILIES: [RegExp, string][] = [\n [/^(helvetica|helv)/i, 'Helvetica'],\n [/^(times|tiro)/i, 'Times'],\n [/^cour(ier|$)/i, 'Courier'],\n]\n\n/**\n * BaseFont (or bare resource name) → Inkbar font fields; undefined for Symbol and ZapfDingbats.\n * A family matches by prefix, so `HelveticaNeue` reads as Helvetica and `CourierNewPS` as\n * Courier. Any other name keeps its own family, minus a trailing `MT` or `PSMT`.\n * With `knownOnly`, a name outside Helvetica, Times and Courier gives undefined: a bare\n * resource id such as `F1` is not a family.\n */\nexport function fontFromBaseName(\n name: string,\n knownOnly = false\n): FontFields | undefined {\n const bare = name.replace(/^[A-Z]{6}\\+/, '')\n if (/^(symbol|zapfdingbats|zadb)/i.test(bare)) return undefined\n const cut = bare.search(/[-,]/)\n const base = cut < 0 ? bare : bare.slice(0, cut)\n const style = cut < 0 ? '' : bare.slice(cut + 1)\n const known = FAMILIES.find(([re]) => re.test(base))\n if (knownOnly && !known) return undefined\n const fontFamily = known ? known[1] : base.replace(/(PS)?MT$/, '')\n if (!fontFamily) return undefined\n const font: FontFields = { fontFamily }\n if (/bold|black|heavy/i.test(style)) font.fontWeight = 'bold'\n if (/italic|oblique/i.test(style)) font.fontStyle = 'italic'\n return font\n}\n\nconst finite = (v: PdfValue | undefined): v is number =>\n typeof v === 'number' && Number.isFinite(v)\n\nasync function numbers(objs: PdfObjects, v: PdfValue | undefined, counts: number[]) {\n const arr = await objs.resolve(v)\n if (!Array.isArray(arr) || !counts.includes(arr.length)) return undefined\n const out = await Promise.all(arr.map((n) => objs.resolve(n)))\n return out.every(finite) ? out : undefined\n}\n\nasync function dictOf(objs: PdfObjects, v: PdfValue | undefined) {\n const d = await objs.resolve(v)\n return isDict(d) ? d : undefined\n}\n\n/** The font's /BaseFont, looked up in a /DR resource dictionary. */\nasync function baseFontIn(objs: PdfObjects, dr: PdfValue | undefined, resource: string) {\n const res = await dictOf(objs, dr)\n const fonts = res && (await dictOf(objs, dictGet(res, 'Font')))\n const font = fonts && (await dictOf(objs, dictGet(fonts, resource)))\n const base = font && (await objs.resolve(dictGet(font, 'BaseFont')))\n return isName(base) ? base.name : undefined\n}\n\n/**\n * The font a `/DA` font name selects: its `/BaseFont` in the annotation's `/DR`, then the\n * AcroForm's `/DR`, else the name itself when it is a standard family.\n */\nexport async function readFont(\n objs: PdfObjects,\n annot: PdfDict,\n daFont: string\n): Promise<FontFields | undefined> {\n const root = await dictOf(objs, dictGet(objs.trailer, 'Root'))\n const acroForm = root && (await dictOf(objs, dictGet(root, 'AcroForm')))\n const sources = [dictGet(annot, 'DR'), acroForm && dictGet(acroForm, 'DR')]\n for (const dr of sources) {\n const base = await baseFontIn(objs, dr, daFont)\n if (base !== undefined) return fontFromBaseName(base)\n }\n return fontFromBaseName(daFont, true)\n}\n\nasync function readHead(objs: PdfObjects, le: PdfValue | undefined) {\n let v = await objs.resolve(le)\n if (Array.isArray(v)) v = await objs.resolve(v[0])\n return isName(v) && PDF_NAME.test(v.name) ? v.name : undefined\n}\n\n/** `rect` is the annotation's [x1 y1 x2 y2], used to reject a fringe that leaves no box. */\nexport async function readFreeTextFields(\n objs: PdfObjects,\n ref: PdfRef,\n rect: readonly number[],\n daFont: string | undefined\n): Promise<FreeTextFields> {\n const fields: FreeTextFields = {}\n try {\n const annot = await objs.get(ref)\n if (!isDict(annot)) return fields\n\n const cl = await numbers(objs, dictGet(annot, 'CL'), [4, 6])\n if (cl) {\n fields.callout = []\n for (let i = 0; i < cl.length; i += 2)\n fields.callout.push({ x: cl[i]!, y: cl[i + 1]! })\n }\n\n const rd = await numbers(objs, dictGet(annot, 'RD'), [4])\n if (rd && rect.length === 4 && rd.every((n) => n >= 0)) {\n const [left, top, right, bottom] = rd as [number, number, number, number]\n const width = Math.abs(rect[2]! - rect[0]!)\n const height = Math.abs(rect[3]! - rect[1]!)\n if (left + right < width && top + bottom < height)\n fields.fringe = { left, top, right, bottom }\n }\n\n const head = await readHead(objs, dictGet(annot, 'LE'))\n if (head !== undefined) fields.head = head\n\n if (daFont !== undefined) {\n const font = await readFont(objs, annot, daFont)\n if (font) fields.font = font\n }\n } catch {\n // Whatever was read before the failure stands.\n }\n return fields\n}\n\nexport async function readTextIcon(\n objs: PdfObjects,\n ref: PdfRef\n): Promise<string | undefined> {\n try {\n const annot = await objs.get(ref)\n if (!isDict(annot)) return undefined\n const name = await objs.resolve(dictGet(annot, 'Name'))\n return isName(name) && PDF_NAME.test(name.name) ? name.name : undefined\n } catch {\n return undefined\n }\n}\n","import { readFont, refOfPdfjsId, type FontFields } from './annotation-fields'\nimport {\n dictGet,\n isDict,\n isName,\n isRef,\n textString,\n type PdfDict,\n type PdfValue,\n} from './lexer'\n\nimport type { PdfObjects } from './objects'\nimport type { TabsOrder, WidgetAction } from '../model/form/types'\n\n/** What a widget's dictionary holds that PDF.js does not report. */\nexport interface WidgetExtras {\n /** A checkbox or radio widget's on state: the first `/AP /N` key that is not `Off`. */\n onState?: string\n /** A checkbox or radio widget's `/AP /N` has an `Off` appearance. */\n offAppearance?: true\n /** A checkbox or radio field's `/V` state name, which PDF.js reports as an export value. */\n state?: string\n /** A checkbox or radio field's `/DV` state name. */\n defaultState?: string\n /** The `/DA` font, resolved through `/DR` to its `/BaseFont`. */\n font?: FontFields\n /** `/MK /CA`. */\n caption?: string\n /** The field has `/PMD`, which marks a barcode field. */\n barcode?: true\n /** `/TU` from the widget or its terminal field; PDF.js reads only the widget's. */\n tooltip?: string\n}\n\n/** Form details read from the file's own objects. */\nexport interface FormExtras {\n /** SubmitForm actions, by widget id. */\n submits: Map<string, WidgetAction>\n /** Names of fields holding a certificate signature. */\n signed: Set<string>\n /** Fields a signature's `/Lock` or FieldMDP transform makes read-only. */\n lockedFields: Set<string>\n /** DocMDP with P 1: no changes at all. */\n lockAll: boolean\n /** Page `/Tabs`, by page index, for pages that set one. */\n tabs: Map<number, TabsOrder>\n /** What each widget's own dictionary adds, by PDF.js widget id (`12R`). */\n widgets: Map<string, WidgetExtras>\n /**\n * The page a widget's GoTo goes to, by widget id: from its `/A`, or its `/Dest` when it has no\n * `/A`. Named destinations are in only when the reader was given a resolver.\n */\n destPages: Map<string, number>\n /** Widgets whose own `/A` is a JavaScript action (not one that only has JavaScript in `/Next`). */\n scriptActions: Set<string>\n /**\n * The GoTo, URI, Named, ResetForm and SubmitForm actions in each widget `/A`'s `/Next` chain,\n * in order, by widget id.\n */\n next: Map<string, WidgetAction[]>\n}\n\nexport interface ReadFormExtrasOptions {\n /** The page index a named destination points at, if any. */\n destinationPage?: (name: string) => Promise<number | undefined>\n}\n\nexport function emptyFormExtras(): FormExtras {\n return {\n submits: new Map(),\n signed: new Set(),\n lockedFields: new Set(),\n lockAll: false,\n tabs: new Map(),\n widgets: new Map(),\n destPages: new Map(),\n scriptActions: new Set(),\n next: new Map(),\n }\n}\n\n/** Deep enough for any real form; it also stops a /Parent or /Kids cycle. */\nconst MAX_DEPTH = 32\n\nconst TABS = new Set(['R', 'C', 'S', 'W', 'A'])\n\nconst refKey = (num: number, gen: number) => (gen === 0 ? `${num}R` : `${num}R${gen}`)\n\nasync function dictOf(objs: PdfObjects, v: PdfValue | undefined) {\n const d = await objs.resolve(v)\n return isDict(d) ? d : undefined\n}\n\nasync function arrayOf(objs: PdfObjects, v: PdfValue | undefined) {\n const a = await objs.resolve(v)\n return Array.isArray(a) ? a : []\n}\n\n/** `key` on `dict` or the nearest `/Parent` that has it. */\nasync function inherited(objs: PdfObjects, dict: PdfDict, key: string) {\n let node: PdfDict | undefined = dict\n for (let depth = 0; node && depth < MAX_DEPTH; depth++) {\n const v = dictGet(node, key)\n if (v !== undefined) return objs.resolve(v)\n node = await dictOf(objs, dictGet(node, 'Parent'))\n }\n return undefined\n}\n\n/**\n * `key` on the widget, else on its terminal field: the widget itself when it carries `/T`,\n * otherwise its `/Parent`. For keys that are not inherited, such as `/TU`.\n */\nasync function terminal(objs: PdfObjects, widget: PdfDict, key: string) {\n const own = dictGet(widget, key)\n if (own !== undefined) return objs.resolve(own)\n if (dictGet(widget, 'T') !== undefined) return undefined\n const parent = await dictOf(objs, dictGet(widget, 'Parent'))\n const v = parent && dictGet(parent, key)\n return v === undefined ? undefined : objs.resolve(v)\n}\n\ninterface FieldNode {\n name: string\n dict: PdfDict\n}\n\n/** Terminal fields under `/AcroForm /Fields`, plus the full name of every field object by ref. */\nasync function walkFields(objs: PdfObjects, acroForm: PdfDict | undefined) {\n const terminals: FieldNode[] = []\n const names = new Map<string, string>()\n const seen = new Set<string>()\n const visit = async (v: PdfValue, prefix: string, depth: number) => {\n if (depth > MAX_DEPTH) return\n if (isRef(v)) {\n const key = refKey(v.num, v.gen)\n if (seen.has(key)) return\n seen.add(key)\n }\n const dict = await dictOf(objs, v)\n if (!dict) return\n const part = textString(await objs.resolve(dictGet(dict, 'T')))\n const name = part === undefined ? prefix : prefix ? `${prefix}.${part}` : part\n if (isRef(v)) names.set(refKey(v.num, v.gen), name)\n const kids = await arrayOf(objs, dictGet(dict, 'Kids'))\n const fieldKids: PdfValue[] = []\n for (const kid of kids) {\n const kd = await dictOf(objs, kid)\n if (kd && dictGet(kd, 'T') !== undefined) fieldKids.push(kid)\n }\n if (fieldKids.length === 0) {\n if (name) terminals.push({ name, dict })\n return\n }\n for (const kid of fieldKids) await visit(kid, name, depth + 1)\n }\n if (acroForm)\n for (const f of await arrayOf(objs, dictGet(acroForm, 'Fields')))\n await visit(f, '', 0)\n return { terminals, names }\n}\n\n/** Names from a `/Fields` array of strings or field references. */\nasync function fieldNames(\n objs: PdfObjects,\n v: PdfValue | undefined,\n names: Map<string, string>\n): Promise<string[]> {\n const out: string[] = []\n for (const item of await arrayOf(objs, v)) {\n const name = isRef(item)\n ? names.get(refKey(item.num, item.gen))\n : textString(await objs.resolve(item))\n if (name !== undefined) out.push(name)\n }\n return out\n}\n\nconst covers = (lock: string, name: string) =>\n name === lock || name.startsWith(`${lock}.`)\n\n/** Fields a `/Lock` or FieldMDP `/TransformParams` dictionary makes read-only. */\nasync function lockedBy(\n objs: PdfObjects,\n lock: PdfDict,\n all: readonly string[],\n names: Map<string, string>\n): Promise<string[]> {\n const action = await objs.resolve(dictGet(lock, 'Action'))\n if (isName(action, 'All')) return [...all]\n const listed = await fieldNames(objs, dictGet(lock, 'Fields'), names)\n const hit = (n: string) => listed.some((l) => covers(l, n))\n if (isName(action, 'Include')) return all.filter(hit)\n if (isName(action, 'Exclude')) return all.filter((n) => !hit(n))\n return []\n}\n\n/** The `/TransformParams` of each signature reference using `method`. */\nasync function transforms(objs: PdfObjects, sig: PdfDict, method: string) {\n const out: PdfDict[] = []\n for (const r of await arrayOf(objs, dictGet(sig, 'Reference'))) {\n const ref = await dictOf(objs, r)\n if (!ref || !isName(await objs.resolve(dictGet(ref, 'TransformMethod')), method))\n continue\n const params = await dictOf(objs, dictGet(ref, 'TransformParams'))\n if (params) out.push(params)\n }\n return out\n}\n\nasync function readDocMdp(objs: PdfObjects, root: PdfDict): Promise<boolean> {\n const perms = await dictOf(objs, dictGet(root, 'Perms'))\n const sig = perms && (await dictOf(objs, dictGet(perms, 'DocMDP')))\n if (!sig) return false\n for (const params of await transforms(objs, sig, 'DocMDP')) {\n if ((await objs.resolve(dictGet(params, 'P'))) === 1) return true\n }\n return false\n}\n\n/** Page refs in page order, and each page's `/Tabs`. */\nasync function walkPages(objs: PdfObjects, root: PdfDict) {\n const pages = new Map<string, number>()\n const tabs = new Map<number, TabsOrder>()\n const seen = new Set<string>()\n const visit = async (v: PdfValue | undefined, depth: number) => {\n if (depth > MAX_DEPTH) return\n if (isRef(v)) {\n const key = refKey(v.num, v.gen)\n if (seen.has(key)) return\n seen.add(key)\n }\n const node = await dictOf(objs, v)\n if (!node) return\n const kids = dictGet(node, 'Kids')\n if (kids !== undefined && !isName(dictGet(node, 'Type'), 'Page')) {\n for (const kid of await arrayOf(objs, kids)) await visit(kid, depth + 1)\n return\n }\n const index = pages.size\n pages.set(isRef(v) ? refKey(v.num, v.gen) : `#${index}`, index)\n const t = await objs.resolve(dictGet(node, 'Tabs'))\n if (isName(t) && TABS.has(t.name)) tabs.set(index, t.name as TabsOrder)\n }\n await visit(dictGet(root, 'Pages'), 0)\n return { pages, tabs }\n}\n\n/** A submit URL: a string, or a file specification's `/UF` or `/F`. */\nasync function fileSpecUrl(objs: PdfObjects, v: PdfValue | undefined) {\n const f = await objs.resolve(v)\n const direct = textString(f)\n if (direct !== undefined) return direct\n if (!isDict(f)) return undefined\n return (\n textString(await objs.resolve(dictGet(f, 'UF'))) ??\n textString(await objs.resolve(dictGet(f, 'F')))\n )\n}\n\n/** ResetForm `/Flags` bit 1: `/Fields` lists the fields to leave alone. */\nconst RESET_EXCLUDE = 1\nconst SUBMIT_EXCLUDE = 1\nconst SUBMIT_HTML = 4\nconst SUBMIT_GET = 8\nconst SUBMIT_XFDF = 32\nconst SUBMIT_PDF = 256\n\nasync function readSubmit(\n objs: PdfObjects,\n action: PdfDict,\n names: Map<string, string>\n): Promise<WidgetAction | undefined> {\n const url = await fileSpecUrl(objs, dictGet(action, 'F'))\n if (url === undefined) return undefined\n const raw = await objs.resolve(dictGet(action, 'Flags'))\n const flags = typeof raw === 'number' ? raw : 0\n const fields = await fieldNames(objs, dictGet(action, 'Fields'), names)\n const include = (flags & SUBMIT_EXCLUDE) === 0\n if (flags & SUBMIT_XFDF) return { kind: 'submit', url, fields, include, format: 'xfdf' }\n if (flags & SUBMIT_PDF) return { kind: 'submit', url, fields, include, format: 'pdf' }\n if (flags & SUBMIT_HTML) {\n const method = flags & SUBMIT_GET ? 'GET' : 'POST'\n return { kind: 'submit', url, fields, include, format: 'html', method }\n }\n return { kind: 'submit', url, fields, include, format: 'fdf' }\n}\n\nconst FF_PUSHBUTTON = 1 << 16\n\n/** A widget's GoTo destination: its `/A`'s when that is a GoTo, else `/Dest` when it has no `/A`. */\nasync function destinationOf(\n objs: PdfObjects,\n widget: PdfDict,\n action: PdfDict | undefined\n) {\n if (!action) return objs.resolve(dictGet(widget, 'Dest'))\n const s = await objs.resolve(dictGet(action, 'S'))\n return isName(s, 'GoTo') ? objs.resolve(dictGet(action, 'D')) : undefined\n}\n\n/** A string object's bytes as a Latin-1 string: how PDF.js keys a name tree. */\nfunction rawString(v: PdfValue | undefined): string | undefined {\n if (typeof v !== 'object' || v === null || Array.isArray(v) || v.kind !== 'string')\n return undefined\n let out = ''\n for (const c of v.bytes) out += String.fromCharCode(c)\n return out\n}\n\n/**\n * The actions an action's `/Next` runs after it, in order (ISO 32000 §12.6.2): each entry,\n * then that entry's own `/Next`, depth first. A cycle (back to the `/A` itself, `ref`, too) or a\n * chain deeper than `MAX_DEPTH` stops.\n */\nasync function nextChain(\n objs: PdfObjects,\n action: PdfDict,\n ref: PdfValue | undefined\n): Promise<PdfDict[]> {\n const out: PdfDict[] = []\n const seen = new Set<string>(isRef(ref) ? [refKey(ref.num, ref.gen)] : [])\n /** False for a ref already visited; marks it visited. */\n const fresh = (v: PdfValue | undefined) => {\n if (!isRef(v)) return true\n const key = refKey(v.num, v.gen)\n if (seen.has(key)) return false\n seen.add(key)\n return true\n }\n const visit = async (v: PdfValue | undefined, depth: number) => {\n if (depth > MAX_DEPTH || v === undefined || !fresh(v)) return\n const next = await objs.resolve(v)\n for (const item of Array.isArray(next) ? next : [next]) {\n if (!fresh(item)) continue\n const d = await dictOf(objs, item)\n if (!d) continue\n out.push(d)\n await visit(dictGet(d, 'Next'), depth + 1)\n }\n }\n await visit(dictGet(action, 'Next'), 0)\n return out\n}\n\nasync function readWidget(\n objs: PdfObjects,\n widget: PdfDict,\n acroFormDa: string | undefined\n): Promise<WidgetExtras> {\n const extras: WidgetExtras = {}\n const ft = await inherited(objs, widget, 'FT')\n const ff = await inherited(objs, widget, 'Ff')\n if (isName(ft, 'Btn') && !(typeof ff === 'number' && ff & FF_PUSHBUTTON)) {\n const ap = await dictOf(objs, dictGet(widget, 'AP'))\n const n = ap && (await dictOf(objs, dictGet(ap, 'N')))\n const on = n && [...n.entries.keys()].find((k) => k !== 'Off')\n if (on !== undefined) extras.onState = on\n if (n?.entries.has('Off')) extras.offAppearance = true\n const v = await inherited(objs, widget, 'V')\n if (isName(v)) extras.state = v.name\n const dv = await inherited(objs, widget, 'DV')\n if (isName(dv)) extras.defaultState = dv.name\n }\n const da = textString(await inherited(objs, widget, 'DA')) ?? acroFormDa\n const daFont = da && /\\/([^\\s/]+)\\s+[-+\\d.]+\\s+Tf/.exec(da)?.[1]\n const font = daFont ? await readFont(objs, widget, daFont) : undefined\n if (font) extras.font = font\n const mk = await dictOf(objs, dictGet(widget, 'MK'))\n const caption = mk && textString(await objs.resolve(dictGet(mk, 'CA')))\n if (caption) extras.caption = caption\n if ((await inherited(objs, widget, 'PMD')) !== undefined) extras.barcode = true\n const tooltip = textString(await terminal(objs, widget, 'TU'))\n if (tooltip) extras.tooltip = tooltip\n return extras\n}\n\n/**\n * Reads what PDF.js leaves out of widget data: SubmitForm actions, certificate signatures and\n * the locks they set, DocMDP, page `/Tabs`, GoTo pages, which `/A`s are JavaScript, the\n * actions in each `/A`'s `/Next` chain, and per-widget on states,\n * stored and default state names, `/DA` fonts, captions and barcode marks. Never throws: what cannot be read is left out.\n */\nexport async function readFormExtras(\n objs: PdfObjects | undefined,\n widgetIds: readonly string[],\n options: ReadFormExtrasOptions = {}\n): Promise<FormExtras> {\n const extras = emptyFormExtras()\n if (!objs) return extras\n try {\n const root = await dictOf(objs, dictGet(objs.trailer, 'Root'))\n if (!root) return extras\n const acroForm = await dictOf(objs, dictGet(root, 'AcroForm'))\n const { terminals, names } = await walkFields(objs, acroForm)\n const all = terminals.map((t) => t.name)\n const acroFormDa = acroForm && textString(await objs.resolve(dictGet(acroForm, 'DA')))\n /** Each named destination's page, asked of the resolver once per name. */\n const named = new Map<string, Promise<number | undefined> | undefined>()\n const namedPage = (name: string) => {\n if (!named.has(name)) named.set(name, options.destinationPage?.(name))\n return named.get(name)\n }\n\n for (const { name, dict } of terminals) {\n try {\n if (!isName(await inherited(objs, dict, 'FT'), 'Sig')) continue\n const sig = await dictOf(objs, dictGet(dict, 'V'))\n if (!sig) continue\n extras.signed.add(name)\n const locks = await transforms(objs, sig, 'FieldMDP')\n const lock = await dictOf(objs, dictGet(dict, 'Lock'))\n if (lock) locks.push(lock)\n for (const l of locks)\n for (const n of await lockedBy(objs, l, all, names)) extras.lockedFields.add(n)\n } catch {\n // One unreadable signature does not stop the others.\n }\n }\n\n extras.lockAll = await readDocMdp(objs, root).catch(() => false)\n const { pages, tabs } = await walkPages(objs, root)\n extras.tabs = tabs\n\n for (const id of widgetIds) {\n try {\n const ref = refOfPdfjsId(id)\n const widget = ref && (await dictOf(objs, ref))\n if (!widget) continue\n extras.widgets.set(id, await readWidget(objs, widget, acroFormDa))\n const action = await dictOf(objs, dictGet(widget, 'A'))\n const s = action && (await objs.resolve(dictGet(action, 'S')))\n if (action && isName(s, 'SubmitForm')) {\n const submit = await readSubmit(objs, action, names)\n if (submit) extras.submits.set(id, submit)\n }\n const pageOf = async (dest: PdfValue | undefined) => {\n const name = isName(dest) ? dest.name : rawString(dest)\n if (name !== undefined) return namedPage(name)\n const target = (await arrayOf(objs, dest))[0]\n return isRef(target) ? pages.get(refKey(target.num, target.gen)) : undefined\n }\n const page = await pageOf(await destinationOf(objs, widget, action))\n if (page !== undefined) extras.destPages.set(id, page)\n if (!action) continue\n if (isName(s, 'JavaScript')) extras.scriptActions.add(id)\n const next: WidgetAction[] = []\n for (const a of await nextChain(objs, action, dictGet(widget, 'A'))) {\n const ns = await objs.resolve(dictGet(a, 'S'))\n if (isName(ns, 'GoTo')) {\n const p = await pageOf(await objs.resolve(dictGet(a, 'D')))\n if (p !== undefined) next.push({ kind: 'goto', page: p })\n } else if (isName(ns, 'URI')) {\n const url = textString(await objs.resolve(dictGet(a, 'URI')))\n if (url) next.push({ kind: 'uri', url })\n } else if (isName(ns, 'Named')) {\n const n = await objs.resolve(dictGet(a, 'N'))\n if (isName(n)) next.push({ kind: 'named', name: n.name })\n } else if (isName(ns, 'ResetForm')) {\n const flags = await objs.resolve(dictGet(a, 'Flags'))\n next.push({\n kind: 'reset',\n fields: await fieldNames(objs, dictGet(a, 'Fields'), names),\n include: typeof flags !== 'number' || (flags & RESET_EXCLUDE) === 0,\n })\n } else if (isName(ns, 'SubmitForm')) {\n const submit = await readSubmit(objs, a, names)\n if (submit) next.push(submit)\n }\n // JavaScript in the chain runs with the widget's Action scripts; other kinds are\n // not supported.\n }\n if (next.length > 0) extras.next.set(id, next)\n } catch {\n // One unreadable widget does not stop the others.\n }\n }\n } catch {\n // Whatever was read before the failure stands.\n }\n return extras\n}\n","import { dictGet, isDict, isName, PdfSyntaxError, type PdfDict } from './lexer'\n\nconst ENDSTREAM = Uint8Array.from('endstream', (c) => c.charCodeAt(0))\n\nfunction matchesAt(bytes: Uint8Array, at: number, pattern: Uint8Array): boolean {\n if (at < 0 || at + pattern.length > bytes.length) return false\n for (let i = 0; i < pattern.length; i++) if (bytes[at + i] !== pattern[i]) return false\n return true\n}\n\nfunction findEndstream(bytes: Uint8Array, from: number): number {\n for (let i = from; i + ENDSTREAM.length <= bytes.length; i++) {\n if (matchesAt(bytes, i, ENDSTREAM)) return i\n }\n return bytes.length\n}\n\n/** Raw stream bytes: trusts `length` when `endstream` follows it, otherwise scans. */\nfunction rawData(\n bytes: Uint8Array,\n start: number,\n length: number | undefined\n): Uint8Array {\n if (length !== undefined && Number.isInteger(length) && length >= 0) {\n let i = start + length\n while (i < bytes.length && (bytes[i] === 10 || bytes[i] === 13 || bytes[i] === 32))\n i++\n if (matchesAt(bytes, i, ENDSTREAM)) return bytes.subarray(start, start + length)\n }\n let end = findEndstream(bytes, start)\n if (end > start && bytes[end - 1] === 10) end--\n if (end > start && bytes[end - 1] === 13) end--\n return bytes.subarray(start, end)\n}\n\n/** The single filter parameter dictionary, if any. Anything else that is defined is an error. */\nfunction decodeParms(dict: PdfDict): PdfDict | undefined {\n const parms = dictGet(dict, 'DecodeParms') ?? dictGet(dict, 'DP')\n const first = Array.isArray(parms) ? parms[0] : parms\n if (first === undefined || first === null) return undefined\n if (!isDict(first)) throw new PdfSyntaxError('Unsupported /DecodeParms')\n return first\n}\n\nfunction numberParam(parms: PdfDict | undefined, key: string, fallback: number): number {\n const v = parms ? dictGet(parms, key) : undefined\n return typeof v === 'number' ? v : fallback\n}\n\nasync function inflate(data: Uint8Array): Promise<Uint8Array> {\n const stream = new Blob([data as BlobPart])\n .stream()\n .pipeThrough(new DecompressionStream('deflate'))\n return new Uint8Array(await new Response(stream).arrayBuffer())\n}\n\nfunction paeth(a: number, b: number, c: number): number {\n const p = a + b - c\n const pa = Math.abs(p - a)\n const pb = Math.abs(p - b)\n const pc = Math.abs(p - c)\n if (pa <= pb && pa <= pc) return a\n return pb <= pc ? b : c\n}\n\nfunction undoPngPredictor(\n data: Uint8Array,\n columns: number,\n colors: number,\n bits: number\n): Uint8Array {\n const bpp = Math.max(1, Math.ceil((colors * bits) / 8))\n const rowBytes = Math.ceil((columns * colors * bits) / 8)\n const rows = Math.floor(data.length / (rowBytes + 1))\n const out = new Uint8Array(rows * rowBytes)\n for (let r = 0; r < rows; r++) {\n const type = data[r * (rowBytes + 1)]!\n const src = r * (rowBytes + 1) + 1\n const dst = r * rowBytes\n for (let x = 0; x < rowBytes; x++) {\n const raw = data[src + x]!\n const left = x >= bpp ? out[dst + x - bpp]! : 0\n const up = r > 0 ? out[dst - rowBytes + x]! : 0\n const upLeft = r > 0 && x >= bpp ? out[dst - rowBytes + x - bpp]! : 0\n let value: number\n switch (type) {\n case 0:\n value = raw\n break\n case 1:\n value = raw + left\n break\n case 2:\n value = raw + up\n break\n case 3:\n value = raw + ((left + up) >> 1)\n break\n case 4:\n value = raw + paeth(left, up, upLeft)\n break\n default:\n throw new PdfSyntaxError(`Unknown PNG filter type ${type}`)\n }\n out[dst + x] = value & 0xff\n }\n }\n return out\n}\n\n/** The decoded data of the stream whose dictionary is `dict` and whose data starts at `start`. `length` is `/Length`, already resolved. */\nexport async function decodeStream(\n bytes: Uint8Array,\n dict: PdfDict,\n start: number,\n length: number | undefined\n): Promise<Uint8Array> {\n const filter = dictGet(dict, 'Filter') ?? dictGet(dict, 'F')\n const filters = Array.isArray(filter) ? filter : filter === undefined ? [] : [filter]\n if (filters.length === 0) return rawData(bytes, start, length)\n if (filters.length > 1 || !isName(filters[0], 'FlateDecode')) {\n throw new PdfSyntaxError('Unsupported stream filter')\n }\n const inflated = await inflate(rawData(bytes, start, length))\n const parms = decodeParms(dict)\n const predictor = numberParam(parms, 'Predictor', 1)\n if (predictor === 1) return inflated\n if (predictor < 10) throw new PdfSyntaxError(`Unsupported predictor ${predictor}`)\n return undoPngPredictor(\n inflated,\n numberParam(parms, 'Columns', 1),\n numberParam(parms, 'Colors', 1),\n numberParam(parms, 'BitsPerComponent', 8)\n )\n}\n","import { isDict, parseIndirect, parseValue, type PdfDict, type PdfValue } from './lexer'\nimport { decodeStream } from './stream'\n\nexport type XrefEntry =\n | { type: 'offset'; offset: number; gen: number }\n | { type: 'compressed'; stream: number; index: number }\n | { type: 'free' }\n\nexport interface Xref {\n entries: Map<number, XrefEntry>\n trailer: PdfDict\n}\n\nconst isWhite = (c: number): boolean =>\n c === 0 || c === 9 || c === 10 || c === 12 || c === 13 || c === 32\n\nconst latin1 = (bytes: Uint8Array, from: number, to: number): string => {\n let out = ''\n for (let i = from; i < to; i++) out += String.fromCharCode(bytes[i]!)\n return out\n}\n\nfunction readToken(bytes: Uint8Array, offset: number): { token: string; end: number } {\n let i = offset\n while (i < bytes.length && isWhite(bytes[i]!)) i++\n const start = i\n while (i < bytes.length && !isWhite(bytes[i]!)) i++\n return { token: latin1(bytes, start, i), end: i }\n}\n\nfunction readInt(bytes: Uint8Array, offset: number): { n: number; end: number } {\n const { token, end } = readToken(bytes, offset)\n if (!/^\\d+$/.test(token)) throw new Error(`Expected an integer at ${offset}`)\n return { n: Number(token), end }\n}\n\nfunction findStartxref(bytes: Uint8Array): number {\n const tail = latin1(bytes, Math.max(0, bytes.length - 1024), bytes.length)\n const at = tail.lastIndexOf('startxref')\n if (at < 0) throw new Error('No startxref')\n return readInt(bytes, bytes.length - tail.length + at + 9).n\n}\n\ninterface Section {\n entries: Map<number, XrefEntry>\n trailer: PdfDict\n}\n\nfunction readTable(bytes: Uint8Array, offset: number): Section {\n const entries = new Map<number, XrefEntry>()\n let i = readToken(bytes, offset).end // past \"xref\"\n for (;;) {\n const head = readToken(bytes, i)\n if (head.token.startsWith('trailer')) {\n // The dictionary may follow the keyword with no space: `trailer<<`.\n const trailer = parseValue(bytes, head.end - (head.token.length - 7)).value\n if (!isDict(trailer)) throw new Error('Trailer is not a dictionary')\n return { entries, trailer }\n }\n const first = readInt(bytes, i)\n const count = readInt(bytes, first.end)\n i = count.end\n for (let k = 0; k < count.n; k++) {\n const off = readInt(bytes, i)\n const gen = readInt(bytes, off.end)\n const kind = readToken(bytes, gen.end)\n i = kind.end\n if (kind.token === 'n') {\n entries.set(first.n + k, { type: 'offset', offset: off.n, gen: gen.n })\n } else if (kind.token === 'f') {\n entries.set(first.n + k, { type: 'free' })\n } else {\n throw new Error(`Bad xref entry type \"${kind.token}\"`)\n }\n }\n }\n}\n\nconst numbers = (v: PdfValue | undefined): number[] | undefined =>\n Array.isArray(v) && v.every((x) => typeof x === 'number' && x >= 0)\n ? (v as number[])\n : undefined\n\nasync function readStream(bytes: Uint8Array, offset: number): Promise<Section> {\n const obj = parseIndirect(bytes, offset)\n const dict = obj.value\n if (!isDict(dict) || obj.streamStart === undefined) {\n throw new Error('Xref stream expected')\n }\n const length = dict.entries.get('Length')\n const data = await decodeStream(\n bytes,\n dict,\n obj.streamStart,\n typeof length === 'number' ? length : undefined\n )\n const w = numbers(dict.entries.get('W'))\n if (!w || w.length !== 3 || w.some((x) => x > 8)) throw new Error('Bad /W')\n const size = dict.entries.get('Size')\n const index = numbers(dict.entries.get('Index')) ?? [\n 0,\n typeof size === 'number' ? size : 0,\n ]\n const [w0, w1, w2] = w as [number, number, number]\n const rowLength = w0 + w1 + w2\n if (rowLength === 0) throw new Error('Empty xref rows')\n const field = (at: number, width: number): number => {\n let n = 0\n for (let k = 0; k < width; k++) n = n * 256 + data[at + k]!\n return n\n }\n const entries = new Map<number, XrefEntry>()\n let row = 0\n for (let s = 0; s + 1 < index.length; s += 2) {\n for (let k = 0; k < index[s + 1]!; k++, row++) {\n const at = row * rowLength\n if (at + rowLength > data.length) return { entries, trailer: dict }\n const type = w0 === 0 ? 1 : field(at, w0)\n const a = field(at + w0, w1)\n const b = field(at + w0 + w1, w2)\n const num = index[s]! + k\n if (type === 0) entries.set(num, { type: 'free' })\n else if (type === 1) entries.set(num, { type: 'offset', offset: a, gen: b })\n else if (type === 2) entries.set(num, { type: 'compressed', stream: a, index: b })\n }\n }\n return { entries, trailer: dict }\n}\n\nasync function readSection(bytes: Uint8Array, offset: number): Promise<Section> {\n if (!Number.isInteger(offset) || offset < 0 || offset >= bytes.length) {\n throw new Error('Xref offset out of range')\n }\n return readToken(bytes, offset).token === 'xref'\n ? readTable(bytes, offset)\n : readStream(bytes, offset)\n}\n\n/** Newest entry wins along the /Prev chain (and a hybrid file's /XRefStm). Undefined when startxref or a section cannot be read. */\nexport async function readXref(bytes: Uint8Array): Promise<Xref | undefined> {\n try {\n const entries = new Map<number, XrefEntry>()\n const visited = new Set<number>()\n let trailer: PdfDict | undefined\n let next: number | undefined = findStartxref(bytes)\n while (next !== undefined && !visited.has(next)) {\n visited.add(next)\n const section = await readSection(bytes, next)\n trailer ??= section.trailer\n const hybrid = section.trailer.entries.get('XRefStm')\n // A hybrid file's table marks compressed objects free; its XRefStm holds the real entries.\n if (typeof hybrid === 'number' && !visited.has(hybrid)) {\n visited.add(hybrid)\n const extra = await readSection(bytes, hybrid)\n for (const [num, e] of extra.entries) if (!entries.has(num)) entries.set(num, e)\n }\n for (const [num, e] of section.entries) if (!entries.has(num)) entries.set(num, e)\n const prev = section.trailer.entries.get('Prev')\n next = typeof prev === 'number' ? prev : undefined\n }\n return trailer ? { entries, trailer } : undefined\n } catch {\n return undefined\n }\n}\n","import {\n isDict,\n isRef,\n parseIndirect,\n parseValue,\n type PdfDict,\n type PdfRef,\n type PdfValue,\n} from './lexer'\nimport { decodeStream } from './stream'\nimport { readXref, type Xref } from './xref'\n\nexport interface PdfObjects {\n trailer: PdfDict\n /** The object `ref` names, or undefined if it is missing, free, or unreadable. Never throws. */\n get(ref: PdfRef): Promise<PdfValue | undefined>\n /** `v` with one level of reference followed; other values as they are. */\n resolve(v: PdfValue | undefined): Promise<PdfValue | undefined>\n}\n\ninterface ObjectStream {\n decoded: Uint8Array\n first: number\n /** Object numbers and offsets from the header, in order. */\n pairs: { num: number; offset: number }[]\n}\n\nclass Reader implements PdfObjects {\n readonly trailer: PdfDict\n private readonly objectStreams = new Map<number, Promise<ObjectStream | undefined>>()\n\n constructor(\n private readonly bytes: Uint8Array,\n private readonly xref: Xref\n ) {\n this.trailer = xref.trailer\n }\n\n async get(ref: PdfRef): Promise<PdfValue | undefined> {\n try {\n return await this.load(ref, true)\n } catch {\n return undefined\n }\n }\n\n async resolve(v: PdfValue | undefined): Promise<PdfValue | undefined> {\n return isRef(v) ? this.get(v) : v\n }\n\n /** `followLength` is false while resolving a /Length, so a self-referencing length cannot recurse. */\n private async load(ref: PdfRef, followLength: boolean): Promise<PdfValue | undefined> {\n const entry = this.xref.entries.get(ref.num)\n if (!entry || entry.type === 'free') return undefined\n if (entry.type === 'offset') {\n if (entry.gen !== ref.gen) return undefined\n const obj = parseIndirect(this.bytes, entry.offset)\n return obj.num === ref.num && obj.gen === ref.gen ? obj.value : undefined\n }\n if (ref.gen !== 0) return undefined\n const container = await this.objectStream(entry.stream, followLength)\n if (!container) return undefined\n let pair = container.pairs[entry.index]\n if (pair?.num !== ref.num) pair = container.pairs.find((p) => p.num === ref.num)\n if (!pair) return undefined\n return parseValue(container.decoded, container.first + pair.offset).value\n }\n\n private objectStream(\n num: number,\n followLength: boolean\n ): Promise<ObjectStream | undefined> {\n let cached = this.objectStreams.get(num)\n if (!cached) {\n cached = this.readObjectStream(num, followLength).catch(() => undefined)\n this.objectStreams.set(num, cached)\n }\n return cached\n }\n\n private async readObjectStream(\n num: number,\n followLength: boolean\n ): Promise<ObjectStream | undefined> {\n const entry = this.xref.entries.get(num)\n if (entry?.type !== 'offset') return undefined\n const obj = parseIndirect(this.bytes, entry.offset)\n const dict = obj.value\n if (obj.num !== num || !isDict(dict) || obj.streamStart === undefined)\n return undefined\n const n = dict.entries.get('N')\n const first = dict.entries.get('First')\n if (typeof n !== 'number' || typeof first !== 'number') return undefined\n let length = dict.entries.get('Length')\n if (isRef(length)) length = followLength ? await this.loadLength(length) : undefined\n const decoded = await decodeStream(\n this.bytes,\n dict,\n obj.streamStart,\n typeof length === 'number' ? length : undefined\n )\n const pairs: ObjectStream['pairs'] = []\n let at = 0\n for (let i = 0; i < n; i++) {\n const a = parseValue(decoded, at)\n const b = parseValue(decoded, a.end)\n if (typeof a.value !== 'number' || typeof b.value !== 'number') return undefined\n pairs.push({ num: a.value, offset: b.value })\n at = b.end\n }\n return { decoded, first, pairs }\n }\n\n private async loadLength(ref: PdfRef): Promise<PdfValue | undefined> {\n try {\n return await this.load(ref, false)\n } catch {\n return undefined\n }\n }\n}\n\n/** Undefined when the file is encrypted (`/Encrypt` in the trailer) or its xref cannot be read. */\nexport async function openPdfObjects(bytes: Uint8Array): Promise<PdfObjects | undefined> {\n try {\n const xref = await readXref(bytes)\n if (!xref || xref.trailer.entries.has('Encrypt')) return undefined\n return new Reader(bytes, xref)\n } catch {\n return undefined\n }\n}\n","import type { PdfjsDocument } from './types'\nimport type { Destination, RawDestination } from '../model/destination'\n\n/** A coordinate from a destination array: a finite number, or `undefined` for `null` or junk. */\nfunction coord(value: unknown): number | undefined {\n return typeof value === 'number' && Number.isFinite(value) ? value : undefined\n}\n\n/**\n * The destination `raw` names, through PDF.js, which looks a name up in the catalog's\n * `/Names /Dests` tree and its older `/Dests` dictionary. `undefined` when the name is unknown,\n * the array is malformed, or it names no page of the document.\n */\nexport async function resolveDestination(\n proxy: PdfjsDocument,\n raw: RawDestination\n): Promise<Destination | undefined> {\n try {\n const array: readonly unknown[] | null | undefined =\n typeof raw === 'string' ? await proxy.getDestination(raw) : raw\n if (!array) return undefined\n const target = array[0]\n const page =\n typeof target === 'number'\n ? target\n : typeof target === 'object' && target !== null && 'num' in target\n ? await proxy.getPageIndex(target as { num: number; gen: number })\n : undefined\n if (\n page === undefined ||\n !Number.isInteger(page) ||\n page < 0 ||\n page >= proxy.numPages\n ) {\n return undefined\n }\n const name = (array[1] as { name?: unknown } | null | undefined)?.name\n // Lenient files omit or misspell the fit; the page alone is still a usable target.\n switch (typeof name === 'string' ? name.toLowerCase() : '') {\n case 'xyz':\n return {\n page,\n fit: 'xyz',\n left: coord(array[2]),\n top: coord(array[3]),\n zoom: coord(array[4]),\n }\n case 'fit':\n return { page, fit: 'fit' }\n case 'fitb':\n return { page, fit: 'fitb' }\n case 'fith':\n return { page, fit: 'fith', top: coord(array[2]) }\n case 'fitbh':\n return { page, fit: 'fitbh', top: coord(array[2]) }\n case 'fitv':\n return { page, fit: 'fitv', left: coord(array[2]) }\n case 'fitbv':\n return { page, fit: 'fitbv', left: coord(array[2]) }\n case 'fitr': {\n const [left, bottom, right, top] = [2, 3, 4, 5].map((i) => coord(array[i]))\n if (\n left === undefined ||\n bottom === undefined ||\n right === undefined ||\n top === undefined\n ) {\n return undefined\n }\n // Some writers give the corners in the other order.\n return {\n page,\n fit: 'fitr',\n rect: {\n x: Math.min(left, right),\n y: Math.min(bottom, top),\n width: Math.abs(right - left),\n height: Math.abs(top - bottom),\n },\n }\n }\n default:\n return { page, fit: 'fit' }\n }\n } catch {\n // An unreadable name tree, or a reference that is not a page.\n return undefined\n }\n}\n\n/**\n * The page index a named destination points at. `undefined` when the name is unknown or its\n * destination names no page of the document.\n */\nexport async function destinationPage(\n proxy: PdfjsDocument,\n name: string\n): Promise<number | undefined> {\n return (await resolveDestination(proxy, name))?.page\n}\n","import { applyMatrix, multiplyMatrix, type Matrix } from '../model/geometry'\n\nimport type { PdfjsModule, PdfjsPage } from './types'\nimport type { PageGlyph } from '../model/glyph-advances'\n\ninterface Glyph {\n unicode: string\n width: number\n isSpace: boolean\n}\n\ninterface Font {\n fontMatrix?: readonly number[]\n vertical?: boolean\n isType3Font?: boolean\n}\n\nconst IDENTITY: Matrix = [1, 0, 0, 1, 0, 0]\nconst FONT_IDENTITY = [0.001, 0, 0, 0.001, 0, 0]\n\n/** The parts of PDF.js's canvas state that move the pen, copied on save. */\ninterface State {\n ctm: Matrix\n textMatrix: Matrix\n x: number\n y: number\n lineX: number\n lineY: number\n font: Font\n fontSize: number\n fontDirection: number\n charSpacing: number\n wordSpacing: number\n hScale: number\n leading: number\n rise: number\n}\n\n/**\n * The glyphs a page draws, in content order, with where each starts and where its own width ends\n * in user space. The pen moves the way PDF.js's canvas renderer moves it (`showText` and\n * `showType3Text`): text matrix and moves, the current transformation matrix, font size and font\n * matrix, character and word spacing, horizontal scaling, and `TJ` kerning. Glyphs in vertical\n * fonts are left out. Annotation appearances are not read.\n */\nexport async function pageGlyphs(\n page: PdfjsPage,\n pdfjs: PdfjsModule\n): Promise<PageGlyph[]> {\n const ops = pdfjs.OPS\n const list = await page.getOperatorList({\n annotationMode: pdfjs.AnnotationMode.DISABLE,\n })\n const out: PageGlyph[] = []\n let s: State = {\n ctm: IDENTITY,\n textMatrix: IDENTITY,\n x: 0,\n y: 0,\n lineX: 0,\n lineY: 0,\n font: {},\n fontSize: 0,\n fontDirection: 1,\n charSpacing: 0,\n wordSpacing: 0,\n hScale: 1,\n leading: 0,\n rise: 0,\n }\n const saved: State[] = []\n const save = () => {\n saved.push(s)\n s = { ...s }\n }\n const restore = () => {\n s = saved.pop() ?? s\n }\n const setFont = (name: unknown, size: unknown) => {\n let font: Font = {}\n try {\n font = (page.commonObjs.get(String(name)) as Font | null) ?? {}\n } catch {\n // A font PDF.js has not resolved draws nothing; keep the size so the pen still moves.\n }\n const n = Number(size)\n s.font = font\n s.fontDirection = n < 0 ? -1 : 1\n s.fontSize = Math.abs(n)\n }\n const moveText = (x: number, y: number) => {\n s.x = s.lineX += x\n s.y = s.lineY += y\n }\n const show = (glyphs: readonly (Glyph | number | null)[]) => {\n const { font, fontSize, fontDirection, charSpacing, wordSpacing } = s\n if (fontSize === 0) return\n const fontMatrix = font.fontMatrix ?? FONT_IDENTITY\n const toUser = multiplyMatrix(s.textMatrix, s.ctm)\n const at = (x: number): ReturnType<typeof applyMatrix> =>\n applyMatrix(toUser, { x: s.x + x, y: s.y + s.rise })\n const hScale = s.hScale * fontDirection\n let x = 0\n for (const g of glyphs) {\n if (typeof g === 'number') {\n x += (-g * fontSize) / 1000\n continue\n }\n if (!g) continue\n const spacing = charSpacing + (g.isSpace ? wordSpacing : 0)\n // A Type3 width goes through the whole font matrix; other fonts scale by its first entry.\n const width = font.isType3Font\n ? (g.width * fontMatrix[0]! + fontMatrix[4]!) * fontSize\n : g.width * fontSize * fontMatrix[0]!\n if (!font.vertical) {\n out.push({\n text: g.unicode,\n start: at(x * hScale),\n end: at((x + width) * hScale),\n })\n }\n x += width + spacing * (font.isType3Font ? 1 : fontDirection)\n }\n s.x += x * hScale\n }\n for (let i = 0; i < list.fnArray.length; i++) {\n const args = list.argsArray[i] as unknown[] | null\n switch (list.fnArray[i]) {\n case ops.save:\n save()\n break\n case ops.restore:\n restore()\n break\n case ops.paintFormXObjectBegin:\n save()\n if (args?.[0]) s.ctm = multiplyMatrix(args[0] as unknown as Matrix, s.ctm)\n break\n case ops.paintFormXObjectEnd:\n restore()\n break\n case ops.transform:\n s.ctm = multiplyMatrix(args as unknown as Matrix, s.ctm)\n break\n case ops.beginText:\n s.textMatrix = IDENTITY\n s.x = s.lineX = s.y = s.lineY = 0\n break\n case ops.setTextMatrix:\n s.textMatrix = args![0] as Matrix\n s.x = s.lineX = s.y = s.lineY = 0\n break\n case ops.moveText:\n moveText(Number(args![0]), Number(args![1]))\n break\n case ops.setLeadingMoveText:\n s.leading = Number(args![1])\n moveText(Number(args![0]), Number(args![1]))\n break\n case ops.setLeading:\n s.leading = -Number(args![0])\n break\n case ops.nextLine:\n moveText(0, s.leading)\n break\n case ops.setFont:\n setFont(args![0], args![1])\n break\n case ops.setGState:\n for (const [key, value] of args![0] as [string, unknown][]) {\n if (key === 'Font') {\n const [name, size] = value as [unknown, unknown]\n setFont(name, size)\n }\n }\n break\n case ops.setCharSpacing:\n s.charSpacing = Number(args![0])\n break\n case ops.setWordSpacing:\n s.wordSpacing = Number(args![0])\n break\n case ops.setHScale:\n s.hScale = Number(args![0]) / 100\n break\n case ops.setTextRise:\n s.rise = Number(args![0])\n break\n case ops.showText:\n show(args![0] as (Glyph | number | null)[])\n break\n }\n }\n return out\n}\n","import { InkError } from '../model/errors'\n\nimport type { PdfAssets, PdfjsDocument, PdfjsLoadingTask, PdfjsModule } from './types'\n\nconst REQUIRED: ReadonlyArray<keyof PdfAssets> = [\n 'worker',\n 'cMaps',\n 'standardFonts',\n 'wasm',\n]\n\nexport function assertAssets(value: unknown): asserts value is PdfAssets {\n const record = (typeof value === 'object' && value !== null ? value : {}) as Record<\n string,\n unknown\n >\n const missing = REQUIRED.filter(\n (k) => typeof record[k] !== 'string' || record[k] === ''\n )\n if (value === undefined || value === null || missing.length > 0) {\n throw new InkError(\n 'AssetConfigMissing',\n 'openDocument needs an `assets` option naming the PDF.js worker, cMaps, standardFonts and wasm locations. ' +\n 'Vite users: add the @inkbar/core/vite plugin and pass `assets` from \"virtual:inkbar-assets\".',\n { missing: value == null ? [...REQUIRED] : missing }\n )\n }\n}\n\nlet modulePromise: Promise<PdfjsModule> | undefined\nlet configuredWorker: string | undefined\n\n/**\n * Loads PDF.js once. `#pdfjs` resolves to the legacy build in Node and the\n * modern build everywhere else (see package.json \"imports\").\n */\nexport async function loadPdfjs(assets: PdfAssets): Promise<PdfjsModule> {\n assertAssets(assets)\n modulePromise ??= import('#pdfjs').catch((cause: unknown) => {\n modulePromise = undefined\n throw new InkError(\n 'AssetLoadFailed',\n 'PDF.js could not be imported',\n { url: assets.worker },\n cause\n )\n }) as Promise<PdfjsModule>\n const pdfjs = await modulePromise\n if (configuredWorker === undefined) {\n pdfjs.GlobalWorkerOptions.workerSrc = assets.worker\n configuredWorker = assets.worker\n } else if (configuredWorker !== assets.worker) {\n throw new InkError(\n 'AssetConfigMissing',\n 'PDF.js worker URL cannot change after the first document is opened',\n { configured: configuredWorker, requested: assets.worker }\n )\n }\n return pdfjs\n}\n\nexport interface OpenProxyOptions {\n assets: PdfAssets\n password?: string | undefined\n /** PDF.js log level (0 errors, 1 warnings, 5 infos). Left to PDF.js when omitted. */\n verbosity?: number | undefined\n}\n\nexport async function openProxy(\n pdfjs: PdfjsModule,\n bytes: Uint8Array,\n options: OpenProxyOptions\n): Promise<{ task: PdfjsLoadingTask; proxy: PdfjsDocument }> {\n const { assets, password, verbosity } = options\n const task = pdfjs.getDocument({\n data: bytes,\n ...(password !== undefined ? { password } : {}),\n ...(verbosity !== undefined ? { verbosity } : {}),\n cMapUrl: assets.cMaps,\n cMapPacked: true,\n standardFontDataUrl: assets.standardFonts,\n wasmUrl: assets.wasm,\n ...(assets.icc !== undefined ? { iccUrl: assets.icc } : {}),\n })\n try {\n const proxy = await task.promise\n return { task, proxy }\n } catch (cause: unknown) {\n try {\n await task.destroy()\n } catch {\n // The caller already receives the mapped load error below; a failure\n // while tearing down the half-open task adds nothing actionable.\n }\n throw mapLoadError(cause, { assets, passwordSupplied: password !== undefined })\n }\n}\n\n/** `PasswordResponses` values from PDF.js (`NEED_PASSWORD = 1`, `INCORRECT_PASSWORD = 2`). */\nconst INCORRECT_PASSWORD = 2\n\n/**\n * PDF.js raises these from `task.promise` when the worker script cannot be\n * imported (in browsers after its real Worker fails and the fake-worker\n * fallback also fails to import `workerSrc`).\n */\nconst WORKER_FAILURE =\n /Setting up fake worker failed|No \"GlobalWorkerOptions\\.workerSrc\" specified/i\n\n/**\n * Only the worker is mapped here. CMap, standard-font and wasm failures are\n * PDF.js warnings with fallbacks that never reject the open promise, so they\n * cannot be detected at open time.\n *\n * PDF.js 6 exports only some exception classes (`PasswordException`,\n * `InvalidPDFException`, `ResponseException`, `AbortException`), and errors\n * that cross the worker boundary are rebuilt by name, so match on `name`.\n * Inputs here are always in-memory bytes, so there is no fetch to fail:\n * every non-password failure means the bytes are not a usable PDF.\n */\nexport function mapLoadError(\n cause: unknown,\n context: { assets: PdfAssets; passwordSupplied?: boolean }\n): InkError {\n const { assets, passwordSupplied = false } = context\n const name = (cause as { name?: unknown } | null)?.name\n const rawMessage = (cause as { message?: unknown } | null)?.message\n const message =\n typeof rawMessage === 'string' && rawMessage !== ''\n ? rawMessage\n : 'Unknown PDF.js error'\n if (WORKER_FAILURE.test(message)) {\n return new InkError(\n 'AssetLoadFailed',\n 'The PDF.js worker could not be loaded. Check the `assets.worker` URL.',\n { url: assets.worker },\n cause\n )\n }\n if (name === 'PasswordException') {\n const wrong = (cause as { code?: unknown }).code === INCORRECT_PASSWORD\n return new InkError(\n 'PasswordRequired',\n wrong\n ? 'The password is incorrect'\n : 'This document is encrypted and needs a password',\n { passwordSupplied, incorrect: wrong },\n cause\n )\n }\n // InvalidPDFException, FormatError, UnknownErrorException, MissingPDFException,\n // UnexpectedResponseException, ResponseException and anything unrecognised.\n return new InkError(\n 'InvalidPdf',\n message,\n {\n pdfjsErrorName: typeof name === 'string' ? name : undefined,\n pdfjsMessage: message,\n },\n cause\n )\n}\n","/** Parses a PDF date string (`D:YYYYMMDDHHmmSSOHH'mm'`) into ISO 8601. Returns `fallback` on anything unparseable. */\nexport function parsePdfDate(value: string | null | undefined, fallback: string): string {\n if (!value) return fallback\n const m =\n /^(?:D:)?(\\d{4})(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?(Z|[+-]\\d{2}(?:'\\d{2}')?)?/.exec(\n value.trim()\n )\n if (!m) return fallback\n const [, y, mo = '01', d = '01', h = '00', mi = '00', s = '00', zone] = m\n let offsetMinutes = 0\n if (zone && zone !== 'Z') {\n const sign = zone.startsWith('-') ? -1 : 1\n const zh = Number(zone.slice(1, 3))\n const zm = Number(zone.slice(4, 6) || 0)\n offsetMinutes = sign * (zh * 60 + zm)\n }\n const utc =\n Date.UTC(Number(y), Number(mo) - 1, Number(d), Number(h), Number(mi), Number(s)) -\n offsetMinutes * 60_000\n if (Number.isNaN(utc)) return fallback\n return new Date(utc).toISOString()\n}\n","import type { AnnotationType } from './types'\n\nexport interface AnnotationDefaults {\n color(type: AnnotationType): string\n /** Fill colour for redactions. */\n fill(): string\n opacity(type: AnnotationType): number\n}\n\nconst COLORS: Record<AnnotationType, string> = {\n highlight: '#F2C230',\n underline: '#2B5A9E',\n strikeout: '#C0392B',\n squiggly: '#1F7A4D',\n text: '#F2C230',\n // Free text: the text colour (`defaultStyle.color`). A box's fill has no default.\n freetext: '#151820',\n square: '#C0392B',\n circle: '#C0392B',\n line: '#151820',\n polyline: '#151820',\n polygon: '#151820',\n ink: '#151820',\n // A stamp draws its image; the colour is only what XFDF requires every annotation to carry.\n stamp: '#151820',\n // The loupe's rim.\n loupe: '#151820',\n // The dimming colour.\n mask: '#000000',\n redact: '#C0392B',\n}\n\nexport const staticDefaults: AnnotationDefaults = {\n color: (type) => COLORS[type],\n fill: () => '#000000',\n opacity: (type) => (type === 'highlight' ? 0.4 : 1),\n}\n\nconst VARIABLES: Record<AnnotationType, string> = {\n highlight: '--ink-highlight',\n underline: '--ink-underline',\n strikeout: '--ink-strikeout',\n squiggly: '--ink-squiggly',\n text: '--ink-note',\n freetext: '--ink-free-text',\n square: '--ink-shape',\n circle: '--ink-shape',\n line: '--ink-shape',\n polyline: '--ink-shape',\n polygon: '--ink-shape',\n ink: '--ink-ink',\n stamp: '--ink-ink',\n loupe: '--ink-shape',\n mask: '--ink-mask',\n redact: '--ink-redact',\n}\n\n/** Resolves default colours from CSS custom properties on `el`, falling back to `staticDefaults`. */\nexport function cssVariableDefaults(el: Element): AnnotationDefaults {\n const read = (name: string): string | undefined => {\n const view = el.ownerDocument.defaultView\n if (!view) return undefined\n return normalizeColor(view.getComputedStyle(el).getPropertyValue(name))\n }\n return {\n color: (type) => read(VARIABLES[type]) ?? staticDefaults.color(type),\n fill: () => read('--ink-redact-fill') ?? staticDefaults.fill(),\n opacity: (type) => staticDefaults.opacity(type),\n }\n}\n\n/** Accepts `#rgb`, `#rrggbb`, `rgb(r, g, b)` and `rgb(r g b)`; returns `#RRGGBB` or undefined. */\nexport function normalizeColor(value: string): string | undefined {\n const v = value.trim()\n const short = /^#([0-9a-f])([0-9a-f])([0-9a-f])$/i.exec(v)\n if (short) {\n const [, r = '', g = '', b = ''] = short\n return `#${r}${r}${g}${g}${b}${b}`.toUpperCase()\n }\n if (/^#[0-9a-f]{6}$/i.test(v)) return v.toUpperCase()\n const rgb = /^rgba?\\(\\s*(\\d{1,3})[\\s,]+(\\d{1,3})[\\s,]+(\\d{1,3})/i.exec(v)\n if (rgb) {\n const hex = [rgb[1], rgb[2], rgb[3]]\n .map((n) => Math.min(255, Number(n)).toString(16).padStart(2, '0'))\n .join('')\n return `#${hex}`.toUpperCase()\n }\n return undefined\n}\n","// Free-text callouts as PDF and XFDF store them: `rect` holds box and leader line together,\n// `fringe` insets it to the text box, `callout` runs from the tip to the box and `head` is the\n// ending at the tip.\nimport { Fringe as GlossFringe } from 'gloss-format'\nimport { z } from 'zod'\n\nimport { isKnown, LINE_ENDINGS } from './pdf-names'\n\nimport type { Annotation, FreeTextAnnotation, LineEnding } from './types'\nimport type { Point, Rect } from '../geometry'\n\n/**\n * The insets from a free text's `rect` to its text box, in points (PDF `/RD`, XFDF `fringe`,\n * both in this order).\n */\nexport const FringeSchema = z.object(GlossFringe.shape)\n\nexport type Fringe = z.infer<typeof FringeSchema>\n\n/** An ending's length, and its full width, as a multiple of the stroke width. */\nconst ENDING_SCALE = 3\n\n/**\n * A free text's text box: `rect` inset by `fringe`, or `rect` itself without one. Insets wider\n * or taller than `rect` leave a box of width or height 0 at the inset origin.\n */\nexport function freeTextBox(a: Pick<FreeTextAnnotation, 'rect' | 'fringe'>): Rect {\n const { rect, fringe } = a\n if (!fringe) return rect\n return {\n x: rect.x + fringe.left,\n y: rect.y + fringe.bottom,\n width: Math.max(0, rect.width - fringe.left - fringe.right),\n height: Math.max(0, rect.height - fringe.top - fringe.bottom),\n }\n}\n\n/**\n * True for a free-text callout drawn the standard way: a box with a leader line through\n * `callout`. A callout with `cornerRadius` is Inkbar's speech bubble instead.\n */\nexport function isStandardCallout(\n a: Annotation\n): a is FreeTextAnnotation & { callout: Point[] } {\n return (\n a.type === 'freetext' &&\n a.intent === 'FreeTextCallout' &&\n a.callout !== undefined &&\n a.callout.length >= 2 &&\n a.cornerRadius === undefined\n )\n}\n\n/**\n * The leader line's stroke: the border colour, else the text colour, and the border width, with\n * 1 pt when the box has no border.\n */\nexport function calloutStroke(a: FreeTextAnnotation): { color: string; width: number } {\n return {\n color: a.borderColor ?? a.defaultStyle.color,\n width: a.width > 0 ? a.width : 1,\n }\n}\n\n/**\n * The `rect` and `fringe` that hold the text box `box` and a leader line through `callout`\n * stroked `width` points wide: every point is padded by half the stroke, and by the ending's\n * size as well when `head` is one Inkbar draws.\n */\nexport function withCalloutBounds(\n box: Rect,\n callout: readonly Point[],\n width: number,\n head: LineEnding | undefined\n): { rect: Rect; fringe: Fringe } {\n const drawn = head !== undefined && head !== 'None' && isKnown(LINE_ENDINGS, head)\n const pad = width / 2 + (drawn ? ENDING_SCALE * Math.max(width, 1) : 0)\n const xs = [box.x, box.x + box.width, ...callout.map((p) => p.x)]\n const ys = [box.y, box.y + box.height, ...callout.map((p) => p.y)]\n const left = Math.min(...xs) - pad\n const bottom = Math.min(...ys) - pad\n const right = Math.max(...xs) + pad\n const top = Math.max(...ys) + pad\n return {\n rect: { x: left, y: bottom, width: right - left, height: top - bottom },\n fringe: {\n left: box.x - left,\n top: top - (box.y + box.height),\n right: right - (box.x + box.width),\n bottom: box.y - bottom,\n },\n }\n}\n","import {\n Circle,\n Color,\n commonFields,\n FreeText,\n FreeTextStyle as GlossFreeTextStyle,\n GLOSS_FORMAT,\n GLOSS_VERSION,\n Highlight,\n Ink,\n Line,\n LineEnding as GlossLineEnding,\n Note,\n NoteIcon,\n Point,\n Polygon,\n Polyline,\n Rect,\n Redact,\n Square,\n Stamp,\n type Annotation as GlossAnnotation,\n type GlossDocument,\n type UnknownAnnotation,\n} from 'gloss-format'\nimport { z } from 'zod'\n\nimport { FringeSchema } from './callout'\n\nimport type { FieldValue } from '../form/types'\n\nexport {\n GLOSS_FORMAT,\n GLOSS_MEDIA_TYPE,\n GLOSS_SCHEMA_ID,\n GLOSS_VERSION,\n} from 'gloss-format'\n\n// Each schema starts from its Gloss definition and rebuilds it as a plain object, so unknown keys\n// are dropped on import, nested ones included. Inkbar then requires what it always fills in.\n\nexport const PointSchema = z.object(Point.shape)\nexport const RectSchema = z.object(Rect.shape)\nexport const QuadSchema = z.object({\n p1: PointSchema,\n p2: PointSchema,\n p3: PointSchema,\n p4: PointSchema,\n})\n\n/** What Inkbar adds to every Gloss type: the fields it always fills in, and its viewer state. */\nconst Base = {\n /** Bounding box in PDF user space. */\n rect: RectSchema,\n /** Resolved #RRGGBB. Written into the PDF later, so it is always concrete. */\n color: Color,\n opacity: commonFields.opacity.removeDefault(),\n createdAt: commonFields.createdAt.unwrap(),\n modifiedAt: commonFields.modifiedAt.unwrap(),\n /** Created in this session, or imported from the file. Viewer state, never exported. */\n source: z.enum(['session', 'pdf']),\n /** Embedded annotations are locked until the engine can rewrite the file. Viewer state, never exported. */\n locked: z.boolean().optional(),\n /**\n * Embedded annotations only: whether the file carries its own appearance stream for it. PDF.js\n * paints the page with it; without one, it paints a stand-in for most types but nothing for a\n * note. Viewer state, never exported.\n */\n hasAppearance: z.boolean().optional(),\n}\n\nconst Quads = z.array(QuadSchema).min(1)\n\nexport const TextMarkupSchema = z.object({\n ...Highlight.shape,\n ...Base,\n type: z.enum(['highlight', 'underline', 'strikeout', 'squiggly']),\n quads: Quads,\n})\n\n/** A note's icon (XFDF `icon`): a PDF name, so a name Inkbar does not know is kept. */\nexport const NoteIconSchema = NoteIcon\n\nexport const NoteSchema = z.object({ ...Note.shape, ...Base })\n\n/** A line ending (XFDF `head`/`tail`): a PDF name, so a name Inkbar does not know is kept. */\nexport const LineEndingSchema = GlossLineEnding\n\n/**\n * A key a type refuses outright rather than dropping like other unknown keys: one an older\n * shape used (so its value is not silently lost), or one that means nothing on the type (so a\n * later version is free to give it a meaning).\n */\nconst Refused = z.never().optional()\n\n/**\n * A free-text box's text style, keyed by the CSS property names XFDF writes in its\n * `defaultstyle` string. The older `align` is refused; other unknown keys are dropped.\n */\nexport const FreeTextStyleSchema = z.object({\n ...GlossFreeTextStyle.shape,\n /** The text colour. */\n color: Color,\n align: Refused,\n})\n\n/**\n * Free text, as XFDF has it: `color` is the box's fill and the text style lives in\n * `defaultStyle`. A box in the older shape (top-level `fontFamily`, `fontSize`, `align`) is\n * refused rather than silently losing its style; other unknown keys are dropped.\n */\nexport const FreeTextSchema = z.object({\n ...FreeText.shape,\n ...Base,\n /** The box's fill (XFDF `color`). Absent means no fill. */\n color: FreeText.shape.color,\n /** The box's border colour. Absent means the text colour. */\n borderColor: Color.optional(),\n defaultStyle: FreeTextStyleSchema,\n fringe: FringeSchema.optional(),\n callout: z.array(PointSchema).min(2).max(3).optional(),\n fontFamily: Refused,\n fontSize: Refused,\n align: Refused,\n})\n\nexport const SquareSchema = z.object({ ...Square.shape, ...Base })\n\nexport const CircleSchema = z.object({ ...Circle.shape, ...Base, cornerRadius: Refused })\n\nexport const ShapeSchema = z.discriminatedUnion('type', [SquareSchema, CircleSchema])\n\nexport const LineSchema = z.object({\n ...Line.shape,\n ...Base,\n start: PointSchema,\n end: PointSchema,\n})\n\nconst Vertices = z.array(PointSchema).min(2)\n\nexport const PolylineSchema = z.object({ ...Polyline.shape, ...Base, vertices: Vertices })\n\nexport const PolygonSchema = z.object({\n ...Polygon.shape,\n ...Base,\n vertices: Vertices,\n head: Refused,\n tail: Refused,\n})\n\nexport const PolySchema = z.discriminatedUnion('type', [PolylineSchema, PolygonSchema])\n\nconst InkShape = z.object({\n ...Ink.shape,\n ...Base,\n inklist: z.array(z.array(PointSchema).min(1)).min(1),\n /** Pen pressure from 0 to 1, one value per point of each stroke. Absent means even pressure. */\n pressure: z.array(z.array(z.number().min(0).max(1))).optional(),\n})\n\n/** Pressure must have one value per point of each stroke. */\nfunction checkPressure(\n a: { inklist: unknown[][]; pressure?: unknown[][] | undefined },\n ctx: z.core.$RefinementCtx\n): void {\n if (!a.pressure) return\n const ok =\n a.pressure.length === a.inklist.length &&\n a.pressure.every((p, i) => p.length === a.inklist[i]?.length)\n if (!ok)\n ctx.addIssue({\n code: 'custom',\n path: ['pressure'],\n message: 'pressure must have the same shape as inklist',\n })\n}\n\nexport const InkSchema = InkShape.superRefine(checkPressure)\n\n/** A PNG or JPEG image as a base64 `data:` URL, as XFDF carries a stamp's `<imagedata>`. */\nexport { IMAGE_DATA_URL } from 'gloss-format'\n\n/**\n * An image on the page (XFDF `stamp`), drawn to fill `rect`. Image and typed signatures are\n * stamps with `subject: 'Signature'`.\n */\nexport const StampSchema = z.object({ ...Stamp.shape, ...Base })\n\n/**\n * A loupe (Inkbar's own type, a circle with `custom.inkbar.type: 'loupe'` in a file): a circle\n * inscribed in `rect` that shows the page content under its own centre, magnified. `color` and\n * `width` draw its rim.\n */\nexport const LoupeSchema = z.object({\n type: z.literal('loupe'),\n ...commonFields,\n /** How many times larger the content under the centre is drawn. Above 1. */\n magnification: z.number().gt(1).default(2),\n /** The rim's width in points. */\n width: z.number().nonnegative().default(2),\n ...Base,\n})\n\n/**\n * A mask (Inkbar's own type, a circle or square with `custom.inkbar.type: 'mask'` in a file):\n * dims everything on the page outside `shape` drawn in `rect`, an ellipse inscribed in it or the\n * rectangle itself. `color` is the dimming colour and `dim` how strongly it covers, from 0 to 1.\n * One per page: adding a second replaces the first.\n */\nexport const MaskSchema = z.object({\n type: z.literal('mask'),\n ...commonFields,\n shape: z.enum(['rect', 'ellipse']),\n dim: z.number().min(0).max(1).default(0.5),\n ...Base,\n})\n\nexport const RedactSchema = z.object({\n ...Redact.shape,\n ...Base,\n /** Present when the mark came from text; absent for an area mark. */\n quads: Quads.optional(),\n /** Colour the redaction will be filled with when applied. */\n interiorColor: Color,\n})\n\nexport const AnnotationSchema = z.discriminatedUnion('type', [\n TextMarkupSchema,\n NoteSchema,\n FreeTextSchema,\n SquareSchema,\n CircleSchema,\n LineSchema,\n PolylineSchema,\n PolygonSchema,\n InkSchema,\n StampSchema,\n LoupeSchema,\n MaskSchema,\n RedactSchema,\n])\n\n/** The viewer's own state on an annotation, left out of exports. */\nconst VIEWER_STATE = { source: true, locked: true, hasAppearance: true } as const\n\n/** One exported annotation: the stored annotation without its viewer state. */\nexport const ExportedAnnotationSchema = z.discriminatedUnion('type', [\n TextMarkupSchema.omit(VIEWER_STATE),\n NoteSchema.omit(VIEWER_STATE),\n FreeTextSchema.omit(VIEWER_STATE),\n SquareSchema.omit(VIEWER_STATE),\n CircleSchema.omit(VIEWER_STATE),\n LineSchema.omit(VIEWER_STATE),\n PolylineSchema.omit(VIEWER_STATE),\n PolygonSchema.omit(VIEWER_STATE),\n InkShape.omit(VIEWER_STATE).superRefine(checkPressure),\n StampSchema.omit(VIEWER_STATE),\n LoupeSchema.omit(VIEWER_STATE),\n MaskSchema.omit(VIEWER_STATE),\n RedactSchema.omit(VIEWER_STATE),\n])\n\nexport type Annotation = z.infer<typeof AnnotationSchema>\nexport type ExportedAnnotation = z.infer<typeof ExportedAnnotationSchema>\nexport type AnnotationType = Annotation['type']\nexport type AnnotationOfType<T extends AnnotationType> = Extract<Annotation, { type: T }>\nexport type TextMarkupAnnotation = z.infer<typeof TextMarkupSchema>\nexport type NoteAnnotation = z.infer<typeof NoteSchema>\nexport type FreeTextAnnotation = z.infer<typeof FreeTextSchema>\nexport type FreeTextStyle = z.infer<typeof FreeTextStyleSchema>\nexport type ShapeAnnotation = z.infer<typeof ShapeSchema>\nexport type LineAnnotation = z.infer<typeof LineSchema>\nexport type PolyAnnotation = z.infer<typeof PolySchema>\nexport type InkAnnotation = z.infer<typeof InkSchema>\nexport type StampAnnotation = z.infer<typeof StampSchema>\nexport type LoupeAnnotation = z.infer<typeof LoupeSchema>\nexport type MaskAnnotation = z.infer<typeof MaskSchema>\nexport type RedactAnnotation = z.infer<typeof RedactSchema>\nexport type LineEnding = z.infer<typeof LineEndingSchema>\n/**\n * What `update` takes: any of a type's fields. A free-text `defaultStyle` may be partial; it\n * merges into the current one.\n */\nexport type AnnotationPatch = Annotation extends infer A\n ? A extends FreeTextAnnotation\n ? Omit<Partial<A>, 'defaultStyle'> & { defaultStyle?: Partial<FreeTextStyle> }\n : Partial<A>\n : never\n// Point, Rect and Quad types come from ../geometry; the zod schemas above match them structurally.\n\n/** Keys the store fills in; callers never supply them (except an optional `id`). */\ntype Generated = 'id' | 'createdAt' | 'modifiedAt' | 'source' | 'locked'\n/** Keys the store derives or defaults when absent. */\ntype Defaulted = 'rect' | 'color' | 'opacity'\n\n/** Builds the caller-facing shape of one member from its zod input type. */\ntype InputOf<I> = I extends unknown\n ? Omit<I, Generated | Defaulted> &\n Partial<Pick<I, Extract<Defaulted, keyof I>>> & { id?: string }\n : never\n\ntype FreeTextInput = z.input<typeof FreeTextSchema>\n/** Free text may leave out `defaultStyle`, or any of its keys: the store fills the text colour. */\ntype FreeTextCallerInput = Omit<InputOf<FreeTextInput>, 'defaultStyle'> & {\n defaultStyle?: Partial<z.input<typeof FreeTextStyleSchema>>\n}\n\ntype RedactInput = z.input<typeof RedactSchema>\ntype RedactBase = Omit<InputOf<RedactInput>, 'interiorColor' | 'rect' | 'quads'> & {\n interiorColor?: string\n}\ntype RedactCallerInput =\n | (RedactBase & { rect: RedactInput['rect']; quads?: RedactInput['quads'] })\n | (RedactBase & {\n rect?: RedactInput['rect']\n quads: NonNullable<RedactInput['quads']>\n })\n\n/**\n * What callers pass to `add`. Built from zod input types, so fields with defaults or\n * optional fields may be omitted. A redaction needs `rect` or `quads` (the store\n * derives the other), and `interiorColor` defaults to the store's redaction colour. Free text\n * may leave out `defaultStyle`; its text colour defaults to the store's free-text colour.\n */\nexport type AnnotationInput =\n | InputOf<\n | z.input<typeof TextMarkupSchema>\n | z.input<typeof NoteSchema>\n | z.input<typeof ShapeSchema>\n | z.input<typeof LineSchema>\n | z.input<typeof PolySchema>\n | z.input<typeof InkSchema>\n >\n | (InputOf<z.input<typeof StampSchema>> & { rect: z.input<typeof StampSchema>['rect'] })\n | (InputOf<z.input<typeof LoupeSchema>> & { rect: z.input<typeof LoupeSchema>['rect'] })\n | (InputOf<z.input<typeof MaskSchema>> & { rect: z.input<typeof MaskSchema>['rect'] })\n | FreeTextCallerInput\n | RedactCallerInput\n\nexport const AnnotationDocumentSchema = z.object({\n format: z.literal(GLOSS_FORMAT),\n version: z.literal(GLOSS_VERSION),\n documentKey: z.string().optional(),\n /** Validated item by item on import so unknown types can be preserved. */\n annotations: z.array(z.unknown()),\n /** Form field values by full name, validated field by field against the form on import. */\n fields: z.record(z.string(), z.unknown()).optional(),\n})\n\n/**\n * An item whose `type` this version does not know, such as one from a newer writer. It is kept\n * as-is so it survives an import and export round trip.\n */\nexport type ForeignAnnotation = UnknownAnnotation\n\n/** A Gloss document holding Inkbar's annotations and any foreign items it kept. */\nexport interface AnnotationDocument {\n format: GlossDocument['format']\n version: GlossDocument['version']\n documentKey?: string\n annotations: Array<GlossAnnotation | ForeignAnnotation>\n /** Form field values by full name: each field that has one and is not no-export. */\n fields?: Record<string, FieldValue>\n}\n","import {\n pointsFromFlat,\n quadsFromFlat,\n rectFromPoints,\n type Point,\n type Quad,\n type Rect,\n} from '../geometry'\nimport { parsePdfDate } from '../pdf-date'\n\nimport { staticDefaults } from './defaults'\nimport { PDF_NAME } from './pdf-names'\nimport { AnnotationSchema, type Annotation } from './types'\n\nimport type { Fringe } from './callout'\nimport type { PdfjsAnnotationData } from '../../pdfjs/types'\n\nexport const SUPPORTED_SUBTYPES: ReadonlySet<string> = new Set([\n 'Highlight',\n 'Underline',\n 'StrikeOut',\n 'Squiggly',\n 'Text',\n 'FreeText',\n 'Square',\n 'Circle',\n 'Line',\n 'Polygon',\n 'PolyLine',\n 'Ink',\n 'Redact',\n])\n\n/** Subtypes the document reads as links rather than annotations. */\nconst LINK_SUBTYPES: ReadonlySet<string> = new Set(['Link'])\n\nexport interface EmbeddedSummary {\n subtype: string\n count: number\n supported: boolean\n}\n\n/** An RGB colour in 0–255 as upper-case `#RRGGBB`; `fallback` when it has fewer than three parts. */\nexport function pdfColorToHex(\n c: ArrayLike<number> | null | undefined,\n fallback: string\n): string {\n if (!c || c.length < 3) return fallback\n const hex = [c[0]!, c[1]!, c[2]!]\n .map((n) => Math.round(n).toString(16).padStart(2, '0'))\n .join('')\n return `#${hex}`.toUpperCase()\n}\n\n/** PDF.js hands back `rect` already in user space, but not always ordered; normalise with min/max. */\nfunction rectFromPdf(r: ArrayLike<number>): Rect {\n return rectFromPoints({ x: r[0]!, y: r[1]! }, { x: r[2]!, y: r[3]! })\n}\n\n/** A PDF name exactly as PDF.js gives it (names are case-sensitive), or undefined if invalid. */\nfunction pdfName(raw: string | undefined): string | undefined {\n return raw !== undefined && PDF_NAME.test(raw) ? raw : undefined\n}\n\n/** `head` and `tail` from a Line's or PolyLine's `/LE`, left out when both are `None`. */\nfunction lineEndingsOf(\n raw: readonly string[] | undefined\n): { head: string; tail: string } | Record<string, never> {\n // PDF.js already turns a name it does not know into `None`.\n const endings = raw?.map((e) => pdfName(e) ?? 'None')\n return endings && endings.length === 2 && endings.some((e) => e !== 'None')\n ? { head: endings[0]!, tail: endings[1]! }\n : {}\n}\n\n/**\n * Imported ids are `pdf:<page>:<pdfjsId>` (page is 0-based, pdfjsId is the annotation's object\n * reference such as `12R`). They are stable across opens of the same file, and `inReplyTo`\n * uses the same scheme so threads resolve.\n */\nexport function importedId(page: number, pdfjsId: string): string {\n return `pdf:${page}:${pdfjsId}`\n}\n\n/**\n * @internal An imported annotation whose fields PDF.js leaves out, to be read from the file itself once\n * the document is ready: a FreeText's `/CL`, `/RD`, `/LE` and `/DA` font, or a note's `/Name`\n * when PDF.js reports `NoIcon`.\n */\nexport interface EmbeddedTarget {\n /** The imported id, `pdf:<page>:<pdfjsId>`. */\n id: string\n subtype: 'FreeText' | 'Text'\n /** The annotation's `/Rect` as PDF.js gives it, `[x1, y1, x2, y2]`. */\n rect: readonly number[]\n /** FreeText only: the `/DA` font resource name. */\n daFont?: string\n}\n\n/**\n * The fields read from the file for one embedded annotation: what PDF.js left out. They merge\n * onto the annotation as it is when they land, so edits made in between are kept.\n */\nexport interface EmbeddedFieldPatch {\n /** FreeText `/CL`: the tip, an optional bend, and where the line meets the box. */\n callout?: Point[]\n /** FreeText `/RD`. */\n fringe?: Fringe\n /** FreeText `/LE`. */\n head?: string\n /** Text `/Name`. */\n icon?: string\n /** FreeText `/DA` font, merged into `defaultStyle`. */\n font?: { fontFamily?: string; fontWeight?: 'bold'; fontStyle?: 'italic' }\n}\n\n/**\n * Imports one page's PDF.js annotation data. `targets` is @internal: the annotations whose\n * missing fields the document reads from the file after `ready`.\n */\nexport function importEmbeddedPage(\n page: number,\n raw: PdfjsAnnotationData[],\n importedAt: string\n): {\n annotations: Annotation[]\n counts: Record<string, number>\n targets: EmbeddedTarget[]\n} {\n const counts: Record<string, number> = {}\n const annotations: Annotation[] = []\n const targets: EmbeddedTarget[] = []\n for (const data of raw) {\n counts[data.subtype] = (counts[data.subtype] ?? 0) + 1\n if (!SUPPORTED_SUBTYPES.has(data.subtype) || data.hidden || data.noView) continue\n const converted = convert(page, data, importedAt)\n if (!converted) continue\n annotations.push(converted)\n const target = targetOf(converted.id, data)\n if (target) targets.push(target)\n }\n return { annotations, counts, targets }\n}\n\nfunction targetOf(id: string, d: PdfjsAnnotationData): EmbeddedTarget | undefined {\n const rect = Array.from(d.rect)\n if (d.subtype === 'Text')\n return d.name === 'NoIcon' ? { id, subtype: 'Text', rect } : undefined\n if (d.subtype !== 'FreeText') return undefined\n const daFont = d.defaultAppearanceData?.fontName\n return { id, subtype: 'FreeText', rect, ...(daFont ? { daFont } : {}) }\n}\n\nexport function summarise(perPage: Record<string, number>[]): EmbeddedSummary[] {\n const totals = new Map<string, number>()\n for (const counts of perPage) {\n for (const [k, v] of Object.entries(counts)) totals.set(k, (totals.get(k) ?? 0) + v)\n }\n return [...totals.entries()]\n .map(([subtype, count]) => ({\n subtype,\n count,\n supported: SUPPORTED_SUBTYPES.has(subtype) || LINK_SUBTYPES.has(subtype),\n }))\n .sort((a, b) => (a.subtype < b.subtype ? -1 : a.subtype > b.subtype ? 1 : 0))\n}\n\nfunction convert(\n page: number,\n d: PdfjsAnnotationData,\n importedAt: string\n): Annotation | undefined {\n const created = parsePdfDate(\n d.creationDate,\n parsePdfDate(d.modificationDate, importedAt)\n )\n const author = d.titleObj?.str\n const contents = d.contentsObj?.str\n const stroke = d.borderStyle?.width ?? 1\n const quads: Quad[] = d.quadPoints ? quadsFromFlat(d.quadPoints) : []\n const optional = (v: unknown) => v !== undefined && v !== ''\n const withColor = (type: Annotation['type'], source = d.color) =>\n pdfColorToHex(source, staticDefaults.color(type))\n const intent = pdfName(d.it)\n const base = (type: Annotation['type'], color = withColor(type)) => ({\n id: importedId(page, d.id),\n page,\n rect: rectFromPdf(d.rect),\n color,\n opacity: d.opacity ?? 1,\n ...(optional(author) ? { author } : {}),\n ...(optional(contents) ? { contents } : {}),\n ...(d.inReplyTo ? { inReplyTo: importedId(page, d.inReplyTo) } : {}),\n ...(intent !== undefined ? { intent } : {}),\n createdAt: created,\n modifiedAt: parsePdfDate(d.modificationDate, created),\n source: 'pdf' as const,\n locked: true,\n hasAppearance: d.hasAppearance === true,\n })\n const fillOf = (c: ArrayLike<number> | null | undefined) =>\n c && c.length >= 3 ? { interiorColor: pdfColorToHex(c, '#FFFFFF') } : {}\n\n let candidate: Record<string, unknown>\n switch (d.subtype) {\n case 'Highlight':\n case 'Underline':\n case 'StrikeOut':\n case 'Squiggly': {\n if (quads.length === 0) return undefined\n const type =\n d.subtype === 'StrikeOut' ? 'strikeout' : (d.subtype.toLowerCase() as 'highlight')\n candidate = { ...base(type), type, quads }\n break\n }\n case 'Text': {\n // PDF.js reports `NoIcon` for any note with an appearance stream, hiding its `/Name`.\n // Leave the icon out then, as when there is no `/Name`, so the default `Note` applies.\n const icon = d.name === 'NoIcon' ? undefined : pdfName(d.name)\n candidate = {\n ...base('text'),\n type: 'text',\n ...(icon !== undefined ? { icon } : {}),\n }\n break\n }\n case 'FreeText': {\n // XFDF and PDF agree: `/C` is the box's fill, `/DA` the text's colour and size.\n const da = d.defaultAppearanceData\n const { color: _stroke, ...rest } = base('freetext')\n candidate = {\n ...rest,\n ...(d.color && d.color.length >= 3\n ? { color: pdfColorToHex(d.color, '#FFFFFF') }\n : {}),\n type: 'freetext',\n contents: contents ?? '',\n width: d.borderStyle?.width ?? 0,\n defaultStyle: {\n color: pdfColorToHex(\n da?.fontColor as ArrayLike<number> | undefined,\n staticDefaults.color('freetext')\n ),\n ...(da && da.fontSize > 0 ? { fontSize: da.fontSize } : {}),\n },\n }\n break\n }\n case 'Square':\n case 'Circle': {\n const type = d.subtype.toLowerCase() as 'square' | 'circle'\n candidate = { ...base(type), type, width: stroke, ...fillOf(d.interiorColor) }\n break\n }\n case 'Line': {\n const l = d.lineCoordinates ?? [d.rect[0], d.rect[1], d.rect[2], d.rect[3]]\n candidate = {\n ...base('line'),\n type: 'line',\n start: { x: l[0], y: l[1] },\n end: { x: l[2], y: l[3] },\n width: stroke,\n ...lineEndingsOf(d.lineEndings),\n }\n break\n }\n case 'Polygon':\n case 'PolyLine': {\n const type = d.subtype === 'Polygon' ? 'polygon' : 'polyline'\n const vertices = d.vertices ? pointsFromFlat(d.vertices) : []\n if (vertices.length < 2) return undefined\n candidate = {\n ...base(type),\n type,\n vertices,\n width: stroke,\n ...fillOf(d.interiorColor),\n ...(type === 'polyline' ? lineEndingsOf(d.lineEndings) : {}),\n }\n break\n }\n case 'Ink': {\n const inklist: Point[][] = (d.inkLists ?? [])\n .map((p) => pointsFromFlat(p))\n .filter((p) => p.length > 0)\n if (inklist.length === 0) return undefined\n candidate = { ...base('ink'), type: 'ink', inklist, width: stroke }\n break\n }\n case 'Redact':\n // PDF.js 6.4 exposes neither QuadPoints nor /OverlayText for Redact, so only quads\n // that happen to be present are used, and `overlaidText` (the text beneath) is ignored.\n candidate = {\n ...base('redact'),\n type: 'redact',\n interiorColor: pdfColorToHex(d.interiorColor, staticDefaults.fill()),\n ...(quads.length > 0 ? { quads } : {}),\n }\n break\n default:\n return undefined\n }\n const parsed = AnnotationSchema.safeParse(candidate)\n return parsed.success ? parsed.data : undefined\n}\n","import type { Rect } from './geometry'\n\n/**\n * Where a link or outline item goes: a page and how to frame it, as the PDF destination types\n * describe it. Every coordinate is PDF user space in points, origin bottom-left, before /Rotate.\n * `page` is 0-based. A missing coordinate (`null` in the file) is left as it is on screen.\n */\nexport type Destination =\n | {\n page: number\n fit: 'xyz'\n left?: number | undefined\n top?: number | undefined\n zoom?: number | undefined\n }\n | { page: number; fit: 'fit' | 'fitb' }\n | { page: number; fit: 'fith' | 'fitbh'; top?: number | undefined }\n | { page: number; fit: 'fitv' | 'fitbv'; left?: number | undefined }\n | { page: number; fit: 'fitr'; rect: Rect }\n\n/** A destination as a PDF holds it: a name to look up, or an explicit `[page, /Fit, ...]` array. */\nexport type RawDestination = string | readonly unknown[]\n\n/** The page-navigation actions a Named link can ask for. */\nexport type NamedAction = 'NextPage' | 'PrevPage' | 'FirstPage' | 'LastPage'\n\nconst NAMED_ACTIONS: readonly string[] = ['NextPage', 'PrevPage', 'FirstPage', 'LastPage']\n\n/** Whether `s` is one of the four page-navigation actions Inkbar follows. */\nexport function isNamedAction(s: unknown): s is NamedAction {\n return typeof s === 'string' && NAMED_ACTIONS.includes(s)\n}\n\n/**\n * What a link or outline item points at, before it is followed: a destination still to resolve\n * (`dest`) or already resolved, a URL for the host to open, a page-navigation action, or a target\n * Inkbar does not follow (another file, an app to launch, a URL with an unsafe scheme).\n */\nexport type LinkTarget =\n | { kind: 'dest'; raw: RawDestination }\n | { kind: 'resolved'; dest: Destination }\n | { kind: 'url'; url: string; newWindow: boolean }\n | { kind: 'named'; action: NamedAction }\n | { kind: 'unsupported'; reason: 'remote' | 'launch' | 'unsafe-url' | 'unknown' }\n","/** The schemes a form may hand the host, as PDF.js allows for `/URI`. */\nconst SAFE = new Set(['http:', 'https:', 'mailto:', 'tel:'])\n\n/**\n * `url` when it is absolute and uses http, https, mailto or tel; otherwise `undefined`, so a\n * `javascript:`, `data:`, `file:` or relative URL from a PDF never reaches the host.\n */\nexport function safeUrl(url: string): string | undefined {\n try {\n return SAFE.has(new URL(url).protocol) ? url : undefined\n } catch {\n return undefined\n }\n}\n\n/**\n * A mail address, kept unless it reads as a URL with another scheme (a script passing\n * `javascript:…` as a recipient). A `mailto:` or `tel:` prefix is kept as it was given, not\n * stripped, so the host may see `mailto:a@example.com` as a recipient.\n */\nexport function safeAddress(address: string): string | undefined {\n try {\n return SAFE.has(new URL(address).protocol) ? address : undefined\n } catch {\n return address\n }\n}\n","import { importedId } from './annotations/embedded'\nimport { isNamedAction, type LinkTarget } from './destination'\nimport { safeUrl } from './form/url'\nimport { quadsFromFlat, rectFromPoints, type Quad, type Rect } from './geometry'\n\nimport type { PdfjsAnnotationData } from '../pdfjs/types'\n\n/** A clickable region of a page: where it is and where it goes. */\nexport interface PageLink {\n /** Stable across opens of the same file, as imported annotation ids are. */\n id: string\n /** 0-based. */\n page: number\n /** User space, before /Rotate. */\n rect: Rect\n /** One quad per line when the link wraps; the rect is their bounds. */\n quads?: Quad[]\n /** Position in the page's `/Annots`, which Tab follows unless the page's `/Tabs` says otherwise. */\n order?: number\n target: LinkTarget\n}\n\n/** A URL with a scheme of its own, as opposed to a file name or relative path. */\nconst HAS_SCHEME = /^[a-z][a-z0-9+.-]*:/i\n\n/**\n * Why PDF.js's `unsafeUrl` was not passed on. PDF.js reads a GoToR's file and destination into\n * `file#dest`, and a Launch's file as a bare name, so those two are told apart by the `#`; a\n * scheme `safeUrl` refuses (`javascript:`, `file:`, `data:`) is unsafe whatever follows it.\n */\nfunction unsafeReason(unsafeUrl: string): 'remote' | 'launch' | 'unsafe-url' {\n if (HAS_SCHEME.test(unsafeUrl)) return 'unsafe-url'\n return unsafeUrl.includes('#') ? 'remote' : 'launch'\n}\n\n/** The fields PDF.js gives a link, and an outline item, for where it goes. */\nexport type PdfjsTargetFields = Pick<\n PdfjsAnnotationData,\n 'dest' | 'action' | 'url' | 'unsafeUrl' | 'newWindow'\n>\n\n/**\n * Where a link or outline item goes, from what PDF.js read of its `/Dest` or `/A`. A\n * destination stays raw (`dest`); a URL is passed only through `safeUrl`.\n */\nexport function targetOf(data: PdfjsTargetFields): LinkTarget {\n if (data.dest !== undefined && data.dest !== null)\n return { kind: 'dest', raw: data.dest }\n if (isNamedAction(data.action)) return { kind: 'named', action: data.action }\n if (data.url) {\n const url = safeUrl(data.url)\n if (url) return { kind: 'url', url, newWindow: !!data.newWindow }\n }\n if (data.unsafeUrl) {\n // PDF.js may repeat a safe `url` here; only what `safeUrl` refuses is unsafe.\n return safeUrl(data.unsafeUrl)\n ? { kind: 'unsupported', reason: 'unknown' }\n : { kind: 'unsupported', reason: unsafeReason(data.unsafeUrl) }\n }\n return { kind: 'unsupported', reason: 'unknown' }\n}\n\n/**\n * A link annotation read from PDF.js, or `undefined` for anything that is not a visible link.\n * Links are never Gloss annotations: they are read-only structure of the file. `order` is its\n * position in the page's `/Annots`.\n */\nexport function linkFromPdfjs(\n page: number,\n data: PdfjsAnnotationData,\n order?: number\n): PageLink | undefined {\n if (data.subtype !== 'Link' || data.hidden || data.noView) return undefined\n const quads = data.quadPoints ? quadsFromFlat(data.quadPoints) : []\n return {\n id: importedId(page, data.id),\n page,\n rect: rectFromPoints(\n { x: data.rect[0], y: data.rect[1] },\n { x: data.rect[2], y: data.rect[3] }\n ),\n ...(quads.length > 0 ? { quads } : {}),\n ...(order === undefined ? {} : { order }),\n target: targetOf(data),\n }\n}\n","/** Runs `task(0..count-1)` with at most `limit` in flight; results come back in index order. */\nexport async function mapInOrder<T>(\n count: number,\n limit: number,\n task: (index: number) => Promise<T>\n): Promise<T[]> {\n const results = new Array<T>(count)\n let next = 0\n const worker = async (): Promise<void> => {\n while (next < count) {\n const i = next++\n results[i] = await task(i)\n }\n }\n await Promise.all(Array.from({ length: Math.min(limit, count) }, worker))\n return results\n}\n","import { targetOf, type PdfjsTargetFields } from '../model/links'\nimport { mapInOrder } from '../model/map-in-order'\n\nimport { resolveDestination } from './destinations'\n\nimport type { PdfjsDocument } from './types'\nimport type { Destination, RawDestination } from '../model/destination'\nimport type { OutlineItem } from '../model/outline'\n\n/** Destinations looked up at once. A long outline names many, each a request to the worker. */\nconst CONCURRENCY = 8\n\n/** One node of `getOutline()`, limited to the fields Inkbar reads. */\ninterface PdfjsOutlineNode extends PdfjsTargetFields {\n title: string\n bold?: boolean\n italic?: boolean\n /** `/Count`: positive when the item starts expanded. */\n count?: number | undefined\n items: PdfjsOutlineNode[]\n}\n\n/**\n * The document's outline, every destination resolved in full: the current item needs each\n * one's position. `[]` when the file has none or PDF.js cannot read it.\n */\nexport async function readOutline(proxy: PdfjsDocument): Promise<OutlineItem[]> {\n const roots = (await proxy.getOutline().catch(() => null)) as PdfjsOutlineNode[] | null\n if (!roots || roots.length === 0) return []\n\n // Destinations in document order, resolved together, then handed out in the same order.\n const raws: RawDestination[] = []\n const collect = (nodes: readonly PdfjsOutlineNode[]): void => {\n for (const node of nodes) {\n const target = targetOf(node)\n if (target.kind === 'dest') raws.push(target.raw)\n collect(node.items ?? [])\n }\n }\n collect(roots)\n const dests: (Destination | undefined)[] = await mapInOrder(\n raws.length,\n CONCURRENCY,\n (i) => resolveDestination(proxy, raws[i]!)\n )\n\n let next = 0\n const build = (nodes: readonly PdfjsOutlineNode[], path: string): OutlineItem[] =>\n nodes.map((node, i) => {\n const id = path === '' ? String(i) : `${path}.${i}`\n let target = targetOf(node)\n if (target.kind === 'dest') {\n const dest = dests[next++]\n target = dest\n ? { kind: 'resolved', dest }\n : { kind: 'unsupported', reason: 'unknown' }\n }\n return {\n id,\n // Titles may carry line breaks and tabs; the panel shows one line.\n title: String(node.title ?? '')\n .replace(/\\s+/g, ' ')\n .trim(),\n target,\n bold: !!node.bold,\n italic: !!node.italic,\n open: (node.count ?? 0) > 0,\n children: build(node.items ?? [], id),\n }\n })\n return build(roots, '')\n}\n","import type { FieldValue, FormField } from './types'\n\n/**\n * Why `value` cannot be the field's value, or `undefined` when it can. A locked or read-only\n * field is `readOnly`; otherwise the value must suit the type: any text within `maxLength`, an\n * option of a non-editable choice, an array of options for a multi-select list, an on state or\n * `Off` for a checkbox or radio, and `{ signature }` for a signature field. A button has no value.\n */\nexport function checkValue(\n field: FormField,\n value: unknown\n): 'readOnly' | 'invalid' | undefined {\n if (field.locked || field.flags.readOnly) return 'readOnly'\n return suits(field, value) ? undefined : 'invalid'\n}\n\n/** Whether `value` suits the field's type, whatever its flags. */\nexport function suits(field: FormField, value: unknown): boolean {\n const isOption = (v: unknown) => field.options.some((o) => o.value === v)\n switch (field.type) {\n case 'text':\n return (\n typeof value === 'string' &&\n (field.maxLength === undefined || value.length <= field.maxLength)\n )\n case 'combo':\n return typeof value === 'string' && (field.flags.editable || isOption(value))\n case 'list':\n return field.flags.multiSelect\n ? Array.isArray(value) && value.every(isOption)\n : typeof value === 'string' && isOption(value)\n case 'checkbox':\n case 'radio':\n return (\n value === 'Off' ||\n (typeof value === 'string' &&\n (isOption(value) || field.widgets.some((w) => w.onState === value)))\n )\n case 'signature':\n return (\n typeof value === 'object' &&\n value !== null &&\n !Array.isArray(value) &&\n typeof (value as { signature?: unknown }).signature === 'string' &&\n (value as { signature: string }).signature !== ''\n )\n case 'button':\n return false\n }\n}\n\n/**\n * A checked value as it is stored: frozen, a multi-select's options in option order without\n * repeats, and a signature with only its id.\n */\nexport function normaliseValue(field: FormField, value: FieldValue): FieldValue {\n if (Array.isArray(value)) {\n const chosen = new Set(value)\n return Object.freeze(\n field.options.map((o) => o.value).filter((v) => chosen.has(v) && chosen.delete(v))\n )\n }\n if (typeof value === 'object')\n return Object.freeze({ signature: (value as { signature: string }).signature })\n return value\n}\n\n/** The value a reset gives: the PDF's default, else empty for the type, else none. */\nexport function resetValue(field: FormField): FieldValue | undefined {\n if (field.defaultValue !== undefined) return field.defaultValue\n switch (field.type) {\n case 'text':\n case 'combo':\n return ''\n case 'checkbox':\n case 'radio':\n return 'Off'\n case 'list':\n return field.flags.multiSelect ? Object.freeze([]) : undefined\n default:\n return undefined\n }\n}\n\nexport function sameValue(a: FieldValue | undefined, b: FieldValue | undefined): boolean {\n if (a === b) return true\n if (a === undefined || b === undefined) return false\n if (Array.isArray(a) || Array.isArray(b))\n return (\n Array.isArray(a) &&\n Array.isArray(b) &&\n a.length === b.length &&\n a.every((v, i) => v === b[i])\n )\n return (\n typeof a === 'object' &&\n typeof b === 'object' &&\n (a as { signature: string }).signature === (b as { signature: string }).signature\n )\n}\n","import { z } from 'zod'\n\nimport { checkValue, normaliseValue } from './values'\n\nimport type { FieldValue, FieldValues, FormField } from './types'\n\n/** A Gloss value the form could not apply. No script runs on one, so none is `script`. */\nexport interface GlossRejection {\n name: string\n reason: 'unknown' | 'readOnly' | 'invalid'\n}\n\n/** A field value as Gloss writes it: text, the options of a multi-select, or a signature id. */\nexport const GlossFieldValueSchema = z.union([\n z.string(),\n z.array(z.string()),\n z.looseObject({ signature: z.string().min(1) }),\n])\n\n/** Gloss's `fields`: values keyed by full field name. */\nexport const GlossFieldsSchema = z.record(z.string().min(1), GlossFieldValueSchema)\n\n/**\n * The values to export: every field that has one and is not no-export, in field order, with a\n * multi-select's options in option order.\n */\nexport function fieldsToGloss(\n values: FieldValues,\n fields: readonly FormField[]\n): Record<string, FieldValue> {\n const out: Record<string, FieldValue> = {}\n for (const field of fields) {\n const value = values[field.name]\n if (value === undefined || field.flags.noExport) continue\n out[field.name] = normaliseValue(field, value)\n }\n return out\n}\n\n/**\n * The values of a Gloss `fields` map that suit the form, and the names that do not: unknown,\n * read-only (or locked), or invalid for the field. Anything other than a map applies nothing.\n */\nexport function fieldsFromGloss(\n raw: unknown,\n fields: readonly FormField[]\n): { values: FieldValues; rejected: GlossRejection[] } {\n const values: Record<string, FieldValue> = {}\n const rejected: GlossRejection[] = []\n if (typeof raw !== 'object' || raw === null || Array.isArray(raw))\n return { values, rejected }\n const byName = new Map(fields.map((f) => [f.name, f]))\n for (const [name, value] of Object.entries(raw)) {\n const field = byName.get(name)\n if (!field) {\n rejected.push({ name, reason: 'unknown' })\n continue\n }\n const parsed = GlossFieldValueSchema.safeParse(value)\n const reason = checkValue(field, value) ?? (parsed.success ? undefined : 'invalid')\n if (reason || !parsed.success) {\n rejected.push({ name, reason: reason ?? 'invalid' })\n continue\n }\n values[name] = normaliseValue(field, parsed.data)\n }\n return { values, rejected }\n}\n","import { fieldsToGloss } from './gloss'\n\nimport type { FieldValue, FieldValues, FormField } from './types'\n\n/**\n * The values a submit sends: every field with a value that is not no-export, limited to\n * `names` (or everything but them, when `include` is false). A name covers the fields under it.\n * An empty list means every field.\n */\nexport function submitValues(\n values: FieldValues,\n fields: readonly FormField[],\n names: readonly string[],\n include: boolean\n): FieldValues {\n const all = fieldsToGloss(values, fields)\n if (names.length === 0) return Object.freeze(all)\n const listed = (name: string) =>\n names.some((n) => name === n || name.startsWith(`${n}.`))\n const out: Record<string, FieldValue> = {}\n for (const [name, value] of Object.entries(all))\n if (listed(name) === include) out[name] = value\n return Object.freeze(out)\n}\n","/**\n * PDF.js's scripting API defines `submitForm`, `mailDoc`, `mailForm` (on Doc) and `launchURL`\n * (on App) as empty methods, so a script calling them is silent. They cannot be replaced from a\n * script run inside the sandbox: scripts run as global code, where `this` is the global object,\n * and PDF.js copies each Doc method onto it as a bound, non-writable, non-configurable property\n * before any script runs. So the bridge rewrites the four empty bodies in the scripting source\n * before the sandbox evaluates it. Each replacement reports the call through the sandbox's own\n * `send` channel, with a command name only Inkbar uses; the host maps the arguments.\n */\n\n/** The command a rewritten method sends. */\nexport const ACTION_COMMAND = 'inkbar:action'\n\nexport type PatchedMethod = 'submitForm' | 'mailDoc' | 'mailForm' | 'launchURL'\n\nconst METHODS: readonly PatchedMethod[] = [\n 'submitForm',\n 'mailDoc',\n 'mailForm',\n 'launchURL',\n]\n\n/** The empty method as it appears in PDF.js's scripting source, one class member per line. */\nconst stub = (method: PatchedMethod) => `\\n ${method}() {}\\n`\n\nconst replacement = (method: PatchedMethod) =>\n `\\n ${method}(...args) { this._send({ command: \"${ACTION_COMMAND}\", method: \"${method}\", args }); }\\n`\n\n/** How many times each empty method appears in `source`. */\nexport function countStubs(source: string): Record<PatchedMethod, number> {\n const counts = {} as Record<PatchedMethod, number>\n for (const m of METHODS) counts[m] = source.split(stub(m)).length - 1\n return counts\n}\n\n/**\n * Rewrites the four empty methods. Throws when any of them does not appear exactly once, which\n * means the PDF.js build differs from the one this was written against.\n */\nexport function patchScriptingSource(source: string): string {\n const counts = countStubs(source)\n const off = METHODS.filter((m) => counts[m] !== 1)\n if (off.length > 0)\n throw new Error(`The PDF.js scripting source does not match: ${off.join(', ')}`)\n return METHODS.reduce((src, m) => src.replace(stub(m), () => replacement(m)), source)\n}\n\ninterface SourceModule {\n stringToNewUTF8(source: string): number\n}\n\n/**\n * Wraps the engine's string copy so the first string it receives, the scripting source that\n * `Sandbox.create` hands it, is patched. A mismatch throws inside `create`, which then fails to\n * start the sandbox; `failure()` gives the reason.\n */\nexport function patchSandboxSource(module: SourceModule): {\n failure(): Error | undefined\n} {\n const original = module.stringToNewUTF8.bind(module)\n let done = false\n let failure: Error | undefined\n module.stringToNewUTF8 = (source: string) => {\n if (done) return original(source)\n done = true\n try {\n return original(patchScriptingSource(source))\n } catch (e) {\n failure = e instanceof Error ? e : new Error(String(e))\n throw failure\n }\n }\n return { failure: () => failure }\n}\n","import { InkError } from '../model/errors'\nimport { submitValues } from '../model/form/submit'\nimport { safeAddress, safeUrl } from '../model/form/url'\nimport { sameValue } from '../model/form/values'\n\nimport { ACTION_COMMAND, patchSandboxSource } from './sandbox-patch'\n\nimport type { PdfjsSandbox, QuickJSSandbox } from '#pdfjs-sandbox'\nimport type { PdfAssets, PdfjsDocument } from './types'\nimport type {\n FormController,\n FormScripting,\n KeystrokeResult,\n} from '../model/form/controller'\nimport type {\n FieldValue,\n ViewerAction,\n FormEvent,\n FormField,\n FormWidget,\n WidgetOverride,\n} from '../model/form/types'\n\n/** Where the sandbox module comes from. An object, so tests can see whether it was loaded. */\nexport const sandboxLoader = {\n load: (): Promise<{ QuickJSSandbox: typeof QuickJSSandbox }> =>\n import('#pdfjs-sandbox'),\n}\n\nexport interface FormScriptingOptions {\n proxy: PdfjsDocument\n assets: PdfAssets\n form: FormController\n info: { title?: string | undefined; author?: string | undefined; pageCount: number }\n /**\n * Whether the values the form starts from (a host's initial values over the file's) run\n * calculate once the sandbox starts. Off for a controlled host, which hears of nothing\n * before it opened the document.\n */\n calculateAtStart?: boolean | undefined\n /** Tests only: the result carries the PDF.js sandbox as `_sandboxForTesting`. */\n testing?: boolean | undefined\n}\n\n/** What the sandbox sends: a widget update (with `id`) or a command. */\ntype Update = Record<string, unknown> & { id?: unknown; command?: unknown }\n\n/** The event PDF.js's sandbox dispatches to a widget's scripts. */\ntype SandboxEvent = Record<string, unknown> & { id: string; name: string }\n\n/**\n * Runs the document's JavaScript in PDF.js's QuickJS sandbox, wired to `form`. Resolves\n * `undefined` without loading the sandbox when the document has no JavaScript. A sandbox that\n * fails to load or start is reported as a `FormScriptError` on `form`, and resolves `undefined`,\n * so the form stays fillable without scripts.\n *\n * The sandbox gets its own `window`: alerts go to `form`'s `alert` event, `app.response` returns\n * `null` and asks the host with a `prompt` action, and timers are tracked and cleared on destroy.\n * Nothing reaches the page's `window.alert`, `prompt` or `confirm`, and nothing is fetched.\n */\nexport async function createFormScripting(\n opts: FormScriptingOptions\n): Promise<(FormScripting & { _sandboxForTesting?: PdfjsSandbox }) | undefined> {\n const { proxy, assets, form } = opts\n // The sandbox runs on a browser page; elsewhere (Node) the form works without scripts.\n if (typeof window === 'undefined') return undefined\n // Cheap, and never misses JavaScript; the stricter check below needs the field objects.\n if (!(await proxy.hasJSActions())) return undefined\n const [objects, calculationOrder, actions] = await Promise.all([\n proxy.getFieldObjects(),\n proxy.getCalculationOrderIds(),\n proxy.getJSActions(),\n ])\n const hasFieldScripts = [...(objects?.values() ?? [])].some((list) =>\n list.some((o) => hasEntries((o as { actions?: unknown }).actions))\n )\n if (!hasFieldScripts && !hasEntries(actions)) return undefined\n\n const fields = form.fields.get()\n const byName = new Map(fields.map((f) => [f.name, f]))\n const byWidget = new Map(\n fields.flatMap((f) => f.widgets.map((w) => [w.id, f] as const))\n )\n const widgets = new Map(fields.flatMap((f) => f.widgets.map((w) => [w.id, w] as const)))\n /** Fields PDF.js reads as a date or time, from their standard format scripts. */\n const dates = new Set(\n [...(objects?.entries() ?? [])]\n .filter(([, list]) =>\n list.some((o) => (o as { hasDatetimeHTML?: unknown }).hasDatetimeHTML === true)\n )\n .map(([name]) => name)\n )\n /** What the sandbox holds, by field name, in the form's terms. */\n const mirror = new Map<string, FieldValue>()\n for (const f of fields) if (f.value !== undefined) mirror.set(f.name, f.value)\n\n let dead = false\n /** Updates sent during a synchronous dispatch, applied together once it returns. */\n let buffer: Update[] | undefined\n const report = (cause: unknown) => {\n if (dead) return\n const message = cause instanceof Error ? cause.message : String(cause)\n form._error(new InkError('FormScriptError', message, {}, cause))\n }\n const onSend = (detail: unknown) => {\n if (dead || typeof detail !== 'object' || detail === null) return\n if (buffer) buffer.push(detail as Update)\n else apply([detail as Update], { values: true })\n }\n\n const win = createWindow(form, onSend, report, () => dead)\n let sandbox: PdfjsSandbox | undefined\n try {\n sandbox = await withTimeout(\n sandboxLoader.load().then(({ QuickJSSandbox }) => QuickJSSandbox(assets.wasm)),\n SANDBOX_TIMEOUT_MS\n )\n const support = sandbox.support\n const engine = sandbox._module\n if (!support || !engine) throw new Error('The PDF.js sandbox has no engine')\n support.win = win.shim\n const patch = patchSandboxSource(engine)\n try {\n sandbox.create({\n objects,\n calculationOrder,\n appInfo: { platform: navigator.platform, language: navigator.language },\n docInfo: {\n Title: opts.info.title ?? '',\n Author: opts.info.author ?? '',\n numPages: opts.info.pageCount,\n URL: '',\n baseURL: '',\n actions,\n },\n })\n } catch (cause) {\n win.clear()\n throw patch.failure() ?? cause\n }\n } catch (cause) {\n dead = true\n // A sandbox that loaded but has no engine, or did not start, is still torn down.\n // PDF.js's `nukeSandbox` can throw on a half-built one.\n try {\n sandbox?.nukeSandbox()\n } catch {\n // Nothing else holds it.\n }\n form._error(\n new InkError(\n 'FormScriptError',\n \"The form's scripts could not start; it can still be filled in\",\n {},\n cause\n )\n )\n return undefined\n }\n\n /** Page events run one after another. */\n let pages: Promise<void> = Promise.resolve()\n /** Pages whose actions the sandbox already has. */\n const visited = new Set<number>()\n\n /** Dispatches `event` and returns what the scripts sent while it ran. */\n const run = (event: SandboxEvent): Update[] => {\n const outer = buffer\n const got: Update[] = []\n buffer = got\n try {\n sandbox.dispatchEvent(event)\n } catch (cause) {\n report(cause)\n } finally {\n buffer = outer\n }\n return got\n }\n\n const fieldOf = (id: unknown) => (typeof id === 'string' ? byWidget.get(id) : undefined)\n const ownOf = (u: Update, field: FormField) => fieldOf(u.id) === field\n\n /**\n * Applies updates. `values: false` keeps the sandbox's values out of the form (an undo\n * replaying a state calculate already produced). The `source` field's own updates are\n * skipped when its commit was rejected, and its value always, since the form writes it.\n */\n function apply(\n updates: readonly Update[],\n o: { values: boolean; source?: { field: FormField; accepted: boolean } }\n ) {\n const next: Record<string, FieldValue> = {}\n for (const u of updates) {\n if (dead) return\n if (u.id === undefined || u.id === null) {\n command(u)\n continue\n }\n const field = fieldOf(u.id)\n if (!field) continue\n const own = o.source?.field === field\n if (own && !o.source?.accepted) continue\n if ('value' in u) {\n // A date or time field reports the time its scripts parsed; its text is the\n // formatted value.\n const raw =\n dates.has(field.name) && typeof u.value === 'number'\n ? u.formattedValue\n : u.value\n const value =\n raw === u.value || typeof raw === 'string'\n ? fromSandbox(field, u.id as string, raw)\n : undefined\n if (value !== undefined) {\n mirror.set(field.name, value)\n if (o.values && !own) next[field.name] = value\n }\n }\n if ('formattedValue' in u)\n form._setFormatted(\n field.name,\n typeof u.formattedValue === 'string' ? u.formattedValue : undefined\n )\n const override = overrideOf(u)\n if (override) {\n const siblings: unknown[] = Array.isArray(u.siblings)\n ? (u.siblings as unknown[])\n : []\n for (const id of [u.id, ...siblings])\n if (typeof id === 'string' && widgets.has(id))\n form._setWidgetState(id, override)\n }\n if (u.focus === true) form._focus(u.id as string)\n }\n if (Object.keys(next).length > 0) form._scriptValues(next)\n }\n\n function command(u: Update) {\n switch (u.command) {\n case 'print':\n form._emitAction({ kind: 'print' })\n break\n case ACTION_COMMAND: {\n const action = scriptAction(u.method, u.args, form)\n if (action) form._emitAction(action)\n break\n }\n case 'error':\n report(new Error(typeof u.value === 'string' ? u.value : 'A form script failed'))\n break\n // `println`, `clear` and the viewer commands (zoom, page, layout, menu items) have no\n // place in the form, so they are dropped.\n }\n }\n\n /**\n * Commits `value` to `field` in the sandbox: validate, calculate and format run. Returns the\n * value the sandbox kept, which a script may have changed, or `undefined` when rejected.\n */\n const commitTo = (\n field: FormField,\n value: FieldValue,\n values: boolean\n ): FieldValue | undefined => {\n const event = commitEvent(field, value)\n if (!event) {\n mirror.set(field.name, value)\n return value\n }\n const updates = run(event)\n // PDF.js answers a rejected commit with an empty value and a selection; an accepted one\n // reports the value and its formatted text without one.\n const accepted = !updates.some((u) => ownOf(u, field) && 'selRange' in u)\n apply(updates, { values, source: { field, accepted } })\n if (!accepted) return undefined\n const echo = updates.filter((u) => ownOf(u, field) && 'value' in u).at(-1)\n const kept = echo ? scriptChange(field, echo) : undefined\n const stored = kept !== undefined && !sameValue(kept, value) ? kept : value\n mirror.set(field.name, stored)\n return stored\n }\n\n /**\n * The value a script changed a commit to, from the sandbox's echo of it; `undefined` when\n * the echo is no change. The sandbox reports a text value as the string it was given (it\n * keeps the original alongside any number it parses), so a different string is a script's\n * change. A number is the sandbox's own parse: a date or time field reports the time it\n * read. A checkbox or radio echo names the first widget with the export value, which is\n * not always the one chosen, so the chosen state stands; a rejection shows as a selection.\n */\n const scriptChange = (field: FormField, echo: Update): FieldValue | undefined => {\n switch (field.type) {\n case 'text':\n case 'combo':\n return typeof echo.value === 'string'\n ? fromSandbox(field, echo.id as string, echo.value)\n : undefined\n case 'list':\n return fromSandbox(field, echo.id as string, echo.value)\n default:\n return undefined\n }\n }\n\n const scripting: FormScripting & { _sandboxForTesting?: PdfjsSandbox } = {\n commit(name, value) {\n const field = byName.get(name)\n if (dead || !field) return value\n return commitTo(field, value, true)\n },\n sync(values, calculate) {\n if (dead) return\n for (const field of fields) {\n const value = values[field.name]\n if (value === undefined || sameValue(value, mirror.get(field.name))) continue\n commitTo(field, value, calculate)\n if (dead) return\n }\n },\n dispatch(event) {\n const field = byWidget.get(event.widget)\n const widget = widgets.get(event.widget)\n if (dead || !field || !widget) return\n const value = event.value ?? currentValue(form, field, widget)\n apply(run(toSandboxEvent(event, value)), { values: true })\n },\n keystroke(widget, text, change, selStart, selEnd) {\n const field = byWidget.get(widget)\n if (dead || !field) return undefined\n const updates = run({\n id: widget,\n name: 'Keystroke',\n value: text,\n change,\n selStart,\n selEnd,\n willCommit: false,\n })\n // The sandbox now holds the typed text as the field's value; the next sync puts the\n // committed value back.\n mirror.delete(field.name)\n apply(updates, { values: true, source: { field, accepted: false } })\n return keystrokeResult(updates, field, text, change, selStart, selEnd)\n },\n pageEvent(page, name) {\n if (dead) return Promise.resolve()\n // In order, so a page's close follows its open. Like PDF.js's viewer, the page's own\n // actions go with its first open; the sandbox keeps them for later events.\n const step = pages.then(async () => {\n let actions: unknown = null\n if (name === 'PageOpen' && !visited.has(page)) {\n visited.add(page)\n actions = await (await proxy.getPage(page + 1)).getJSActions()\n }\n if (dead) return\n apply(run({ id: 'page', name, pageNumber: page + 1, actions }), { values: true })\n })\n pages = step.catch(report)\n return pages\n },\n destroy() {\n if (dead) return\n dead = true\n win.clear()\n try {\n sandbox.nukeSandbox()\n } catch {\n // The engine is being dropped either way; nothing else holds it.\n }\n },\n }\n if (opts.testing) scripting._sandboxForTesting = sandbox\n\n apply(run({ id: 'doc', name: 'Open' }), { values: true })\n // The form may start from values other than the file's (a host's initial values).\n scripting.sync(form.values.get(), opts.calculateAtStart === true)\n return scripting\n}\n\n/** A scalar from the sandbox as text; anything else is empty. */\nfunction textOf(v: unknown): string {\n if (typeof v === 'string') return v\n return typeof v === 'number' || typeof v === 'boolean' ? String(v) : ''\n}\n\n/** How long the sandbox may take to load before the form goes on without scripts. */\nconst SANDBOX_TIMEOUT_MS = 10_000\n\n/**\n * Rejects when `promise` takes longer than `ms`, so a stalled wasm load never holds up the\n * document. A sandbox that arrives late is torn down.\n */\nfunction withTimeout(promise: Promise<PdfjsSandbox>, ms: number): Promise<PdfjsSandbox> {\n return new Promise((resolve, reject) => {\n let late = false\n const timer = setTimeout(() => {\n late = true\n reject(new Error(`The PDF.js sandbox did not load within ${ms} ms`))\n }, ms)\n promise.then(\n (sandbox) => {\n clearTimeout(timer)\n if (late) sandbox.nukeSandbox()\n else resolve(sandbox)\n },\n (cause: unknown) => {\n clearTimeout(timer)\n reject(cause instanceof Error ? cause : new Error(String(cause)))\n }\n )\n })\n}\n\nfunction hasEntries(value: unknown): boolean {\n if (value instanceof Map) return value.size > 0\n return typeof value === 'object' && value !== null && Object.keys(value).length > 0\n}\n\ninterface ShimWindow {\n shim: Record<string, unknown>\n /** Clears every timer the scripts started. */\n clear(): void\n}\n\n/** The `window` the sandbox sees. */\nfunction createWindow(\n form: FormController,\n onSend: (detail: unknown) => void,\n report: (cause: unknown) => void,\n isDead: () => boolean\n): ShimWindow {\n type Id = ReturnType<typeof setTimeout>\n const timers = new Map<Id, 'timeout' | 'interval'>()\n const clear = (id: Id) => {\n const kind = timers.get(id)\n if (!kind) return\n timers.delete(id)\n if (kind === 'interval') clearInterval(id)\n else clearTimeout(id)\n }\n const noop = () => undefined\n class ShimEvent {\n readonly type: string\n readonly detail: unknown\n constructor(type: string, init?: { detail?: unknown }) {\n this.type = type\n this.detail = init?.detail\n }\n }\n const shim = {\n alert: (message: string) => {\n if (!isDead()) form._alert(message)\n },\n confirm: () => false,\n // PDF.js calls this synchronously, so it cannot wait for an answer: the host is asked\n // and the script gets the cancel result.\n prompt: (message: string) => {\n if (!isDead()) form._emitAction({ kind: 'prompt', message })\n return null\n },\n setTimeout: (fn: () => void, ms: number) => {\n if (isDead()) return 0\n const id = setTimeout(() => {\n timers.delete(id)\n if (!isDead()) fn()\n }, ms)\n timers.set(id, 'timeout')\n return id\n },\n setInterval: (fn: () => void, ms: number) => {\n if (isDead()) return 0\n const id = setInterval(() => {\n if (!isDead()) fn()\n }, ms)\n timers.set(id, 'interval')\n return id\n },\n clearTimeout: clear,\n clearInterval: clear,\n console: { log: noop, info: noop, warn: noop, debug: noop, error: report },\n URL,\n CustomEvent: ShimEvent,\n dispatchEvent: (event: ShimEvent) => {\n if (event.type === 'updatefromsandbox') onSend(event.detail)\n return true\n },\n }\n return {\n shim,\n clear() {\n for (const id of [...timers.keys()]) clear(id)\n },\n }\n}\n\n/** The event that commits `value` the way a person would, or none for a field without one. */\nfunction commitEvent(field: FormField, value: FieldValue): SandboxEvent | undefined {\n const first = field.widgets[0]\n if (!first) return undefined\n switch (field.type) {\n case 'checkbox':\n case 'radio': {\n const on = field.widgets.find((w) => w.onState !== undefined && w.onState === value)\n // A radio group has no widget to turn off; the sandbox keeps its choice.\n if (!on && (value !== 'Off' || field.type === 'radio')) return undefined\n return { id: (on ?? first).id, name: 'Validate', value: on !== undefined }\n }\n case 'text':\n case 'combo':\n case 'list': {\n if (typeof value !== 'string' && !Array.isArray(value)) return undefined\n const end = typeof value === 'string' ? value.length : 0\n return {\n id: first.id,\n name: 'Keystroke',\n value,\n change: '',\n willCommit: true,\n commitKey: 1,\n selStart: end,\n selEnd: end,\n }\n }\n default:\n return undefined\n }\n}\n\n/** The value an event carries when the form layer gives none: what the widget shows. */\nfunction currentValue(\n form: FormController,\n field: FormField,\n widget: FormWidget\n): string | boolean | readonly string[] | undefined {\n const value = form.get(field.name)\n switch (field.type) {\n case 'checkbox':\n case 'radio':\n return widget.onState !== undefined && value === widget.onState\n case 'text':\n case 'combo':\n case 'list':\n return typeof value === 'string' || Array.isArray(value) ? value : ''\n default:\n return undefined\n }\n}\n\nfunction toSandboxEvent(\n event: FormEvent,\n value: string | boolean | readonly string[] | undefined\n): SandboxEvent {\n const out: SandboxEvent = { id: event.widget, name: event.name }\n if (value !== undefined) out.value = value\n for (const key of ['change', 'selStart', 'selEnd', 'willCommit', 'commitKey'] as const)\n if (event[key] !== undefined) out[key] = event[key]\n return out\n}\n\n/** A value from the sandbox in the form's terms; `undefined` for a field without one. */\nfunction fromSandbox(\n field: FormField,\n id: string,\n value: unknown\n): FieldValue | undefined {\n switch (field.type) {\n case 'checkbox':\n case 'radio': {\n if (value === 'Off' || value === '' || value === null || value === undefined)\n return 'Off'\n // The sandbox holds export values and sends the widget it turned on.\n const on =\n field.widgets.find((w) => w.id === id && w.onState !== undefined) ??\n field.widgets.find((w) => w.onState === value)\n return on?.onState ?? textOf(value)\n }\n case 'list':\n if (field.flags.multiSelect)\n return Array.isArray(value)\n ? value.map(textOf)\n : value === ''\n ? []\n : [textOf(value)]\n return Array.isArray(value) ? textOf(value[0]) : textOf(value)\n case 'text':\n case 'combo':\n return Array.isArray(value) ? textOf(value[0]) : textOf(value)\n default:\n return undefined\n }\n}\n\n/** `[\"RGB\", r, g, b]`, `[\"G\", g]`, `[\"CMYK\", c, m, y, k]` or `[\"T\"]` as `#rrggbb`. */\nfunction colorOf(value: unknown): string | undefined {\n if (!Array.isArray(value) || typeof value[0] !== 'string') return undefined\n const [space, ...raw] = value as [string, ...unknown[]]\n const n = raw.map((v) => (typeof v === 'number' ? Math.min(1, Math.max(0, v)) : 0))\n let rgb: number[]\n if (space === 'T') return 'transparent'\n if (space === 'G') rgb = [n[0] ?? 0, n[0] ?? 0, n[0] ?? 0]\n else if (space === 'RGB') rgb = [n[0] ?? 0, n[1] ?? 0, n[2] ?? 0]\n else if (space === 'CMYK') {\n const k = n[3] ?? 0\n rgb = [n[0] ?? 0, n[1] ?? 0, n[2] ?? 0].map((c) => (1 - c) * (1 - k))\n } else return undefined\n return `#${rgb\n .map((c) =>\n Math.round(c * 255)\n .toString(16)\n .padStart(2, '0')\n )\n .join('')}`\n}\n\nfunction overrideOf(u: Update): WidgetOverride | undefined {\n const o: WidgetOverride = {}\n if (typeof u.hidden === 'boolean') o.hidden = u.hidden\n // `display`: 0 visible, 1 hidden, 2 no print, 3 no view.\n if (typeof u.display === 'number') o.hidden = u.display % 2 === 1\n if (typeof u.readonly === 'boolean') o.readOnly = u.readonly\n if (typeof u.required === 'boolean') o.required = u.required\n const text = colorOf(u.textColor ?? u.fgColor)\n const fill = colorOf(u.fillColor ?? u.bgColor)\n const stroke = colorOf(u.strokeColor ?? u.borderColor)\n if (text) o.textColor = text\n if (fill) o.fillColor = fill\n if (stroke) o.strokeColor = stroke\n if (typeof u.textSize === 'number' && Number.isFinite(u.textSize) && u.textSize >= 0)\n o.textSize = u.textSize\n return Object.keys(o).length > 0 ? o : undefined\n}\n\nfunction keystrokeResult(\n updates: readonly Update[],\n field: FormField,\n text: string,\n change: string,\n selStart: number,\n selEnd: number\n): KeystrokeResult {\n const merged = text.slice(0, selStart) + change + text.slice(selEnd)\n const caret = selStart + change.length\n const own = updates.filter((u) => {\n const id = typeof u.id === 'string' ? u.id : undefined\n return id !== undefined && field.widgets.some((w) => w.id === id) && 'value' in u\n })\n const last = own.at(-1)\n if (!last) return { accepted: true, value: merged, selStart: caret, selEnd: caret }\n const value = textOf(last.value)\n // A refused keystroke comes back as the text before it.\n const accepted = !(value === text && merged !== text)\n const range = Array.isArray(last.selRange) ? last.selRange : []\n const start = typeof range[0] === 'number' ? range[0] : caret\n const end = typeof range[1] === 'number' ? range[1] : start\n return accepted\n ? { accepted, value, selStart: start, selEnd: end }\n : { accepted, value: text, selStart, selEnd }\n}\n\n/** Maps a rewritten method's call (positional or Acrobat's single-object form) to an action. */\nfunction scriptAction(\n method: unknown,\n args: unknown,\n form: FormController\n): ViewerAction | undefined {\n const list = Array.isArray(args) ? (args as unknown[]) : []\n const first = list[0]\n const named =\n typeof first === 'object' && first !== null && !Array.isArray(first)\n ? (first as Record<string, unknown>)\n : undefined\n const arg = (key: string, index: number): unknown => (named ? named[key] : list[index])\n const str = (key: string, index: number): string | undefined => {\n const v = arg(key, index)\n return typeof v === 'string' ? v : undefined\n }\n switch (method) {\n case 'submitForm': {\n const url = safeUrl(str('cURL', 0) ?? '')\n if (!url) return undefined\n const format = submitFormat(\n str('cSubmitAs', 15),\n arg('bPDF', 8),\n arg('bXML', 6),\n arg('bFDF', 1)\n )\n const raw = arg('aFields', 3)\n const names = (Array.isArray(raw) ? raw : raw === undefined ? [] : [raw]).filter(\n (n): n is string => typeof n === 'string'\n )\n return {\n kind: 'submit',\n url,\n fields: submitValues(form.values.get(), form.fields.get(), names, true),\n format,\n ...(format === 'html'\n ? { method: arg('bGet', 4) === true ? 'GET' : 'POST' }\n : {}),\n }\n }\n case 'mailDoc':\n case 'mailForm': {\n const out: ViewerAction & { kind: 'mail' } = {\n kind: 'mail',\n withData: method === 'mailForm',\n }\n const to = str('cTo', 1)\n const cc = str('cCc', 2)\n const bcc = str('cBcc', 3)\n const subject = str('cSubject', 4)\n const body = str('cMsg', 5)\n for (const address of [to, cc, bcc])\n if (address !== undefined && safeAddress(address) === undefined) return undefined\n if (to !== undefined) out.to = to\n if (cc !== undefined) out.cc = cc\n if (bcc !== undefined) out.bcc = bcc\n if (subject !== undefined) out.subject = subject\n if (body !== undefined) out.body = body\n return out\n }\n case 'launchURL': {\n const url = safeUrl(str('cURL', 0) ?? '')\n return url\n ? { kind: 'open-url', url, newWindow: arg('bNewFrame', 1) === true }\n : undefined\n }\n default:\n return undefined\n }\n}\n\n/** `cSubmitAs` wins, then `bPDF`, then `bXML`; otherwise FDF, or HTML when `bFDF` is false. */\nfunction submitFormat(\n submitAs: string | undefined,\n pdf: unknown,\n xml: unknown,\n fdf: unknown\n): 'fdf' | 'xfdf' | 'html' | 'pdf' {\n switch (submitAs?.toUpperCase()) {\n case 'FDF':\n return 'fdf'\n case 'XFDF':\n case 'XFD':\n case 'XML':\n return 'xfdf'\n case 'HTML':\n return 'html'\n case 'PDF':\n return 'pdf'\n }\n if (pdf === true) return 'pdf'\n if (xml === true) return 'xfdf'\n return fdf === false ? 'html' : 'fdf'\n}\n","import type { PdfjsPage } from './types'\n\n/** The prefix PDF.js gives an annotation's id in its structure tree. */\nconst ANNOTATION_PREFIX = 'pdfjs_internal_id_'\n\ninterface StructNode {\n type?: unknown\n id?: unknown\n children?: unknown\n}\n\n/**\n * The page's annotations in structure order, by PDF.js annotation id (`12R`): the order of the\n * OBJR references in the page's part of the structure tree, depth first. Empty when the file has\n * no structure tree or PDF.js cannot read it.\n */\nexport async function structureAnnotationOrder(page: PdfjsPage): Promise<string[]> {\n let root: unknown\n try {\n root = await page.getStructTree()\n } catch {\n return []\n }\n const out: string[] = []\n const seen = new Set<string>()\n const walk = (node: unknown, depth: number) => {\n if (depth > 64 || typeof node !== 'object' || node === null) return\n const n = node as StructNode\n if (n.type === 'annotation' && typeof n.id === 'string') {\n const id = n.id.startsWith(ANNOTATION_PREFIX)\n ? n.id.slice(ANNOTATION_PREFIX.length)\n : n.id\n if (!seen.has(id)) {\n seen.add(id)\n out.push(id)\n }\n }\n if (Array.isArray(n.children)) for (const kid of n.children) walk(kid, depth + 1)\n }\n walk(root, 0)\n return out\n}\n","import {\n readFreeTextFields,\n readTextIcon,\n refOfPdfjsId,\n} from '../../pdf/annotation-fields'\nimport { openPdfObjects, type PdfObjects } from '../../pdf/objects'\n\nimport { AnnotationSchema, type Annotation } from './types'\n\nimport type { EmbeddedFieldPatch, EmbeddedTarget } from './embedded'\nimport type { PdfRef } from '../../pdf/lexer'\n\n/**\n * `a` with `fields` merged in: `callout`, `fringe`, `head` and the font keys of `defaultStyle`\n * on a FreeText, `icon` on a note. Undefined when `a` is not embedded, the fields do not fit its\n * type, or the result fails the schema.\n */\nexport function withEmbeddedFields(\n a: Annotation,\n fields: EmbeddedFieldPatch\n): Annotation | undefined {\n if (a.source !== 'pdf') return undefined\n const { callout, fringe, head, icon, font } = fields\n let candidate: Record<string, unknown>\n if (a.type === 'text') {\n if (icon === undefined || callout || fringe || head !== undefined || font)\n return undefined\n candidate = { ...a, icon }\n } else if (a.type === 'freetext') {\n if (icon !== undefined) return undefined\n candidate = {\n ...a,\n ...(callout ? { callout } : {}),\n ...(fringe ? { fringe } : {}),\n ...(head !== undefined ? { head } : {}),\n defaultStyle: { ...a.defaultStyle, ...font },\n }\n } else {\n return undefined\n }\n const parsed = AnnotationSchema.safeParse(candidate)\n return parsed.success ? parsed.data : undefined\n}\n\n/**\n * Reads every target once, calling `getData` only if a target names an annotation in\n * `annotations` by an object reference, and returns the fields read, by id. A target the file\n * adds nothing to, or whose fields would fail the schema, is left out. Never throws: any\n * failure leaves the annotations as they are.\n */\nexport async function readEmbeddedFields(\n annotations: readonly Annotation[],\n targets: readonly EmbeddedTarget[],\n getData: () => Promise<Uint8Array>\n): Promise<Map<string, EmbeddedFieldPatch>> {\n const read = new Map<string, EmbeddedFieldPatch>()\n if (targets.length === 0) return read\n try {\n const byId = new Map(annotations.map((a) => [a.id, a]))\n const work = targets.flatMap((target) => {\n const current = byId.get(target.id)\n const ref = refOfPdfjsId(target.id.split(':')[2] ?? '')\n return current && ref ? [{ target, current, ref }] : []\n })\n if (work.length === 0) return read\n const objs = await openPdfObjects(await getData())\n if (!objs) return read\n for (const { target, current, ref } of work) {\n try {\n const fields = await readFields(objs, target, ref)\n if (fields && withEmbeddedFields(current, fields)) read.set(current.id, fields)\n } catch {\n // One unreadable annotation does not stop the others.\n }\n }\n } catch {\n // Unreadable bytes leave every annotation as PDF.js imported it.\n }\n return read\n}\n\nasync function readFields(\n objs: PdfObjects,\n target: EmbeddedTarget,\n ref: PdfRef\n): Promise<EmbeddedFieldPatch | undefined> {\n if (target.subtype === 'Text') {\n const icon = await readTextIcon(objs, ref)\n return icon === undefined ? undefined : { icon }\n }\n const fields = await readFreeTextFields(objs, ref, target.rect, target.daFont)\n return Object.keys(fields).length > 0 ? fields : undefined\n}\n","/** True only when the build or runtime says production; browsers without `process` count as dev. */\nexport function isProduction(): boolean {\n try {\n return process.env.NODE_ENV === 'production'\n } catch {\n return false\n }\n}\n","import { isProduction } from '../env'\nimport { readonly, writable, type Readable } from '../readable'\n\nimport { withEmbeddedFields } from './embedded-fields'\n\nimport type { RecordBase, RecordStore } from '../records'\nimport type { AnnotationChange, AnnotationEdit, AnnotationStore } from './store'\nimport type { Annotation } from './types'\n\n/** The part of a history plugins use: one undo step across annotations and record stores. */\nexport interface PluginHistory {\n batch(fn: () => void): void\n /**\n * Makes the store's changes undo steps: on their own, or joining the open batch or edit. The\n * returned function stops tracking: existing entries forget the store, so undo and redo never\n * replay it again, even once it is tracked again, and an entry left with nothing is dropped.\n */\n track(store: RecordStore<RecordBase>): () => void\n /**\n * Runs `fn` synchronously for every user `add`, `update` and `remove` of an annotation, inside\n * that edit's undo entry, so whatever `fn` changes undoes with the edit. Never runs for\n * `replace`, so never for undo and redo. Returns a function that removes `fn`.\n */\n react(fn: (edit: AnnotationEdit) => void): () => void\n}\n\nexport interface History extends PluginHistory {\n readonly canUndo: Readable<boolean>\n readonly canRedo: Readable<boolean>\n undo(): void\n redo(): void\n clear(): void\n /**\n * Runs `fn` and records everything it changes as one undo entry. Change events still fire once\n * per annotation. Nested calls join the outer batch. `fn` must be synchronous; changes after an\n * `await` are not part of the batch; a dev build warns when `fn` returns a promise. A throwing\n * `fn` still records what it changed, then rethrows. A batch whose list ends where it began\n * (the same annotations, by identity, in the same order) records nothing and keeps redo.\n * Calling `undo()` or `redo()` inside `fn` is not supported. On a controlled or destroyed\n * history this only runs `fn`, and a history destroyed inside `fn` records nothing.\n */\n batch(fn: () => void): void\n /**\n * Runs `fn` and records none of what it changes in the tracked record stores: each changed\n * record becomes part of the baseline, written into every step on both stacks (and the open\n * step), so undo and redo leave it as `fn` left it. A step left with nothing else to replay is\n * dropped. Nested calls, and calls inside a batch, work the same way. Annotation changes inside\n * `fn` are recorded as usual. On a controlled or destroyed history this only runs `fn`.\n */\n baseline(fn: () => void): void\n /** Unsubscribes from the store and empties both stacks; undo and redo become no-ops. */\n destroy(): void\n}\n\ninterface Snapshot<T> {\n before: readonly T[]\n after: readonly T[]\n}\n\ninterface RecordSnapshot extends Snapshot<RecordBase> {\n /** The ids whose record differs between `before` and `after`. */\n changed: Set<string>\n}\n\ninterface Entry {\n annotations: Snapshot<Annotation>\n /** Each tracked store that changed in this step. */\n records: Map<RecordStore<RecordBase>, RecordSnapshot>\n /** The baseline write this entry's record snapshots hold everything up to. */\n folded: number\n}\n\n/** A record a baseline write left (`undefined` when it removed it), and when. */\ninterface Override {\n record: RecordBase | undefined\n seq: number\n}\n\n/** Where an open step (a batch or an edit with its reactions) began. */\ninterface Start {\n annotations: readonly Annotation[]\n records: Map<RecordStore<RecordBase>, readonly RecordBase[]>\n}\n\nconst noop = () => {}\n\n/**\n * Snapshot-based undo and redo over an uncontrolled store.\n *\n * In controlled mode the host owns the list, so history is the host's concern (the Vue layer\n * offers `useHistory`). There `createHistory` returns an inert History: `canUndo` and `canRedo`\n * stay false, `undo` and `redo` do nothing, and nothing is recorded.\n */\nexport function createHistory(\n store: AnnotationStore,\n opts: { limit?: number } = {}\n): History {\n const canUndo = writable(false)\n const canRedo = writable(false)\n\n if (store.mode === 'controlled') {\n return {\n canUndo: readonly(canUndo),\n canRedo: readonly(canRedo),\n undo() {},\n redo() {},\n clear() {},\n batch(fn) {\n fn()\n },\n baseline(fn) {\n fn()\n },\n track: () => noop,\n react: () => noop,\n destroy() {},\n }\n }\n\n const limit = opts.limit ?? 200\n const undoStack: Entry[] = []\n const redoStack: Entry[] = []\n let previous = store.list.get()\n let replaying = false\n /**\n * Open step depth (batches, and an edit while its reactions run); while above zero, changes\n * update the baselines but push no entry.\n */\n let depth = 0\n /** Open `baseline` depth; while above zero, tracked record changes rebase every step. */\n let quiet = 0\n /** How many baseline writes there have been; each entry notes the last it holds. */\n let seq = 0\n /**\n * The latest baseline write of each record, by store and id. Entries fold in the ones newer\n * than they are when they replay, so a write costs no pass over every snapshot.\n */\n const overrides = new Map<RecordStore<RecordBase>, Map<string, Override>>()\n /** The lists when the outermost step opened (or were restarted by a replace). */\n let start: Start | null = null\n /** Each tracked store with its list as of the last change history saw. */\n const tracked = new Map<\n RecordStore<RecordBase>,\n { previous: readonly RecordBase[]; unsubscribe: () => void }\n >()\n const reactions = new Set<(edit: AnnotationEdit) => void>()\n\n const sync = () => {\n canUndo.set(undoStack.length > 0)\n canRedo.set(redoStack.length > 0)\n }\n\n const push = (entry: Entry) => {\n undoStack.push(entry)\n if (undoStack.length > limit) undoStack.shift()\n redoStack.length = 0\n sync()\n }\n\n /**\n * Forgets `recordStore`'s records in every entry, so undo and redo leave it alone. An entry\n * left with nothing to replay (no annotation change, no other store) is dropped.\n */\n const dropEntries = (recordStore: RecordStore<RecordBase>) => {\n overrides.delete(recordStore)\n for (const stack of [undoStack, redoStack]) {\n const kept = stack.filter((entry) => {\n if (!entry.records.delete(recordStore)) return true\n const { before, after } = entry.annotations\n return entry.records.size > 0 || !sameList(before, after)\n })\n stack.splice(0, stack.length, ...kept)\n }\n sync()\n }\n\n /**\n * Makes a tracked store's change from `before` to `after` part of every step's baseline: the\n * open step's start takes it now, and each entry folds it in when it replays. A written record\n * no longer differs within any step, so a step whose changes were only those records is\n * dropped now.\n */\n const rebase = (\n recordStore: RecordStore<RecordBase>,\n before: readonly RecordBase[],\n after: readonly RecordBase[]\n ) => {\n const delta = changesBetween(before, after)\n if (delta.size === 0) return\n seq++\n let latest = overrides.get(recordStore)\n if (!latest) overrides.set(recordStore, (latest = new Map<string, Override>()))\n for (const [id, record] of delta) latest.set(id, { record, seq })\n const startRecords = start?.records.get(recordStore)\n if (start && startRecords)\n start.records.set(recordStore, withChanges(startRecords, delta))\n let dropped = false\n for (const stack of [undoStack, redoStack]) {\n const kept = stack.filter((entry) => {\n const snapshot = entry.records.get(recordStore)\n if (!snapshot) return true\n let touched = false\n for (const id of delta.keys()) touched = snapshot.changed.delete(id) || touched\n if (!touched || snapshot.changed.size > 0) return true\n entry.records.delete(recordStore)\n const { before: b, after: a } = entry.annotations\n return entry.records.size > 0 || !sameList(b, a)\n })\n if (kept.length < stack.length) {\n dropped = true\n stack.splice(0, stack.length, ...kept)\n }\n }\n if (dropped) sync()\n }\n\n /** Brings `entry`'s record snapshots up to the latest baseline writes. */\n const fold = (entry: Entry) => {\n for (const [s, snapshot] of entry.records) {\n const latest = overrides.get(s)\n if (!latest) continue\n const delta = new Map<string, RecordBase | undefined>()\n for (const [id, o] of latest) if (o.seq > entry.folded) delta.set(id, o.record)\n if (delta.size === 0) continue\n snapshot.before = withChanges(snapshot.before, delta)\n snapshot.after = withChanges(snapshot.after, delta)\n }\n entry.folded = seq\n }\n\n /** A record snapshot from `before` to `after`, or `undefined` when no record differs. */\n const snapshotOf = (\n before: readonly RecordBase[],\n after: readonly RecordBase[]\n ): RecordSnapshot | undefined => {\n const changed = new Set(changesBetween(before, after).keys())\n return changed.size > 0 ? { before, after, changed } : undefined\n }\n\n const resetStacks = () => {\n undoStack.length = 0\n redoStack.length = 0\n overrides.clear()\n sync()\n }\n\n /** Opens the outermost step from `annotations` and every tracked store's baseline. */\n const open = (annotations: readonly Annotation[]) => {\n const records = new Map<RecordStore<RecordBase>, readonly RecordBase[]>()\n for (const [s, t] of tracked) records.set(s, t.previous)\n start = { annotations, records }\n }\n\n /**\n * Closes the outermost step: one entry for everything that changed since it opened. A step\n * whose annotation list ends where it began (the same objects in the same order) and whose\n * stores hold the same records records nothing. Records are compared by id and identity, in\n * any order, the same rule `rebase` uses.\n */\n const close = () => {\n const from = start\n start = null\n if (!from) return\n const annotations = { before: from.annotations, after: store.list.get() }\n previous = annotations.after\n const records = new Map<RecordStore<RecordBase>, RecordSnapshot>()\n for (const [s, t] of tracked) {\n const after = s.list.get()\n const snapshot = snapshotOf(from.records.get(s) ?? t.previous, after)\n t.previous = after\n if (snapshot) records.set(s, snapshot)\n }\n if (records.size === 0 && sameList(annotations.before, annotations.after)) return\n push({ annotations, records, folded: seq })\n }\n\n let destroyed = false\n const unsubscribe = store.on('change', (change: AnnotationChange) => {\n const current = store.list.get()\n // Our own replays (and any other history replace) never become entries.\n if (replaying || (change.kind === 'replace' && change.reason === 'history')) {\n previous = current\n return\n }\n if (change.kind === 'replace' && change.reason === 'embedded') {\n // Fields read from the file late fill in what the import missed: no step, and every\n // snapshot gets the same fields so undo never brings back the unfilled version. Each\n // snapshot keeps its own edits, such as a colour changed before the fields arrived.\n const fill = (list: readonly Annotation[]) =>\n list.map((a) => {\n const f = change.fields.get(a.id)\n return (f && withEmbeddedFields(a, f)) || a\n })\n for (const { annotations } of [...undoStack, ...redoStack]) {\n annotations.before = fill(annotations.before)\n annotations.after = fill(annotations.after)\n }\n if (start) start.annotations = fill(start.annotations)\n previous = current\n return\n }\n if (change.kind === 'replace') {\n previous = current\n if (depth > 0) open(current)\n resetStacks()\n return\n }\n if (depth > 0) {\n // Inside a batch or another edit's reactions: react, and the open step records it all.\n previous = current\n for (const fn of [...reactions]) fn(change)\n return\n }\n // An edit on its own: its reactions run inside a step that opens before the edit.\n open(previous)\n depth++\n try {\n for (const fn of [...reactions]) fn(change)\n } finally {\n // A history destroyed by a reaction records nothing more.\n if (--depth === 0 && !destroyed) close()\n }\n })\n\n /** Replays a step's lists under the `replaying` guard, skipping stores no longer tracked. */\n const apply = (entry: Entry, side: 'before' | 'after') => {\n fold(entry)\n replaying = true\n try {\n const { annotations } = entry\n if (!sameList(annotations.before, annotations.after))\n store.replaceAll([...annotations[side]], 'history')\n for (const [s, snapshot] of entry.records)\n if (tracked.has(s)) s.replaceAll([...snapshot[side]], 'history')\n } finally {\n replaying = false\n }\n }\n\n return {\n canUndo: readonly(canUndo),\n canRedo: readonly(canRedo),\n undo() {\n const entry = undoStack.pop()\n if (destroyed || !entry) return\n redoStack.push(entry)\n apply(entry, 'before')\n sync()\n },\n redo() {\n const entry = redoStack.pop()\n if (destroyed || !entry) return\n undoStack.push(entry)\n apply(entry, 'after')\n sync()\n },\n batch(fn) {\n if (destroyed) {\n fn()\n return\n }\n if (depth++ === 0) open(store.list.get())\n try {\n const result: unknown = fn()\n if (\n result !== null &&\n typeof result === 'object' &&\n typeof (result as { then?: unknown }).then === 'function' &&\n !isProduction()\n ) {\n console.warn(\n '[inkbar] history.batch(fn): fn returned a promise. Changes after its first await are not part of the batch.'\n )\n }\n } finally {\n // A history destroyed inside `fn` records nothing more.\n if (--depth === 0 && !destroyed) close()\n }\n },\n baseline(fn) {\n if (destroyed) {\n fn()\n return\n }\n quiet++\n try {\n fn()\n } finally {\n quiet--\n }\n },\n track(recordStore) {\n if (destroyed || tracked.has(recordStore)) return noop\n const unsubscribeStore = recordStore.on('change', (change) => {\n const t = tracked.get(recordStore)\n if (!t) return\n const before = t.previous\n const current = recordStore.list.get()\n t.previous = current\n // Our own replays (and any other history replace) never become entries.\n if (replaying || (change.kind === 'replace' && change.reason === 'history'))\n return\n if (quiet > 0 && change.kind !== 'replace') {\n rebase(recordStore, before, current)\n return\n }\n if (change.kind === 'replace') {\n // A reset starts the store over, so no older step holding its records can be replayed.\n if (depth > 0 && start) start.records.set(recordStore, current)\n dropEntries(recordStore)\n return\n }\n if (depth > 0) return\n const snapshot = snapshotOf(before, current)\n if (!snapshot) return\n push({\n annotations: { before: previous, after: previous },\n records: new Map([[recordStore, snapshot]]),\n folded: seq,\n })\n })\n tracked.set(recordStore, {\n previous: recordStore.list.get(),\n unsubscribe: unsubscribeStore,\n })\n // Tracked inside an open step: the step covers it from here.\n if (start) start.records.set(recordStore, recordStore.list.get())\n return () => {\n if (tracked.get(recordStore)?.unsubscribe !== unsubscribeStore) return\n unsubscribeStore()\n tracked.delete(recordStore)\n // As a reset does: no step replays the store again, even if it is tracked again,\n // so none can rewind a baseline write or a change made while it was untracked.\n dropEntries(recordStore)\n start?.records.delete(recordStore)\n }\n },\n react(fn) {\n if (destroyed) return noop\n // Wrapped, so the same function added twice runs twice and each handle removes its own.\n const run = (edit: AnnotationEdit) => fn(edit)\n reactions.add(run)\n return () => {\n reactions.delete(run)\n }\n },\n destroy() {\n destroyed = true\n start = null\n unsubscribe()\n for (const t of tracked.values()) t.unsubscribe()\n tracked.clear()\n reactions.clear()\n resetStacks()\n },\n clear() {\n previous = store.list.get()\n for (const [s, t] of tracked) t.previous = s.list.get()\n resetStacks()\n },\n }\n}\n\n/** Each record that differs between two lists, by id; `undefined` for one removed. */\nfunction changesBetween(\n before: readonly RecordBase[],\n after: readonly RecordBase[]\n): Map<string, RecordBase | undefined> {\n const was = new Map(before.map((r) => [r.id, r]))\n const delta = new Map<string, RecordBase | undefined>()\n for (const r of after) {\n if (was.get(r.id) !== r) delta.set(r.id, r)\n was.delete(r.id)\n }\n for (const id of was.keys()) delta.set(id, undefined)\n return delta\n}\n\n/** `list` with `delta` written in: changed records replaced, removed ones dropped, new ones added. */\nfunction withChanges(\n list: readonly RecordBase[],\n delta: ReadonlyMap<string, RecordBase | undefined>\n): readonly RecordBase[] {\n const seen = new Set<string>()\n const out: RecordBase[] = []\n for (const r of list) {\n if (!delta.has(r.id)) {\n out.push(r)\n continue\n }\n seen.add(r.id)\n const next = delta.get(r.id)\n if (next) out.push(next)\n }\n for (const [id, r] of delta) if (r && !seen.has(id)) out.push(r)\n return out\n}\n\n/** The same objects in the same order. */\nfunction sameList<T>(a: readonly T[], b: readonly T[]): boolean {\n return a === b || (a.length === b.length && a.every((x, i) => x === b[i]))\n}\n","import type { ExportedAnnotation } from './types'\nimport type { Annotation as GlossAnnotation } from 'gloss-format'\n\n/** Inkbar's own data in a Gloss file, under custom.inkbar. */\nexport interface InkbarCustom {\n type?: 'loupe' | 'mask'\n magnification?: number\n dim?: number\n pressure?: number[][]\n borderColor?: string\n}\n\ntype Item = Record<string, unknown>\n\nconst isObject = (v: unknown): v is Item =>\n typeof v === 'object' && v !== null && !Array.isArray(v)\n\n/** `rest` with `own` merged into a copy of its `custom.inkbar`; `own` wins. */\nfunction withCustom(rest: Item, own: InkbarCustom): Item {\n const custom = isObject(rest.custom) ? rest.custom : {}\n const inkbar = isObject(custom.inkbar) ? custom.inkbar : {}\n return { ...rest, custom: { ...custom, inkbar: { ...inkbar, ...own } } }\n}\n\n/**\n * An annotation as a Gloss file writes it. Gloss has no loupe or mask and no pen pressure or\n * free-text border colour, so these go under `custom.inkbar`, with loupes and masks written as\n * the circle or square they draw.\n */\nexport function toFile(annotation: ExportedAnnotation): GlossAnnotation {\n switch (annotation.type) {\n case 'ink': {\n const { pressure, ...rest } = annotation\n return (pressure ? withCustom(rest, { pressure }) : rest) as GlossAnnotation\n }\n case 'freetext': {\n const { borderColor, ...rest } = annotation\n return (borderColor ? withCustom(rest, { borderColor }) : rest) as GlossAnnotation\n }\n case 'loupe': {\n const { magnification, ...rest } = annotation\n return withCustom(\n { ...rest, type: 'circle' },\n { type: 'loupe', magnification }\n ) as GlossAnnotation\n }\n case 'mask': {\n const { shape, dim, ...rest } = annotation\n return withCustom(\n { ...rest, type: shape === 'ellipse' ? 'circle' : 'square' },\n { type: 'mask', dim }\n ) as GlossAnnotation\n }\n default:\n return annotation\n }\n}\n\n/**\n * Moves `keys` from `custom.inkbar` to the top level of `raw`, replacing any top-level value\n * (an absent key deletes it), then drops `custom.inkbar`, and `custom`, if that leaves them\n * empty. Everything else under `custom` stays as it was.\n */\nfunction lift(raw: Item, inkbar: Item, keys: readonly string[], extra: Item = {}): Item {\n const item: Item = { ...raw, ...extra }\n const left: Item = { ...inkbar }\n let consumed = false\n for (const key of keys) {\n delete item[key]\n if (key in left) {\n item[key] = left[key]\n delete left[key]\n consumed = true\n }\n }\n if (!consumed || !isObject(raw.custom)) return item\n const { inkbar: _inkbar, ...others } = raw.custom\n const custom = Object.keys(left).length > 0 ? { ...others, inkbar: left } : others\n if (Object.keys(custom).length > 0) item.custom = custom\n else delete item.custom\n return item\n}\n\n/** A file item read back by `fromFile`. */\nexport interface FromFile {\n /** The object for ExportedAnnotationSchema to parse. */\n item: Record<string, unknown>\n /**\n * Top-level keys of `item` that the file keeps under `custom.inkbar`, so an error in one is\n * reported at `custom.inkbar.<key>`.\n */\n lifted: readonly string[]\n}\n\n/**\n * A raw file item as Inkbar parses it: Inkbar's own data moves out of `custom.inkbar`. An item\n * it doesn't recognise passes through unchanged.\n */\nexport function fromFile(raw: Record<string, unknown>): FromFile {\n const inkbar =\n isObject(raw.custom) && isObject(raw.custom.inkbar) ? raw.custom.inkbar : {}\n const from = (keys: readonly string[], extra?: Item): FromFile => ({\n item: lift(raw, inkbar, keys, extra),\n lifted: keys,\n })\n const unchanged: FromFile = { item: raw, lifted: [] }\n switch (raw.type) {\n // A top-level `pressure` or `borderColor`, as older files wrote them, is dropped.\n case 'ink':\n return from(['pressure'])\n case 'freetext':\n return from(['borderColor'])\n case 'circle':\n if (inkbar.type === 'loupe') return from(['type', 'magnification'])\n if (inkbar.type === 'mask') return from(['type', 'dim'], { shape: 'ellipse' })\n return unchanged\n case 'square':\n if (inkbar.type === 'mask') return from(['type', 'dim'], { shape: 'rect' })\n return unchanged\n default:\n return unchanged\n }\n}\n","import { isProduction } from '../env'\nimport { fieldsFromGloss, type GlossRejection } from '../form/gloss'\n\nimport { fromFile, toFile } from './gloss-mapping'\nimport {\n AnnotationDocumentSchema,\n ExportedAnnotationSchema,\n GLOSS_FORMAT,\n GLOSS_VERSION,\n type Annotation,\n type AnnotationDocument,\n type ForeignAnnotation,\n} from './types'\n\nimport type { AnnotationStore } from './store'\nimport type { FieldValue, FieldValues, FormField } from '../form/types'\nimport type { Annotation as GlossAnnotation } from 'gloss-format'\n\nexport interface ImportResult {\n imported: number\n /**\n * Items whose `type` this version does not know (they still need a string `id` and a numeric\n * `page`). Keep them and pass them back to exportAnnotations.\n */\n unknown: ForeignAnnotation[]\n errors: { index: number; issues: string[] }[]\n /** The document's `fields` names that were applied, and the ones that were not, with why. */\n fields: { applied: string[]; rejected: GlossRejection[] }\n}\n\nexport interface ImportOptions {\n /** `replace` drops every session annotation first; `merge` overwrites by id and keeps the rest. */\n mode: 'replace' | 'merge'\n}\n\n/**\n * @internal The Gloss types this core parses, taken from its own schemas rather than Gloss's\n * list, so a type a later Gloss adds is still treated as foreign here. Loupes and masks are\n * Inkbar's own types: a file writes them as circles and squares, so a `loupe` or `mask` item is\n * foreign too.\n */\nexport const KNOWN_TYPES: ReadonlySet<string> = new Set(\n ExportedAnnotationSchema.options\n .flatMap((o) => [...o.shape.type._zod.values] as string[])\n .filter((type) => type !== 'loupe' && type !== 'mask')\n)\n\n/**\n * Session annotations plus any preserved foreign items. Embedded (`source: 'pdf'`) ones stay in\n * the file. `source` and `locked` are viewer state and are left out.\n *\n * The result is a JSON copy (`JSON.parse(JSON.stringify(...))`), the same data a serialised\n * export would carry: editing it never touches the store, and values JSON cannot hold, such as\n * functions or `undefined` inside `custom`, are left out exactly as `JSON.stringify` would.\n *\n * Gloss has no loupe or mask, pen pressure or free-text border colour, so Inkbar writes these\n * under `custom.inkbar`, with loupes and masks as the circle or square they draw. Every other key\n * under `custom` goes out as it is.\n *\n * `fields`, when given and not empty, goes out as the document's `fields` (see `fieldsToGloss`).\n *\n * The result validates against the Gloss schema (`gloss-format/schema.json`). Foreign items\n * validate as unknown annotations while their type is one Gloss does not define.\n */\nexport function exportAnnotations(\n store: AnnotationStore,\n preserved: readonly ForeignAnnotation[] = [],\n documentKey?: string,\n fields: Readonly<Record<string, FieldValue>> = {}\n): AnnotationDocument {\n const session: GlossAnnotation[] = store.list\n .get()\n .filter((a) => a.source === 'session')\n .map(({ source: _source, locked: _locked, ...rest }) => toFile(rest))\n return {\n format: GLOSS_FORMAT,\n version: GLOSS_VERSION,\n ...(documentKey === undefined ? {} : { documentKey }),\n annotations: JSON.parse(JSON.stringify([...session, ...preserved])) as Array<\n GlossAnnotation | ForeignAnnotation\n >,\n ...(Object.keys(fields).length === 0\n ? {}\n : { fields: JSON.parse(JSON.stringify(fields)) as Record<string, FieldValue> }),\n }\n}\n\n/** @internal A validated import that has not touched the store yet. */\nexport interface ImportPlan {\n result: ImportResult\n /** Every id the payload brings in, known or foreign. */\n ids: ReadonlySet<string>\n /** The `fields` values that suit the form, for the document to apply. */\n fieldValues: FieldValues\n /** Applies the plan to the store (one `replaceAll(..., 'import')`). */\n apply(): void\n}\n\n/**\n * Validates the envelope (throws a TypeError when it is not a gloss v1 document),\n * then each item on its own. Embedded annotations are never touched; imported items become\n * session annotations. With no form to apply them to, every `fields` name is reported as\n * unknown; `InkDocument.importAnnotations` applies them to the document's form.\n */\nexport function importAnnotations(\n store: AnnotationStore,\n data: AnnotationDocument | string,\n opts: ImportOptions\n): ImportResult {\n const plan = planImport(store, data, opts)\n plan.apply()\n return plan.result\n}\n\n/**\n * @internal Validation half of `importAnnotations`, so the document can record foreign items\n * before the store publishes the change.\n *\n * Ids are unique across the payload: the first item with an id claims it, and later ones (known\n * or foreign) are reported in `errors`, even when the first was itself rejected. An id that\n * matches an embedded annotation is rejected for known and foreign items alike. In `merge` mode an incoming item replaces whatever session\n * annotation has its id, whether the incoming item is known or foreign.\n */\nexport function planImport(\n store: AnnotationStore,\n data: AnnotationDocument | string,\n opts: ImportOptions,\n formFields: readonly FormField[] = []\n): ImportPlan {\n const raw: unknown = typeof data === 'string' ? JSON.parse(data) : data\n const envelope = AnnotationDocumentSchema.safeParse(raw)\n if (!envelope.success) {\n throw new TypeError(\n `Expected a ${GLOSS_FORMAT} v${GLOSS_VERSION} document: ${envelope.error.issues\n .map((i) => `${i.path.join('.') || '(root)'}: ${i.message}`)\n .join('; ')}`\n )\n }\n const embeddedIds = new Set(\n store.list\n .get()\n .filter((a) => a.source === 'pdf')\n .map((a) => a.id)\n )\n const fields = fieldsFromGloss(envelope.data.fields, formFields)\n const result: ImportResult = {\n imported: 0,\n unknown: [],\n errors: [],\n fields: { applied: Object.keys(fields.values), rejected: fields.rejected },\n }\n const incoming: Annotation[] = []\n /** id -> index of the first item that used it, whether that item was accepted or not. */\n const seen = new Map<string, number>()\n /** Ids the import actually brings in. */\n const accepted = new Set<string>()\n /**\n * Reserves `id` for the item at `index`. Later items with the same id are duplicates even\n * when this one is rejected for reusing an embedded id.\n */\n const claim = (id: string, index: number): boolean => {\n const first = seen.get(id)\n if (first !== undefined) {\n result.errors.push({\n index,\n issues: [`id: duplicate id \"${id}\", already used by item ${first}`],\n })\n return false\n }\n seen.set(id, index)\n if (embeddedIds.has(id)) {\n result.errors.push({\n index,\n issues: [\n 'id: matches an annotation embedded in the PDF, which import never replaces',\n ],\n })\n return false\n }\n accepted.add(id)\n return true\n }\n\n envelope.data.annotations.forEach((raw, index) => {\n const type = (raw as { type?: unknown } | null)?.type\n if (typeof type === 'string' && !KNOWN_TYPES.has(type)) {\n if (!isForeign(raw)) {\n result.errors.push({\n index,\n issues: [\n `type: unknown type \"${type}\" needs a string id and a numeric page to be preserved`,\n ],\n })\n } else if (claim(raw.id, index)) {\n result.unknown.push(raw)\n }\n return\n }\n // Inkbar's own data comes back out of `custom.inkbar`: a circle or square marked there as a\n // loupe or mask becomes one. Unknown keys, including `source` and `locked`, are dropped here.\n const { item, lifted } =\n isRecord(raw) && typeof type === 'string'\n ? fromFile(raw)\n : { item: raw, lifted: [] as readonly string[] }\n const parsed = ExportedAnnotationSchema.safeParse(item)\n if (!parsed.success) {\n result.errors.push({\n index,\n // An error in a key Inkbar keeps under custom.inkbar names it where the file has it.\n issues: parsed.error.issues.map((i) => {\n const path = i.path.join('.')\n const own = typeof i.path[0] === 'string' && lifted.includes(i.path[0])\n return `${own ? `custom.inkbar.${path}` : path}: ${i.message}`\n }),\n })\n return\n }\n if (!claim(parsed.data.id, index)) return\n incoming.push({ ...parsed.data, source: 'session' })\n result.imported++\n })\n\n if (result.unknown.length > 0 && !isProduction()) {\n const types = [...new Set(result.unknown.map((u) => u.type))]\n console.warn(\n `[inkbar] importAnnotations kept ${result.unknown.length} annotation(s) of unknown type ` +\n `(${types.join(', ')}). They are not shown, and exportAnnotations writes them back out.`\n )\n }\n\n const ids: ReadonlySet<string> = accepted\n return {\n result,\n ids,\n fieldValues: fields.values,\n apply() {\n const current = store.list.get()\n const embedded = current.filter((a) => a.source === 'pdf')\n if (opts.mode === 'replace') {\n store.replaceAll([...embedded, ...incoming], 'import')\n return\n }\n const byId = new Map(\n current\n .filter((a) => a.source === 'session' && !ids.has(a.id))\n .map((a) => [a.id, a])\n )\n for (const a of incoming) byId.set(a.id, a)\n store.replaceAll([...embedded, ...byId.values()], 'import')\n },\n }\n}\n\nfunction isRecord(item: unknown): item is Record<string, unknown> {\n return typeof item === 'object' && item !== null && !Array.isArray(item)\n}\n\nfunction isForeign(item: unknown): item is ForeignAnnotation {\n if (!isRecord(item)) return false\n const { type, id, page } = item\n return typeof type === 'string' && typeof id === 'string' && typeof page === 'number'\n}\n","import { v7 as uuidv7 } from 'uuid'\n\nimport { isProduction } from '../env'\nimport { Emitter } from '../events'\nimport { rectFromQuad, unionRects, type Point, type Rect } from '../geometry'\nimport { readonly, writable, type Readable } from '../readable'\n\nimport { withEmbeddedFields } from './embedded-fields'\nimport {\n AnnotationSchema,\n type Annotation,\n type AnnotationInput,\n type AnnotationPatch,\n} from './types'\n\nimport type { AnnotationDefaults } from './defaults'\nimport type { EmbeddedFieldPatch } from './embedded'\n\nexport type AnnotationChange =\n | { kind: 'add'; annotation: Annotation }\n | { kind: 'update'; id: string; before: Annotation; after: Annotation }\n | {\n kind: 'remove'\n /** The annotation `remove` was called with. */\n annotation: Annotation\n /** Everything that went: `annotation` first, then the replies removed with it. */\n removed: Annotation[]\n }\n | { kind: 'replace'; reason: 'import' | 'sync' | 'history' }\n | {\n kind: 'replace'\n /** Fields read from the file after `ready` filled in embedded annotations. */\n reason: 'embedded'\n /** What was merged into each annotation, by id. */\n fields: ReadonlyMap<string, EmbeddedFieldPatch>\n }\n\n/** The changes `edit` reports: one per `add`, `update` or `remove` call that changed something. */\nexport type AnnotationEdit = Extract<\n AnnotationChange,\n { kind: 'add' | 'update' | 'remove' }\n>\n\nexport type StoreMode =\n | { mode: 'uncontrolled'; initial?: Annotation[] }\n | {\n mode: 'controlled'\n initial: Annotation[]\n onChange: (next: Annotation[], change: AnnotationChange) => void\n }\n\nexport interface AnnotationStore {\n readonly mode: 'uncontrolled' | 'controlled'\n readonly list: Readable<readonly Annotation[]>\n readonly selection: Readable<readonly string[]>\n /** The colour, fill and opacity defaults new annotations get. */\n readonly defaults: AnnotationDefaults\n get(id: string): Annotation | undefined\n byPage(page: number): Annotation[]\n /**\n * Returns the completed annotation. In controlled mode it is proposed to the host, not\n * applied. Throws an `Error` naming the id when it is already in the list, whether it came\n * from `input.id` or the store's `id` generator.\n */\n add(input: AnnotationInput): Annotation\n /**\n * `id`, `type`, `createdAt` and `source` cannot be patched, nor can `locked` on an embedded\n * (`source: 'pdf'`) annotation: those keys are ignored. `modifiedAt` is always bumped. A\n * locked annotation refuses any patch to its geometry, `page` or `contents`.\n */\n update(id: string, patch: AnnotationPatch): Annotation | undefined\n remove(id: string): boolean\n select(ids: string[]): void\n /**\n * Uncontrolled: embedded annotations survive (the list may edit them like `update` would, but\n * cannot drop or add them). Controlled: proposes the list minus embedded items to `onChange`.\n */\n replaceAll(list: Annotation[], reason: 'import' | 'sync' | 'history'): void\n /**\n * Controlled mode only: the host pushes its current list. Embedded (`source: 'pdf'`) items\n * belong to the store, so they stay in `list` whatever the host sends; host items that reuse\n * an embedded id are dropped.\n */\n setControlledValue(list: Annotation[]): void\n /**\n * @internal Replaces the annotations embedded in the file (`source: 'pdf'`). Applied\n * directly in both modes and never passed to `onChange`; the document calls it once on open.\n */\n _setEmbedded(list: readonly Annotation[]): void\n /**\n * @internal Merges fields read from the file into embedded annotations, by id, onto their\n * current version (only ids still present with `source: 'pdf'`; a merge that fails the schema\n * is skipped). A host edit to a read field made before the pass lands is overwritten by the\n * read value. Applied directly in both modes and never passed to `onChange`. Emits\n * `{ kind: 'replace', reason: 'embedded', fields }` when anything changed.\n */\n _patchEmbedded(fields: ReadonlyMap<string, EmbeddedFieldPatch>): void\n /**\n * @internal Like `get`, but in controlled mode it also sees changes proposed to the host and\n * not applied yet: the list `update` and `remove` build on.\n */\n _getProposed(id: string): Annotation | undefined\n /**\n * @internal Pins annotations to what they fill (a signature to its signature field): a\n * pinned annotation takes patches only to `contents` and to `custom` outside its `inkbar`\n * key, and refuses any other (no move, resize, restyle, new image or new author), while\n * `remove` still works. Replaces the whole set.\n */\n _setPinned(ids: ReadonlySet<string>): void\n /** @internal Whether `_setPinned` pinned `id`. */\n _isPinned(id: string): boolean\n /** @internal The pinned ids, for the overlay. */\n readonly _pinned: Readable<ReadonlySet<string>>\n completeInput(input: AnnotationInput): Annotation\n on(event: 'change', fn: (change: AnnotationChange) => void): () => void\n /**\n * Fires synchronously for every `add`, `update` and `remove` that changes something, in both\n * modes, before the list is set (uncontrolled) or `onChange` is called (controlled). Never\n * for `replace`.\n */\n on(event: 'edit', fn: (change: AnnotationEdit) => void): () => void\n destroy(): void\n}\n\nexport interface StoreOptions {\n mode: StoreMode\n defaults: AnnotationDefaults\n now?: () => string\n id?: () => string\n}\n\n/** Keys a locked annotation refuses to change. */\nconst LOCKED_KEYS = new Set([\n 'page',\n 'rect',\n 'quads',\n 'inklist',\n 'start',\n 'end',\n 'vertices',\n 'callout',\n 'contents',\n 'imagedata',\n 'rotation',\n])\n\n/**\n * Keys a pinned annotation still takes: its comment and the host's own data. Geometry, style,\n * its image or ink, its author (who signed), subject, rotation and lock are refused.\n */\nconst PINNED_KEYS = new Set(['contents', 'custom'])\n\n/**\n * Whether `patch` changes nothing a pinned annotation keeps: only `PINNED_KEYS`, and a\n * `custom` that leaves Inkbar's own `custom.inkbar` (which can carry ink pressure) as it was.\n */\nfunction pinnedAccepts(before: Annotation, patch: Record<string, unknown>): boolean {\n if (Object.keys(patch).some((k) => !PINNED_KEYS.has(k))) return false\n if (!('custom' in patch)) return true\n const inkbar = (c: unknown) => (c as { inkbar?: unknown } | undefined)?.inkbar\n return deepEqual(inkbar(patch.custom), inkbar(before.custom))\n}\n\nfunction keepKey(target: Record<string, unknown>, from: Annotation, key: string): void {\n if (Object.prototype.hasOwnProperty.call(from, key))\n target[key] = (from as Record<string, unknown>)[key]\n else delete target[key]\n}\n\n/** `proposed` as a replacement for embedded `current`, with what the file owns kept from `current`. */\nfunction guardEmbedded(current: Annotation, proposed: Annotation): Annotation {\n if (proposed === current) return current\n if (proposed.type !== current.type) return current\n const candidate: Record<string, unknown> = {\n ...proposed,\n id: current.id,\n createdAt: current.createdAt,\n source: 'pdf',\n }\n keepKey(candidate, current, 'locked')\n keepKey(candidate, current, 'hasAppearance')\n if (current.locked) for (const key of LOCKED_KEYS) keepKey(candidate, current, key)\n const parsed = AnnotationSchema.safeParse(candidate)\n return parsed.success ? parsed.data : current\n}\n\nexport function deriveRect(input: AnnotationInput): Rect {\n switch (input.type) {\n case 'highlight':\n case 'underline':\n case 'strikeout':\n case 'squiggly':\n return unionRects(input.quads.map(rectFromQuad))\n case 'redact':\n if (input.quads) return unionRects(input.quads.map(rectFromQuad))\n break\n case 'ink': {\n const pad = (input.width ?? 2) / 2\n const r = bounds(input.inklist.flat())\n return {\n x: r.x - pad,\n y: r.y - pad,\n width: r.width + pad * 2,\n height: r.height + pad * 2,\n }\n }\n case 'line':\n return bounds([input.start, input.end])\n case 'polyline':\n case 'polygon':\n return bounds(input.vertices)\n default:\n break\n }\n if (input.rect) return input.rect\n throw new TypeError(`rect is required for ${input.type}`)\n}\n\nfunction bounds(pts: readonly Point[]): Rect {\n const xs = pts.map((p) => p.x)\n const ys = pts.map((p) => p.y)\n const x = Math.min(...xs)\n const y = Math.min(...ys)\n return { x, y, width: Math.max(...xs) - x, height: Math.max(...ys) - y }\n}\n\n/** `o` without its `undefined` values. */\nfunction withoutUndefined(o: object): Record<string, unknown> {\n return Object.fromEntries(Object.entries(o).filter(([, v]) => v !== undefined))\n}\n\n/**\n * A `defaultStyle` patch merges one level deep into the current one, so changing the weight\n * keeps the font and size. An `undefined` value removes its key.\n */\nfunction mergedStyle(\n before: Annotation,\n patch: AnnotationPatch\n): { defaultStyle?: Record<string, unknown> } {\n const next = (patch as { defaultStyle?: unknown }).defaultStyle\n if (before.type !== 'freetext' || next === undefined || next === null) return {}\n return { defaultStyle: withoutUndefined({ ...before.defaultStyle, ...next }) }\n}\n\n/** Pending-map key; only annotation changes are tracked, and the prefix keeps ids apart from any other slot. */\nfunction changeKey(change: Exclude<AnnotationChange, { kind: 'replace' }>): string {\n return `annotation:${change.kind === 'update' ? change.id : change.annotation.id}`\n}\n\n/** Structural equality for plain JSON values, ignoring `modifiedAt` at the top level. */\nfunction sameIgnoringModifiedAt(a: Annotation, b: Annotation): boolean {\n const { modifiedAt: _a, ...restA } = a\n const { modifiedAt: _b, ...restB } = b\n return deepEqual(restA, restB)\n}\n\nfunction deepEqual(a: unknown, b: unknown): boolean {\n if (Object.is(a, b)) return true\n if (typeof a !== 'object' || typeof b !== 'object' || a === null || b === null)\n return false\n if (Array.isArray(a) !== Array.isArray(b)) return false\n const ka = Object.keys(a)\n const kb = Object.keys(b)\n if (ka.length !== kb.length) return false\n return ka.every(\n (k) =>\n Object.prototype.hasOwnProperty.call(b, k) &&\n deepEqual((a as Record<string, unknown>)[k], (b as Record<string, unknown>)[k])\n )\n}\n\nfunction isApplied(change: AnnotationChange, current: readonly Annotation[]): boolean {\n switch (change.kind) {\n case 'add':\n return current.some((a) => a.id === change.annotation.id)\n case 'remove':\n return !current.some((a) => a.id === change.annotation.id)\n case 'update': {\n const mine = current.find((a) => a.id === change.id)\n if (!mine) return false\n // A host or server may re-stamp modifiedAt, so fall back to a structural match.\n return mine === change.after || sameIgnoringModifiedAt(mine, change.after)\n }\n case 'replace':\n return true\n }\n}\n\ninterface Pending {\n id: string\n change: AnnotationChange\n timer: ReturnType<typeof setTimeout>\n}\n\nexport function createAnnotationStore(opts: StoreOptions): AnnotationStore {\n const now = opts.now ?? (() => new Date().toISOString())\n const nextId = opts.id ?? (() => uuidv7())\n const list = writable<readonly Annotation[]>([...(opts.mode.initial ?? [])])\n const selection = writable<readonly string[]>([])\n const pinned = writable<ReadonlySet<string>>(new Set())\n const emitter = new Emitter<{ change: AnnotationChange; edit: AnnotationEdit }>()\n const controlled = opts.mode.mode === 'controlled' ? opts.mode : undefined\n const pending = new Map<string, Pending>()\n /**\n * Controlled mode: the list as the store last proposed it, embedded items included. Later\n * proposals build on it, so several mutations in a row (one highlight per page, a bulk\n * remove, add then select) all reach the host. It resets to the applied list when the host\n * pushes a value or a pending change's check fires without one.\n */\n let proposed: readonly Annotation[] | undefined\n let destroyed = false\n\n /** What mutations build on: the pending proposal in controlled mode, else the list. */\n const basis = (): readonly Annotation[] => proposed ?? list.get()\n const findIn = (items: readonly Annotation[], id: string): Annotation | undefined =>\n items.find((a) => a.id === id)\n\n function completeInput(input: AnnotationInput): Annotation {\n const ts = now()\n const candidate: Record<string, unknown> = {\n ...input,\n id: input.id ?? nextId(),\n rect: input.rect ?? deriveRect(input),\n color: input.color ?? opts.defaults.color(input.type),\n opacity: input.opacity ?? opts.defaults.opacity(input.type),\n createdAt: ts,\n modifiedAt: ts,\n source: 'session',\n }\n if (input.type === 'freetext') {\n // A box's `color` is its fill, which has no default: the default colour is the text's.\n if (input.color === undefined) delete candidate.color\n candidate.defaultStyle = {\n color: opts.defaults.color('freetext'),\n ...withoutUndefined(input.defaultStyle ?? {}),\n }\n }\n if (input.type === 'redact') {\n if (input.interiorColor === undefined)\n candidate.interiorColor = opts.defaults.fill()\n }\n return AnnotationSchema.parse(candidate)\n }\n\n function clearPending(key: string): void {\n const entry = pending.get(key)\n if (!entry) return\n clearTimeout(entry.timer)\n pending.delete(key)\n }\n\n function warnIfIgnored(key: string): void {\n const entry = pending.get(key)\n if (!entry) return\n pending.delete(key)\n // Later proposals may still be pending; they keep building on the proposed list.\n if (pending.size === 0) proposed = undefined\n // A refused add leaves nothing to select. Pruning makes the refusal observable, so a\n // one-shot tool that reported it made returns to ready.\n pruneSelection(basis())\n if (isApplied(entry.change, list.get()) || isProduction()) return\n console.warn(\n `[inkbar] ControlledMutationIgnored: the host did not apply a ${entry.change.kind} for ` +\n `annotation ${entry.id}. In controlled mode, pass the list from onChange back into the store.`\n )\n }\n\n function commit(next: readonly Annotation[], change: AnnotationChange): void {\n if (change.kind !== 'replace') emitter.emit('edit', change)\n if (controlled) {\n if (change.kind !== 'replace') {\n const key = changeKey(change)\n clearPending(key)\n // Two macrotasks. Vue applies the change in a microtask; React may apply it after its\n // scheduler's macrotask plus an effect, so one macrotask warns a host that did apply it.\n const entry: Pending = {\n id: change.kind === 'update' ? change.id : change.annotation.id,\n change,\n timer: setTimeout(() => {\n entry.timer = setTimeout(() => {\n warnIfIgnored(key)\n }, 0)\n }, 0),\n }\n pending.set(key, entry)\n }\n proposed =\n change.kind === 'replace'\n ? [\n ...list.get().filter((a) => a.source === 'pdf'),\n ...next.filter((a) => a.source !== 'pdf'),\n ]\n : next\n // Embedded items are the store's, never the host's.\n controlled.onChange(\n next.filter((a) => a.source !== 'pdf'),\n change\n )\n return\n }\n list.set(next)\n emitter.emit('change', change)\n }\n\n /**\n * Uncontrolled `replaceAll` cannot drop or forge embedded annotations: every current embedded\n * item stays (taking the list's version of it, guarded like `update`, when the list has one),\n * and items claiming `source: 'pdf'` that the store does not hold are dropped. History\n * snapshots contain the embedded items, so undo and redo of their edits still work.\n */\n function withEmbedded(proposed: readonly Annotation[]): Annotation[] {\n const current = new Map(\n list\n .get()\n .filter((a) => a.source === 'pdf')\n .map((a) => [a.id, a])\n )\n const seen = new Set<string>()\n const out: Annotation[] = []\n for (const a of proposed) {\n const mine = current.get(a.id)\n if (mine) {\n if (!seen.has(a.id)) out.push(guardEmbedded(mine, a))\n seen.add(a.id)\n } else if (a.source !== 'pdf') {\n out.push(a)\n }\n }\n return [...[...current.values()].filter((a) => !seen.has(a.id)), ...out]\n }\n\n function pruneSelection(next: readonly Annotation[]): void {\n const known = new Set(next.map((a) => a.id))\n const current = selection.get()\n if (current.every((id) => known.has(id))) return\n selection.set(current.filter((id) => known.has(id)))\n }\n\n const store: AnnotationStore = {\n mode: opts.mode.mode,\n list: readonly(list),\n selection: readonly(selection),\n defaults: opts.defaults,\n get: (id) => list.get().find((a) => a.id === id),\n _getProposed: (id) => findIn(basis(), id),\n byPage: (page) => list.get().filter((a) => a.page === page),\n completeInput,\n add(input) {\n const a = completeInput(input)\n // Covers ids from the input and from the `id` option's generator alike.\n if (findIn(basis(), a.id))\n throw new Error(`An annotation with id ${a.id} already exists`)\n if (destroyed) return a\n // One mask per page: a new one replaces the page's session mask in the same change, so\n // the history step and the host's `onChange` see the swap once.\n const replaced =\n a.type === 'mask'\n ? basis().filter(\n (x) => x.type === 'mask' && x.page === a.page && x.source !== 'pdf'\n )\n : []\n const gone = new Set(replaced.map((x) => x.id))\n for (const x of replaced) clearPending(changeKey({ kind: 'add', annotation: x }))\n commit([...basis().filter((x) => !gone.has(x.id)), a], {\n kind: 'add',\n annotation: a,\n })\n if (!controlled && gone.size > 0) pruneSelection(list.get())\n return a\n },\n update(id, patch) {\n const before = findIn(basis(), id)\n if (destroyed || !before) return undefined\n if (before.locked && Object.keys(patch).some((k) => LOCKED_KEYS.has(k)))\n return undefined\n // A pinned annotation is what fills its field, as it is: only keys that leave its look\n // and place alone change.\n if (pinned.get().has(id) && !pinnedAccepts(before, patch)) return undefined\n const candidate: Record<string, unknown> = {\n ...before,\n ...patch,\n ...mergedStyle(before, patch),\n id: before.id,\n type: before.type,\n createdAt: before.createdAt,\n source: before.source,\n modifiedAt: now(),\n }\n // An embedded annotation's lock and appearance belong to the file: the patch's are ignored.\n if (before.source === 'pdf') {\n keepKey(candidate, before, 'locked')\n keepKey(candidate, before, 'hasAppearance')\n }\n const after = AnnotationSchema.parse(candidate)\n const swap = (items: readonly Annotation[]): Annotation[] =>\n items.map((a) => (a.id === id ? after : a))\n const next = swap(basis())\n const change: AnnotationEdit = { kind: 'update', id, before, after }\n if (controlled && before.source === 'pdf') {\n // The host never holds embedded items, so their edits apply here.\n emitter.emit('edit', change)\n list.set(swap(list.get()))\n if (proposed) proposed = next\n emitter.emit('change', change)\n } else {\n commit(next, change)\n }\n return after\n },\n remove(id) {\n const items = basis()\n const target = findIn(items, id)\n if (destroyed || !target || target.locked) return false\n const doomed = new Set<string>([id])\n let grew = true\n while (grew) {\n grew = false\n for (const a of items) {\n if (a.inReplyTo !== undefined && doomed.has(a.inReplyTo) && !doomed.has(a.id)) {\n doomed.add(a.id)\n grew = true\n }\n }\n }\n const next = items.filter((a) => !doomed.has(a.id))\n const removed = [target, ...items.filter((a) => a.id !== id && doomed.has(a.id))]\n commit(next, { kind: 'remove', annotation: target, removed })\n if (!controlled) pruneSelection(next)\n return true\n },\n _setPinned(ids) {\n const current = pinned.get()\n if (current.size === ids.size && [...ids].every((id) => current.has(id))) return\n pinned.set(new Set(ids))\n },\n _isPinned: (id) => pinned.get().has(id),\n _pinned: readonly(pinned),\n select(ids) {\n const known = new Set(basis().map((a) => a.id))\n selection.set(ids.filter((id) => known.has(id)))\n },\n replaceAll(list, reason) {\n if (destroyed) return\n const next = controlled ? [...list] : withEmbedded(list)\n commit(next, { kind: 'replace', reason })\n if (!controlled) pruneSelection(next)\n },\n setControlledValue(value) {\n if (!controlled)\n throw new TypeError('setControlledValue is only valid in controlled mode')\n if (destroyed) return\n const embedded = list.get().filter((a) => a.source === 'pdf')\n const embeddedIds = new Set(embedded.map((a) => a.id))\n const next = [...embedded, ...value.filter((a) => !embeddedIds.has(a.id))]\n list.set(next)\n proposed = undefined\n for (const [key, entry] of [...pending]) {\n if (isApplied(entry.change, next)) clearPending(key)\n }\n pruneSelection(next)\n emitter.emit('change', { kind: 'replace', reason: 'sync' })\n },\n _setEmbedded(items) {\n if (destroyed) return\n const ids = new Set(items.map((a) => a.id))\n const next = [\n ...items,\n ...list.get().filter((a) => a.source !== 'pdf' && !ids.has(a.id)),\n ]\n proposed = undefined\n list.set(next)\n pruneSelection(next)\n emitter.emit('change', { kind: 'replace', reason: 'import' })\n },\n _patchEmbedded(fields) {\n if (destroyed) return\n const applied = new Map<string, EmbeddedFieldPatch>()\n const merge = (items: readonly Annotation[]): Annotation[] =>\n items.map((a) => {\n const f = a.source === 'pdf' ? fields.get(a.id) : undefined\n const merged = f && withEmbeddedFields(a, f)\n if (!merged) return a\n applied.set(a.id, f)\n return merged\n })\n const next = merge(list.get())\n if (applied.size === 0) return\n list.set(next)\n // A pending controlled proposal holds the embedded items too.\n if (proposed) proposed = merge(proposed)\n emitter.emit('change', { kind: 'replace', reason: 'embedded', fields: applied })\n },\n on: (event: 'change' | 'edit', fn: (change: never) => void) =>\n emitter.on(event, fn as never),\n destroy() {\n destroyed = true\n proposed = undefined\n for (const key of [...pending.keys()]) clearPending(key)\n emitter.clear()\n },\n }\n return store\n}\n","import { Emitter } from '../events'\nimport { readonly, writable, type Readable } from '../readable'\nimport { createRecordStore, type RecordStore } from '../records'\n\nimport { submitValues } from './submit'\nimport { safeUrl } from './url'\nimport { checkValue, normaliseValue, resetValue, sameValue, suits } from './values'\n\nimport type { AnnotationEdit, AnnotationStore } from '../annotations/store'\nimport type { InkError } from '../errors'\nimport type {\n FieldsChange,\n FieldsMode,\n FieldValue,\n FieldValues,\n ViewerAction,\n FormEvent,\n FormField,\n FormSetResult,\n FormWidget,\n TabsOrder,\n WidgetAction,\n WidgetOverride,\n} from './types'\n\nexport interface FieldRecord {\n readonly id: string\n readonly value: FieldValue\n}\n\nexport interface FormController {\n /** Structure, read once on load. */\n readonly fields: Readable<readonly FormField[]>\n /** What the screen and the sandbox hold, keyed by full name. */\n readonly values: Readable<FieldValues>\n /** Formatted text per field, for display when not focused; set by scripts. */\n readonly formatted: Readable<Readonly<Record<string, string>>>\n /** Script-driven widget state: hidden, readOnly, required, colours, by widget id. */\n readonly widgetState: Readable<Readonly<Record<string, WidgetOverride>>>\n /**\n * Whether the form has JavaScript: a widget's scripts, or document-level or page scripts\n * running in the sandbox.\n */\n readonly hasScripts: boolean\n get(name: string): FieldValue | undefined\n /**\n * Commits `values` as a person would: each runs its validate and calculate scripts, and the\n * whole call is one undo step. A value that is unknown, read-only, invalid for the field or\n * rejected by a script is left out and listed in `rejected`. In controlled mode the full map\n * is reported once afterwards, as a `commit` naming the fields set and the fields a\n * calculation changed.\n */\n set(values: FieldValues): FormSetResult\n /**\n * Restores the PDF's default values of `names`, or of every field. Read-only fields reset\n * too, as in Acrobat; locked fields keep theirs.\n */\n reset(names?: readonly string[]): void\n /**\n * Controlled mode only: the host pushes its values. Names it leaves out keep their value.\n * Pushing what the form already holds does nothing; otherwise calculate scripts run, and a\n * calculation that changes more is reported once. Before the fields load, the push waits for\n * them.\n */\n setControlledValue(next: FieldValues): void\n on(event: 'action', fn: (a: ViewerAction) => void): () => void\n on(event: 'alert', fn: (message: string) => void): () => void\n /**\n * A script failed. The document keeps working; the form layer shows or logs it. Errors from\n * before the first listener (a sandbox that failed to start while the document opened) go to\n * that listener once, as it subscribes.\n */\n on(event: 'error', fn: (e: InkError) => void): () => void\n /** A script asked to move focus to this widget (by id). */\n on(event: 'focus', fn: (widgetId: string) => void): () => void\n /** A widget's `/GoTo` action ran: show this page (zero-based). */\n on(event: 'goto', fn: (page: number) => void): () => void\n /** @internal The scripting seam and the form layer. */\n readonly _store: RecordStore<FieldRecord>\n _attachScripting(s: FormScripting): void\n _emitAction(a: ViewerAction): void\n /**\n * Runs the widget's scripts for `event`, and on `Action` its non-script action (reset,\n * submit, URI, named Print, GoTo). A Blur drops the widget's uncommitted text.\n */\n _dispatch(event: FormEvent): void\n /**\n * @internal Runs `fn` as one undo step, so a widget's activation (its new value, its Mouse Up\n * and its Action, with the scripts and reset they run) undoes at once.\n */\n _step(fn: () => void): void\n /**\n * Applies a keystroke to the widget's text as typed so far (its uncommitted text, else the\n * field's value as shown: a combo's option label for its export value). Without scripting it\n * accepts every keystroke. The uncommitted text is dropped when the field's value changes or\n * the widget blurs.\n */\n _keystroke(\n widget: string,\n change: string,\n selStart: number,\n selEnd: number\n ): KeystrokeResult\n /**\n * @internal Drops the widget's uncommitted text (Escape in a text field), and the sandbox,\n * which saw each keystroke, goes back to the stored value. Its next keystroke builds on that.\n */\n _revert(widget: string): void\n /**\n * @internal The viewer's current page became `page` (`PageOpen`) or another (`PageClose`):\n * runs the page's open or close scripts. Resolves once they ran; nothing runs without scripts.\n */\n _pageEvent(page: number, name: PageEventName): Promise<void>\n /** @internal Sets a field's formatted text; `undefined` clears it. */\n _setFormatted(name: string, text: string | undefined): void\n /** @internal Merges into a widget's override; `undefined` clears it. */\n _setWidgetState(widgetId: string, override: WidgetOverride | undefined): void\n /** @internal Reports a script error to `onError` and the `error` listeners. */\n _error(e: InkError): void\n /** @internal A script's `app.alert`. */\n _alert(message: string): void\n /** @internal A script moved focus to a widget. */\n _focus(widgetId: string): void\n /**\n * @internal Values a script set (a calculation, or a script assigning a field). Read-only\n * fields take them; locked fields and values that do not suit the field are skipped. Inside\n * a commit, reset or widget event they join its undo step. Outside one (a timer, a page's\n * open or close script, a keystroke script) they are no undo step: they become the history's\n * baseline, so undo never rewinds them. A controlled host hears of them as `calculate`.\n */\n _scriptValues(values: FieldValues): void\n /** @internal Each page's `/Tabs`, for pages that set one; set with the fields. */\n readonly _tabs: ReadonlyMap<number, TabsOrder>\n /**\n * @internal For each page whose `/Tabs` is `S`, its annotation ids in structure-tree order;\n * set with the fields.\n */\n readonly _structure: ReadonlyMap<number, readonly string[]>\n /** @internal Sets the structure once the file's fields are read, applying any waiting push. */\n _load(\n fields: readonly FormField[],\n tabs?: ReadonlyMap<number, TabsOrder>,\n structure?: ReadonlyMap<number, readonly string[]>\n ): void\n /**\n * @internal Applies values already checked by `fieldsFromGloss`, as an import: neither the\n * values nor what they calculate are an undo step. A controlled host hears of both as one\n * `import`.\n */\n _import(values: FieldValues): void\n /**\n * @internal Keeps signature fields and the annotations that sign them in step, from now\n * until `_destroy`. Each signing annotation is pinned in the store. Removing one (by a person,\n * an import, a controlled host that drops it, or undo) clears its field, and clearing the\n * field (a reset, a host's push of another value, an import) removes the annotation.\n */\n _linkAnnotations(link: SignatureLink): void\n /**\n * @internal Signs signature field `name` with annotation `id`, reported to a controlled\n * host as a `commit`. When the annotation is not in the list yet (a controlled host has it\n * proposed), the field is signed once it arrives, and stays empty if the host drops it.\n */\n _signWith(name: string, id: string): void\n /**\n * @internal Whether `name` waits for a signature a controlled host has proposed and not\n * applied or dropped yet.\n */\n _awaitingSignature(name: string): boolean\n /**\n * @internal `set` or `reset` gave these fields a value, whether or not it differs from the\n * one they held. The form layer clears a refused commit's mark on them. A host's push is not\n * reported: it clears a mark only where it changes the value.\n */\n _onPut(fn: (names: readonly string[]) => void): () => void\n /** @internal Destroys the scripting and drops every listener. */\n _destroy(): void\n}\n\n/** What `_linkAnnotations` needs from the document. */\nexport interface SignatureLink {\n store: AnnotationStore\n /** The history's `react`: runs inside a person's edit, so the field clears in the same step. */\n react(fn: (edit: AnnotationEdit) => void): () => void\n /**\n * True when undo and redo replay the field values together with the annotations, so an\n * annotation replay leaves the fields to theirs.\n */\n replays: boolean\n}\n\n/** A page event a page's scripts may handle. */\nexport type PageEventName = 'PageOpen' | 'PageClose'\n\nexport interface KeystrokeResult {\n accepted: boolean\n value: string\n selStart: number\n selEnd: number\n}\n\nexport interface FormScripting {\n /**\n * Runs validate for `name` with `value`, then calculate. Synchronous. Returns the value to\n * store (a script may change it), or `undefined` when a script rejected it.\n */\n commit(name: string, value: FieldValue): FieldValue | undefined\n /** After values change without a user commit (host push, import, reset, undo). */\n sync(values: FieldValues, calculate: boolean): void\n /** Runs a widget event's scripts. Synchronous. */\n dispatch(event: FormEvent): void\n /**\n * Runs the widget's keystroke scripts on `text`, the text typed so far. `undefined` when the\n * widget has no field in the sandbox.\n */\n keystroke(\n widget: string,\n text: string,\n change: string,\n selStart: number,\n selEnd: number\n ): KeystrokeResult | undefined\n /** Runs `page`'s (zero-based) open or close scripts; resolves once they ran. */\n pageEvent(page: number, name: PageEventName): Promise<void>\n destroy(): void\n}\n\nexport interface FormControllerOptions {\n fields: readonly FormField[]\n mode: FieldsMode\n onError(e: InkError): void\n /** Runs `fn` as one undo step. Defaults to running it. */\n batch?: ((fn: () => void) => void) | undefined\n /**\n * Runs `fn` without an undo step: what it changes becomes the history's baseline. Defaults\n * to running it.\n */\n quiet?: ((fn: () => void) => void) | undefined\n}\n\n/** How many errors from before the first `error` listener are kept for it. */\nconst UNHEARD_LIMIT = 20\n\n/**\n * The document's form values, in a record store keyed by field name (`{ id: name, value }`).\n * In controlled mode the store is the working copy: a change shows and reaches the sandbox at\n * once, and the host hears of it after.\n */\nexport function createFormController(opts: FormControllerOptions): FormController {\n const controlled = opts.mode.mode === 'controlled' ? opts.mode : undefined\n const batch = opts.batch ?? ((fn: () => void) => fn())\n const quiet = opts.quiet ?? ((fn: () => void) => fn())\n const fields = writable<readonly FormField[]>([])\n let byName = new Map<string, FormField>()\n let byWidget = new Map<string, FormField>()\n let widgets = new Map<string, FormWidget>()\n let loaded = false\n let tabs: ReadonlyMap<number, TabsOrder> = new Map()\n let structure: ReadonlyMap<number, readonly string[]> = new Map()\n /** A push that arrived before the fields loaded. */\n let waiting: FieldValues | undefined\n let scripting: FormScripting | undefined\n let destroyed = false\n const emitter = new Emitter<{\n action: ViewerAction\n alert: string\n error: InkError\n focus: string\n goto: number\n put: readonly string[]\n }>()\n /**\n * Errors reported before anything listened for them, the newest `UNHEARD_LIMIT`;\n * `undefined` once something has.\n */\n let unheard: InkError[] | undefined = []\n /** How many changes are running whose values are reported when they finish. */\n let depth = 0\n /** Text typed into a widget and not yet committed, by widget id. */\n const pending = new Map<string, string>()\n const formatted = writable<Readonly<Record<string, string>>>({})\n const widgetState = writable<Readonly<Record<string, WidgetOverride>>>({})\n\n const store = createRecordStore<FieldRecord>('form.fields')\n /** The annotations signature fields are signed with, once linked. */\n let annotations: AnnotationStore | undefined\n /** Whether undo and redo replay the field values along with the annotations. */\n let replays = false\n /** Signatures proposed to a controlled host and not in the list yet: annotation id to field. */\n const awaiting = new Map<string, string>()\n /**\n * Signatures whose annotation went and cleared their field, by annotation id, when the\n * field values have no undo history of their own (controlled fields). Undo or redo that\n * brings the annotation back signs its field again.\n */\n const dropped = new Map<string, string>()\n const unlink: (() => void)[] = []\n\n let cachedList: readonly FieldRecord[] | undefined\n let cachedMap: FieldValues = Object.freeze({})\n const current = (): FieldValues => {\n const list = store.list.get()\n if (list !== cachedList) {\n cachedList = list\n cachedMap = Object.freeze(Object.fromEntries(list.map((r) => [r.id, r.value])))\n }\n return cachedMap\n }\n const values: Readable<FieldValues> = {\n get: current,\n subscribe: (fn) => store.list.subscribe(() => fn(current())),\n }\n\n /** Drops the uncommitted text of the field's widgets. */\n const dropPending = (name: string) => {\n for (const w of byName.get(name)?.widgets ?? []) pending.delete(w.id)\n }\n\n store.on('change', (change) => {\n if (change.kind === 'add' || change.kind === 'remove') dropPending(change.record.id)\n else if (change.kind === 'update') dropPending(change.id)\n else\n for (const id of [...change.added, ...change.updated, ...change.removed])\n dropPending(id)\n // Only an uncontrolled document has undo history, so no controlled host hears of this.\n if (change.kind !== 'replace' || change.reason !== 'history') return\n within(() => scripting?.sync(current(), false))\n })\n\n /** Writes one value (none removes it), skipping one equal to what is stored. */\n const write = (name: string, value: FieldValue | undefined): boolean => {\n const before = store.get(name)\n if (sameValue(before?.value, value)) return false\n if (value === undefined) store.remove(name)\n else if (before) store.update(name, { value })\n else store.add({ id: name, value })\n return true\n }\n\n /** Writes several values as one change, so subscribers hear of it once. */\n const writeAll = (entries: readonly (readonly [string, FieldValue])[]) => {\n const list = new Map(store.list.get().map((r) => [r.id, r]))\n for (const [name, value] of entries) list.set(name, { id: name, value })\n store.replaceAll([...list.values()], 'reset')\n }\n\n /** The names whose value differs between two maps. */\n const changed = (a: FieldValues, b: FieldValues): string[] =>\n [...new Set([...Object.keys(a), ...Object.keys(b)])].filter(\n (name) => !sameValue(a[name], b[name])\n )\n\n /**\n * Runs `fn` as one undo step (or through `step`), then reports to a controlled host when the\n * values changed.\n */\n const reporting = (\n fn: () => void,\n change: (names: string[]) => FieldsChange | undefined,\n step = batch\n ) => {\n const before = current()\n depth++\n try {\n step(fn)\n } finally {\n depth--\n }\n const after = current()\n if (!controlled || destroyed || after === before) return\n const names = changed(before, after)\n const report = names.length > 0 ? change(names) : undefined\n if (report) controlled.onChange(after, report)\n }\n\n /**\n * The entries of a host's values that suit their fields, normalised. Read-only only stops a\n * person, so a host may set a read-only field; a locked one keeps its value.\n */\n const valid = (next: FieldValues): [string, FieldValue][] =>\n Object.entries(next).flatMap(([name, value]): [string, FieldValue][] => {\n const field = byName.get(name)\n return field && !field.locked && suits(field, value)\n ? [[name, normaliseValue(field, value)]]\n : []\n })\n\n /** Runs `fn` as part of a change the caller reports itself. */\n const within = (fn: () => void) => {\n depth++\n try {\n fn()\n } finally {\n depth--\n }\n }\n\n /** The names an action's include or exclude list picks; every field when the list is empty. */\n const picked = (names: readonly string[], include: boolean): string[] => {\n const all = fields.get().map((f) => f.name)\n if (names.length === 0) return all\n const listed = (name: string) =>\n names.some((n) => name === n || name.startsWith(`${n}.`))\n return all.filter((name) => listed(name) === include)\n }\n\n /** A widget's non-script action. Inkbar never sends, opens or prints; the host is told. */\n const runAction = (action: WidgetAction) => {\n switch (action.kind) {\n case 'reset':\n form.reset(picked(action.fields, action.include))\n break\n case 'submit': {\n // The file's own URLs get the same check as a script's.\n const url = safeUrl(action.url)\n if (!url) break\n form._emitAction({\n kind: 'submit',\n url,\n fields: submitValues(current(), fields.get(), action.fields, action.include),\n format: action.format,\n ...(action.method ? { method: action.method } : {}),\n })\n break\n }\n case 'uri': {\n const url = safeUrl(action.url)\n if (url)\n form._emitAction({\n kind: 'open-url',\n url,\n newWindow: action.newWindow === true,\n })\n break\n }\n case 'named':\n if (action.name === 'Print') form._emitAction({ kind: 'print' })\n break\n case 'goto':\n if (!destroyed) emitter.emit('goto', action.page)\n break\n }\n }\n\n const load = (\n list: readonly FormField[],\n pageTabs?: ReadonlyMap<number, TabsOrder>,\n pageStructure?: ReadonlyMap<number, readonly string[]>\n ) => {\n loaded = true\n tabs = pageTabs ?? new Map()\n structure = pageStructure ?? new Map()\n fields.set(list)\n byName = new Map(list.map((f) => [f.name, f]))\n byWidget = new Map(list.flatMap((f) => f.widgets.map((w) => [w.id, f] as const)))\n widgets = new Map(list.flatMap((f) => f.widgets.map((w) => [w.id, w] as const)))\n const start = new Map<string, FieldValue>()\n for (const f of list) if (f.value !== undefined) start.set(f.name, f.value)\n for (const [name, value] of valid(opts.mode.initial ?? {})) start.set(name, value)\n if (waiting) for (const [name, value] of valid(waiting)) start.set(name, value)\n waiting = undefined\n store.replaceAll(\n [...start].map(([id, value]) => ({ id, value })),\n 'reset'\n )\n }\n\n /** The annotation a signature field's value names, if it has one. */\n const signatureOf = (name: string): string | undefined => {\n const value = store.get(name)?.value\n return typeof value === 'object' && !Array.isArray(value)\n ? (value as { signature: string }).signature\n : undefined\n }\n\n /** Each signed signature field's annotation id, by field name. */\n const signedFields = (): Map<string, string> => {\n const out = new Map<string, string>()\n for (const f of fields.get()) {\n if (f.type !== 'signature') continue\n const id = signatureOf(f.name)\n if (id !== undefined) out.set(f.name, id)\n }\n return out\n }\n\n const pin = () => annotations?._setPinned(new Set(signedFields().values()))\n\n /**\n * Clears the signature fields whose annotation has gone, as a commit. One a controlled host\n * still has proposed (an import's, say) has not gone; it goes once the host drops it.\n */\n const dropDangling = () => {\n const linked = annotations\n if (!linked || destroyed) return\n const gone = [...signedFields()].filter(\n ([, id]) => !linked.get(id) && !linked._getProposed(id)\n )\n if (gone.length > 0)\n reporting(\n () => {\n for (const [name, id] of gone) {\n if (!replays) dropped.set(id, name)\n write(name, undefined)\n }\n },\n (names) => ({ kind: 'commit', names })\n )\n pin()\n }\n\n /** Signs again the fields whose dropped signature an undo or redo brought back. */\n const restore = () => {\n const linked = annotations\n if (!linked || destroyed) return\n for (const [id, name] of [...dropped]) {\n if (!linked.get(id)) continue\n dropped.delete(id)\n const field = byName.get(name)\n if (field?.type === 'signature' && !field.locked && signatureOf(name) === undefined)\n sign(name, id)\n }\n }\n\n /** Writes a signature, as a commit. */\n const sign = (name: string, id: string) =>\n reporting(\n () => {\n write(name, Object.freeze({ signature: id }))\n },\n (names) => ({ kind: 'commit', names })\n )\n\n /** Signs the fields whose proposed annotation has arrived, and forgets ones a host dropped. */\n const land = () => {\n const linked = annotations\n if (!linked) return\n for (const [id, name] of [...awaiting]) {\n if (linked.get(id)) {\n awaiting.delete(id)\n if (byName.get(name)?.type === 'signature' && signatureOf(name) === undefined)\n sign(name, id)\n } else if (!linked._getProposed(id)) awaiting.delete(id)\n }\n }\n\n const form: FormController = {\n fields: readonly(fields),\n values,\n formatted: readonly(formatted),\n widgetState: readonly(widgetState),\n get hasScripts() {\n return (\n scripting !== undefined ||\n fields.get().some((f) => f.widgets.some((w) => w.hasScripts))\n )\n },\n get: (name) => store.get(name)?.value,\n set(next) {\n const result: FormSetResult = { applied: [], rejected: [] }\n if (destroyed) return result\n reporting(\n () => {\n for (const [name, value] of Object.entries(next)) {\n const field = byName.get(name)\n const reason = field ? checkValue(field, value) : 'unknown'\n if (reason || !field) {\n result.rejected.push({ name, reason: reason ?? 'unknown' })\n continue\n }\n const stored = normaliseValue(field, value)\n const kept = scripting ? scripting.commit(name, stored) : stored\n // A value the scripts reject leaves the typed text, so the user can correct it.\n if (kept === undefined) {\n result.rejected.push({ name, reason: 'script' })\n continue\n }\n dropPending(name)\n write(name, suits(field, kept) ? normaliseValue(field, kept) : stored)\n result.applied.push(name)\n }\n },\n (changedNames) => ({\n kind: 'commit',\n names: [...new Set([...result.applied, ...changedNames])],\n })\n )\n if (result.applied.length > 0 && !destroyed) emitter.emit('put', result.applied)\n return result\n },\n reset(names) {\n if (destroyed) return\n const targets = names ? names.flatMap((n) => byName.get(n) ?? []) : fields.get()\n reporting(\n () => {\n let any = false\n for (const field of targets)\n if (!field.locked) any = write(field.name, resetValue(field)) || any\n if (any) scripting?.sync(current(), true)\n },\n (changedNames) => ({ kind: 'reset', names: changedNames })\n )\n const put = targets.flatMap((f) => (f.locked ? [] : [f.name]))\n if (put.length > 0 && !destroyed) emitter.emit('put', put)\n },\n setControlledValue(next) {\n if (!controlled || destroyed) return\n if (!loaded) {\n waiting = { ...waiting, ...next }\n return\n }\n // A push clears a refused mark only by changing the value (which the form layer sees):\n // hosts echo the whole map after every change, and an echo is no push of its own.\n const pushed = valid(next).filter(\n ([name, value]) => !sameValue(store.get(name)?.value, value)\n )\n if (pushed.length === 0) return\n writeAll(pushed)\n const expected = current()\n within(() => scripting?.sync(expected, true))\n const after = current()\n if (after === expected) return\n const names = changed(expected, after)\n if (names.length > 0) controlled.onChange(after, { kind: 'calculate', names })\n },\n on(\n event: 'action' | 'alert' | 'error' | 'focus' | 'goto',\n fn: (payload: never) => void\n ) {\n const stop = emitter.on(\n event,\n fn as (payload: ViewerAction | string | InkError | number) => void\n )\n if (event === 'error' && unheard) {\n const early = unheard\n unheard = undefined\n for (const e of early) (fn as (e: InkError) => void)(e)\n }\n return stop\n },\n _store: store,\n _attachScripting(s) {\n if (destroyed) {\n s.destroy()\n return\n }\n scripting?.destroy()\n scripting = s\n },\n _emitAction(a) {\n if (!destroyed) emitter.emit('action', a)\n },\n _dispatch(event) {\n if (destroyed) return\n // Text typed and then left uncommitted is dropped, and the sandbox, which saw each\n // keystroke, goes back to the stored value.\n const abandoned = event.name === 'Blur' && pending.delete(event.widget)\n const widget = widgets.get(event.widget)\n // Without scripts, a JavaScript button still opens the URL its script would.\n const action = widget?.action ?? (scripting ? undefined : widget?.fallback)\n // The `/A`'s `/Next` actions follow it, scripts or not.\n const next = event.name === 'Action' ? (widget?.next ?? []) : []\n // An Action's scripts and the reset it runs are one step.\n batch(() => {\n if (scripting)\n reporting(\n () => {\n scripting?.dispatch(event)\n if (abandoned) scripting?.sync(current(), false)\n },\n (names) => ({ kind: 'calculate', names })\n )\n if (event.name === 'Action' && action && !destroyed) runAction(action)\n for (const n of next) if (!destroyed) runAction(n)\n })\n },\n _step(fn) {\n if (destroyed) return\n batch(fn)\n },\n _keystroke(widget, change, selStart, selEnd) {\n const field = byWidget.get(widget)\n const stored = field ? store.get(field.name)?.value : undefined\n const text = typeof stored === 'string' ? stored : ''\n // An editable combo shows an option's label for its export value, and is typed into.\n const shown =\n field?.type === 'combo'\n ? (field.options.find((o) => o.value === text)?.label ?? text)\n : text\n const before = pending.get(widget) ?? shown\n const caret = selStart + change.length\n const result = (!destroyed &&\n scripting?.keystroke(widget, before, change, selStart, selEnd)) || {\n accepted: true,\n value: before.slice(0, selStart) + change + before.slice(selEnd),\n selStart: caret,\n selEnd: caret,\n }\n if (!destroyed && result.accepted) pending.set(widget, result.value)\n return result\n },\n _revert(widget) {\n if (destroyed || !pending.delete(widget)) return\n within(() => scripting?.sync(current(), false))\n },\n _pageEvent(page, name) {\n if (destroyed || !scripting) return Promise.resolve()\n return scripting.pageEvent(page, name)\n },\n _setFormatted(name, text) {\n if (destroyed) return\n const { [name]: _old, ...rest } = formatted.get()\n formatted.set(Object.freeze(text === undefined ? rest : { ...rest, [name]: text }))\n },\n _setWidgetState(widgetId, override) {\n if (destroyed) return\n const { [widgetId]: old, ...rest } = widgetState.get()\n widgetState.set(\n Object.freeze(\n override === undefined\n ? rest\n : { ...rest, [widgetId]: Object.freeze({ ...old, ...override }) }\n )\n )\n },\n _error(e) {\n if (destroyed) return\n opts.onError(e)\n if (!unheard) emitter.emit('error', e)\n else if (unheard.push(e) > UNHEARD_LIMIT) unheard.shift()\n },\n _alert(message) {\n if (!destroyed) emitter.emit('alert', message)\n },\n _focus(widgetId) {\n if (!destroyed && widgets.has(widgetId)) emitter.emit('focus', widgetId)\n },\n _scriptValues(next) {\n if (destroyed) return\n const entries = Object.entries(next).flatMap(\n ([name, value]): [string, FieldValue][] => {\n const field = byName.get(name)\n return field && !field.locked && suits(field, value)\n ? [[name, normaliseValue(field, value)]]\n : []\n }\n )\n if (entries.length === 0) return\n const apply = () => {\n for (const [name, value] of entries) write(name, value)\n }\n if (depth > 0) apply()\n else reporting(apply, (names) => ({ kind: 'calculate', names }), quiet)\n },\n get _tabs() {\n return tabs\n },\n get _structure() {\n return structure\n },\n _load: load,\n _import(next) {\n if (destroyed) return\n const before = current()\n const entries = Object.entries(next).filter(\n ([name, value]) => !sameValue(before[name], value)\n )\n // Nothing to change: no reset reaches the store, so the undo steps stay.\n if (entries.length === 0) return\n writeAll(entries)\n if (changed(before, current()).length === 0) return\n // What the import calculates is no undo step either.\n quiet(() => within(() => scripting?.sync(current(), true)))\n const names = changed(before, current())\n if (controlled && names.length > 0)\n controlled.onChange(current(), { kind: 'import', names })\n },\n _linkAnnotations(link) {\n if (destroyed || annotations) return\n const linked = link.store\n annotations = linked\n replays = link.replays\n let signed = signedFields()\n unlink.push(\n store.on('change', (change) => {\n const before = signed\n signed = signedFields()\n // Undo and redo replay the annotations too: a signature that went with the step has\n // already gone.\n const replay = change.kind === 'replace' && change.reason === 'history'\n if (!replay) {\n const kept = new Set(signed.values())\n for (const [name, id] of before)\n if (signed.get(name) !== id && !kept.has(id)) linked.remove(id)\n }\n dropDangling()\n }),\n linked.on('change', (change) => {\n const replay = change.kind === 'replace' && change.reason === 'history'\n if (replay && link.replays) {\n pin()\n return\n }\n if (replay) restore()\n land()\n dropDangling()\n }),\n link.react((edit) => {\n if (edit.kind === 'remove') dropDangling()\n })\n )\n dropDangling()\n },\n _signWith(name, id) {\n if (destroyed) return\n if (!annotations || annotations.get(id)) sign(name, id)\n else awaiting.set(id, name)\n },\n _awaitingSignature(name) {\n // A proposal the host let lapse without pushing a list no longer counts. The query\n // forgets nothing: `land` does that when the list next changes, so a late push still\n // signs the field.\n for (const [id, field] of awaiting)\n if (field === name && annotations?._getProposed(id)) return true\n return false\n },\n _onPut(fn) {\n return emitter.on('put', fn)\n },\n _destroy() {\n if (destroyed) return\n destroyed = true\n for (const stop of unlink.splice(0)) stop()\n awaiting.clear()\n dropped.clear()\n unheard = undefined\n scripting?.destroy()\n scripting = undefined\n emitter.clear()\n store.destroy()\n },\n }\n // A document builds its controller before the file's fields are read, and loads them later.\n if (opts.fields.length > 0) load(opts.fields)\n return form\n}\n","import { fontFromBaseName } from '../../pdf/annotation-fields'\nimport { pdfColorToHex } from '../annotations/embedded'\n\nimport { suits } from './values'\n\nimport type {\n FieldFlags,\n FieldOption,\n FieldValue,\n FormField,\n FormFieldType,\n FormWidget,\n WidgetAction,\n WidgetAppearance,\n} from './types'\nimport type { FormExtras, WidgetExtras } from '../../pdf/form-fields'\nimport type { PdfjsAnnotationData } from '../../pdfjs/types'\n\n/** One widget as PDF.js reported it, with the page it sits on. */\nexport interface RawWidget {\n page: number\n data: PdfjsAnnotationData\n /** Position among all the page's annotations in `/Annots`; else among its widgets. */\n at?: number\n}\n\n// `/Ff` bits (PDF 32000-1, tables 221, 226, 228 and 230).\nconst FF = {\n readOnly: 1 << 0,\n required: 1 << 1,\n noExport: 1 << 2,\n multiline: 1 << 12,\n password: 1 << 13,\n fileSelect: 1 << 20,\n doNotSpellCheck: 1 << 22,\n doNotScroll: 1 << 23,\n comb: 1 << 24,\n radiosInUnison: 1 << 25,\n edit: 1 << 18,\n multiSelect: 1 << 21,\n}\n\n// Annotation `/F` bits.\nconst F_HIDDEN = 1 << 1\nconst F_PRINT = 1 << 2\nconst F_NO_VIEW = 1 << 5\n\nconst BORDER_STYLES = ['solid', 'dashed', 'beveled', 'inset', 'underline'] as const\nconst ALIGN = ['left', 'center', 'right'] as const\n\nfunction fieldType(d: PdfjsAnnotationData): FormFieldType | undefined {\n switch (d.fieldType) {\n case 'Tx':\n return 'text'\n case 'Ch':\n return d.combo ? 'combo' : 'list'\n case 'Sig':\n return 'signature'\n case 'Btn':\n if (d.pushButton) return 'button'\n if (d.radioButton) return 'radio'\n return d.checkBox ? 'checkbox' : undefined\n default:\n return undefined\n }\n}\n\nfunction flagsOf(type: FormFieldType, ff: number): FieldFlags {\n const has = (bit: number) => (ff & bit) !== 0\n const text = type === 'text'\n const choice = type === 'combo' || type === 'list'\n return {\n readOnly: has(FF.readOnly),\n required: has(FF.required),\n noExport: has(FF.noExport),\n multiline: text && has(FF.multiline),\n password: text && has(FF.password),\n comb: text && has(FF.comb),\n fileSelect: text && has(FF.fileSelect),\n doNotSpellCheck: (text || choice) && has(FF.doNotSpellCheck),\n doNotScroll: text && has(FF.doNotScroll),\n multiSelect: type === 'list' && has(FF.multiSelect),\n editable: type === 'combo' && has(FF.edit),\n radiosInUnison: (type === 'radio' || type === 'checkbox') && has(FF.radiosInUnison),\n }\n}\n\nconst hex = (c: ArrayLike<number> | null | undefined): string | undefined =>\n c && c.length >= 3 ? pdfColorToHex(c, '') : undefined\n\nfunction appearanceOf(\n d: PdfjsAnnotationData,\n type: FormFieldType,\n extra: WidgetExtras | undefined\n): WidgetAppearance {\n const da = d.defaultAppearanceData\n const appearance: WidgetAppearance = {\n fontSize: da && Number.isFinite(da.fontSize) ? da.fontSize : 0,\n align: ALIGN[d.textAlignment ?? 0] ?? 'left',\n fileAppearance: d.hasAppearance === true,\n }\n const font =\n extra?.font ?? (da?.fontName ? fontFromBaseName(da.fontName, true) : undefined)\n if (font?.fontFamily) {\n appearance.font = {\n family: font.fontFamily,\n ...(font.fontWeight ? { fontWeight: font.fontWeight } : {}),\n ...(font.fontStyle ? { fontStyle: font.fontStyle } : {}),\n }\n }\n const color = hex(da?.fontColor as ArrayLike<number> | undefined)\n if (color) appearance.color = color\n const width = d.borderStyle?.width ?? 0\n if (width > 0) {\n const borderColor = hex(d.borderColor)\n appearance.border = {\n ...(borderColor ? { color: borderColor } : {}),\n width,\n style: BORDER_STYLES[(d.borderStyle?.style ?? 1) - 1] ?? 'solid',\n }\n }\n const background = hex(d.backgroundColor)\n if (background) appearance.background = background\n if (extra?.caption !== undefined) {\n if (type === 'button') appearance.caption = extra.caption\n else if (type === 'checkbox' || type === 'radio')\n appearance.checkStyle = extra.caption\n }\n if (type === 'checkbox' || type === 'radio') {\n appearance.onAppearance = extra?.onState !== undefined\n appearance.offAppearance = extra?.offAppearance === true\n }\n return appearance\n}\n\n/** Whether the widget's own `/A` is JavaScript: read from the file, else from PDF.js. */\nfunction scriptAction(d: PdfjsAnnotationData, id: string, extras: FormExtras): boolean {\n // PDF.js's `actions.Action` holds the JavaScript of the whole `/A` chain, `/Next` included,\n // so it is only the answer when the file's own objects could not be read.\n return extras.widgets.has(id) ? extras.scriptActions.has(id) : hasActionScript(d)\n}\n\nconst uriOf = (d: PdfjsAnnotationData): WidgetAction | undefined =>\n d.url\n ? { kind: 'uri', url: d.url, ...(d.newWindow ? { newWindow: true } : {}) }\n : undefined\n\nfunction actionOf(\n d: PdfjsAnnotationData,\n id: string,\n extras: FormExtras,\n namesById: ReadonlyMap<string, string>\n): WidgetAction | undefined {\n const submit = extras.submits.get(id)\n if (submit) return submit\n // A JavaScript `/A`'s URL is its fallback, not a second action: see `fallbackOf`.\n if (scriptAction(d, id, extras)) return undefined\n if (d.resetForm) {\n const refs = d.resetForm.refs.flatMap((r) => namesById.get(r) ?? [])\n return {\n kind: 'reset',\n fields: [...d.resetForm.fields, ...refs],\n include: d.resetForm.include,\n }\n }\n const uri = uriOf(d)\n if (uri) return uri\n if (d.action) return { kind: 'named', name: d.action }\n const page = extras.destPages.get(id)\n if (page !== undefined) return { kind: 'goto', page }\n return undefined\n}\n\n/**\n * The URL a JavaScript `/A` opens: PDF.js fills `url` and `newWindow` from its\n * `app.launchURL`. The script opens it itself when it runs.\n */\nfunction fallbackOf(\n d: PdfjsAnnotationData,\n id: string,\n extras: FormExtras\n): WidgetAction | undefined {\n return scriptAction(d, id, extras) ? uriOf(d) : undefined\n}\n\nfunction hasActionScript(d: PdfjsAnnotationData): boolean {\n const actions = d.actions\n if (!actions) return false\n return actions instanceof Map ? actions.has('Action') : 'Action' in actions\n}\n\nconst rotationOf = (r: number | undefined): FormWidget['rotation'] => {\n const n = ((Math.round((r ?? 0) / 90) % 4) + 4) % 4\n return ([0, 90, 180, 270] as const)[n]!\n}\n\nfunction widgetOf(\n raw: RawWidget,\n type: FormFieldType,\n extras: FormExtras,\n namesById: ReadonlyMap<string, string>,\n order: ReadonlyMap<RawWidget, number>\n): FormWidget {\n const { data: d, page } = raw\n const extra = extras.widgets.get(d.id)\n const [x1, y1, x2, y2] = d.rect\n const flags = d.annotationFlags ?? 0\n const widget: FormWidget = {\n id: d.id,\n page,\n rect: {\n x: Math.min(x1, x2),\n y: Math.min(y1, y2),\n width: Math.abs(x2 - x1),\n height: Math.abs(y2 - y1),\n },\n rotation: rotationOf(d.rotation),\n hidden: (flags & F_HIDDEN) !== 0 || d.hidden === true,\n printOnly: (flags & F_NO_VIEW) !== 0 && (flags & F_PRINT) !== 0,\n appearance: appearanceOf(d, type, extra),\n hasScripts: hasScripts(d.actions),\n }\n const at = order.get(raw)\n if (at !== undefined) widget.order = at\n if (type === 'checkbox' || type === 'radio') {\n const on = extra?.onState ?? (type === 'radio' ? d.buttonValue : d.exportValue)\n if (on) widget.onState = on\n }\n const action = actionOf(d, d.id, extras, namesById)\n if (action) widget.action = action\n const fallback = fallbackOf(d, d.id, extras)\n if (fallback) widget.fallback = fallback\n const next = extras.next.get(d.id)\n if (next) widget.next = next\n return widget\n}\n\nfunction hasScripts(actions: PdfjsAnnotationData['actions']): boolean {\n if (!actions) return false\n return actions instanceof Map ? actions.size > 0 : Object.keys(actions).length > 0\n}\n\n/** Checkbox and radio options: each widget's on state, labelled with its export value. */\nfunction stateOptions(widgets: readonly RawWidget[], onStates: readonly FormWidget[]) {\n const options: FieldOption[] = []\n widgets.forEach((w, i) => {\n const value = onStates[i]!.onState\n if (value === undefined || options.some((o) => o.value === value)) return\n const label = (w.data.radioButton ? w.data.buttonValue : w.data.exportValue) ?? value\n options.push({ value, label })\n })\n return options\n}\n\n/** A checkbox or radio value as a state name: PDF.js maps `/V` through `/Opt` to an export value. */\nfunction stateValue(\n v: PdfjsAnnotationData['fieldValue'],\n options: readonly FieldOption[]\n): string | undefined {\n if (typeof v !== 'string') return undefined\n if (v === 'Off' || options.some((o) => o.value === v)) return v\n const byLabel = options.filter((o) => o.label === v)\n return byLabel.length === 1 ? byLabel[0]!.value : v\n}\n\nfunction choiceValue(\n v: PdfjsAnnotationData['fieldValue'],\n multi: boolean\n): FieldValue | undefined {\n if (v === null || v === undefined) return undefined\n const list = Array.isArray(v) ? v : [v]\n if (multi) return list\n return list[0]\n}\n\nfunction buildField(\n name: string,\n widgets: readonly RawWidget[],\n extras: FormExtras,\n namesById: ReadonlyMap<string, string>,\n order: ReadonlyMap<RawWidget, number>\n): FormField | undefined {\n const d = widgets[0]!.data\n const type = fieldType(d)\n if (!type) return undefined\n const flags = flagsOf(type, d.fieldFlags ?? 0)\n const built = widgets.map((w) => widgetOf(w, type, extras, namesById, order))\n let options: FieldOption[] = []\n let value: FieldValue | undefined\n let defaultValue: FieldValue | undefined\n if (type === 'checkbox' || type === 'radio') {\n options = stateOptions(widgets, built)\n const stored = widgets\n .map((w) => extras.widgets.get(w.data.id)?.state)\n .find((s) => s !== undefined)\n value = stored ?? stateValue(d.fieldValue, options) ?? 'Off'\n const storedDefault = widgets\n .map((w) => extras.widgets.get(w.data.id)?.defaultState)\n .find((s) => s !== undefined)\n defaultValue = storedDefault ?? stateValue(d.defaultFieldValue, options)\n } else if (type === 'combo' || type === 'list') {\n options = (d.options ?? []).map((o) => ({\n value: o.exportValue,\n label: o.displayValue,\n }))\n value = choiceValue(d.fieldValue, flags.multiSelect)\n defaultValue = choiceValue(d.defaultFieldValue, flags.multiSelect)\n } else if (type === 'text') {\n if (typeof d.fieldValue === 'string') value = d.fieldValue\n if (typeof d.defaultFieldValue === 'string') defaultValue = d.defaultFieldValue\n }\n\n const signed = extras.signed.has(name)\n const barcode = widgets.some((w) => extras.widgets.get(w.data.id)?.barcode)\n const field: FormField = {\n name,\n type,\n flags,\n options,\n widgets: built,\n locked:\n signed ||\n extras.lockAll ||\n extras.lockedFields.has(name) ||\n flags.fileSelect ||\n barcode,\n }\n if (type === 'text' && d.maxLen) field.maxLength = d.maxLen\n // Like a value a host sets, a default the field cannot hold is dropped: a reset then\n // empties the field instead.\n if (defaultValue !== undefined && suits(field, defaultValue))\n field.defaultValue = defaultValue\n if (value !== undefined) field.value = value\n const tooltip = d.alternativeText || extras.widgets.get(d.id)?.tooltip\n if (tooltip) field.tooltip = tooltip\n if (signed) field.signed = 'certificate'\n return field\n}\n\n/**\n * Terminal fields from the widgets PDF.js reports, grouped by full name, in the order of each\n * field's first widget. `raw` lists each page's widgets in its `/Annots` order, which each\n * widget's `order` keeps. Widgets of unknown field types are left out.\n */\nexport function buildFormFields(\n raw: readonly RawWidget[],\n extras: FormExtras\n): FormField[] {\n const groups = new Map<string, RawWidget[]>()\n const namesById = new Map<string, string>()\n const order = new Map<RawWidget, number>()\n const perPage = new Map<number, number>()\n for (const w of raw) {\n const name = w.data.fieldName\n if (w.data.subtype !== 'Widget' || !name) continue\n const at = perPage.get(w.page) ?? 0\n order.set(w, w.at ?? at)\n perPage.set(w.page, at + 1)\n namesById.set(w.data.id, name)\n let group = groups.get(name)\n if (!group) groups.set(name, (group = []))\n group.push(w)\n }\n const fields: FormField[] = []\n for (const [name, widgets] of groups) {\n const field = buildField(name, widgets, extras, namesById, order)\n if (field) fields.push(field)\n }\n return fields\n}\n","import type { MeasureChar } from './text'\n\n/**\n * Measures characters on an offscreen canvas in the font family PDF.js reports for a run, the\n * same family its text layer measures with. Undefined where there is no canvas (Node), so text\n * items carry no advances there. Widths are cached per family and character.\n */\nexport function canvasMeasureChar(): MeasureChar | undefined {\n if (typeof OffscreenCanvas === 'undefined') return undefined\n const ctx = new OffscreenCanvas(1, 1).getContext('2d')\n if (!ctx) return undefined\n const cache = new Map<string, Map<string, number>>()\n return (char, family) => {\n let widths = cache.get(family)\n if (!widths) cache.set(family, (widths = new Map<string, number>()))\n let w = widths.get(char)\n if (w === undefined) {\n ctx.font = `100px ${family}`\n w = ctx.measureText(char).width\n widths.set(char, w)\n }\n return w\n }\n}\n","/**\n * Internal (not exported from the package): one in-flight or settled lookup per page index.\n * A lookup that rejects is evicted, so the next request for that page asks again instead of\n * replaying the failure for the rest of the session.\n */\nexport interface PageCache<T> {\n get(index: number): Promise<T>\n clear(): void\n}\n\nexport function createPageCache<T>(fetch: (index: number) => Promise<T>): PageCache<T> {\n const cache = new Map<number, Promise<T>>()\n return {\n get(index) {\n const cached = cache.get(index)\n if (cached) return cached\n const fetched = fetch(index)\n cache.set(index, fetched)\n fetched.catch(() => {\n if (cache.get(index) === fetched) cache.delete(index)\n })\n return fetched\n },\n clear: () => cache.clear(),\n }\n}\n","import type { Rect } from './geometry'\nimport type { PdfjsPage } from '../pdfjs/types'\n\nexport type PageRotation = 0 | 90 | 180 | 270\n\nexport interface PageInfo {\n index: number\n /** CropBox ∩ MediaBox in user space before /Rotate, as PDF.js reports `page.view`. */\n box: Rect\n /** The page's own /Rotate. View rotation applied by the viewer is separate. */\n rotate: PageRotation\n userUnit: number\n /** Unrotated box width in points. */\n width: number\n /** Unrotated box height in points. */\n height: number\n}\n\nexport function pageInfoFromProxy(page: PdfjsPage, index: number): PageInfo {\n const [x1, y1, x2, y2] = page.view as [number, number, number, number]\n const box: Rect = {\n x: Math.min(x1, x2),\n y: Math.min(y1, y2),\n width: Math.abs(x2 - x1),\n height: Math.abs(y2 - y1),\n }\n return {\n index,\n box,\n rotate: normaliseRotation(page.rotate),\n userUnit: page.userUnit > 0 ? page.userUnit : 1,\n width: box.width,\n height: box.height,\n }\n}\n\n/** PDF.js already rejects /Rotate values that are not multiples of 90; this also folds negatives. */\nfunction normaliseRotation(rotate: number): PageRotation {\n const r = (((Math.round(rotate / 90) * 90) % 360) + 360) % 360\n return r as PageRotation\n}\n","import type { TextContent, TextItem } from './text'\n\n/** Gap, as a fraction of the font size, above which two items on a line read as separate words. */\nexport const GAP_SPACE = 0.15\n\n/** How far off the baseline, as a fraction of the font size, an item can sit and still share the line. */\nconst SAME_LINE = 0.5\n\nexport interface SearchableText {\n page: number\n /** The joined page text. */\n raw: string\n /** The normalised text matched against. */\n norm: string\n /** `normToRaw[i]` is the raw index norm char `i` came from; the last entry is `raw.length`. */\n normToRaw: Int32Array\n /** Index into `content.items` for each raw char, `-1` for an inserted space. */\n rawToItem: Int32Array\n /** Offset within that item's `str` for each raw char, `-1` for an inserted space. */\n rawToOffset: Int32Array\n content: TextContent\n}\n\nconst FOLD: Record<string, string> = {}\nfor (const c of '‘’‚‛') FOLD[c] = \"'\"\nfor (const c of '“”„‟') FOLD[c] = '\"'\nfor (const c of '‐‑‒–—―') FOLD[c] = '-'\n\n/** A line ending in one of these joins to the next line's word: hyphen, U+2010, U+2011, soft hyphen. */\nconst JOINING_HYPHENS = new Set(['-', '\\u2010', '\\u2011', '\\u00ad'])\n\nconst MARKS = /\\p{M}/gu\nconst WHITESPACE = /^\\s$/u\n/** Sticky: set `lastIndex` to test the code point at that index without slicing. */\nconst LETTER_AT = /\\p{L}/uy\n\n/** One code point to its normalised form: NFKD, marks stripped, quotes and dashes folded. */\nfunction fold(ch: string): string {\n const out = ch.normalize('NFKD').replace(MARKS, '')\n let s = ''\n for (const c of out) s += FOLD[c] ?? c\n return s\n}\n\nfunction letterAt(s: string, i: number): boolean {\n LETTER_AT.lastIndex = i\n return LETTER_AT.test(s)\n}\n\nconst isSpace = (ch: string | undefined) => ch !== undefined && WHITESPACE.test(ch)\n\nfunction lineGap(prev: TextItem, next: TextItem): { gap: number; sameLine: boolean } {\n const dx = prev.quad.p4.x - prev.quad.p3.x\n const dy = prev.quad.p4.y - prev.quad.p3.y\n const len = Math.hypot(dx, dy)\n const ux = len === 0 ? 1 : dx / len\n const uy = len === 0 ? 0 : dy / len\n // Boxes run along the baseline whatever the text direction, so right-to-left text reads from\n // the end of one box back to the start of the one before it.\n const rtl = prev.dir === 'rtl' && next.dir === 'rtl'\n const from = rtl ? next.quad.p4 : prev.quad.p4\n const to = rtl ? prev.quad.p3 : next.quad.p3\n const sx = to.x - from.x\n const sy = to.y - from.y\n const size = Math.max(prev.fontSize, next.fontSize)\n return {\n gap: sx * ux + sy * uy,\n sameLine: Math.abs(sx * -uy + sy * ux) <= SAME_LINE * size,\n }\n}\n\n/**\n * Joins a page's items the way the page reads: in content order with nothing between them,\n * a space after an item that ends its line, and a space where two items on a line sit further\n * apart than `GAP_SPACE` of the font size. Neither adds a space next to whitespace already there.\n */\nexport function searchableText(content: TextContent): SearchableText {\n const chars: string[] = []\n const item: number[] = []\n const offset: number[] = []\n // Raw indexes of spaces inserted for a line end, which the hyphen rule looks for.\n const eolSpace = new Set<number>()\n let prev: TextItem | undefined\n\n const space = (eol: boolean) => {\n if (eol) eolSpace.add(chars.length)\n chars.push(' ')\n item.push(-1)\n offset.push(-1)\n }\n\n content.items.forEach((it, i) => {\n if (it.str === '') {\n if (it.hasEOL && chars.length > 0 && !isSpace(chars[chars.length - 1])) space(true)\n return\n }\n if (prev && chars.length > 0 && !isSpace(chars[chars.length - 1])) {\n const { gap, sameLine } = lineGap(prev, it)\n const size = Math.max(prev.fontSize, it.fontSize)\n if (!isSpace(it.str[0]) && (!sameLine || gap > GAP_SPACE * size)) space(false)\n }\n for (let k = 0; k < it.str.length; k++) {\n chars.push(it.str[k]!)\n item.push(i)\n offset.push(k)\n }\n if (it.hasEOL && !isSpace(it.str[it.str.length - 1])) space(true)\n prev = it\n })\n\n const raw = chars.join('')\n let norm = ''\n const map: number[] = []\n for (let r = 0; r < raw.length;) {\n const ch = String.fromCodePoint(raw.codePointAt(r)!)\n if (JOINING_HYPHENS.has(ch) && eolSpace.has(r + 1) && letterAt(raw, r + 2)) {\n // \"docu-⏎ment\": drop the hyphen and the space the line end added.\n r += 2\n continue\n }\n for (const c of fold(ch)) {\n const out = isSpace(c) ? ' ' : c\n if (out === ' ' && norm.endsWith(' ')) continue\n norm += out\n for (let u = 0; u < out.length; u++) map.push(r)\n }\n r += ch.length\n }\n map.push(raw.length)\n const normToRaw = Int32Array.from(map)\n\n return {\n page: content.page,\n raw,\n norm,\n normToRaw,\n rawToItem: Int32Array.from(item),\n rawToOffset: Int32Array.from(offset),\n content,\n }\n}\n\n/** Folds a query the way `norm` is folded; case is lowered here only when the match ignores it. */\nexport function normalizeQuery(query: string, matchCase: boolean): string {\n let out = ''\n for (const ch of query) out += fold(ch)\n out = out.replace(/\\s+/gu, ' ')\n return matchCase ? out : out.toLowerCase()\n}\n\n/** Whether `query` folds to nothing but whitespace, which a search treats as no query at all. */\nexport function isBlankQuery(query: string): boolean {\n return normalizeQuery(query, true).trim() === ''\n}\n","import { rectFromQuads, type Point, type Quad, type Rect } from './geometry'\nimport { isBlankQuery, normalizeQuery, type SearchableText } from './search-text'\n\nimport type { TextItem } from './text'\n\n/** How much page text `before` and `after` carry on each side of a hit. */\nexport const CONTEXT_CHARS = 40\n\nexport interface SearchOptions {\n /** Defaults to false. Ignored for a `RegExp`, whose own `i` flag rules. */\n matchCase?: boolean\n /** Requires a hit to have no letter, digit or underscore next to it. */\n wholeWord?: boolean\n /** Page indices to search, in the order given. Defaults to every page in order. */\n pages?: readonly number[]\n signal?: AbortSignal\n}\n\nexport interface SearchHit {\n page: number\n /** Offsets into `pageText(page)`. */\n start: number\n end: number\n /** The page text the hit covers. */\n text: string\n /** One quad per run of text the hit touches. */\n quads: Quad[]\n rect: Rect\n /**\n * True when every quad is cut where the page draws its glyphs. False when some text could not\n * be matched to the page's glyphs (right-to-left or vertical text, or an unusual file) and its\n * quad is cut at estimated widths, which can fall short of the glyphs; pad those before\n * covering text with them.\n */\n exact: boolean\n /** Up to `CONTEXT_CHARS` of page text either side of the hit, whitespace collapsed. */\n before: string\n after: string\n}\n\nexport interface SearchResults extends AsyncIterable<SearchHit> {\n all(): Promise<SearchHit[]>\n}\n\nconst WORD_BEFORE = /[\\p{L}\\p{N}_]$/u\nconst WORD_AFTER = /^[\\p{L}\\p{N}_]/u\n\nconst escapeRegExp = (s: string) => s.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n\n/** Match ranges `[start, end)` into `norm`, in order and without overlap. */\nfunction normRanges(\n norm: string,\n query: string | RegExp,\n matchCase: boolean\n): [number, number][] {\n const out: [number, number][] = []\n if (typeof query === 'string') {\n if (isBlankQuery(query)) return out\n const needle = normalizeQuery(query, true)\n const haystack = matchCase ? norm : norm.toLowerCase()\n const target = matchCase ? needle : needle.toLowerCase()\n // Indexes into `norm` only carry over when folding case kept every length.\n if (haystack.length === norm.length && target.length === needle.length) {\n for (\n let at = haystack.indexOf(target);\n at !== -1;\n at = haystack.indexOf(target, at + target.length)\n )\n out.push([at, at + target.length])\n return out\n }\n // Lower-casing changed a length (\"İ\" is two UTF-16 units), so search `norm` itself.\n return regexRanges(norm, new RegExp(escapeRegExp(needle), 'giu'))\n }\n // Global so `exec` walks the text; not sticky, which would stop at the first gap.\n const flags = query.flags.replace(/[gy]/g, '') + 'g'\n return regexRanges(norm, new RegExp(query.source, flags))\n}\n\nfunction regexRanges(norm: string, re: RegExp): [number, number][] {\n const out: [number, number][] = []\n const unicode = re.unicode || re.flags.includes('v')\n for (let m = re.exec(norm); m; m = re.exec(norm)) {\n if (m[0] !== '') {\n out.push([m.index, m.index + m[0].length])\n continue\n }\n // Step past an empty match by a whole code point: a unicode regexp moved to the middle of\n // a surrogate pair backs up to its start and finds the same empty match again.\n re.lastIndex = m.index + (unicode && norm.codePointAt(m.index)! > 0xffff ? 2 : 1)\n }\n return out\n}\n\nconst lerp = (a: Point, b: Point, t: number): Point => ({\n x: a.x + (b.x - a.x) * t,\n y: a.y + (b.y - a.y) * t,\n})\n\n/**\n * The part of an item's quad from character `a` to `b`, cut along its baseline at the item's\n * `advances`, or at an equal share per character when it has none. With advances it spans every\n * boundary from `a` to `b` and the end of every glyph in between, so glyphs the pen drew out of\n * order, or that kerning overlaps with the next one, stay inside it.\n */\nfunction cutQuad(it: TextItem, a: number, b: number): Quad {\n const q = it.quad\n const len = it.str.length\n const span = it.advances?.slice(a, b + 1)\n const ends = it.glyphEnds?.slice(a, b) ?? []\n const t0 = span ? Math.min(...span) : a / len\n const t1 = span ? Math.max(...span, ...ends) : b / len\n return {\n p1: lerp(q.p1, q.p2, t0),\n p2: lerp(q.p1, q.p2, t1),\n p3: lerp(q.p3, q.p4, t0),\n p4: lerp(q.p3, q.p4, t1),\n }\n}\n\nfunction quadsFor(\n st: SearchableText,\n start: number,\n end: number\n): { quads: Quad[]; exact: boolean } {\n const spans = new Map<number, [number, number]>()\n for (let r = start; r < end; r++) {\n const i = st.rawToItem[r]!\n if (i < 0) continue\n const k = st.rawToOffset[r]!\n const span = spans.get(i)\n if (span) {\n span[0] = Math.min(span[0], k)\n span[1] = Math.max(span[1], k + 1)\n } else spans.set(i, [k, k + 1])\n }\n const quads: Quad[] = []\n let exact = true\n for (const [i, [a, b]] of spans) {\n const it = st.content.items[i]!\n quads.push(cutQuad(it, a, b))\n // Glyph ends are only set when the item's boundaries come from the page's glyphs.\n if (!it.glyphEnds) exact = false\n }\n return { quads, exact }\n}\n\nconst collapse = (s: string) => s.replace(/\\s+/gu, ' ')\n\n/** Every hit for `query` on one page, in page order. */\nexport function matchPage(\n st: SearchableText,\n query: string | RegExp,\n opts: { matchCase: boolean; wholeWord: boolean }\n): SearchHit[] {\n const hits: SearchHit[] = []\n for (const [ns, ne] of normRanges(st.norm, query, opts.matchCase)) {\n if (opts.wholeWord) {\n if (WORD_BEFORE.test(st.norm.slice(Math.max(0, ns - 2), ns))) continue\n if (WORD_AFTER.test(st.norm.slice(ne, ne + 2))) continue\n }\n const start = st.normToRaw[ns]!\n const last = st.normToRaw[ne - 1]!\n const end = last + (st.raw.codePointAt(last)! > 0xffff ? 2 : 1)\n const { quads, exact } = quadsFor(st, start, end)\n if (quads.length === 0) continue\n hits.push({\n page: st.page,\n start,\n end,\n text: st.raw.slice(start, end),\n quads,\n rect: rectFromQuads(quads),\n exact,\n before: collapse(st.raw.slice(Math.max(0, start - CONTEXT_CHARS), start)),\n after: collapse(st.raw.slice(end, end + CONTEXT_CHARS)),\n })\n }\n return hits\n}\n","import { v7 as uuidv7 } from 'uuid'\n\nimport { InkError } from './errors'\n\nexport type DocumentSource =\n | ArrayBuffer\n | Uint8Array\n | Blob\n | string\n | { url: string; key: string }\n | { data: ArrayBuffer | Uint8Array; key: string }\n\nexport interface ResolvedSource {\n /** Identity of the document. Hosts reuse it to avoid reloads when a signed URL changes. */\n key: string\n bytes(): Promise<Uint8Array>\n}\n\nexport function resolveSource(\n src: DocumentSource,\n fetchImpl: typeof fetch = globalThis.fetch\n): ResolvedSource {\n if (typeof src === 'string')\n return { key: src, bytes: () => fetchBytes(src, fetchImpl) }\n if (src instanceof ArrayBuffer || src instanceof Uint8Array) {\n const data = toBytes(src)\n return { key: `bytes:${uuidv7()}`, bytes: () => Promise.resolve(data.slice()) }\n }\n if ('url' in src) {\n const { url } = src\n return { key: src.key, bytes: () => fetchBytes(url, fetchImpl) }\n }\n if ('data' in src) {\n const data = toBytes(src.data)\n return { key: src.key, bytes: () => Promise.resolve(data.slice()) }\n }\n const blob = src\n return {\n key: `bytes:${uuidv7()}`,\n bytes: async () => new Uint8Array(await blob.arrayBuffer()),\n }\n}\n\nconst DEFAULT_FILE_NAME = 'document.pdf'\n\n/** `name` ending in `.pdf` (any case), else with it added. */\nconst asPdf = (name: string): string => (/\\.pdf$/i.test(name) ? name : `${name}.pdf`)\n\n/** A URL's last path segment, decoded, without its query or hash; null when it has none. */\nfunction urlFileName(url: string): string | null {\n let path: string\n try {\n path = new URL(url, 'http://localhost').pathname\n } catch {\n return null\n }\n const last = path.split('/').pop() ?? ''\n if (last === '') return null\n try {\n return decodeURIComponent(last)\n } catch {\n return last\n }\n}\n\n/**\n * The name to save `src` under: a File's name, else a URL's last path segment, with `.pdf`\n * added when it has none; `document.pdf` when neither gives one.\n */\nexport function sourceFileName(src: DocumentSource): string {\n let name: string | null = null\n if (typeof src === 'string') name = urlFileName(src)\n else if (src instanceof ArrayBuffer || src instanceof Uint8Array) name = null\n else if ('url' in src) name = urlFileName(src.url)\n else if ('data' in src) name = null\n else if (typeof (src as Partial<File>).name === 'string') name = (src as File).name\n return name ? asPdf(name) : DEFAULT_FILE_NAME\n}\n\n/**\n * A view over the host's bytes. `bytes()` hands PDF.js a copy each time: PDF.js transfers the\n * buffer it is given to its worker, which would empty the host's array and break a reopen\n * (a password retry, for one).\n */\nfunction toBytes(data: ArrayBuffer | Uint8Array): Uint8Array {\n return data instanceof Uint8Array ? data : new Uint8Array(data)\n}\n\nasync function fetchBytes(url: string, fetchImpl: typeof fetch): Promise<Uint8Array> {\n if (typeof fetchImpl !== 'function') {\n throw new InkError(\n 'SourceFetchFailed',\n 'No fetch implementation available for URL sources',\n {\n url,\n }\n )\n }\n let res: Response\n try {\n res = await fetchImpl(url, { credentials: 'same-origin' })\n } catch (cause) {\n throw new InkError('SourceFetchFailed', `Could not fetch ${url}`, { url }, cause)\n }\n if (!res.ok) {\n throw new InkError(\n 'SourceFetchFailed',\n `Fetching ${url} returned HTTP ${res.status}`,\n {\n url,\n status: res.status,\n }\n )\n }\n try {\n return new Uint8Array(await res.arrayBuffer())\n } catch (cause) {\n throw new InkError(\n 'SourceFetchFailed',\n `Reading the body of ${url} failed`,\n { url },\n cause\n )\n }\n}\n","import type { Point } from './geometry'\nimport type { TextItem } from './text'\n\n/**\n * One glyph as the page draws it, in content order: its text, where the pen starts it and where\n * its own width ends, before any character or word spacing. Both points are in user space.\n */\nexport interface PageGlyph {\n text: string\n start: Point\n end: Point\n}\n\n/** A text item's baseline: where it starts, its unit direction and its width, in user space. */\nexport interface TextRun extends Pick<TextItem, 'str' | 'dir' | 'fontSize'> {\n origin: Point\n along: Point\n width: number\n}\n\n/** Where each character of a run starts and where its glyph ends, as fractions of the run's width. */\nexport interface GlyphBounds {\n /** `str.length + 1` boundaries: see `TextItem.advances`. */\n advances: number[]\n /** `str.length` glyph ends: see `TextItem.glyphEnds`. */\n ends: number[]\n}\n\n/** How many glyphs past the last match to look for the start of the next item first. */\nconst LOOKAHEAD = 256\n/** How far, as a fraction of the font size, a glyph may start from the item origin and still match. */\nconst START_SLACK = 0.05\n/** How far off the baseline, as a fraction of the font size, a glyph may sit (text rise). */\nconst RISE_SLACK = 1\n\n/**\n * Each item's character boundaries as fractions of its width (see `TextItem.advances`), from the\n * glyphs that drew it. PDF.js builds text items from the same glyphs in the same order. An item\n * matches a glyph sequence that spells its text and whose first glyph starts at the item's origin.\n * Boundaries are where the pen put each glyph, projected onto the item's baseline, so they hold\n * through moves, scaling and spacing inside an item, and may run past 1 when PDF.js reports a\n * width shorter than the glyphs it drew. An item that cannot be matched, or that runs right to\n * left or top to bottom, gets undefined.\n */\nexport function glyphAdvances(\n runs: readonly TextRun[],\n glyphs: readonly PageGlyph[]\n): (GlyphBounds | undefined)[] {\n let next = 0\n return runs.map((run) => {\n if (run.dir !== 'ltr' || run.str.trim() === '' || !(run.width > 0)) return undefined\n const tryFrom = (from: number, to: number) => {\n for (let start = from; start < to; start++) {\n const m = matchRun(run, glyphs, start)\n if (m) return m\n }\n return undefined\n }\n // Look just past the last match first; items PDF.js reorders or drops are found by a full pass.\n const m =\n tryFrom(next, Math.min(glyphs.length, next + LOOKAHEAD)) ??\n tryFrom(0, glyphs.length)\n if (!m) return undefined\n next = m.next\n return m.bounds\n })\n}\n\n/** The text a glyph's text stands for in PDF.js text content, which expands ligatures. */\nfunction variants(text: string): string[] {\n const n = text.normalize('NFKC')\n return n === text ? [text] : [text, n]\n}\n\n/** A glyph the item may leave out: a space, or a character that draws nothing. */\nconst skippable = (text: string) => /^[\\s\\p{Cf}]*$/u.test(text)\n\nfunction matchRun(\n run: TextRun,\n glyphs: readonly PageGlyph[],\n start: number\n): { bounds: GlyphBounds; next: number } | undefined {\n const { str, origin, along, width, fontSize } = run\n const t = (p: Point) =>\n ((p.x - origin.x) * along.x + (p.y - origin.y) * along.y) / width\n const off = (p: Point) =>\n Math.abs((p.x - origin.x) * along.y - (p.y - origin.y) * along.x)\n const first = glyphs[start]\n if (\n !first ||\n Math.abs(t(first.start) * width) > START_SLACK * fontSize ||\n off(first.start) > RISE_SLACK * fontSize\n )\n return undefined\n const bounds: number[] = []\n const ends: number[] = []\n let end = 0\n let g = start\n while (bounds.length < str.length) {\n const glyph = glyphs[g]\n const at = bounds.length\n const text =\n glyph && variants(glyph.text).find((v) => v !== '' && str.startsWith(v, at))\n if (glyph && text) {\n const t0 = t(glyph.start)\n end = t(glyph.end)\n for (let k = 0; k < text.length; k++) {\n bounds.push(t0 + ((end - t0) * k) / text.length)\n ends.push(t0 + ((end - t0) * (k + 1)) / text.length)\n }\n g++\n } else if (at > 0 && /\\s/u.test(str[at]!)) {\n // A space PDF.js inserted for a gap: it runs from the last glyph to the next one.\n bounds.push(end)\n ends.push(end)\n } else if (at > 0 && glyph && skippable(glyph.text)) g++\n else return undefined\n }\n return { bounds: { advances: [...bounds, end], ends }, next: g }\n}\n","import { rectFromQuad, type Point, type Quad, type Rect } from './geometry'\nimport { glyphAdvances, type PageGlyph, type TextRun } from './glyph-advances'\n\nimport type { PdfjsTextContent, PdfjsTextItem } from '../pdfjs/types'\n\nexport interface TextItem {\n str: string\n dir: 'ltr' | 'rtl' | 'ttb'\n fontName: string\n fontSize: number\n hasEOL: boolean\n /** Glyph-run box in user space, following the run's rotation. */\n quad: Quad\n /** Axis-aligned bounds of `quad`. */\n rect: Rect\n /**\n * How far along the run each character boundary lies, as a fraction of its width: `str.length + 1`\n * entries, from 0 to 1 or a little past it. Taken from where the page draws each glyph when the\n * glyphs can be matched to the run, else measured in the run's fallback font. Absent when neither\n * works, in which case every character takes an equal share.\n */\n advances?: readonly number[]\n /**\n * Where each character's glyph ends, as a fraction of the run's width: `str.length` entries, set\n * with `advances` when they come from the page's glyphs. Kerning can pull the next character\n * back over the end of a glyph, so a glyph may end past the next boundary.\n */\n glyphEnds?: readonly number[]\n}\n\n/** How far `char` advances in `fontFamily`, in any unit; only ratios within a run are used. */\nexport type MeasureChar = (char: string, fontFamily: string) => number\n\nexport interface TextContent {\n page: number\n items: TextItem[]\n}\n\n/** Fractions of the font size used when PDF.js has no usable metrics for the font. */\nconst FALLBACK_ASCENT = 0.75\nconst FALLBACK_DESCENT = 0.25\n\n/**\n * Converts `getTextContent()` output to user-space boxes.\n *\n * For an item with transform [a, b, c, d, e, f] (already in user space):\n * - (e, f) is the start of the run on the baseline;\n * - u = (a, b) / |(a, b)| is the baseline direction, along which the run advances `width`;\n * - v = (c, d) / |(c, d)| is the glyph-up direction, and `fontSize` = |(c, d)|;\n * - the box spans from `descent * fontSize` below the baseline to `ascent * fontSize` above it,\n * using the font's ascent/descent from `styles` when PDF.js provides them, else 0.75 / 0.25.\n *\n * So p3 = (e, f) - v * descent * fontSize, p4 = p3 + u * width, p1 = p3 + v * (ascent + descent) * fontSize,\n * p2 = p4 + (p1 - p3). `rect` is the axis-aligned bounding box of the quad.\n */\nexport function textContentFromPdfjs(\n page: number,\n tc: PdfjsTextContent,\n measure?: MeasureChar,\n glyphs?: readonly PageGlyph[]\n): TextContent {\n const items: TextItem[] = []\n const runs: TextRun[] = []\n const families: string[] = []\n for (const raw of tc.items) {\n if (!('str' in raw)) continue\n const item: PdfjsTextItem = raw\n const [a, b, c, d, e, f] = item.transform as [\n number,\n number,\n number,\n number,\n number,\n number,\n ]\n const baseLen = Math.hypot(a, b)\n const fontSize = Math.hypot(c, d)\n const u: Point = baseLen === 0 ? { x: 1, y: 0 } : { x: a / baseLen, y: b / baseLen }\n const v: Point =\n fontSize === 0 ? { x: -u.y, y: u.x } : { x: c / fontSize, y: d / fontSize }\n const { ascent, descent } = metrics(tc.styles[item.fontName])\n const below = descent * fontSize\n const total = (ascent + descent) * fontSize\n const w = item.width\n const p3 = { x: e - v.x * below, y: f - v.y * below }\n const p4 = { x: p3.x + u.x * w, y: p3.y + u.y * w }\n const p1 = { x: p3.x + v.x * total, y: p3.y + v.y * total }\n const p2 = { x: p4.x + v.x * total, y: p4.y + v.y * total }\n const quad: Quad = { p1, p2, p3, p4 }\n const dir = isDir(item.dir) ? item.dir : 'ltr'\n items.push({\n str: item.str,\n dir,\n fontName: item.fontName,\n fontSize,\n hasEOL: item.hasEOL,\n quad,\n rect: rectFromQuad(quad),\n })\n runs.push({\n str: item.str,\n dir,\n fontSize,\n origin: { x: e, y: f },\n along: u,\n width: w,\n })\n families.push(tc.styles[item.fontName]?.fontFamily ?? 'sans-serif')\n }\n // The glyphs the page draws give exact boundaries; measuring is the fallback for the rest.\n const exact = glyphs ? glyphAdvances(runs, glyphs) : []\n items.forEach((it, i) => {\n const bounds = exact[i]\n if (bounds) {\n it.advances = bounds.advances\n it.glyphEnds = bounds.ends\n } else if (measure && it.dir === 'ltr') {\n const advances = advancesOf(it.str, families[i]!, measure)\n if (advances) it.advances = advances\n }\n })\n return { page, items }\n}\n\n/** Each character boundary of `str` as a fraction of its measured width, or undefined if it measures 0. */\nfunction advancesOf(\n str: string,\n family: string,\n measure: MeasureChar\n): number[] | undefined {\n const ends = [0]\n let sum = 0\n for (let i = 0; i < str.length; i++) {\n const cp = str.codePointAt(i)!\n // A surrogate pair is measured whole on its first unit; the second unit adds nothing.\n if (cp > 0xffff) {\n sum += measure(String.fromCodePoint(cp), family)\n ends.push(sum)\n i++\n } else sum += measure(str[i]!, family)\n ends.push(sum)\n }\n if (!(sum > 0)) return undefined\n return ends.map((e) => e / sum)\n}\n\nfunction metrics(style: PdfjsTextContent['styles'][string] | undefined): {\n ascent: number\n descent: number\n} {\n // Vertical fonts report metrics for horizontal layout, so they get the fallback box too.\n if (!style || style.vertical)\n return { ascent: FALLBACK_ASCENT, descent: FALLBACK_DESCENT }\n const ascent = style.ascent\n const descent = Math.abs(style.descent)\n if (!(ascent > 0) || !Number.isFinite(descent) || ascent + descent <= 0) {\n return { ascent: FALLBACK_ASCENT, descent: FALLBACK_DESCENT }\n }\n return { ascent, descent }\n}\n\nfunction isDir(dir: string): dir is TextItem['dir'] {\n return dir === 'ltr' || dir === 'rtl' || dir === 'ttb'\n}\n","import { emptyFormExtras, readFormExtras, type FormExtras } from '../pdf/form-fields'\nimport { openPdfObjects } from '../pdf/objects'\nimport { destinationPage, resolveDestination } from '../pdfjs/destinations'\nimport { pageGlyphs } from '../pdfjs/glyphs'\nimport { assertAssets, loadPdfjs, openProxy } from '../pdfjs/load'\nimport { readOutline } from '../pdfjs/outline'\nimport { createFormScripting } from '../pdfjs/scripting'\nimport { structureAnnotationOrder } from '../pdfjs/structure'\n\nimport { staticDefaults, type AnnotationDefaults } from './annotations/defaults'\nimport {\n importEmbeddedPage,\n summarise,\n type EmbeddedSummary,\n type EmbeddedTarget,\n} from './annotations/embedded'\nimport { readEmbeddedFields } from './annotations/embedded-fields'\nimport { createHistory, type History } from './annotations/history'\nimport {\n exportAnnotations,\n planImport,\n type ImportOptions,\n type ImportResult,\n} from './annotations/json'\nimport {\n createAnnotationStore,\n type AnnotationStore,\n type StoreMode,\n} from './annotations/store'\nimport { InkError, isInkError } from './errors'\nimport { createFormController, type FormController } from './form/controller'\nimport { fieldsToGloss } from './form/gloss'\nimport { buildFormFields, type RawWidget } from './form/structure'\nimport { linkFromPdfjs, type PageLink } from './links'\nimport { mapInOrder } from './map-in-order'\nimport { canvasMeasureChar } from './measure-char'\nimport { createPageCache, type PageCache } from './page-cache'\nimport { pageInfoFromProxy, type PageInfo } from './pages'\nimport { readonly, writable, type Readable } from './readable'\nimport {\n matchPage,\n type SearchHit,\n type SearchOptions,\n type SearchResults,\n} from './search'\nimport { searchableText, type SearchableText } from './search-text'\nimport { resolveSource, sourceFileName, type DocumentSource } from './source'\nimport { textContentFromPdfjs, type TextContent } from './text'\n\nimport type { AnnotationDocument, ForeignAnnotation } from './annotations/types'\nimport type { Destination, RawDestination } from './destination'\nimport type { FieldsMode, FormField } from './form/types'\nimport type { OutlineItem } from './outline'\nimport type {\n PdfAssets,\n PdfjsAnnotationData,\n PdfjsDocument,\n PdfjsModule,\n PdfjsPage,\n} from '../pdfjs/types'\n\nexport type DocumentStatus =\n { state: 'loading' } | { state: 'ready' } | { state: 'error'; error: InkError }\n\n/** A document's status plus `idle`, for a host with no document open. */\nexport type InkStatus = DocumentStatus | { state: 'idle' }\n\nexport interface DocumentInfo {\n title?: string | undefined\n author?: string | undefined\n pageCount: number\n isEncrypted: boolean\n}\n\nexport interface OpenOptions {\n assets: PdfAssets\n password?: string | undefined\n fetch?: typeof fetch | undefined\n /**\n * Defaults to uncontrolled. In controlled mode the host owns only session annotations:\n * embedded (`source: 'pdf'`) ones live in the store, are never passed to `onChange`, and stay\n * in `list` whatever the host pushes back.\n */\n annotations?: StoreMode | undefined\n /**\n * Form field values; defaults to uncontrolled, starting from the PDF's. In controlled mode a\n * commit applies at once and is reported with the full map, and the host's push wins.\n */\n fields?: FieldsMode | undefined\n /** Colour defaults. Pass `cssVariableDefaults(element)` from the DOM layer to read theme variables. */\n defaults?: AnnotationDefaults | undefined\n /**\n * Undo history, on by default. `false` disables it. In controlled mode history is always\n * inert: the host owns the list, so it owns undo too. Field values join it only while both\n * annotations and fields are uncontrolled.\n */\n history?: boolean | { limit?: number | undefined } | undefined\n /** PDF.js verbosity level; 0 = errors only. Defaults to PDF.js's own level. */\n verbosity?: number | undefined\n}\n\nexport interface InkDocument {\n readonly key: string\n readonly status: Readable<DocumentStatus>\n /** Resolves when status is ready; rejects with the InkError when it is error. */\n readonly ready: Promise<void>\n readonly pages: readonly PageInfo[]\n readonly info: DocumentInfo\n text(page: number): Promise<TextContent>\n /** The page's text as search sees it: items joined the way the page reads. */\n pageText(page: number): Promise<string>\n /**\n * Finds `query` in the document's text, a page at a time. A string matches ignoring case,\n * accents and quote style; a `RegExp` runs on the same normalised text.\n */\n search(query: string | RegExp, opts?: SearchOptions): SearchResults\n /**\n * Annotations embedded in the file arrive here as `source: 'pdf'`, `locked: true` before\n * `ready` resolves. They stay in `list` in both modes and cannot be removed; in controlled\n * mode they never reach `onChange`. Fields PDF.js leaves out (a FreeText's callout, fringe,\n * head and font, a note's icon) are read from the file after `ready` and fill in later, as a\n * `{ kind: 'replace', reason: 'embedded', fields }` change.\n */\n readonly annotations: AnnotationStore\n /**\n * The page's links, in file order. Complete once `ready` resolves, `[]` before. Links are\n * read-only structure of the file and never join `annotations`.\n */\n links(page: number): readonly PageLink[]\n /**\n * Looks a destination up in the file: a name through its name tree, or an explicit array.\n * `undefined` when it names no page. Answers are cached per document by the destination.\n */\n resolveDestination(raw: RawDestination): Promise<Destination | undefined>\n /**\n * The document's outline (its bookmarks), each destination already resolved. Read on the first\n * call, after `ready`, and cached; `[]` when the file has none. Rejects as `ready` does.\n */\n outline(): Promise<readonly OutlineItem[]>\n /** What the file contained, by PDF subtype, including subtypes Inkbar does not show. */\n readonly embedded: readonly EmbeddedSummary[]\n readonly history: History\n /** The form's fields and values; empty when the file has no fields. */\n readonly form: FormController\n /**\n * Session annotations only, plus unknown-type items kept from earlier imports, and `fields`\n * with every field value that is not no-export.\n */\n exportAnnotations(format: 'json'): AnnotationDocument\n /**\n * Defaults to `{ mode: 'replace' }`. Embedded annotations are never touched. `fields`, when\n * present, sets the values it names and leaves the rest; that is not an undo step.\n */\n importAnnotations(data: AnnotationDocument | string, opts?: ImportOptions): ImportResult\n /**\n * The name to save the file under: the opened File's name, else the URL's last path segment,\n * else `document.pdf`.\n */\n readonly fileName: string\n /**\n * The PDF as a file, for download and print: today the bytes it was opened from, without\n * this session's annotations. Waits for `ready`; rejects as `ready` does.\n */\n getData(): Promise<Uint8Array>\n /** Writes the document with its annotations. Needs @inkbar/engine; rejects with EngineUnavailable otherwise. */\n save(): Promise<Uint8Array>\n destroy(): void\n /** @internal PDF.js handles for the DOM layer. Not part of the public contract. */\n readonly _pdfjs: {\n module: PdfjsModule\n proxy: PdfjsDocument\n getPage(index: number): Promise<PdfjsPage>\n }\n}\n\ninterface PdfjsInfoDict {\n Title?: unknown\n Author?: unknown\n EncryptFilterName?: unknown\n}\n\n/**\n * Opens a document. Resolves once loading has finished, whether it succeeded or not:\n * check `status` or await `ready`, which rejects with the InkError. Only a missing\n * `assets` option (a programmer error) makes this promise itself reject.\n */\nexport async function openDocument(\n source: DocumentSource,\n options: OpenOptions\n): Promise<InkDocument> {\n assertAssets(options?.assets)\n const resolved = resolveSource(source, options.fetch)\n const status = writable<DocumentStatus>({ state: 'loading' })\n const pages: PageInfo[] = []\n const info: DocumentInfo = { pageCount: 0, isEncrypted: false }\n let pageCache: PageCache<PdfjsPage> | undefined\n let destroyed = false\n let handles: InkDocument['_pdfjs'] | undefined\n const measure = canvasMeasureChar()\n let destroyTask: (() => Promise<void>) | undefined\n\n const store = createAnnotationStore({\n mode: options.annotations ?? { mode: 'uncontrolled' },\n defaults: options.defaults ?? staticDefaults,\n })\n const embedded: EmbeddedSummary[] = []\n const linksByPage = new Map<number, PageLink[]>()\n const destinationCache = new Map<string, Promise<Destination | undefined>>()\n /** The outline, read on the first `outline()` call: most viewers never show it. */\n let outlineRead: Promise<readonly OutlineItem[]> | undefined\n let preserved: ForeignAnnotation[] = []\n /** Embedded annotations whose PDF.js data lacks fields the file holds; read after `ready`. */\n const targets: EmbeddedTarget[] = []\n /** The file's form fields and what was read for them from its objects, filled before `ready`. */\n const formData: {\n fields: FormField[]\n extras: FormExtras\n /** Annotation ids in structure order, for pages whose `/Tabs` is `S`. */\n structure: Map<number, string[]>\n } = {\n fields: [],\n extras: emptyFormExtras(),\n structure: new Map(),\n }\n const fieldsMode = options.fields ?? { mode: 'uncontrolled' }\n /** One undo step once the history exists, which is after `ready`. */\n let step = (fn: () => void): void => fn()\n /** No undo step: changes join the history's baseline once it exists. */\n let quietly = (fn: () => void): void => fn()\n // Built before the fields are read, so it exists from the start; they load before `ready`.\n const form = createFormController({\n fields: [],\n mode: fieldsMode,\n // Script errors stay off `status`: the document has no error event, so they reach the\n // form's own `on('error')`. One from before `ready` waits for the first listener.\n onError: () => undefined,\n batch: (fn) => step(fn),\n quiet: (fn) => quietly(fn),\n })\n\n const destroyedError = (): InkError =>\n new InkError('DocumentDestroyed', 'The document has been destroyed')\n\n const load = (async () => {\n const pdfjs = await loadPdfjs(options.assets)\n const bytes = await resolved.bytes()\n const { task, proxy } = await openProxy(pdfjs, bytes, {\n assets: options.assets,\n password: options.password,\n verbosity: options.verbosity,\n })\n destroyTask = () => task.destroy()\n const cache = createPageCache((index) => proxy.getPage(index + 1))\n pageCache = cache\n const getPage = (index: number): Promise<PdfjsPage> => {\n if (destroyed) return Promise.reject(destroyedError())\n if (!Number.isInteger(index) || index < 0 || index >= proxy.numPages) {\n return Promise.reject(\n new InkError('PageOutOfRange', `Page ${index} does not exist`, {\n index,\n pageCount: proxy.numPages,\n })\n )\n }\n // A failed lookup is not cached: the next mount of the page asks PDF.js again.\n return cache.get(index)\n }\n handles = { module: pdfjs, proxy, getPage }\n const meta = await proxy.getMetadata().catch(() => {\n // Metadata is optional: PDF.js throws on malformed Info dictionaries or XMP, and\n // title/author are nice-to-have. The document itself has opened, so carry on without it.\n return undefined\n })\n const docInfo = (meta?.info ?? {}) as PdfjsInfoDict\n const title = nonEmptyString(docInfo.Title)\n const author = nonEmptyString(docInfo.Author)\n if (title !== undefined) info.title = title\n if (author !== undefined) info.author = author\n info.pageCount = proxy.numPages\n info.isEncrypted =\n docInfo.EncryptFilterName !== null && docInfo.EncryptFilterName !== undefined\n for (let i = 0; i < proxy.numPages; i++)\n pages.push(pageInfoFromProxy(await getPage(i), i))\n\n const importedAt = new Date().toISOString()\n const perPage = await mapInOrder(proxy.numPages, EMBEDDED_CONCURRENCY, async (i) => {\n const page = await getPage(i)\n const raw: PdfjsAnnotationData[] = await page.getAnnotations().catch(() => {\n // A page whose annotations PDF.js cannot parse still renders; it just has none to show.\n return []\n })\n // Widgets and links keep their place in `/Annots`, which Tab order shares between them.\n const widgets = raw.flatMap((data, at): RawWidget[] =>\n data.subtype === 'Widget' ? [{ page: i, data, at }] : []\n )\n const links = raw.flatMap((data, at) => linkFromPdfjs(i, data, at) ?? [])\n return { ...importEmbeddedPage(i, raw, importedAt), widgets, links }\n })\n perPage.forEach((r, i) => {\n if (r.links.length > 0) linksByPage.set(i, r.links)\n })\n embedded.push(...summarise(perPage.map((r) => r.counts)))\n const fromFile = perPage.flatMap((r) => r.annotations)\n targets.push(...perPage.flatMap((r) => r.targets))\n if (fromFile.length > 0) store._setEmbedded(fromFile)\n\n const widgets = perPage.flatMap((r) => r.widgets)\n if (widgets.length > 0) {\n // PDF.js has detached the bytes it was given, so the file's objects are read from a copy.\n const objs = await proxy\n .getData()\n .then(openPdfObjects)\n .catch(() => undefined)\n formData.extras = await readFormExtras(\n objs,\n widgets.map((w) => w.data.id),\n { destinationPage: (name) => destinationPage(proxy, name) }\n )\n formData.fields = buildFormFields(widgets, formData.extras)\n // A page whose `/Tabs` is `S` and that holds fields is read in its structure tree's\n // order. Tagged files often set S on every page, so pages without fields are skipped.\n const withFields = new Set(\n formData.fields.flatMap((f) => f.widgets.map((w) => w.page))\n )\n const structured = [...formData.extras.tabs].flatMap(([page, order]) =>\n order === 'S' && withFields.has(page) ? [page] : []\n )\n const orders = await mapInOrder(\n structured.length,\n EMBEDDED_CONCURRENCY,\n async (i) => structureAnnotationOrder(await getPage(structured[i]!))\n )\n structured.forEach((page, i) => formData.structure.set(page, orders[i]!))\n }\n form._load(formData.fields, formData.extras.tabs, formData.structure)\n // Scripts start before `ready`, so the form a host first sees has run its open scripts,\n // and they are not an undo step. Only a document with fields and JavaScript loads the\n // sandbox; one without fields does no extra work. A failure, or a sandbox that does not\n // load in time, leaves the form without scripts and never fails the document.\n if (formData.fields.length === 0) return\n const scripting = await createFormScripting({\n proxy,\n assets: options.assets,\n form,\n info,\n calculateAtStart: fieldsMode.mode === 'uncontrolled',\n }).catch((cause: unknown) => {\n form._error(\n new InkError(\n 'FormScriptError',\n \"The form's scripts could not start; it can still be filled in\",\n {},\n cause\n )\n )\n return undefined\n })\n if (scripting) form._attachScripting(scripting)\n })()\n\n const ready = load.then(\n () => {\n status.set({ state: 'ready' })\n },\n (cause: unknown) => {\n const error = isInkError(cause)\n ? cause\n : new InkError('InvalidPdf', errorMessage(cause), {}, cause)\n if (error.code === 'PasswordRequired') info.isEncrypted = true\n status.set({ state: 'error', error })\n throw error\n }\n )\n // Keep the rejection observed so hosts that only watch `status` get no unhandled-rejection warning.\n await ready.catch(() => undefined)\n\n // Created after the embedded import, so loading the file is not an undoable step.\n const historyOption = options.history ?? true\n const historyLimit =\n historyOption === false ? 0 : historyOption === true ? undefined : historyOption.limit\n const history = createHistory(\n store,\n historyLimit === undefined ? {} : { limit: historyLimit }\n )\n const replays =\n historyOption !== false &&\n store.mode === 'uncontrolled' &&\n fieldsMode.mode === 'uncontrolled'\n if (replays) history.track(form._store)\n step = (fn) => history.batch(fn)\n quietly = (fn) => history.baseline(fn)\n // Signature fields and the annotations that sign them change together from here.\n form._linkAnnotations({ store, react: (fn) => history.react(fn), replays })\n\n // Fills in fields PDF.js leaves out, read from the file's own bytes. It runs after `ready`\n // so it never delays it, and a failure leaves the annotations as PDF.js imported them.\n void ready.then(\n () => {\n if (destroyed || !handles) return\n const { proxy } = handles\n void readEmbeddedFields(store.list.get(), targets, () => proxy.getData())\n .then((patched) => {\n if (!destroyed && patched.size > 0) store._patchEmbedded(patched)\n })\n .catch(() => undefined)\n },\n () => undefined\n )\n\n /**\n * A page's text with item boundaries measured or, with `glyphs`, taken from where the page\n * draws each glyph. Reading the glyphs means reading the page's drawing commands, which also\n * decodes its images, so search does it only for pages with hits.\n */\n async function pageContent(page: number, glyphs: boolean): Promise<TextContent> {\n if (destroyed) throw destroyedError()\n if (!handles) throw statusError(status.get())\n const p = await handles.getPage(page)\n const tc = await p.getTextContent()\n // A page with no text (a scan) has no glyphs worth reading its drawing commands for.\n const placed =\n glyphs && tc.items.length > 0\n ? await pageGlyphs(p, handles.module).catch(() => undefined)\n : undefined\n return textContentFromPdfjs(page, tc, measure, placed)\n }\n\n /** Each page's searchable text, and whether its boundaries come from the page's glyphs. */\n const searchable = new Map<number, Promise<{ st: SearchableText; placed: boolean }>>()\n const abortError = (signal: AbortSignal | undefined): unknown =>\n signal?.reason ?? new DOMException('Aborted', 'AbortError')\n const searchableFor = (page: number, placed: boolean): Promise<SearchableText> => {\n let cached = searchable.get(page)\n if (!cached) {\n cached = pageContent(page, placed).then((c) => ({ st: searchableText(c), placed }))\n } else if (placed) {\n // Only the boundaries change, so hits found in the measured text keep their offsets.\n cached = cached.then((c) =>\n c.placed\n ? c\n : pageContent(page, true).then((pc) => ({\n st: searchableText(pc),\n placed: true,\n }))\n )\n } else return cached.then((c) => c.st)\n const entry = cached\n searchable.set(page, entry)\n // A failed page is not cached: the next search asks again.\n entry.catch(() => {\n if (searchable.get(page) === entry) searchable.delete(page)\n })\n return entry.then((c) => c.st)\n }\n\n async function* scan(\n query: string | RegExp,\n opts: SearchOptions\n ): AsyncGenerator<SearchHit> {\n const { signal } = opts\n const matchOpts = {\n matchCase: opts.matchCase ?? false,\n wholeWord: opts.wholeWord ?? false,\n }\n const order = opts.pages ?? Array.from({ length: pages.length }, (_, i) => i)\n const check = () => {\n if (signal?.aborted || destroyed) throw abortError(signal)\n }\n check()\n for (let n = 0; n < order.length; n++) {\n if (n > 0) await new Promise<void>((r) => setTimeout(r))\n check()\n let hits: SearchHit[]\n try {\n hits = matchPage(await searchableFor(order[n]!, false), query, matchOpts)\n // Hit boxes are cut where the page draws its glyphs, read only for pages with hits.\n if (hits.length > 0) {\n check()\n hits = matchPage(await searchableFor(order[n]!, true), query, matchOpts)\n }\n } catch (error) {\n check()\n throw error\n }\n check()\n for (const hit of hits) {\n yield hit\n check()\n }\n }\n }\n\n const doc: InkDocument = {\n key: resolved.key,\n fileName: sourceFileName(source),\n async getData() {\n if (destroyed) throw destroyedError()\n await ready\n if (destroyed) throw destroyedError()\n if (!handles) throw statusError(status.get())\n return handles.proxy.getData()\n },\n status: readonly(status),\n ready,\n pages,\n info,\n text(page) {\n return pageContent(page, true)\n },\n async pageText(page) {\n return searchableText(await doc.text(page)).raw\n },\n search(query, opts = {}) {\n return {\n [Symbol.asyncIterator]: () => scan(query, opts),\n async all() {\n const hits: SearchHit[] = []\n for await (const hit of scan(query, opts)) hits.push(hit)\n return hits\n },\n }\n },\n annotations: store,\n links: (page) => linksByPage.get(page) ?? [],\n resolveDestination(raw) {\n if (destroyed || !handles) return Promise.resolve(undefined)\n const key = JSON.stringify(raw)\n let found = destinationCache.get(key)\n if (!found) {\n found = resolveDestination(handles.proxy, raw).catch(() => undefined)\n destinationCache.set(key, found)\n }\n return found\n },\n outline() {\n outlineRead ??= ready.then(() =>\n destroyed || !handles ? [] : readOutline(handles.proxy)\n )\n return outlineRead\n },\n embedded,\n history,\n form,\n exportAnnotations(format) {\n if (format !== 'json')\n throw new TypeError(`Unsupported export format ${String(format)}`)\n return exportAnnotations(\n store,\n preserved,\n resolved.key,\n fieldsToGloss(form.values.get(), form.fields.get())\n )\n },\n importAnnotations(data, opts = { mode: 'replace' }) {\n const plan = planImport(store, data, opts, form.fields.get())\n // Staged before the store publishes, so a change listener that exports sees it.\n preserved =\n opts.mode === 'replace'\n ? plan.result.unknown\n : [...preserved.filter((u) => !plan.ids.has(u.id)), ...plan.result.unknown]\n plan.apply()\n form._import(plan.fieldValues)\n return plan.result\n },\n save() {\n return Promise.reject(\n new InkError(\n 'EngineUnavailable',\n 'Saving needs @inkbar/engine, which is not registered. Use exportAnnotations(\"json\") to keep annotations without writing the PDF.'\n )\n )\n },\n destroy() {\n if (destroyed) return\n destroyed = true\n history.destroy()\n form._destroy()\n store.destroy()\n pageCache?.clear()\n searchable.clear()\n destinationCache.clear()\n if (destroyTask) {\n teardown(destroyTask)\n }\n },\n get _pdfjs() {\n if (!handles) throw statusError(status.get())\n return handles\n },\n }\n return doc\n}\n\nconst EMBEDDED_CONCURRENCY = 8\n\nfunction teardown(destroyTask: () => Promise<void>): void {\n destroyTask().catch(() => {\n // Teardown is best effort: the document is already marked destroyed and every later call\n // rejects with DocumentDestroyed, so a worker that fails to shut down cleanly changes nothing\n // the host can act on.\n })\n}\n\nfunction statusError(s: DocumentStatus): InkError {\n return s.state === 'error'\n ? s.error\n : new InkError('InvalidPdf', 'The document has not finished loading')\n}\n\nfunction nonEmptyString(value: unknown): string | undefined {\n return typeof value === 'string' && value !== '' ? value : undefined\n}\n\nfunction errorMessage(cause: unknown): string {\n if (cause instanceof Error) return cause.message\n return String(cause)\n}\n","// Geometry edits in user space, shared by the pointer (select tool) and keyboard (overlay)\n// paths so both produce the same patch for the same change.\nimport { translateQuad, translateRect, type Point, type Rect } from '../geometry'\n\nimport {\n calloutStroke,\n freeTextBox,\n isStandardCallout,\n withCalloutBounds,\n} from './callout'\n\nimport type {\n Annotation,\n FreeTextAnnotation,\n LineAnnotation,\n TextMarkupAnnotation,\n} from './types'\n\n/** Smallest width or height a resize leaves, user-space points. */\nexport const MIN_SIZE = 1\n\nconst shift = (p: Point, dx: number, dy: number): Point => ({ x: p.x + dx, y: p.y + dy })\n\n/** The geometry patch that translates `a` by (dx, dy) in user space. */\nexport function translated(a: Annotation, dx: number, dy: number): Partial<Annotation> {\n const patch: Record<string, unknown> = { rect: translateRect(a.rect, dx, dy) }\n if ('quads' in a && a.quads) patch.quads = a.quads.map((q) => translateQuad(q, dx, dy))\n if ('callout' in a && a.callout) patch.callout = a.callout.map((p) => shift(p, dx, dy))\n switch (a.type) {\n case 'line':\n patch.start = shift(a.start, dx, dy)\n patch.end = shift(a.end, dx, dy)\n break\n case 'polyline':\n case 'polygon':\n patch.vertices = a.vertices.map((p) => shift(p, dx, dy))\n break\n case 'ink':\n patch.inklist = a.inklist.map((path) => path.map((p) => shift(p, dx, dy)))\n break\n default:\n }\n return patch\n}\n\n/**\n * True when `rect` is the annotation's whole shape, so resizing means changing `rect`: area\n * redactions, free text, squares, circles, stamps, loupes and masks. Text-derived marks (quads), note icons and\n * point-based shapes are not.\n */\nexport function hasRectGeometry(a: Annotation): boolean {\n switch (a.type) {\n case 'redact':\n return a.quads === undefined || a.quads.length === 0\n case 'freetext':\n case 'square':\n case 'circle':\n case 'stamp':\n case 'loupe':\n case 'mask':\n return true\n default:\n return false\n }\n}\n\n/**\n * Grows (positive) or shrinks (negative) a rect by `dw` and `dh` points, keeping its top-left\n * corner (user space: left edge and top edge, `y + height`) where it is. Neither side goes\n * below `MIN_SIZE`. With `keepAspect`, the side that changes leads and the other follows it in\n * proportion (the width when both change).\n */\nexport function resizedRect(r: Rect, dw: number, dh: number, keepAspect = false): Rect {\n let width = Math.max(MIN_SIZE, r.width + dw)\n let height = Math.max(MIN_SIZE, r.height + dh)\n if (keepAspect && r.width > 0 && r.height > 0) {\n const aspect = r.width / r.height\n if (dw !== 0) height = width / aspect\n else width = height * aspect\n // Neither side below MIN_SIZE, still in proportion.\n const grow = Math.max(MIN_SIZE / width, MIN_SIZE / height, 1)\n width *= grow\n height *= grow\n }\n const top = r.y + r.height\n return { x: r.x, y: top - height, width, height }\n}\n\n/**\n * True for highlight, underline, strikeout and squiggly: marks on text, which a drag passes\n * through to text selection and a click selects.\n */\nexport function isTextMarkup(a: Pick<Annotation, 'type'>): a is TextMarkupAnnotation {\n return (\n a.type === 'highlight' ||\n a.type === 'underline' ||\n a.type === 'strikeout' ||\n a.type === 'squiggly'\n )\n}\n\n/**\n * True for the point-based shapes a corner handle resizes by scaling their points: polylines,\n * polygons and ink. With `hasRectGeometry`, the annotations that get corner handles.\n */\nexport function scalesPoints(a: Annotation): boolean {\n return a.type === 'polyline' || a.type === 'polygon' || a.type === 'ink'\n}\n\n/** True when a corner handle resizes `a`: rect-shaped types and point-based shapes. */\nexport function hasCornerHandles(a: Annotation): boolean {\n return hasRectGeometry(a) || scalesPoints(a)\n}\n\n/**\n * The geometry patch that maps `a` from the box `from` onto the box `to`, both in user space:\n * `rect`, every point field (quads, ink paths, vertices, line ends, callout) and a free text's\n * `fringe` scale with the boxes. Stroke widths and font sizes stay as they are.\n */\nexport function scaled(a: Annotation, from: Rect, to: Rect): Partial<Annotation> {\n const sx = from.width === 0 ? 1 : to.width / from.width\n const sy = from.height === 0 ? 1 : to.height / from.height\n const map = (p: Point): Point => ({\n x: to.x + (p.x - from.x) * sx,\n y: to.y + (p.y - from.y) * sy,\n })\n const sameBox = (r: Rect): boolean =>\n r.x === from.x && r.y === from.y && r.width === from.width && r.height === from.height\n const patch: Record<string, unknown> = {\n // The common case, a rect that is the box, maps exactly rather than through the scale.\n rect: sameBox(a.rect)\n ? { ...to }\n : {\n ...map(a.rect),\n width: a.rect.width * sx,\n height: a.rect.height * sy,\n },\n }\n if ('quads' in a && a.quads)\n patch.quads = a.quads.map((q) => ({\n p1: map(q.p1),\n p2: map(q.p2),\n p3: map(q.p3),\n p4: map(q.p4),\n }))\n if ('callout' in a && a.callout) patch.callout = a.callout.map(map)\n // The text box inside a free text's rect scales with it.\n if (a.type === 'freetext' && a.fringe)\n patch.fringe = {\n left: a.fringe.left * sx,\n top: a.fringe.top * sy,\n right: a.fringe.right * sx,\n bottom: a.fringe.bottom * sy,\n }\n switch (a.type) {\n case 'line':\n patch.start = map(a.start)\n patch.end = map(a.end)\n break\n case 'polyline':\n case 'polygon':\n patch.vertices = a.vertices.map(map)\n break\n case 'ink':\n patch.inklist = a.inklist.map((path) => path.map(map))\n break\n default:\n }\n return patch\n}\n\n/**\n * The patch that moves one end of a line to `to` and refits `rect` to the new ends, padded by\n * half the stroke width on every side.\n */\nexport function movedEndpoint(\n a: LineAnnotation,\n which: 'start' | 'end',\n to: Point\n): Partial<LineAnnotation> {\n const start = which === 'start' ? to : a.start\n const end = which === 'end' ? to : a.end\n const pad = a.width / 2\n const x = Math.min(start.x, end.x)\n const y = Math.min(start.y, end.y)\n return {\n [which]: { ...to },\n rect: {\n x: x - pad,\n y: y - pad,\n width: Math.abs(end.x - start.x) + pad * 2,\n height: Math.abs(end.y - start.y) + pad * 2,\n },\n }\n}\n\n/**\n * True for annotations whose resize keeps their aspect ratio without `Shift`: stamps, loupes,\n * masks and signatures (ink with subject `Signature`).\n */\nexport function keepsAspect(a: Annotation): boolean {\n if (a.type === 'stamp' || a.type === 'loupe' || a.type === 'mask') return true\n return a.type === 'ink' && a.subject === 'Signature'\n}\n\n/**\n * True for a speech bubble: a standard free-text callout (`intent: 'FreeTextCallout'`, `rect`,\n * `fringe`, `callout`) with Inkbar's `cornerRadius`. Inkbar draws it as one rounded outline with\n * a wedge from where `callout`'s last point meets the box to the tip, `callout[0]`.\n */\nexport function isBubble(\n a: Annotation\n): a is FreeTextAnnotation & { callout: [Point, Point, ...Point[]] } {\n return (\n a.type === 'freetext' &&\n a.intent === 'FreeTextCallout' &&\n a.cornerRadius !== undefined &&\n a.callout !== undefined &&\n a.callout.length >= 2\n )\n}\n\n/** True for a free text with a callout to edit: a speech bubble or a standard callout. */\nexport function hasCallout(\n a: Annotation\n): a is FreeTextAnnotation & { callout: [Point, Point, ...Point[]] } {\n return isBubble(a) || isStandardCallout(a)\n}\n\n/**\n * The patch that puts a free text's text box at `box`, refitting `rect` and `fringe` around\n * it. A callout's points become `callout` (its own by default) and `rect` holds them too; any\n * other box keeps its fringe, or has `rect` equal to the box without one.\n */\nexport function withBox(\n a: FreeTextAnnotation,\n box: Rect,\n callout: readonly Point[] | undefined = a.callout\n): Partial<FreeTextAnnotation> {\n if (hasCallout(a) && callout)\n return {\n ...withCalloutBounds(box, callout, calloutStroke(a).width, a.head),\n callout: callout.map((p) => ({ ...p })),\n }\n const f = a.fringe\n if (!f) return { rect: { ...box } }\n return {\n rect: {\n x: box.x - f.left,\n y: box.y - f.bottom,\n width: box.width + f.left + f.right,\n height: box.height + f.bottom + f.top,\n },\n }\n}\n\n/** Half a speech bubble's wedge where it leaves the box, points. */\nexport const WEDGE_HALF = 8\n\ntype Edge = 'left' | 'right' | 'bottom' | 'top'\nconst EDGES: readonly Edge[] = ['left', 'right', 'bottom', 'top']\n\n/**\n * The edge of `box` nearest `p`. `bubblePath` (dom/overlay-render.ts) picks the wedge's edge by\n * the same rule in CSS px; change both together.\n */\nfunction nearestEdge(p: Point, box: Rect): Edge {\n const gaps: Record<Edge, number> = {\n left: Math.abs(p.x - box.x),\n right: Math.abs(p.x - (box.x + box.width)),\n bottom: Math.abs(p.y - box.y),\n top: Math.abs(p.y - (box.y + box.height)),\n }\n return EDGES.reduce((best, e) => (gaps[e] < gaps[best] ? e : best))\n}\n\n/** The side of `box` that `p` lies furthest beyond. */\nfunction edgeBeyond(p: Point, box: Rect): Edge {\n const beyond: Record<Edge, number> = {\n left: box.x - p.x,\n right: p.x - (box.x + box.width),\n bottom: box.y - p.y,\n top: p.y - (box.y + box.height),\n }\n return EDGES.reduce((best, e) => (beyond[e] > beyond[best] ? e : best))\n}\n\n/**\n * `p` carried from the box `from` onto the box `to`: it keeps its fraction along the box edge\n * nearest it and its distance off that edge.\n */\nexport function onMovedEdge(p: Point, from: Rect, to: Rect): Point {\n const edge = nearestEdge(p, from)\n const along = (\n v: number,\n start: number,\n size: number,\n next: number,\n nextSize: number\n ) => next + (size === 0 ? nextSize / 2 : ((v - start) / size) * nextSize)\n if (edge === 'left' || edge === 'right') {\n const x = edge === 'left' ? from.x : from.x + from.width\n const nx = edge === 'left' ? to.x : to.x + to.width\n return { x: nx + p.x - x, y: along(p.y, from.y, from.height, to.y, to.height) }\n }\n const y = edge === 'bottom' ? from.y : from.y + from.height\n const ny = edge === 'bottom' ? to.y : to.y + to.height\n return { x: along(p.x, from.x, from.width, to.x, to.width), y: ny + p.y - y }\n}\n\n/**\n * `p` placed on `box`'s `edge` at its own position along it, kept `margin` points clear of the\n * corners (at most half the edge).\n */\nfunction ontoEdge(p: Point, box: Rect, edge: Edge, margin: number): Point {\n const clamp = (v: number, start: number, size: number) => {\n const m = Math.min(margin, size / 2)\n return Math.min(Math.max(v, start + m), start + size - m)\n }\n if (edge === 'left' || edge === 'right')\n return {\n x: edge === 'left' ? box.x : box.x + box.width,\n y: clamp(p.y, box.y, box.height),\n }\n return {\n x: clamp(p.x, box.x, box.width),\n y: edge === 'bottom' ? box.y : box.y + box.height,\n }\n}\n\n/**\n * The patch that resizes a free text's text box to `to`. A callout's tip and bend stay where\n * they are and its last point moves with the box edge it sits on (`onMovedEdge`).\n */\nexport function resizedBox(a: FreeTextAnnotation, to: Rect): Partial<FreeTextAnnotation> {\n if (!hasCallout(a)) return withBox(a, to)\n const from = freeTextBox(a)\n const last = a.callout.length - 1\n return withBox(\n a,\n to,\n a.callout.map((p, i) => (i === last ? onMovedEdge(p, from, to) : p))\n )\n}\n\n/**\n * The patch that moves a callout's tip to `to`, leaving its text box where it is. A callout\n * without a bend (every bubble) moves its edge point to the side the tip now lies furthest\n * beyond, at its own position along that side and clear of the corners, so the line or wedge\n * never crosses the box; on the same side it stays put. A bend and its edge point stay.\n */\nexport function movedTip(\n a: FreeTextAnnotation & { callout: readonly Point[] },\n to: Point\n): Partial<FreeTextAnnotation> {\n const box = freeTextBox(a)\n if (a.callout.length !== 2) return withBox(a, box, [to, ...a.callout.slice(1)])\n const edge = a.callout[1]!\n const side = edgeBeyond(to, box)\n const margin = (a.cornerRadius ?? 0) + WEDGE_HALF\n return withBox(a, box, [\n to,\n nearestEdge(edge, box) === side ? edge : ontoEdge(edge, box, side, margin),\n ])\n}\n","// Maps the style controls' names (`border`, `fill`, `width`…) to each annotation type's\n// fields and back. Pure: no store, no DOM. A prop maps only where the type has the field, so a\n// patch for a mixed selection lands on each annotation as far as it can.\nimport type { StyleGroup, StyleProps } from './tool-style'\nimport type { Annotation, AnnotationPatch, AnnotationType } from './types'\n\ntype StyleKey = keyof StyleProps\n\n/** For each type, the control-level props it supports and the field each writes. */\nconst FIELDS: Readonly<\n Record<AnnotationType, Readonly<Partial<Record<StyleKey, string>>>>\n> = {\n square: {\n border: 'color',\n fill: 'interiorColor',\n opacity: 'opacity',\n width: 'width',\n dashes: 'dashes',\n },\n circle: {\n border: 'color',\n fill: 'interiorColor',\n opacity: 'opacity',\n width: 'width',\n dashes: 'dashes',\n },\n polygon: {\n border: 'color',\n fill: 'interiorColor',\n opacity: 'opacity',\n width: 'width',\n dashes: 'dashes',\n },\n polyline: {\n border: 'color',\n opacity: 'opacity',\n width: 'width',\n dashes: 'dashes',\n head: 'head',\n tail: 'tail',\n },\n line: {\n border: 'color',\n opacity: 'opacity',\n width: 'width',\n dashes: 'dashes',\n head: 'head',\n tail: 'tail',\n },\n // Ink is drawn solid, so it has no dashes.\n ink: { border: 'color', opacity: 'opacity', width: 'width' },\n highlight: { border: 'color', opacity: 'opacity' },\n underline: { border: 'color', opacity: 'opacity' },\n strikeout: { border: 'color', opacity: 'opacity' },\n squiggly: { border: 'color', opacity: 'opacity' },\n redact: { border: 'color', opacity: 'opacity' },\n // XFDF: a box's `color` is its fill; the text style lives in `defaultStyle`.\n freetext: {\n border: 'borderColor',\n fill: 'color',\n textColor: 'defaultStyle.color',\n opacity: 'opacity',\n width: 'width',\n dashes: 'dashes',\n fontFamily: 'defaultStyle.fontFamily',\n fontSize: 'defaultStyle.fontSize',\n fontWeight: 'defaultStyle.fontWeight',\n fontStyle: 'defaultStyle.fontStyle',\n textDecoration: 'defaultStyle.textDecoration',\n textAlign: 'defaultStyle.textAlign',\n },\n // The rim is the outline; the inside is the magnified page, so there is no fill, and the\n // rim is drawn solid.\n loupe: { border: 'color', opacity: 'opacity', width: 'width' },\n // A mask dims the page outside a shape: nothing for the style controls to change.\n mask: {},\n text: {},\n // An image, signatures among them: the style controls have nothing to change on it.\n stamp: {},\n}\n\nconst GROUPS: Readonly<Record<AnnotationType, StyleGroup | undefined>> = {\n square: 'shape',\n circle: 'shape',\n line: 'shape',\n polyline: 'shape',\n polygon: 'shape',\n loupe: 'shape',\n ink: 'ink',\n freetext: 'text',\n highlight: 'markup',\n underline: 'markup',\n strikeout: 'markup',\n squiggly: 'markup',\n redact: 'redact',\n text: undefined,\n stamp: undefined,\n mask: undefined,\n}\n\nconst SUPPORTED = new Map<AnnotationType, ReadonlySet<StyleKey>>(\n (Object.keys(FIELDS) as AnnotationType[]).map((type) => [\n type,\n new Set(Object.keys(FIELDS[type]) as StyleKey[]),\n ])\n)\n\n/**\n * The props a speech bubble (`intent: 'FreeTextCallout'`) takes from the `shape` group: its\n * outline, fill and opacity, as the shape tool creates it. Its text props stay in `text`.\n */\nconst BUBBLE_SHAPE_PROPS: ReadonlySet<StyleKey> = new Set([\n 'border',\n 'fill',\n 'opacity',\n 'width',\n 'dashes',\n])\n\n/**\n * The style group an annotation's type belongs to; notes belong to none. With `key`, the group\n * that owns that prop on `a`: a speech bubble's outline and fill are `shape`'s, its text `text`'s.\n */\nexport function styleGroupOf(\n a: Pick<Annotation, 'type'> & { intent?: string | undefined },\n key?: StyleKey\n): StyleGroup | undefined {\n if (\n key !== undefined &&\n a.type === 'freetext' &&\n a.intent === 'FreeTextCallout' &&\n BUBBLE_SHAPE_PROPS.has(key)\n )\n return 'shape'\n return GROUPS[a.type]\n}\n\n/** Every group that owns some prop on `a`: two for a speech bubble, else at most one. */\nexport function styleGroupsOf(\n a: Pick<Annotation, 'type'> & { intent?: string | undefined }\n): StyleGroup[] {\n const out = new Set<StyleGroup>()\n const own = GROUPS[a.type]\n if (own) out.add(own)\n for (const key of supportedProps(a.type)) {\n const g = styleGroupOf(a, key)\n if (g) out.add(g)\n }\n return [...out]\n}\n\n/** The types in `group`, from the same table `styleGroupOf` reads. */\nexport function typesInGroup(group: StyleGroup): AnnotationType[] {\n return (Object.keys(GROUPS) as AnnotationType[]).filter((t) => GROUPS[t] === group)\n}\n\n/** The style group a type belongs to. */\nexport function styleGroupOfType(type: AnnotationType): StyleGroup | undefined {\n return GROUPS[type]\n}\n\n/** The control-level props `type` supports. */\nexport function supportedProps(type: AnnotationType): ReadonlySet<StyleKey> {\n return SUPPORTED.get(type) ?? new Set()\n}\n\n/**\n * The control values a field leaves out: `normal` weight and style, no decoration. The field\n * is absent rather than holding them, as XFDF writes only what differs.\n */\nconst UNSET: Readonly<Partial<Record<StyleKey, unknown>>> = {\n fontWeight: 'normal',\n fontStyle: 'normal',\n textDecoration: 'none',\n}\n\n/** The prefix of a field nested in `defaultStyle` (free text). */\nconst STYLE = 'defaultStyle.'\n\n/**\n * The field patch `patch` means on `type`. Props the type lacks are dropped. A `null` fill\n * becomes `interiorColor: undefined` (`color` on free text), which removes the fill when the\n * store applies it; so does `normal` weight or style and no decoration. Free-text text props go\n * into a partial `defaultStyle`, which the store merges into the current one.\n */\nexport function toFields(type: AnnotationType, patch: StyleProps): AnnotationPatch {\n const fields = FIELDS[type]\n const out: Record<string, unknown> = {}\n for (const key of Object.keys(patch) as StyleKey[]) {\n const field = fields[key]\n if (field === undefined) continue\n const raw = patch[key]\n const value = raw === null || raw === UNSET[key] ? undefined : raw\n if (field.startsWith(STYLE)) {\n const style = (out.defaultStyle ??= {}) as Record<string, unknown>\n style[field.slice(STYLE.length)] = value\n } else {\n out[field] = value\n }\n }\n return out\n}\n\n/** The control-level props an annotation shows, for the props its type supports. */\nexport function fromAnnotation(a: Annotation): StyleProps {\n const fields = FIELDS[a.type]\n const record = a as unknown as Record<string, unknown>\n const style = (record.defaultStyle ?? {}) as Record<string, unknown>\n const out: Record<string, unknown> = {}\n for (const key of Object.keys(fields) as StyleKey[]) {\n const field = fields[key] as string\n const value = field.startsWith(STYLE)\n ? style[field.slice(STYLE.length)]\n : record[field]\n if (value !== undefined) out[key] = value\n else if (key === 'fill' || key === 'dashes') out[key] = null\n else if (key === 'head' || key === 'tail') out[key] = 'None'\n else if (UNSET[key] !== undefined) out[key] = UNSET[key]\n }\n return out\n}\n","// The current style per style group, shared by the tools that create into a group and the\n// style controls. Within a group the style is shared: recolouring a line also colours the next\n// rectangle. Groups start empty, so until a control sets a prop each type keeps its theme\n// default (the store's `completeInput` fills it).\n//\n// `set` writes through the store, so in controlled mode every change is proposed to the host's\n// `onChange` and nothing is applied before the host applies it.\nimport { writable, type Readable, type Writable } from '../readable'\n\nimport { freeTextBox } from './callout'\nimport { hasCallout, withBox } from './edit'\nimport {\n fromAnnotation,\n styleGroupOf,\n styleGroupsOf,\n supportedProps,\n toFields,\n typesInGroup,\n} from './style-map'\n\nimport type { AnnotationStore } from './store'\nimport type {\n Annotation,\n AnnotationInput,\n AnnotationPatch,\n FreeTextAnnotation,\n LineEnding,\n} from './types'\n\nexport type StyleGroup = 'shape' | 'ink' | 'text' | 'markup' | 'redact'\n\nexport const STYLE_GROUPS: readonly StyleGroup[] = [\n 'shape',\n 'ink',\n 'text',\n 'markup',\n 'redact',\n]\n\n/** Style as the controls name it; `style-map` turns it into each type's fields. */\nexport interface StyleProps {\n /** #RRGGBB */\n border?: string\n /** `null` means no fill. */\n fill?: string | null\n textColor?: string\n opacity?: number\n width?: number\n /** `null` means solid. */\n dashes?: number[] | null\n head?: LineEnding\n tail?: LineEnding\n fontFamily?: string\n fontSize?: number\n fontWeight?: 'normal' | 'bold'\n fontStyle?: 'normal' | 'italic'\n textDecoration?: 'none' | 'underline'\n textAlign?: 'left' | 'center' | 'right' | 'justify'\n}\n\nexport type StyleKey = keyof StyleProps\n\n/** What the controls show: one value per prop, or `'mixed'` when a selection disagrees. */\nexport type CurrentStyle = { [K in StyleKey]?: StyleProps[K] | 'mixed' }\n\nexport interface ToolStyle {\n get(group: StyleGroup): Readonly<StyleProps>\n readable(group: StyleGroup): Readable<Readonly<StyleProps>>\n /**\n * Values the controls show. Under a select tool, the selection's. Under a creation tool, the\n * selection's when it is non-empty and wholly in the tool's group, else the group's own: a\n * leftover selection from another tool does not take over the controls. `'mixed'` per prop\n * when selected values differ.\n */\n readonly current: Readable<CurrentStyle>\n /**\n * Which props the active tool or the selection supports; controls disable the rest. Under a\n * creation tool, the group's props, plus the selection's when it is wholly in the group.\n */\n readonly supported: Readable<ReadonlySet<StyleKey>>\n /**\n * Updates the active tool's group, or under a select tool (no active group) the group that\n * owns each prop on each selected annotation (a speech bubble's outline is `shape`'s, its\n * text `text`'s). With `apply` it also updates every selected, unlocked annotation that has\n * the props, in one history step; a pinned one keeps its style. `apply` defaults to true under a select tool, and to\n * whether the selection is wholly in the group otherwise. `group` names the group explicitly.\n */\n set(patch: StyleProps, opts?: { group?: StyleGroup; apply?: boolean }): void\n /** Fills an AnnotationInput's unset style fields from the group (input wins). */\n resolve<T extends AnnotationInput>(group: StyleGroup, input: T): T\n /**\n * The style as a control for one group sees it, whatever the active tool: the selection's\n * when every selected annotation is in `group`, else the group's own. Same identity per group.\n */\n scoped(group: StyleGroup): ScopedToolStyle\n}\n\n/** A view of the tool style for one group, as `ToolStyle.scoped` gives it. */\nexport interface ScopedToolStyle {\n readonly group: StyleGroup\n readonly current: Readable<CurrentStyle>\n readonly supported: Readable<ReadonlySet<StyleKey>>\n /** Updates the group, and the selection too when every selected annotation is in it. */\n set(patch: StyleProps): void\n}\n\nexport interface ToolStyleDeps {\n store: AnnotationStore\n history: { batch(fn: () => void): void }\n /** The active tool's style group; `undefined` for select tools. */\n activeGroup: () => StyleGroup | undefined\n /** Fires when the active tool changes, so `current` and `supported` follow it. */\n active?: Readable<unknown>\n}\n\n/** Every prop some type in `group` supports. */\nfunction groupProps(group: StyleGroup): ReadonlySet<StyleKey> {\n const out = new Set<StyleKey>()\n for (const type of typesInGroup(group))\n for (const key of supportedProps(type)) out.add(key)\n return out\n}\n\nfunction sameValue(a: unknown, b: unknown): boolean {\n if (Object.is(a, b)) return true\n if (Array.isArray(a) && Array.isArray(b))\n return a.length === b.length && a.every((v, i) => Object.is(v, b[i]))\n return false\n}\n\nfunction sameRecord(a: Record<string, unknown>, b: Record<string, unknown>): boolean {\n const ka = Object.keys(a)\n if (ka.length !== Object.keys(b).length) return false\n return ka.every((k) => k in b && sameValue(a[k], b[k]))\n}\n\nfunction sameSet<T>(a: ReadonlySet<T>, b: ReadonlySet<T>): boolean {\n return a.size === b.size && [...a].every((v) => b.has(v))\n}\n\n/**\n * A readable recomputed from `fn` whenever any source fires, subscribed to its sources only\n * while it has subscribers. Equal results (by `eq`) are not re-emitted and keep their identity.\n */\nfunction computed<T>(\n sources: readonly Readable<unknown>[],\n fn: () => T,\n eq: (a: T, b: T) => boolean\n): Readable<T> {\n const subs = new Set<(v: T) => void>()\n let cached: { value: T } | undefined\n let stops: (() => void)[] | undefined\n /** Recomputes, keeping the previous value's identity when equal. True when it changed. */\n const recompute = (): boolean => {\n const next = fn()\n if (cached && eq(next, cached.value)) return false\n cached = { value: next }\n return true\n }\n const refresh = (): void => {\n if (!recompute() || !cached) return\n const value = cached.value\n for (const sub of [...subs]) sub(value)\n }\n return {\n // Stable identity for equal values even unobserved: React's useSyncExternalStore reads\n // the snapshot before it subscribes and loops on a fresh object.\n get: () => {\n if (!stops) recompute()\n return (cached as { value: T }).value\n },\n subscribe(sub) {\n if (!stops) {\n recompute()\n stops = sources.map((s) => s.subscribe(refresh))\n }\n subs.add(sub)\n return () => {\n if (!subs.delete(sub) || subs.size > 0) return\n for (const stop of stops ?? []) stop()\n stops = undefined\n }\n },\n }\n}\n\nexport function createToolStyle(deps: ToolStyleDeps): ToolStyle {\n const { store, history, activeGroup } = deps\n const groups = new Map<StyleGroup, Writable<Readonly<StyleProps>>>(\n STYLE_GROUPS.map((g) => [g, writable<Readonly<StyleProps>>({})])\n )\n const groupStore = (g: StyleGroup): Writable<Readonly<StyleProps>> => {\n const w = groups.get(g)\n if (!w) throw new RangeError(`Unknown style group ${String(g)}`)\n return w\n }\n\n /** The selected annotations, including changes proposed to a controlled host. */\n const selected = (): Annotation[] =>\n store.selection\n .get()\n .map((id) => store._getProposed(id) ?? store.get(id))\n .filter((a): a is Annotation => a !== undefined)\n\n const sources: Readable<unknown>[] = [\n store.list,\n store.selection,\n store._pinned,\n ...groups.values(),\n ...(deps.active ? [deps.active] : []),\n ]\n\n /** One value per prop over `items`, `'mixed'` where they differ. */\n const styleOf = (items: readonly Annotation[]): CurrentStyle => {\n const out: Record<string, unknown> = {}\n for (const a of items) {\n const props = fromAnnotation(a) as Record<string, unknown>\n for (const [key, value] of Object.entries(props)) {\n if (!(key in out)) out[key] = value\n else if (out[key] !== 'mixed' && !sameValue(out[key], value)) out[key] = 'mixed'\n }\n }\n return out\n }\n\n /** A pinned annotation (a signature filling its field) keeps its style: it offers none. */\n const propsOf = (items: readonly Annotation[]): ReadonlySet<StyleKey> => {\n const out = new Set<StyleKey>()\n for (const a of items) {\n if (store._isPinned(a.id)) continue\n for (const key of supportedProps(a.type)) out.add(key)\n }\n return out\n }\n\n /** The selection, when it is non-empty and wholly in `group`. */\n const selectedIn = (group: StyleGroup): Annotation[] | null => {\n const items = selected()\n return items.length > 0 && items.every((a) => styleGroupsOf(a).includes(group))\n ? items\n : null\n }\n\n const current = computed<CurrentStyle>(\n sources,\n () => {\n const g = activeGroup()\n if (!g) return styleOf(selected())\n const items = selectedIn(g)\n return items ? styleOf(items) : { ...groupStore(g).get() }\n },\n (a, b) => sameRecord(a, b)\n )\n\n const supported = computed<ReadonlySet<StyleKey>>(\n sources,\n () => {\n const g = activeGroup()\n if (!g) return propsOf(selected())\n const items = selectedIn(g)\n return items ? new Set([...groupProps(g), ...propsOf(items)]) : groupProps(g)\n },\n sameSet\n )\n\n const scopes = new Map<StyleGroup, ScopedToolStyle>()\n function scoped(group: StyleGroup): ScopedToolStyle {\n const known = scopes.get(group)\n if (known) return known\n groupStore(group)\n const scope: ScopedToolStyle = {\n group,\n current: computed<CurrentStyle>(\n sources,\n () => {\n const items = selectedIn(group)\n return items ? styleOf(items) : { ...groupStore(group).get() }\n },\n (a, b) => sameRecord(a, b)\n ),\n supported: computed<ReadonlySet<StyleKey>>(\n sources,\n () => {\n const items = selectedIn(group)\n return items ? propsOf(items) : groupProps(group)\n },\n sameSet\n ),\n set: (patch) => set(patch, { group, apply: selectedIn(group) !== null }),\n }\n scopes.set(group, scope)\n return scope\n }\n\n function set(\n patch: StyleProps,\n opts: { group?: StyleGroup; apply?: boolean } = {}\n ): void {\n const items = selected()\n const active = opts.group ?? activeGroup()\n const keys = (Object.keys(patch) as StyleKey[]).filter((k) => patch[k] !== undefined)\n // The keys each group takes: all of them for the active group, else each prop goes to the\n // group that owns it on each selected annotation.\n const targets = new Map<StyleGroup, Set<StyleKey>>()\n if (active) targets.set(active, new Set(keys))\n else\n for (const a of items)\n for (const key of keys) {\n if (!supportedProps(a.type).has(key)) continue\n const g = styleGroupOf(a, key)\n if (!g) continue\n const own = targets.get(g) ?? new Set<StyleKey>()\n own.add(key)\n targets.set(g, own)\n }\n for (const [g, own] of targets) {\n const allowed = groupProps(g)\n const next: Record<string, unknown> = { ...groupStore(g).get() }\n let changed = false\n for (const key of own) {\n if (!allowed.has(key)) continue\n next[key] = patch[key]\n changed = true\n }\n if (changed) groupStore(g).set(next)\n }\n if (!(opts.apply ?? (active === undefined || selectedIn(active) !== null))) return\n const edits = items\n .filter((a) => !a.locked && !store._isPinned(a.id))\n .map((a) => ({ id: a.id, fields: refit(a, toFields(a.type, patch)) }))\n .filter((e) => Object.keys(e.fields).length > 0)\n if (edits.length === 0) return\n history.batch(() => {\n for (const e of edits) store.update(e.id, e.fields)\n })\n }\n\n /**\n * `fields` with a callout's `rect` and `fringe` refit when they change its border width, so\n * the bounds keep covering the leader, its ending and the outline.\n */\n function refit(a: Annotation, fields: AnnotationPatch): AnnotationPatch {\n if (!('width' in fields) || !hasCallout(a)) return fields\n const next = { ...a, ...fields } as FreeTextAnnotation\n return { ...fields, ...withBox(next, freeTextBox(a)) } as AnnotationPatch\n }\n\n /** `value`'s keys that hold something. */\n const defined = (value: unknown): Record<string, unknown> =>\n Object.fromEntries(\n Object.entries((value ?? {}) as Record<string, unknown>).filter(\n ([, v]) => v !== undefined\n )\n )\n\n function resolve<T extends AnnotationInput>(group: StyleGroup, input: T): T {\n const fields = toFields(input.type, groupStore(group).get()) as Record<\n string,\n unknown\n >\n const out: Record<string, unknown> = { ...input }\n for (const [key, value] of Object.entries(fields)) {\n if (key === 'defaultStyle') {\n // Nested text style: the group's keys fill those the input leaves unset (or undefined).\n out[key] = { ...defined(value), ...defined(out[key]) }\n } else if (value !== undefined && out[key] === undefined) out[key] = value\n }\n return out as T\n }\n\n return {\n get: (g) => groupStore(g).get(),\n readable: (g) => {\n const w = groupStore(g)\n return { get: () => w.get(), subscribe: (fn) => w.subscribe(fn) }\n },\n current,\n supported,\n set,\n resolve,\n scoped,\n }\n}\n","import { isTextMarkup } from './edit'\n\nimport type { Annotation, NoteAnnotation, TextMarkupAnnotation } from './types'\n\n/** What a thread can hang from: a note, or text markup whose `contents` is its comment. */\nexport type ThreadRoot = NoteAnnotation | TextMarkupAnnotation\n\nexport function isThreadRoot(a: Annotation): a is ThreadRoot {\n return a.type === 'text' || isTextMarkup(a)\n}\n\n/**\n * True for a reply: an annotation whose `inReplyTo` names a thread root (a note or text markup)\n * in `list`. Replies show in the thread popover only, never on the page.\n */\nexport function isReply(a: Annotation, list: readonly Annotation[]): boolean {\n if (a.inReplyTo === undefined) return false\n const parent = list.find((x) => x.id === a.inReplyTo)\n return parent !== undefined && isThreadRoot(parent)\n}\n\n/** `list` less its replies (see `isReply`), in the same order. */\nexport function withoutReplies(list: readonly Annotation[]): Annotation[] {\n const roots = new Set(list.filter(isThreadRoot).map((a) => a.id))\n return list.filter((a) => a.inReplyTo === undefined || !roots.has(a.inReplyTo))\n}\n\n/** Direct replies to `id`, in creation order. */\nexport function repliesTo(list: readonly Annotation[], id: string): Annotation[] {\n return list\n .filter((a) => a.inReplyTo === id)\n .sort((a, b) => a.createdAt.localeCompare(b.createdAt))\n}\n\n/**\n * The top of a thread: follows `inReplyTo` up through notes, stopping at text markup (which\n * roots a thread of its own), a missing parent, a parent that cannot root a thread, or a\n * cycle. Null when `start` is neither a note nor text markup.\n */\nexport function threadRoot(\n list: readonly Annotation[],\n start: Annotation\n): ThreadRoot | null {\n if (!isThreadRoot(start)) return null\n const seen = new Set([start.id])\n let current: ThreadRoot = start\n while (current.type === 'text' && current.inReplyTo) {\n const id: string = current.inReplyTo\n const parent = list.find((a) => a.id === id)\n if (!parent || !isThreadRoot(parent) || seen.has(parent.id)) break\n seen.add(parent.id)\n current = parent\n }\n return current\n}\n\n/** The root, then every reply below it, depth first, each level in creation order. */\nexport function threadOf(list: readonly Annotation[], root: ThreadRoot): Annotation[] {\n const out: Annotation[] = [root]\n const seen = new Set([root.id])\n const visit = (id: string): void => {\n for (const r of repliesTo(list, id)) {\n if (seen.has(r.id)) continue\n seen.add(r.id)\n out.push(r)\n visit(r.id)\n }\n }\n visit(root.id)\n return out\n}\n\n/**\n * An unlocked root note with no text and no replies: nothing a reader would miss. Always\n * false for text markup, which is worth keeping without a comment.\n */\nexport function isAbandonedNote(a: Annotation, list: readonly Annotation[]): boolean {\n if (a.type !== 'text' || a.locked || a.inReplyTo || a.contents?.trim()) return false\n return repliesTo(list, a.id).length === 0\n}\n","// Pure geometry for the shape tool: vertices for stars and polygons, Shift constraints and the\n// annotation each kind creates. Everything is PDF user space, points, origin bottom-left.\nimport { withCalloutBounds } from './callout'\n\nimport type { Point, Rect } from '../geometry'\nimport type { PageRotation } from '../pages'\nimport type { AnnotationInput } from './types'\n\n/** Every kind the shape menu can offer. Kinds without a creator yet are not in `SHAPE_KINDS`. */\nexport type ShapeKind =\n | 'line'\n | 'arrow'\n | 'rectangle'\n | 'roundedRectangle'\n | 'ellipse'\n | 'bubble'\n | 'star'\n | 'polygon'\n | 'loupe'\n | 'mask'\n | 'ovalMask'\n\nexport interface ShapeOptions {\n kind: ShapeKind\n /** Points of a star. */\n points: number\n /** Sides of a polygon. */\n sides: number\n}\n\n/** The kinds the shape menu offers today, in menu order. Later kinds extend this. */\nexport const SHAPE_KINDS: readonly ShapeKind[] = [\n 'line',\n 'arrow',\n 'rectangle',\n 'roundedRectangle',\n 'ellipse',\n 'bubble',\n 'star',\n 'polygon',\n 'loupe',\n 'mask',\n 'ovalMask',\n]\n\nexport const DEFAULT_SHAPE_OPTIONS: Readonly<ShapeOptions> = {\n kind: 'rectangle',\n points: 5,\n sides: 6,\n}\n\nconst POINTER_ONLY: ReadonlySet<ShapeKind> = new Set(['loupe', 'mask', 'ovalMask'])\n\n/**\n * True for kinds only a pointer creates: the loupe and the mask. `Enter` with the shape tool\n * does not place them.\n */\nexport function isPointerOnlyKind(kind: ShapeKind): boolean {\n return POINTER_ONLY.has(kind)\n}\n\n/** Magnification of a new loupe. */\nexport const DEFAULT_LOUPE_MAGNIFICATION = 2\n\n/** How strongly a new mask dims the page. */\nexport const DEFAULT_MASK_DIM = 0.5\n\n/** Side of the shape a click or Enter places, in points. */\nexport const DEFAULT_SHAPE_SIZE = 72\n/** Corner radius of a new rounded rectangle, in points. */\nexport const DEFAULT_CORNER_RADIUS = 8\n\n/** How far below and left of its anchor a new speech bubble's tail tip sits, in points. */\nconst BUBBLE_TAIL = 24\n/** A new speech bubble's outline width, in points, before the style group's applies. */\nconst BUBBLE_WIDTH = 1\n\nconst clean = (n: number): number => n + 0\n\n/** The box between two corners. */\nfunction rectOf(a: Point, b: Point): Rect {\n return {\n x: Math.min(a.x, b.x),\n y: Math.min(a.y, b.y),\n width: Math.abs(b.x - a.x),\n height: Math.abs(b.y - a.y),\n }\n}\n\n/**\n * Vertices round a circle, the first at the top centre, clockwise on the page, stretched so their\n * bounds fill `rect`.\n */\nfunction ring(rect: Rect, count: number, radius: (index: number) => number): Point[] {\n const unit = Array.from({ length: count }, (_, i) => {\n const angle = (i * 2 * Math.PI) / count\n const r = radius(i)\n return { x: r * Math.sin(angle), y: r * Math.cos(angle) }\n })\n const xs = unit.map((p) => p.x)\n const ys = unit.map((p) => p.y)\n const fit = (v: number, min: number, max: number, start: number, size: number) =>\n clean(max > min ? start + ((v - min) / (max - min)) * size : start + size / 2)\n const [minX, maxX, minY, maxY] = [\n Math.min(...xs),\n Math.max(...xs),\n Math.min(...ys),\n Math.max(...ys),\n ]\n return unit.map((p) => ({\n x: fit(p.x, minX, maxX, rect.x, rect.width),\n y: fit(p.y, minY, maxY, rect.y, rect.height),\n }))\n}\n\n/**\n * A star's `2 * points` vertices, outer and inner alternating, stretched to fill `rect`, the first\n * at the top centre.\n */\nexport function starVertices(rect: Rect, points: number, innerRatio = 0.5): Point[] {\n const n = Math.max(2, Math.round(points))\n return ring(rect, n * 2, (i) => (i % 2 === 0 ? 1 : innerRatio))\n}\n\n/** A regular polygon's vertices, stretched to fill `rect`, the first at the top centre. */\nexport function polygonVertices(rect: Rect, sides: number): Point[] {\n return ring(rect, Math.max(3, Math.round(sides)), () => 1)\n}\n\nconst LINE_KINDS: ReadonlySet<ShapeKind> = new Set(['line', 'arrow'])\n\n/** True for kinds drawn between two endpoints rather than inside a box. */\nexport function isLineKind(kind: ShapeKind): boolean {\n return LINE_KINDS.has(kind)\n}\n\nconst H = Math.SQRT1_2\n/** Unit steps every 45 degrees, counter-clockwise from +x (y up). */\nconst EIGHT_WAYS: readonly Point[] = [\n { x: 1, y: 0 },\n { x: H, y: H },\n { x: 0, y: 1 },\n { x: -H, y: H },\n { x: -1, y: 0 },\n { x: -H, y: -H },\n { x: 0, y: -1 },\n { x: H, y: -H },\n]\n\n/**\n * Where the drag ends with Shift held: a square or circle for box kinds, the nearest 45 degree\n * angle for lines.\n */\nexport function constrain(kind: ShapeKind, start: Point, end: Point): Point {\n const dx = end.x - start.x\n const dy = end.y - start.y\n if (isLineKind(kind)) {\n const step = Math.round(Math.atan2(dy, dx) / (Math.PI / 4))\n const u = EIGHT_WAYS[((step % 8) + 8) % 8]!\n const length = dx * u.x + dy * u.y\n return { x: clean(start.x + length * u.x), y: clean(start.y + length * u.y) }\n }\n const size = Math.max(Math.abs(dx), Math.abs(dy))\n return {\n x: clean(start.x + (dx < 0 ? -size : size)),\n y: clean(start.y + (dy < 0 ? -size : size)),\n }\n}\n\n/**\n * The two drag corners of the default-size shape centred on `at`. A line or arrow runs left to\n * right on the page as the file displays it: along user space turned anticlockwise by the\n * page's /Rotate `rotation`, which undoes the page's clockwise turn, as a signature is placed.\n */\nexport function defaultEnds(\n kind: ShapeKind,\n at: Point,\n rotation: PageRotation = 0\n): [Point, Point] {\n const half = DEFAULT_SHAPE_SIZE / 2\n if (!isLineKind(kind))\n return [\n { x: at.x - half, y: at.y - half },\n { x: at.x + half, y: at.y + half },\n ]\n const rad = (rotation * Math.PI) / 180\n const dx = Math.round(Math.cos(rad)) * half\n const dy = Math.round(Math.sin(rad)) * half\n return [\n { x: clean(at.x - dx), y: clean(at.y - dy) },\n { x: clean(at.x + dx), y: clean(at.y + dy) },\n ]\n}\n\n/** The annotation a shape kind creates between two points, or `undefined` for a kind without a creator yet. */\nexport function shapeInput(\n kind: ShapeKind,\n page: number,\n start: Point,\n end: Point,\n opts: ShapeOptions\n): AnnotationInput | undefined {\n const rect = rectOf(start, end)\n switch (kind) {\n case 'line':\n return { type: 'line', page, start, end }\n case 'arrow':\n return { type: 'line', page, start, end, intent: 'LineArrow' }\n case 'rectangle':\n return { type: 'square', page, rect }\n case 'roundedRectangle':\n return { type: 'square', page, rect, cornerRadius: DEFAULT_CORNER_RADIUS }\n case 'ellipse':\n return { type: 'circle', page, rect }\n case 'bubble': {\n // A standard callout around the dragged box: the edge point is the box's bottom-left\n // quarter point, and the tail runs from it to the tip below and left.\n const edge = { x: clean(rect.x + rect.width / 4), y: clean(rect.y) }\n const tip = { x: clean(edge.x - BUBBLE_TAIL), y: clean(edge.y - BUBBLE_TAIL) }\n const callout = [tip, edge]\n return {\n type: 'freetext',\n page,\n contents: '',\n intent: 'FreeTextCallout',\n cornerRadius: DEFAULT_CORNER_RADIUS,\n width: BUBBLE_WIDTH,\n ...withCalloutBounds(rect, callout, BUBBLE_WIDTH, undefined),\n callout,\n }\n }\n case 'star':\n return { type: 'polygon', page, vertices: starVertices(rect, opts.points) }\n case 'polygon':\n return { type: 'polygon', page, vertices: polygonVertices(rect, opts.sides) }\n case 'loupe':\n // Always a circle: the square on the drag's longer side, as Shift would make it.\n return {\n type: 'loupe',\n page,\n rect: rectOf(start, constrain(kind, start, end)),\n magnification: DEFAULT_LOUPE_MAGNIFICATION,\n }\n case 'mask':\n case 'ovalMask':\n return {\n type: 'mask',\n page,\n rect,\n shape: kind === 'mask' ? 'rect' : 'ellipse',\n dim: DEFAULT_MASK_DIM,\n }\n default:\n return undefined\n }\n}\n","// Recognises a single freehand stroke as a standard shape, by geometric fitting. Pure: no DOM.\n//\n// The stroke is resampled to evenly spaced points (a fiftieth of its box's diagonal apart, so\n// every test is scale-free). Corners of a closed stroke are where the path turns sharply over a\n// few samples, and corners whose neighbours run straight through them are dropped. Then each\n// kind is fitted and scored from 0 to 1, and the best fit wins:\n//\n// - line: how far the path strays from the chord between its ends;\n// - arrow: a straight shaft, then a short head at one end that folds back towards it;\n// - closed strokes (the ends meet, an overshoot trimmed) that wind once round their centre:\n// - ellipse: how far points stray from the ellipse inscribed in the stroke's box;\n// - rectangle: four corners, sides alternating horizontal and vertical;\n// - polygon: three to eight corners joined by straight sides that do not cross;\n// - star: an outline whose corners alternate far from and near the centre, or a pentagram\n// (five straight strokes that wind twice).\n//\n// A stroke that fails every gate (open and bent, winding more or less than once, sides that\n// cross, a corner count no kind has) gets no candidate, so a scrawl or a scribble comes back\n// undefined or scored low.\nimport { starVertices } from './annotations/shape-geometry'\n\nimport type { Point, Rect } from './geometry'\n\nexport type Recognised =\n | { kind: 'line'; start: Point; end: Point }\n | { kind: 'arrow'; start: Point; end: Point }\n | { kind: 'rectangle'; rect: Rect }\n | { kind: 'ellipse'; rect: Rect }\n /** A triangle or other closed polygon, its vertices where the stroke's corners are. */\n | { kind: 'polygon'; vertices: Point[] }\n /** A regular star, outer and inner vertices alternating, the first tip at the top. */\n | { kind: 'star'; vertices: Point[] }\n\n/** The score a fit needs before a stroke is tidied into its shape. */\nexport const RECOGNISE_THRESHOLD = 0.8\n\n/** Samples either side of a point that its turn is measured over. */\nconst W = 3\n/** Turns, over `2 * W` samples, that make a corner: outward, and back against the loop. */\nconst CONVEX_TURN = (40 * Math.PI) / 180\nconst CONCAVE_TURN = (15 * Math.PI) / 180\n/** Resampled points along the box diagonal. */\nconst DENSITY = 50\n/** A run of path is straight when its chord is at least this share of its length. */\nconst STRAIGHT = 0.95\n/** Corners whose neighbours this straight run through them (a turn under about 23 degrees) go. */\nconst MERGE_STRAIGHT = 0.98\n/** The ends of a closed stroke are within this share of the box diagonal. */\nconst CLOSE_GAP = 0.25\n/** Weights of a line's largest and mean straying from its chord, over its length. */\nconst LINE_MAX = 2\nconst LINE_MEAN = 2\n/** Weight of a polygon side's mean straying from its chord, over its length. */\nconst SIDE_MEAN = 3\n\ninterface Fit {\n shape: Recognised\n score: number\n}\n\nconst dist = (a: Point, b: Point): number => Math.hypot(a.x - b.x, a.y - b.y)\nconst clamp01 = (n: number): number => Math.min(Math.max(n, 0), 1)\nconst round = (n: number): number => Math.round(n * 100) / 100 + 0\nconst pt = (p: Point): Point => ({ x: round(p.x), y: round(p.y) })\n\nfunction boxOf(points: readonly Point[]): Rect {\n let minX = Infinity\n let minY = Infinity\n let maxX = -Infinity\n let maxY = -Infinity\n for (const p of points) {\n minX = Math.min(minX, p.x)\n minY = Math.min(minY, p.y)\n maxX = Math.max(maxX, p.x)\n maxY = Math.max(maxY, p.y)\n }\n return { x: minX, y: minY, width: maxX - minX, height: maxY - minY }\n}\n\nconst diagonal = (r: Rect): number => Math.hypot(r.width, r.height)\n\nfunction lengthOf(points: readonly Point[]): number {\n let total = 0\n for (let i = 1; i < points.length; i++) total += dist(points[i - 1]!, points[i]!)\n return total\n}\n\n/** Points every `spacing` along the path, the first and last included. */\nfunction resample(points: readonly Point[], spacing: number): Point[] {\n const out: Point[] = [points[0]!]\n let carried = 0\n let prev = points[0]!\n for (let i = 1; i < points.length; i++) {\n const next = points[i]!\n let d = dist(prev, next)\n while (carried + d >= spacing) {\n const t = (spacing - carried) / d\n const q = { x: prev.x + t * (next.x - prev.x), y: prev.y + t * (next.y - prev.y) }\n out.push(q)\n prev = q\n d = dist(prev, next)\n carried = 0\n }\n carried += d\n prev = next\n }\n const last = points[points.length - 1]!\n if (dist(out[out.length - 1]!, last) > spacing / 2) out.push(last)\n else out[out.length - 1] = last\n return out\n}\n\n/** Distance from `p` to the segment `a`–`b`. */\nfunction toSegment(p: Point, a: Point, b: Point): number {\n const dx = b.x - a.x\n const dy = b.y - a.y\n const len2 = dx * dx + dy * dy\n const t = len2 === 0 ? 0 : clamp01(((p.x - a.x) * dx + (p.y - a.y) * dy) / len2)\n return Math.hypot(p.x - (a.x + t * dx), p.y - (a.y + t * dy))\n}\n\n/** Path lengths from the first point: `cum[i]` is the length up to point `i`. */\nfunction cumulative(points: readonly Point[]): number[] {\n const cum = [0]\n for (let i = 1; i < points.length; i++)\n cum.push(cum[i - 1]! + dist(points[i - 1]!, points[i]!))\n return cum\n}\n\n/**\n * Corner indices of the loop `r` (its last point joins its first), in order round it. A corner\n * is where the path turns sharply over a few samples: outward by more than `CONVEX_TURN`, or\n * back against the loop's own direction (a star's inner corner) by more than `CONCAVE_TURN`.\n */\nfunction cornersOf(r: readonly Point[]): number[] {\n const n = r.length\n if (n < 2 * W + 2) return []\n const at = (i: number): Point => r[((i % n) + n) % n]!\n const direction = Math.sign(winding(r, centroid(r))) || 1\n const turns = r.map((p, i) => {\n const a = at(i - W)\n const b = at(i + W)\n const turn = Math.atan2(b.y - p.y, b.x - p.x) - Math.atan2(p.y - a.y, p.x - a.x)\n return (\n direction *\n (turn > Math.PI ? turn - 2 * Math.PI : turn < -Math.PI ? turn + 2 * Math.PI : turn)\n )\n })\n /** 1 for an outward corner, -1 for an inward one, 0 for none. */\n const kind = (i: number): number =>\n turns[i]! > CONVEX_TURN ? 1 : turns[i]! < -CONCAVE_TURN ? -1 : 0\n // Each run of sharp turns one way is one corner, at its sharpest. Start where no run is.\n const start = turns.findIndex((_, i) => kind(i) === 0)\n if (start < 0) return []\n const corners: number[] = []\n let best: number | undefined\n for (let k = 0; k <= n; k++) {\n const i = (start + k) % n\n const c = k < n ? kind(i) : 0\n if (best !== undefined && c !== kind(best)) {\n corners.push(best)\n best = undefined\n }\n if (c !== 0 && (best === undefined || Math.abs(turns[i]!) > Math.abs(turns[best]!)))\n best = i\n }\n corners.sort((a, b) => a - b)\n // A jog where the stroke's ends meet can split one corner into two close together: keep the\n // sharper.\n for (let k = 0; corners.length > 1 && k < corners.length;) {\n const next = (k + 1) % corners.length\n if ((corners[next]! - corners[k]! + n) % n > 2 * W) k++\n else\n corners.splice(\n Math.abs(turns[corners[k]!]!) < Math.abs(turns[corners[next]!]!) ? k : next,\n 1\n )\n }\n return mergeStraight(r, corners)\n}\n\n/** Drops corners whose neighbours run straight through them, the straightest first. */\nfunction mergeStraight(r: readonly Point[], corners: number[]): number[] {\n const cum = cumulative(r)\n const total = cum[cum.length - 1]! + dist(r[r.length - 1]!, r[0]!)\n const arc = (a: number, b: number): number =>\n b > a ? cum[b]! - cum[a]! : total - cum[a]! + cum[b]!\n const out = [...corners]\n while (out.length > 3) {\n let drop = -1\n let straightest = MERGE_STRAIGHT\n for (let k = 0; k < out.length; k++) {\n const p = out[(k - 1 + out.length) % out.length]!\n const q = out[(k + 1) % out.length]!\n const a = arc(p, q)\n const ratio = a === 0 ? 1 : dist(r[p]!, r[q]!) / a\n if (ratio > straightest) {\n straightest = ratio\n drop = k\n }\n }\n if (drop < 0) break\n out.splice(drop, 1)\n }\n return out\n}\n\n/** Times the path winds round `c`, signed. */\nfunction winding(points: readonly Point[], c: Point): number {\n let total = 0\n for (let i = 0; i < points.length; i++) {\n const a = points[i]!\n const b = points[(i + 1) % points.length]!\n let d = Math.atan2(b.y - c.y, b.x - c.x) - Math.atan2(a.y - c.y, a.x - c.x)\n if (d > Math.PI) d -= 2 * Math.PI\n if (d < -Math.PI) d += 2 * Math.PI\n total += d\n }\n return total / (2 * Math.PI)\n}\n\n/** Largest and mean distance of `points` from the line through `a` and `b`, over `|ab|`. */\nfunction deviation(\n points: readonly Point[],\n a: Point,\n b: Point\n): { max: number; mean: number } {\n const len = dist(a, b)\n if (len === 0 || points.length === 0) return { max: Infinity, mean: Infinity }\n let max = 0\n let sum = 0\n for (const p of points) {\n const d = Math.abs((b.x - a.x) * (a.y - p.y) - (a.x - p.x) * (b.y - a.y)) / len\n max = Math.max(max, d)\n sum += d\n }\n return { max: max / len, mean: sum / points.length / len }\n}\n\n/** How straight a run from `a` to `b` is: 1 on the chord, falling as the path strays from it. */\nfunction straightness(points: readonly Point[], a: Point, b: Point): number {\n const dev = deviation(points, a, b)\n const bend = 1 - dist(a, b) / lengthOf(points)\n return clamp01(1 - LINE_MAX * dev.max - LINE_MEAN * dev.mean - 2 * bend)\n}\n\nfunction fitLine(r: readonly Point[]): Fit | undefined {\n const a = r[0]!\n const b = r[r.length - 1]!\n if (dist(a, b) / lengthOf(r) < 0.8) return undefined\n return {\n shape: { kind: 'line', start: pt(a), end: pt(b) },\n score: straightness(r, a, b),\n }\n}\n\n/** An arrow whose head is drawn at the end of `r`: a straight shaft, then a short fold back. */\nfunction fitArrow(r: readonly Point[]): Fit | undefined {\n // The tip is where the path first gets (nearly) as far from its start as it ever does: a\n // head with two barbs comes back to the tip, and the second visit may reach a little further.\n const from = r.map((p) => dist(p, r[0]!))\n const far = Math.max(...from)\n let tipAt = from.findIndex((d) => d >= 0.97 * far)\n while (tipAt + 1 < r.length && from[tipAt + 1]! > from[tipAt]!) tipAt++\n const shaft = r.slice(0, tipAt + 1)\n const head = r.slice(tipAt + 1)\n const tail = r[0]!\n const tip = r[tipAt]!\n const shaftLength = lengthOf(shaft)\n const headLength = lengthOf([tip, ...head])\n const total = shaftLength + headLength\n if (shaftLength < 0.6 * total || headLength < 0.06 * shaftLength) return undefined\n const along = { x: (tip.x - tail.x) / shaftLength, y: (tip.y - tail.y) / shaftLength }\n const chord = dist(tail, tip)\n if (chord / shaftLength < STRAIGHT) return undefined\n // The head stays near the tip, folds back from it, and leaves the shaft's line.\n let off = 0\n for (const p of head) {\n if (dist(p, tip) > 0.4 * chord) return undefined\n if ((p.x - tip.x) * along.x + (p.y - tip.y) * along.y > 0.08 * chord) return undefined\n off = Math.max(off, Math.abs((p.x - tip.x) * along.y - (p.y - tip.y) * along.x))\n }\n if (off < 0.04 * chord) return undefined\n return {\n shape: { kind: 'arrow', start: pt(tail), end: pt(tip) },\n score: straightness(shaft, tail, tip),\n }\n}\n\n/**\n * The stroke as a loop, evenly spaced all the way round (the gap between its ends bridged), an\n * overshoot past its start trimmed; undefined when the stroke is open.\n */\nfunction loopOf(r: readonly Point[], size: number, spacing: number): Point[] | undefined {\n const n = r.length\n if (n < 8) return undefined\n // The end may run past the start: close the loop where it comes nearest the start.\n let end = n - 1\n for (let i = Math.floor(n / 2); i < n; i++)\n if (dist(r[i]!, r[0]!) < dist(r[end]!, r[0]!)) end = i\n if (dist(r[end]!, r[0]!) > CLOSE_GAP * size || n - 1 - end > 0.25 * n) return undefined\n const loop = resample([...r.slice(0, end + 1), r[0]!], spacing)\n loop.pop()\n return loop\n}\n\nfunction fitEllipse(loop: readonly Point[], box: Rect): Fit | undefined {\n const rx = box.width / 2\n const ry = box.height / 2\n if (rx === 0 || ry === 0) return undefined\n const cx = box.x + rx\n const cy = box.y + ry\n let sum = 0\n for (const p of loop) sum += Math.abs(Math.hypot((p.x - cx) / rx, (p.y - cy) / ry) - 1)\n const mean = sum / loop.length\n return {\n shape: {\n kind: 'ellipse',\n rect: {\n x: round(box.x),\n y: round(box.y),\n width: round(box.width),\n height: round(box.height),\n },\n },\n score: clamp01(1 - 3 * mean),\n }\n}\n\n/** How closely the loop follows the polygon through `vertices`: 1 on it, falling with distance. */\nfunction polygonFit(\n loop: readonly Point[],\n vertices: readonly Point[],\n size: number\n): number {\n let sum = 0\n for (const p of loop) {\n let best = Infinity\n for (let i = 0; i < vertices.length; i++)\n best = Math.min(\n best,\n toSegment(p, vertices[i]!, vertices[(i + 1) % vertices.length]!)\n )\n sum += best\n }\n return clamp01(1 - (12 * sum) / loop.length / size)\n}\n\n/** Within `tolerance` radians of horizontal (0) or vertical (1); else -1. */\nfunction axisOf(a: Point, b: Point, tolerance: number): { axis: number; off: number } {\n const angle = Math.abs(Math.atan2(b.y - a.y, b.x - a.x)) % Math.PI\n const fromH = Math.min(angle, Math.PI - angle)\n const fromV = Math.abs(angle - Math.PI / 2)\n if (fromH <= tolerance) return { axis: 0, off: fromH }\n if (fromV <= tolerance) return { axis: 1, off: fromV }\n return { axis: -1, off: Math.PI / 4 }\n}\n\nfunction fitRectangle(vertices: readonly Point[], fit: number): Fit | undefined {\n if (vertices.length !== 4) return undefined\n const tolerance = (20 * Math.PI) / 180\n let worst = 0\n for (let i = 0; i < 4; i++) {\n const side = axisOf(vertices[i]!, vertices[(i + 1) % 4]!, tolerance)\n if (\n side.axis < 0 ||\n side.axis !== (axisOf(vertices[0]!, vertices[1]!, tolerance).axis + i) % 2\n )\n return undefined\n worst = Math.max(worst, side.off)\n }\n const xs = vertices.map((v) => v.x).sort((a, b) => a - b)\n const ys = vertices.map((v) => v.y).sort((a, b) => a - b)\n const left = (xs[0]! + xs[1]!) / 2\n const right = (xs[2]! + xs[3]!) / 2\n const bottom = (ys[0]! + ys[1]!) / 2\n const top = (ys[2]! + ys[3]!) / 2\n return {\n shape: {\n kind: 'rectangle',\n rect: {\n x: round(left),\n y: round(bottom),\n width: round(right - left),\n height: round(top - bottom),\n },\n },\n score: clamp01(fit - worst / tolerance / 10),\n }\n}\n\n/** The shape tool's star of `points` tips round `c`, tips at `radius`, the first at the top. */\nfunction regularStar(c: Point, points: number, radius: number): Point[] {\n const box = { x: c.x - radius, y: c.y - radius, width: 2 * radius, height: 2 * radius }\n return starVertices(box, points).map(pt)\n}\n\nconst centroid = (points: readonly Point[]): Point => ({\n x: points.reduce((s, p) => s + p.x, 0) / points.length,\n y: points.reduce((s, p) => s + p.y, 0) / points.length,\n})\n\n/** An outline star: an even number of corners alternating far from and near the centre. */\nfunction fitStar(vertices: readonly Point[], fit: number): Fit | undefined {\n const k = vertices.length\n if (k % 2 !== 0 || k < 8 || k > 16) return undefined\n const c = centroid(vertices)\n const radii = vertices.map((v) => dist(v, c))\n const even = radii.filter((_, i) => i % 2 === 0)\n const odd = radii.filter((_, i) => i % 2 === 1)\n const [outer, inner] = Math.min(...even) > Math.max(...odd) ? [even, odd] : [odd, even]\n if (Math.min(...outer) <= Math.max(...inner)) return undefined\n const mean = (xs: number[]): number => xs.reduce((s, x) => s + x, 0) / xs.length\n const ratio = mean(inner) / mean(outer)\n if (ratio > 0.75) return undefined\n // Tips spread unevenly from the centre make a sloppier star.\n const spread = (Math.max(...outer) - Math.min(...outer)) / mean(outer)\n return {\n shape: { kind: 'star', vertices: regularStar(c, k / 2, mean(outer)) },\n score: clamp01(fit - Math.max(0, spread - 0.2)),\n }\n}\n\n/** A pentagram: five straight strokes that wind twice round the centre. */\nfunction fitPentagram(\n vertices: readonly Point[],\n loop: readonly Point[],\n size: number\n): Fit | undefined {\n if (vertices.length !== 5) return undefined\n const c = centroid(vertices)\n const turns = Math.abs(winding(loop, c))\n if (turns < 1.6 || turns > 2.4) return undefined\n const radii = vertices.map((v) => dist(v, c))\n const mean = radii.reduce((s, x) => s + x, 0) / radii.length\n const spread = (Math.max(...radii) - Math.min(...radii)) / mean\n return {\n shape: { kind: 'star', vertices: regularStar(c, 5, mean) },\n score: clamp01(polygonFit(loop, vertices, size) - Math.max(0, spread - 0.2)),\n }\n}\n\n/** True when two sides of the polygon through `v` cross. */\nfunction crosses(v: readonly Point[]): boolean {\n const k = v.length\n const side = (a: Point, b: Point, c: Point): number =>\n Math.sign((b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x))\n for (let i = 0; i < k; i++)\n for (let j = i + 2; j < k; j++) {\n if (i === 0 && j === k - 1) continue\n const [a, b, c, d] = [v[i]!, v[(i + 1) % k]!, v[j]!, v[(j + 1) % k]!]\n if (side(a, b, c) * side(a, b, d) < 0 && side(c, d, a) * side(c, d, b) < 0)\n return true\n }\n return false\n}\n\n/** How straight the loop runs between consecutive corners: the worst side's score. */\nfunction sidesFit(loop: readonly Point[], corners: readonly number[]): number {\n let worst = 1\n for (let k = 0; k < corners.length; k++) {\n const from = corners[k]!\n const to = corners[(k + 1) % corners.length]!\n const side =\n to > from\n ? loop.slice(from, to + 1)\n : [...loop.slice(from), ...loop.slice(0, to + 1)]\n const a = side[0]!\n const b = side[side.length - 1]!\n const bend = 1 - dist(a, b) / lengthOf(side)\n worst = Math.min(\n worst,\n clamp01(1 - SIDE_MEAN * deviation(side, a, b).mean - 2 * bend)\n )\n }\n return worst\n}\n\nfunction fitClosed(loop: readonly Point[], size: number): Fit[] {\n const box = boxOf(loop)\n const fits: Fit[] = []\n const corners = cornersOf(loop)\n const vertices = corners.map((i) => loop[i]!)\n const pentagram = fitPentagram(vertices, loop, size)\n if (pentagram) fits.push(pentagram)\n // Every other closed kind winds once round its middle.\n const turns = Math.abs(\n winding(loop, { x: box.x + box.width / 2, y: box.y + box.height / 2 })\n )\n if (turns < 0.8 || turns > 1.25) return fits\n const ellipse = fitEllipse(loop, box)\n if (ellipse) fits.push(ellipse)\n if (vertices.length < 3 || crosses(vertices)) return fits\n const fit = polygonFit(loop, vertices, size)\n const rectangle = fitRectangle(vertices, fit)\n if (rectangle) fits.push(rectangle)\n else if (vertices.length <= 8)\n fits.push({\n shape: { kind: 'polygon', vertices: vertices.map(pt) },\n score: Math.min(fit, sidesFit(loop, corners)),\n })\n const star = fitStar(vertices, fit)\n if (star) fits.push(star)\n return fits\n}\n\n/**\n * The standard shape a single freehand stroke (user space points, in drawing order) is closest\n * to, and how well it fits, from 0 to 1. Tidy the stroke only when the score reaches\n * `RECOGNISE_THRESHOLD`. Undefined when no shape fits at all.\n */\nexport function recogniseStroke(\n points: readonly Point[]\n): { shape: Recognised; score: number } | undefined {\n const clean = points.filter(\n (p, i) =>\n Number.isFinite(p.x) &&\n Number.isFinite(p.y) &&\n (i === 0 || p.x !== points[i - 1]!.x || p.y !== points[i - 1]!.y)\n )\n if (clean.length < 2) return undefined\n const size = diagonal(boxOf(clean))\n if (size === 0) return undefined\n // A long path in a small box (a scribble) would resample to thousands of points: cap them.\n const spacing = Math.max(size / DENSITY, lengthOf(clean) / 1000)\n const r = resample(clean, spacing)\n if (r.length < 2) return undefined\n const fits: Fit[] = []\n const line = fitLine(r)\n if (line) fits.push(line)\n const loop = loopOf(r, size, spacing)\n if (loop) fits.push(...fitClosed(loop, size))\n else {\n for (const f of [fitArrow(r), fitArrow([...r].reverse())]) if (f) fits.push(f)\n }\n let best: Fit | undefined\n for (const f of fits) if (!best || f.score > best.score) best = f\n return best && { shape: best.shape, score: round(best.score) }\n}\n","// What the viewer keeps between visits: sidebar widths, saved signatures, plugin settings. The\n// host owns storage through an `InkStorage`; core ships a memory store and a localStorage one.\n// Inkbar touches neither localStorage nor the network unless the host passes a store that does.\n\n/** Where the viewer keeps small values. Values are JSON; the host's store may be async. */\nexport interface InkStorage {\n // eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents -- documents that a promise is allowed\n get(key: string): unknown | Promise<unknown>\n set(key: string, value: unknown): void | Promise<void>\n remove(key: string): void | Promise<void>\n}\n\nconst copy = (value: unknown): unknown =>\n value === undefined ? undefined : (JSON.parse(JSON.stringify(value)) as unknown)\n\n/** Values in memory, gone on reload. The default when a host passes no store. */\nexport function createMemoryStorage(initial: Record<string, unknown> = {}): InkStorage {\n const map = new Map<string, unknown>(\n Object.entries(initial).map(([k, v]) => [k, copy(v)])\n )\n return {\n get: (key) => copy(map.get(key)),\n set(key, value) {\n map.set(key, copy(value))\n },\n remove(key) {\n map.delete(key)\n },\n }\n}\n\n/**\n * A `localStorage` store whose keys go to storage as `keyOf` maps them. Storage is probed once.\n * Where it is blocked (it refuses even a tiny test write, as in some private windows) values\n * stay in memory for the page's life. A full store that already `holdsOurs` is kept, so its\n * values show and writes reject.\n */\nfunction createLocalStore(\n keyOf: (key: string) => string,\n probeKey: string,\n holdsOurs: (storage: Storage) => boolean\n): InkStorage {\n const storage = ((): Storage | undefined => {\n try {\n const s = globalThis.localStorage ?? undefined\n if (!s) return undefined\n try {\n s.setItem(probeKey, '1')\n s.removeItem(probeKey)\n } catch {\n return holdsOurs(s) ? s : undefined\n }\n return s\n } catch {\n return undefined\n }\n })()\n if (!storage) return createMemoryStorage()\n return {\n get(key) {\n try {\n const raw = storage.getItem(keyOf(key))\n return raw === null ? undefined : (JSON.parse(raw) as unknown)\n } catch {\n return undefined\n }\n },\n set(key, value) {\n try {\n storage.setItem(keyOf(key), JSON.stringify(value))\n } catch (cause) {\n return Promise.reject(\n new Error(`Browser storage could not save \"${key}\"`, { cause })\n )\n }\n return undefined\n },\n remove(key) {\n try {\n storage.removeItem(keyOf(key))\n } catch {\n // Nothing to remove from a storage that cannot be reached.\n }\n },\n }\n}\n\n/**\n * Values in `localStorage` as JSON under `<prefix>:<key>`, read on every call so another tab's\n * write shows. Where storage is blocked the values stay in memory. A `set` that storage\n * refuses, as when it is full, keeps the old value and returns a rejected promise.\n */\nexport function createLocalStorage(prefix = 'inkbar'): InkStorage {\n const start = `${prefix}:`\n return createLocalStore(\n (key) => start + key,\n `${start}probe`,\n (s) => {\n for (let i = 0; i < s.length; i++) if (s.key(i)?.startsWith(start)) return true\n return false\n }\n )\n}\n\n/**\n * Like `createLocalStorage`, but keys reach storage exactly as given, with no prefix. Internal:\n * the signature store keeps its caller's key. `own` is the key whose presence marks a full\n * store as ours.\n */\nexport function createRawLocalStorage(own: string): InkStorage {\n return createLocalStore(\n (key) => key,\n `${own}:probe`,\n (s) => s.getItem(own) !== null\n )\n}\n\n/** Keys under `<prefix>.`: `get('x')` reads `<prefix>.x`. */\nexport function scopeStorage(storage: InkStorage, prefix: string): InkStorage {\n const scoped = (key: string): string => `${prefix}.${key}`\n return {\n get: (key) => storage.get(scoped(key)),\n set: (key, value) => storage.set(scoped(key), value),\n remove: (key) => storage.remove(scoped(key)),\n }\n}\n","// Signature templates and where they live. A template is a signature drawn or typed once and\n// placed many times: ink strokes in a unit box, or an image. The host owns storage through a\n// `SignatureStore`; core ships a memory store and a localStorage one as conveniences.\n//\n// These are visual signatures, a mark on the page. Nothing here signs the file.\nimport { v7 as uuidv7 } from 'uuid'\nimport { z } from 'zod'\n\nimport { IMAGE_DATA_URL, PointSchema } from './annotations/types'\nimport { readonly, writable, type Readable } from './readable'\nimport { createRawLocalStorage } from './storage'\n\nimport type { AnnotationInput } from './annotations/types'\nimport type { Point, Rect } from './geometry'\nimport type { InkStorage } from './storage'\n\n/**\n * A saved signature. Ink points lie in a unit box (0 to 1 on both axes, y growing upwards)\n * that `aspect` (width over height) stretches back to shape. An image keeps its own pixels.\n */\nexport type SignatureTemplate =\n | { id: string; kind: 'ink'; inklist: Point[][]; pressure?: number[][]; aspect: number }\n | { id: string; kind: 'image'; imagedata: string; aspect: number }\n\n/** Where templates live. The host's: a server, the browser, or memory. */\nexport interface SignatureStore {\n list(): Promise<SignatureTemplate[]>\n /** Adds the template, or replaces the one with its id. */\n save(t: SignatureTemplate): Promise<void>\n remove(id: string): Promise<void>\n}\n\n/** Options for the `signature` tool: the template a click places. */\nexport interface SignatureOptions {\n templateId?: string\n}\n\n/** How wide a placed signature is, in points. */\nexport const DEFAULT_SIGNATURE_WIDTH = 150\n\n/** A placed ink signature's stroke width, in points. */\nexport const SIGNATURE_INK_WIDTH = 2\n\nconst Aspect = z.number().positive().finite()\nconst TemplateSchema = z\n .discriminatedUnion('kind', [\n z.object({\n id: z.string().min(1),\n kind: z.literal('ink'),\n inklist: z.array(z.array(PointSchema).min(1)).min(1),\n pressure: z.array(z.array(z.number().min(0).max(1))).optional(),\n aspect: Aspect,\n }),\n z.object({\n id: z.string().min(1),\n kind: z.literal('image'),\n imagedata: z.string().regex(IMAGE_DATA_URL),\n aspect: Aspect,\n }),\n ])\n .refine(\n // Pressure must have one value per point of each stroke, or placing the template would\n // produce ink the store refuses.\n (t) =>\n t.kind !== 'ink' ||\n !t.pressure ||\n (t.pressure.length === t.inklist.length &&\n t.pressure.every((p, i) => p.length === t.inklist[i]?.length)),\n { message: 'pressure must have the same shape as inklist', path: ['pressure'] }\n )\n\n/** The items that are valid templates; the rest are skipped. */\nfunction validTemplates(items: readonly unknown[]): SignatureTemplate[] {\n return items.flatMap((item) => {\n const t = TemplateSchema.safeParse(item)\n return t.success ? [t.data as SignatureTemplate] : []\n })\n}\n\nconst copy = (t: SignatureTemplate): SignatureTemplate =>\n JSON.parse(JSON.stringify(t)) as SignatureTemplate\n\nfunction upsert(\n list: readonly SignatureTemplate[],\n t: SignatureTemplate\n): SignatureTemplate[] {\n const i = list.findIndex((x) => x.id === t.id)\n return i < 0 ? [...list, copy(t)] : list.map((x, j) => (j === i ? copy(t) : x))\n}\n\n/** Templates in memory, gone on reload. The default when a host passes no store. */\nexport function createMemorySignatureStore(\n initial: SignatureTemplate[] = []\n): SignatureStore {\n let items = initial.map(copy)\n return {\n list: () => Promise.resolve(items.map(copy)),\n save(t) {\n items = upsert(items, t)\n return Promise.resolve()\n },\n remove(id) {\n items = items.filter((x) => x.id !== id)\n return Promise.resolve()\n },\n }\n}\n\n/** The id of an entry that may not be a template, if it has one. */\nconst idOf = (x: unknown): unknown =>\n typeof x === 'object' && x !== null ? (x as { id?: unknown }).id : undefined\n\n/**\n * Templates under `key` (default `'signatures'`) in `storage`, as a JSON array, read on every\n * call so another tab's write shows. Stored entries it cannot read, such as a later version's\n * templates, are left out of `list`, kept on write, and dropped only when a template takes\n * their id. When `storage.set` rejects, as when it is full, the list stays as it was and `save`\n * or `remove` rejects, so the host can say so.\n */\nexport function createStorageSignatureStore(\n storage: InkStorage,\n key = 'signatures'\n): SignatureStore {\n /** The stored list: the templates, and the entries that are not (kept, never shown). */\n const read = async (): Promise<{ items: SignatureTemplate[]; unread: unknown[] }> => {\n const stored = await storage.get(key)\n if (!Array.isArray(stored)) return { items: [], unread: [] }\n const parsed = stored as unknown[]\n return {\n items: validTemplates(parsed),\n unread: parsed.filter((x) => validTemplates([x]).length === 0),\n }\n }\n /** Writes `next` with the unread entries after it, less any whose id a template now has. */\n const commit = async (next: SignatureTemplate[], unread: unknown[]): Promise<void> => {\n const ids = new Set<unknown>(next.map((t) => t.id))\n const kept = unread.filter((x) => idOf(x) === undefined || !ids.has(idOf(x)))\n try {\n await storage.set(key, [...next, ...kept])\n } catch (cause) {\n throw new Error('The signature could not be saved: browser storage is full', {\n cause,\n })\n }\n }\n return {\n async list() {\n return (await read()).items.map(copy)\n },\n async save(t) {\n const { items, unread } = await read()\n await commit(upsert(items, t), unread)\n },\n async remove(id) {\n const { items, unread } = await read()\n await commit(\n items.filter((x) => x.id !== id),\n unread\n )\n },\n }\n}\n\n/**\n * Templates in `localStorage` under `key`, as a JSON array. Where storage is blocked the\n * templates stay in memory for the page's life, so signing still works. Where storage is full\n * and has no room for a change, `save` or `remove` rejects.\n *\n * @deprecated Pass `storage` (for example `createLocalStorage()`) to the viewer instead.\n */\nexport function createLocalSignatureStore(key: string): SignatureStore {\n return createStorageSignatureStore(createRawLocalStorage(key), key)\n}\n\n/**\n * Fits strokes into a unit box, for an ink template. Points come in any y-up space; they go\n * out between 0 and 1 on both axes, and `aspect` is the box's width over its height. A flat\n * side is given 1% of the long side (a dot, a square), so the aspect stays finite, and the\n * strokes are centred across it.\n */\nexport function normaliseInk(inklist: Point[][]): { inklist: Point[][]; aspect: number } {\n const all = inklist.flat()\n const xs = all.map((p) => p.x)\n const ys = all.map((p) => p.y)\n const minX = Math.min(...xs)\n const minY = Math.min(...ys)\n const w = Math.max(...xs) - minX\n const h = Math.max(...ys) - minY\n const long = Math.max(w, h)\n const boxW = long === 0 ? 1 : Math.max(w, long * 0.01)\n const boxH = long === 0 ? 1 : Math.max(h, long * 0.01)\n const map = (p: Point): Point => ({\n x: (p.x - minX + (boxW - w) / 2) / boxW,\n y: (p.y - minY + (boxH - h) / 2) / boxH,\n })\n return { inklist: inklist.map((path) => path.map(map)), aspect: boxW / boxH }\n}\n\n/**\n * An ink template from strokes in any y-up space, with a new id. Throws a RangeError for no\n * strokes, an empty stroke, or pressure that does not have one value per point.\n */\nexport function createInkTemplate(\n inklist: Point[][],\n pressure?: number[][]\n): SignatureTemplate {\n if (inklist.length === 0 || inklist.some((path) => path.length === 0))\n throw new RangeError('A signature needs at least one stroke, and no empty strokes')\n if (\n pressure &&\n (pressure.length !== inklist.length ||\n pressure.some((p, i) => p.length !== inklist[i]!.length))\n )\n throw new RangeError('pressure must have the same shape as inklist')\n const fitted = normaliseInk(inklist)\n return {\n id: uuidv7(),\n kind: 'ink',\n inklist: fitted.inklist,\n ...(pressure ? { pressure: pressure.map((p) => [...p]) } : {}),\n aspect: fitted.aspect,\n }\n}\n\n/** An image template, with a new id. Throws a TypeError unless `imagedata` is a PNG or JPEG data URL. */\nexport function createImageTemplate(\n imagedata: string,\n aspect: number\n): SignatureTemplate {\n if (!IMAGE_DATA_URL.test(imagedata))\n throw new TypeError('A signature image must be a PNG or JPEG data URL')\n if (!(aspect > 0 && Number.isFinite(aspect)))\n throw new RangeError(`aspect must be positive, got ${aspect}`)\n return { id: uuidv7(), kind: 'image', imagedata, aspect }\n}\n\n/**\n * The annotation that places `t` on `page`, `width` points wide on screen and centred on\n * `centre` (user space). `rotation` is the page's /Rotate (clockwise): the signature is turned\n * back by as much, so it reads upright on the page as the file displays it. A viewer's view\n * rotation is left out; it turns the signature with the page like any annotation. Ink becomes `ink` with `subject: 'Signature'`, its strokes inset by half their\n * width; an image becomes a `stamp` with `subject: 'Signature'`.\n */\nexport function placeSignature(\n t: SignatureTemplate,\n page: number,\n centre: Point,\n width: number = DEFAULT_SIGNATURE_WIDTH,\n rotation: 0 | 90 | 180 | 270 = 0\n): AnnotationInput {\n const height = width / t.aspect\n const sideways = rotation === 90 || rotation === 270\n const rw = sideways ? height : width\n const rh = sideways ? width : height\n const rect: Rect = { x: centre.x - rw / 2, y: centre.y - rh / 2, width: rw, height: rh }\n if (t.kind === 'image')\n return {\n type: 'stamp',\n page,\n subject: 'Signature',\n imagedata: t.imagedata,\n rect,\n ...(rotation === 0 ? {} : { rotation }),\n }\n const pad = SIGNATURE_INK_WIDTH / 2\n const innerW = Math.max(width - pad * 2, 0)\n const innerH = Math.max(height - pad * 2, 0)\n const rad = (rotation * Math.PI) / 180\n const cos = Math.round(Math.cos(rad))\n const sin = Math.round(Math.sin(rad))\n const place = (p: Point): Point => {\n const u = (p.x - 0.5) * innerW\n const v = (p.y - 0.5) * innerH\n // Anticlockwise in user space (y up) undoes the page's clockwise turn on screen.\n return { x: centre.x + u * cos - v * sin, y: centre.y + u * sin + v * cos }\n }\n return {\n type: 'ink',\n page,\n subject: 'Signature',\n inklist: t.inklist.map((path) => path.map(place)),\n ...(t.pressure ? { pressure: t.pressure.map((p) => [...p]) } : {}),\n width: SIGNATURE_INK_WIDTH,\n rect,\n }\n}\n\n/**\n * A store's templates kept at hand, so the `signature` tool places one without waiting and the\n * signature menus share one list. Every change goes through the store first.\n */\nexport interface SignatureLibrary {\n readonly store: SignatureStore\n /** The templates as of the last load; empty until the first `refresh`. */\n readonly templates: Readable<readonly SignatureTemplate[]>\n get(id: string): SignatureTemplate | undefined\n /** Reloads from the store. A store that fails to list leaves the last list. */\n refresh(): Promise<void>\n /** Saves through the store, then reloads. Rejects when the store does. */\n save(t: SignatureTemplate): Promise<void>\n /**\n * Removes through the store, then reloads. Rejects when the store does, and then sets\n * `removeError` for the menus to show.\n */\n remove(id: string): Promise<void>\n /** Why the last removal failed; cleared by the next one, or by `clearRemoveError`. */\n readonly removeError: Readable<string | undefined>\n clearRemoveError(): void\n}\n\nexport function createSignatureLibrary(store: SignatureStore): SignatureLibrary {\n const templates = writable<readonly SignatureTemplate[]>([])\n const removeError = writable<string | undefined>(undefined)\n /**\n * The newest load that succeeded writes, so a slow one cannot undo a later save, and a later\n * one that fails does not throw away a slow success.\n */\n let loads = 0\n let applied = 0\n const refresh = async (): Promise<void> => {\n const n = ++loads\n try {\n // A host store may hand back anything: an invalid template would fail when placed.\n const list = validTemplates(await store.list())\n if (n > applied) {\n applied = n\n templates.set(list)\n }\n } catch {\n // The store is unavailable: keep what was there.\n }\n }\n return {\n store,\n templates: readonly(templates),\n get: (id) => templates.get().find((t) => t.id === id),\n refresh,\n async save(t) {\n await store.save(t)\n await refresh()\n },\n async remove(id) {\n removeError.set(undefined)\n try {\n await store.remove(id)\n } catch (e) {\n removeError.set('The signature could not be removed. Try again.')\n throw e\n }\n await refresh()\n },\n removeError: readonly(removeError),\n clearRemoveError: () => removeError.set(undefined),\n }\n}\n","// Signing a signature field with a saved signature: a visual mark, pinned to the field. Nothing\n// here signs the file with a certificate.\nimport { InkError } from '../errors'\nimport { placeSignature, type SignatureTemplate } from '../signatures'\n\nimport type { InkDocument } from '../document'\n\n/** How much of the widget's box a signature fills, at most, on its constraining side. */\nconst FILL = 0.9\n\n/**\n * Signs signature field `field` on its widget `widget` with template `t`, and returns the new\n * annotation's id. The signature (ink for a drawn one, a stamp for an image, `subject:\n * 'Signature'`) is fitted and centred in the widget's rect, upright as the page's `/Rotate`\n * shows it, and the field's value becomes `{ signature: id }`: one undo step, and in controlled\n * mode one change of each. A controlled host gets the annotation proposed, and the field is\n * signed once the host applies it.\n *\n * The signature is pinned to the field: it can be deleted, which clears the field, but not\n * moved or resized. Throws an `InkError`: `UnknownField` for a field or widget the form does\n * not have, `NotSignatureField` for another type, `FieldReadOnly` for a read-only or locked\n * field (one signed with a certificate included), and `FieldSigned` when it is already signed.\n */\nexport function signField(\n doc: InkDocument,\n field: string,\n widget: string,\n t: SignatureTemplate\n): string {\n const form = doc.form\n const f = form.fields.get().find((x) => x.name === field)\n if (!f)\n throw new InkError('UnknownField', `There is no field named ${field}`, { field })\n if (f.type !== 'signature')\n throw new InkError('NotSignatureField', `${field} is not a signature field`, {\n field,\n type: f.type,\n })\n const w = f.widgets.find((x) => x.id === widget)\n if (!w)\n throw new InkError('UnknownField', `${field} has no widget ${widget}`, {\n field,\n widget,\n })\n const readOnly = form.widgetState.get()[widget]?.readOnly ?? f.flags.readOnly\n if (f.locked || readOnly)\n throw new InkError('FieldReadOnly', `${field} cannot be signed`, { field })\n // A signature a controlled host has not applied yet counts: the field is being signed.\n if (form.get(field) !== undefined || form._awaitingSignature(field))\n throw new InkError('FieldSigned', `${field} is already signed; clear it first`, {\n field,\n })\n const r = w.rect\n const rotation = doc.pages[w.page]?.rotate ?? 0\n // The box's sides as the page shows them: a quarter turn swaps them.\n const sideways = rotation === 90 || rotation === 270\n const across = sideways ? r.height : r.width\n const down = sideways ? r.width : r.height\n const width = Math.min(across, down * t.aspect) * FILL\n const centre = { x: r.x + r.width / 2, y: r.y + r.height / 2 }\n const input = placeSignature(t, w.page, centre, width, rotation)\n let id = ''\n doc.history.batch(() => {\n id = doc.annotations.add(input).id\n form._signWith(field, id)\n })\n return id\n}\n"],"mappings":";;;;AAsBA,IAAa,WAAb,cAA8B,MAAM;CAClC,OAAyB;CACzB;CACA;CAEA,YACE,MACA,SACA,UAAmC,CAAC,GACpC,OACA;EACA,MAAM,SAAS,UAAU,KAAA,IAAY,KAAA,IAAY,EAAE,MAAM,CAAC;EAC1D,KAAK,OAAO;EACZ,KAAK,UAAU;CACjB;AACF;AAEA,SAAgB,WAAW,OAAmC;CAC5D,OACE,iBAAiB,YAChB,OAAO,UAAU,YAChB,UAAU,QACT,MAA6B,SAAS;AAE7C;;;AC5CA,IAAa,UAAb,MAA6D;CAC3D,4BAAoB,IAAI,IAAwC;CAEhE,GAA2B,OAAU,IAAqC;EACxE,IAAI,MAAM,KAAK,UAAU,IAAI,KAAK;EAClC,IAAI,CAAC,KAAK;GACR,sBAAM,IAAI,IAAI;GACd,KAAK,UAAU,IAAI,OAAO,GAAG;EAC/B;EACA,IAAI,IAAI,EAAE;EACV,aAAa;GACX,KAAK,OAAO,EAAE;EAChB;CACF;CAEA,KAA6B,OAAU,SAA0B;EAC/D,MAAM,MAAM,KAAK,UAAU,IAAI,KAAK;EACpC,IAAI,CAAC,KAAK;EACV,KAAK,MAAM,MAAM,CAAC,GAAG,GAAG,GAAG,GAA4B,OAAO;CAChE;CAEA,QAAc;EACZ,KAAK,UAAU,MAAM;CACvB;AACF;;;ACEA,SAAgB,YAAY,GAAW,GAAW,MAAM,KAAe;CACrE,OAAO,KAAK,IAAI,IAAI,CA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