@inkbar/core 0.3.0 → 0.5.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.
- package/README.md +57 -7
- package/dist/dom.d.mts +848 -43
- package/dist/dom.d.mts.map +1 -1
- package/dist/dom.mjs +5520 -769
- package/dist/dom.mjs.map +1 -1
- package/dist/index.d.mts +99 -17
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +3 -3
- package/dist/index.mjs.map +1 -1
- package/dist/signatures-BwaXi7C8.d.mts +2284 -0
- package/dist/signatures-BwaXi7C8.d.mts.map +1 -0
- package/dist/signatures-CMapTKrC.mjs +4712 -0
- package/dist/signatures-CMapTKrC.mjs.map +1 -0
- package/package.json +5 -6
- package/dist/document-BftlPZKU.d.mts +0 -1455
- package/dist/document-BftlPZKU.d.mts.map +0 -1
- package/dist/threads-2USvyGpX.mjs +0 -1901
- package/dist/threads-2USvyGpX.mjs.map +0 -1
- package/schema.json +0 -650
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"threads-2USvyGpX.mjs","names":["uuidv7","uuidv7"],"sources":["../src/model/errors.ts","../src/model/events.ts","../src/model/geometry.ts","../src/model/readable.ts","../src/model/selection.ts","../src/pdfjs/load.ts","../src/model/annotations/defaults.ts","../src/model/pdf-date.ts","../src/model/annotations/types.ts","../src/model/annotations/embedded.ts","../src/model/env.ts","../src/model/annotations/history.ts","../src/model/annotations/json.ts","../src/model/annotations/store.ts","../src/model/page-cache.ts","../src/model/pages.ts","../src/model/source.ts","../src/model/text.ts","../src/model/document.ts","../src/model/annotations/suggestions.ts","../src/model/annotations/threads.ts"],"sourcesContent":["export type InkErrorCode =\n | 'PasswordRequired'\n | 'InvalidPdf'\n | 'SourceFetchFailed'\n | 'AssetConfigMissing'\n | 'AssetLoadFailed'\n | 'EngineUnavailable'\n | 'ControlledMutationIgnored'\n | 'DocumentDestroyed'\n | 'PageOutOfRange'\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\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\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 { 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 { 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","import type { AnnotationType, ConfidenceBucket } 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 /** Outline colour for a suggested redaction, by confidence bucket. */\n suggestion(bucket: ConfidenceBucket): string\n}\n\nconst COLORS: Record<AnnotationType, string> = {\n highlight: '#F2C230',\n underline: '#2B5A9E',\n strikeout: '#C0392B',\n squiggly: '#1F7A4D',\n text: '#F2C230',\n freetext: '#151820',\n square: '#C0392B',\n circle: '#C0392B',\n line: '#151820',\n polyline: '#151820',\n polygon: '#151820',\n ink: '#151820',\n redact: '#C0392B',\n}\n\n/**\n * Suggested-redaction colours, strengthening with confidence: amber for low, orange for\n * medium, the redaction red for high.\n */\nconst SUGGESTION_COLORS: Record<ConfidenceBucket, string> = {\n low: '#D4A017',\n medium: '#E67E22',\n high: '#C0392B',\n}\n\nexport const staticDefaults: AnnotationDefaults = {\n color: (type) => COLORS[type],\n fill: () => '#000000',\n opacity: (type) => (type === 'highlight' ? 0.4 : 1),\n suggestion: (bucket) => SUGGESTION_COLORS[bucket],\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 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 suggestion: (bucket) =>\n read(`--ink-suggestion-${bucket}`) ?? staticDefaults.suggestion(bucket),\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","/** 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 { z } from 'zod'\n\nexport const ANNOTATION_FORMAT = 'inkbar/annotations'\nexport const ANNOTATION_VERSION = 1\n\nconst Hex = z.string().regex(/^#[0-9a-fA-F]{6}$/, 'expected #RRGGBB')\n\nexport const PointSchema = z.object({ x: z.number(), y: z.number() })\nexport const RectSchema = z.object({\n x: z.number(),\n y: z.number(),\n width: z.number().nonnegative(),\n height: z.number().nonnegative(),\n})\nexport const QuadSchema = z.object({\n p1: PointSchema,\n p2: PointSchema,\n p3: PointSchema,\n p4: PointSchema,\n})\n\nconst Base = z.object({\n /** Client id, UUIDv7, assigned at creation and never reassigned. Embedded annotations use `pdf:<ref>`. */\n id: z.string().min(1),\n /** 0-based page index. */\n page: z.number().int().nonnegative(),\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: Hex,\n opacity: z.number().min(0).max(1),\n author: z.string().optional(),\n contents: z.string().optional(),\n /** Id of the parent note; replies form threads. */\n inReplyTo: z.string().optional(),\n /** ISO 8601 date-time. */\n createdAt: z.iso.datetime({ offset: true }),\n /** ISO 8601 date-time. */\n modifiedAt: z.iso.datetime({ offset: true }),\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 /** Host data. Preserved, never interpreted. */\n custom: z.record(z.string(), z.unknown()).optional(),\n})\n\nexport const TextMarkupSchema = Base.extend({\n type: z.enum(['highlight', 'underline', 'strikeout', 'squiggly']),\n quads: z.array(QuadSchema).min(1),\n})\n\nexport const NoteSchema = Base.extend({\n type: z.literal('text'),\n icon: z\n .enum(['comment', 'note', 'help', 'insert', 'key', 'paragraph'])\n .default('comment'),\n})\n\nexport const FreeTextSchema = Base.extend({\n type: z.literal('freetext'),\n /** The text shown on the page. */\n contents: z.string(),\n fontSize: z.number().positive().default(12),\n fontFamily: z.string().default('Helvetica'),\n align: z.enum(['left', 'center', 'right']).default('left'),\n callout: z.array(PointSchema).min(2).max(3).optional(),\n})\n\nexport const ShapeSchema = Base.extend({\n type: z.enum(['square', 'circle']),\n width: z.number().nonnegative().default(1),\n interiorColor: Hex.optional(),\n})\n\nexport const LineEndingSchema = z.enum([\n 'none',\n 'openArrow',\n 'closedArrow',\n 'square',\n 'circle',\n 'diamond',\n 'butt',\n 'slash',\n])\n\nexport const LineSchema = Base.extend({\n type: z.literal('line'),\n start: PointSchema,\n end: PointSchema,\n width: z.number().nonnegative().default(1),\n head: LineEndingSchema.optional(),\n tail: LineEndingSchema.optional(),\n})\n\nexport const PolySchema = Base.extend({\n type: z.enum(['polyline', 'polygon']),\n vertices: z.array(PointSchema).min(2),\n width: z.number().nonnegative().default(1),\n interiorColor: Hex.optional(),\n})\n\nexport const InkSchema = Base.extend({\n type: z.literal('ink'),\n inklist: z.array(z.array(PointSchema).min(1)).min(1),\n width: z.number().nonnegative().default(2),\n})\n\nexport const SuggestionSchema = z.object({\n jobId: z.string().optional(),\n confidence: z.number().min(0).max(1),\n reason: z.string().optional(),\n explanation: z.string().optional(),\n recommendation: z.enum(['redact', 'review', 'keep']).optional(),\n})\n\nexport const RedactSchema = Base.extend({\n type: z.literal('redact'),\n /** Present when the mark came from text; absent for an area mark. */\n quads: z.array(QuadSchema).min(1).optional(),\n origin: z.enum(['user', 'suggested']).default('user'),\n suggestion: SuggestionSchema.optional(),\n overlayText: z.string().optional(),\n /** Colour the redaction will be filled with when applied. */\n interiorColor: Hex,\n})\n\nexport const AnnotationSchema = z.discriminatedUnion('type', [\n TextMarkupSchema,\n NoteSchema,\n FreeTextSchema,\n ShapeSchema,\n LineSchema,\n PolySchema,\n InkSchema,\n RedactSchema,\n])\n\n/** The viewer's own state on an annotation, left out of exports. */\nconst VIEWER_STATE = { source: true, locked: 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 ShapeSchema.omit(VIEWER_STATE),\n LineSchema.omit(VIEWER_STATE),\n PolySchema.omit(VIEWER_STATE),\n InkSchema.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 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 RedactAnnotation = z.infer<typeof RedactSchema>\nexport type Suggestion = z.infer<typeof SuggestionSchema>\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 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.\n */\nexport type AnnotationInput =\n | InputOf<\n | z.input<typeof TextMarkupSchema>\n | z.input<typeof NoteSchema>\n | z.input<typeof FreeTextSchema>\n | z.input<typeof ShapeSchema>\n | z.input<typeof LineSchema>\n | z.input<typeof PolySchema>\n | z.input<typeof InkSchema>\n >\n | RedactCallerInput\n\nexport const AnnotationDocumentSchema = z.object({\n format: z.literal(ANNOTATION_FORMAT),\n version: z.literal(ANNOTATION_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})\n\n/**\n * An item whose `type` this version does not know, written by a newer Inkbar. It is kept as-is\n * so it survives an import and export round trip, and it is valid only under the schema\n * version that produced it.\n */\nexport type ForeignAnnotation = { type: string; id: string; page: number } & Record<\n string,\n unknown\n>\n\nexport interface AnnotationDocument {\n format: typeof ANNOTATION_FORMAT\n version: typeof ANNOTATION_VERSION\n documentKey?: string\n annotations: Array<ExportedAnnotation | ForeignAnnotation>\n}\n\nexport type ConfidenceBucket = 'low' | 'medium' | 'high'\n\nexport function confidenceBucket(confidence: number): ConfidenceBucket {\n if (confidence < 0.5) return 'low'\n if (confidence < 0.8) return 'medium'\n return 'high'\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 { AnnotationSchema, type Annotation } from './types'\n\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\nexport interface EmbeddedSummary {\n subtype: string\n count: number\n supported: boolean\n}\n\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\nconst ICONS: Record<\n string,\n 'comment' | 'note' | 'help' | 'insert' | 'key' | 'paragraph'\n> = {\n comment: 'comment',\n note: 'note',\n help: 'help',\n insert: 'insert',\n key: 'key',\n paragraph: 'paragraph',\n newparagraph: 'paragraph',\n}\n\nconst ENDINGS: Record<string, string> = {\n none: 'none',\n openarrow: 'openArrow',\n closedarrow: 'closedArrow',\n square: 'square',\n circle: 'circle',\n diamond: 'diamond',\n butt: 'butt',\n slash: 'slash',\n rslash: 'slash',\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\nexport function importEmbeddedPage(\n page: number,\n raw: PdfjsAnnotationData[],\n importedAt: string\n): { annotations: Annotation[]; counts: Record<string, number> } {\n const counts: Record<string, number> = {}\n const annotations: Annotation[] = []\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) annotations.push(converted)\n }\n return { annotations, counts }\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),\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 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 createdAt: created,\n modifiedAt: parsePdfDate(d.modificationDate, created),\n source: 'pdf' as const,\n locked: 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 candidate = {\n ...base('text'),\n type: 'text',\n icon: ICONS[(d.name ?? 'comment').toLowerCase()] ?? 'comment',\n }\n break\n case 'FreeText': {\n const da = d.defaultAppearanceData\n candidate = {\n ...base(\n 'freetext',\n pdfColorToHex(\n da?.fontColor as ArrayLike<number> | undefined,\n staticDefaults.color('freetext')\n )\n ),\n type: 'freetext',\n contents: contents ?? '',\n ...(da && da.fontSize > 0 ? { fontSize: da.fontSize } : {}),\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 const endings = d.lineEndings?.map((e) => ENDINGS[e.toLowerCase()] ?? 'none')\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 ...(endings && endings.length === 2 && endings.some((e) => e !== 'none')\n ? { head: endings[0], tail: endings[1] }\n : {}),\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 }\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 origin: 'user',\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","/** 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 type { AnnotationChange, AnnotationStore } from './store'\nimport type { Annotation } from './types'\n\nexport interface History {\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 /** Unsubscribes from the store and empties both stacks; undo and redo become no-ops. */\n destroy(): void\n}\n\ninterface Entry {\n before: readonly Annotation[]\n after: readonly Annotation[]\n}\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 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 /** Open batch depth; while above zero, changes update `previous` but push no entry. */\n let depth = 0\n /** The list when the outermost batch opened (or was restarted by a replace). */\n let batchStart: readonly Annotation[] | null = null\n\n const sync = () => {\n canUndo.set(undoStack.length > 0)\n canRedo.set(redoStack.length > 0)\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') {\n undoStack.length = 0\n redoStack.length = 0\n previous = current\n if (depth > 0) batchStart = current\n sync()\n return\n }\n if (depth > 0) {\n previous = current\n return\n }\n undoStack.push({ before: previous, after: current })\n if (undoStack.length > limit) undoStack.shift()\n redoStack.length = 0\n previous = current\n sync()\n })\n\n const apply = (list: readonly Annotation[]) => {\n replaying = true\n try {\n store.replaceAll([...list], '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) batchStart = 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) {\n const before = batchStart\n batchStart = null\n const after = store.list.get()\n // A list that ends where it began, the same annotations in the same order, is no step.\n if (before && !sameAnnotations(before, after)) {\n undoStack.push({ before, after })\n if (undoStack.length > limit) undoStack.shift()\n redoStack.length = 0\n sync()\n }\n }\n }\n },\n destroy() {\n destroyed = true\n batchStart = null\n unsubscribe()\n undoStack.length = 0\n redoStack.length = 0\n sync()\n },\n clear() {\n undoStack.length = 0\n redoStack.length = 0\n previous = store.list.get()\n sync()\n },\n }\n}\n\n/** The same annotation objects in the same order. */\nfunction sameAnnotations(a: readonly Annotation[], b: readonly Annotation[]): boolean {\n return a === b || (a.length === b.length && a.every((x, i) => x === b[i]))\n}\n","import { isProduction } from '../env'\n\nimport {\n ANNOTATION_FORMAT,\n ANNOTATION_VERSION,\n AnnotationDocumentSchema,\n ExportedAnnotationSchema,\n type Annotation,\n type AnnotationDocument,\n type ExportedAnnotation,\n type ForeignAnnotation,\n} from './types'\n\nimport type { AnnotationStore } from './store'\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}\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\nconst KNOWN_TYPES: ReadonlySet<string> = new Set(\n ExportedAnnotationSchema.options.flatMap(\n (o) => [...o.shape.type._zod.values] as string[]\n )\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 * Without foreign items the result validates against this version's `schema.json`. With them it\n * validates only against the newer schema that produced them, since this version's schema\n * describes only the types it knows.\n */\nexport function exportAnnotations(\n store: AnnotationStore,\n preserved: readonly ForeignAnnotation[] = [],\n documentKey?: string\n): AnnotationDocument {\n const session: ExportedAnnotation[] = store.list\n .get()\n .filter((a) => a.source === 'session')\n .map(({ source: _source, locked: _locked, ...rest }) => rest)\n return {\n format: ANNOTATION_FORMAT,\n version: ANNOTATION_VERSION,\n ...(documentKey === undefined ? {} : { documentKey }),\n annotations: JSON.parse(JSON.stringify([...session, ...preserved])) as Array<\n ExportedAnnotation | ForeignAnnotation\n >,\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 /** 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 an inkbar/annotations v1 document),\n * then each item on its own. Embedded annotations are never touched; imported items become\n * session annotations.\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): 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 an ${ANNOTATION_FORMAT} v${ANNOTATION_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 result: ImportResult = { imported: 0, unknown: [], errors: [] }\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((item, index) => {\n const type = (item as { type?: unknown } | null)?.type\n if (typeof type === 'string' && !KNOWN_TYPES.has(type)) {\n if (!isForeign(item)) {\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(item.id, index)) {\n result.unknown.push(item)\n }\n return\n }\n // Unknown keys, including `source` and `locked`, are dropped here.\n const parsed = ExportedAnnotationSchema.safeParse(item)\n if (!parsed.success) {\n result.errors.push({\n index,\n issues: parsed.error.issues.map((i) => `${i.path.join('.')}: ${i.message}`),\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 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 isForeign(item: unknown): item is ForeignAnnotation {\n if (typeof item !== 'object' || item === null || Array.isArray(item)) return false\n const { type, id, page } = item as Record<string, unknown>\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 {\n AnnotationSchema,\n confidenceBucket,\n type Annotation,\n type AnnotationInput,\n} from './types'\n\nimport type { AnnotationDefaults } from './defaults'\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\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: Partial<Annotation>): 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 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 completeInput(input: AnnotationInput): Annotation\n on(event: 'change', fn: (change: AnnotationChange) => 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])\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 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/** 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 emitter = new Emitter<{ change: AnnotationChange }>()\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 === 'redact') {\n if (input.interiorColor === undefined)\n candidate.interiorColor = opts.defaults.fill()\n if (input.origin === 'suggested' && input.suggestion && input.color === undefined) {\n candidate.color = opts.defaults.suggestion(\n confidenceBucket(input.suggestion.confidence)\n )\n }\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 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 (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 commit([...basis(), a], { kind: 'add', annotation: a })\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 const candidate: Record<string, unknown> = {\n ...before,\n ...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 belongs to the file: a `locked` key in the patch is ignored.\n if (before.source === 'pdf') keepKey(candidate, before, 'locked')\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: AnnotationChange = { kind: 'update', id, before, after }\n if (controlled && before.source === 'pdf') {\n // The host never holds embedded items, so their edits apply here.\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 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 on: (event, fn) => emitter.on(event, fn),\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","/**\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 { 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\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 { rectFromQuad, type Point, type Quad, type Rect } from './geometry'\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\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(page: number, tc: PdfjsTextContent): TextContent {\n const items: TextItem[] = []\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 items.push({\n str: item.str,\n dir: isDir(item.dir) ? item.dir : 'ltr',\n fontName: item.fontName,\n fontSize,\n hasEOL: item.hasEOL,\n quad,\n rect: rectFromQuad(quad),\n })\n }\n return { page, items }\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 { assertAssets, loadPdfjs, openProxy } from '../pdfjs/load'\n\nimport { staticDefaults, type AnnotationDefaults } from './annotations/defaults'\nimport {\n importEmbeddedPage,\n summarise,\n type EmbeddedSummary,\n} from './annotations/embedded'\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 { createPageCache, type PageCache } from './page-cache'\nimport { pageInfoFromProxy, type PageInfo } from './pages'\nimport { readonly, writable, type Readable } from './readable'\nimport { resolveSource, type DocumentSource } from './source'\nimport { textContentFromPdfjs, type TextContent } from './text'\n\nimport type { AnnotationDocument, ForeignAnnotation } from './annotations/types'\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 /** 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.\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 /**\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`.\n */\n readonly annotations: AnnotationStore\n /** What the file contained, by PDF subtype, including subtypes Inkbar does not show. */\n readonly embedded: readonly EmbeddedSummary[]\n readonly history: History\n /** Session annotations only, plus unknown-type items kept from earlier imports. */\n exportAnnotations(format: 'json'): AnnotationDocument\n /** Defaults to `{ mode: 'replace' }`. Embedded annotations are never touched. */\n importAnnotations(data: AnnotationDocument | string, opts?: ImportOptions): ImportResult\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 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 let preserved: ForeignAnnotation[] = []\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 return importEmbeddedPage(i, raw, importedAt)\n })\n embedded.push(...summarise(perPage.map((r) => r.counts)))\n const fromFile = perPage.flatMap((r) => r.annotations)\n if (fromFile.length > 0) store._setEmbedded(fromFile)\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\n const doc: InkDocument = {\n key: resolved.key,\n status: readonly(status),\n ready,\n pages,\n info,\n async text(page) {\n if (destroyed) throw destroyedError()\n if (!handles) throw statusError(status.get())\n const p = await handles.getPage(page)\n return textContentFromPdfjs(page, await p.getTextContent())\n },\n annotations: store,\n embedded,\n history,\n exportAnnotations(format) {\n if (format !== 'json')\n throw new TypeError(`Unsupported export format ${String(format)}`)\n return exportAnnotations(store, preserved, resolved.key)\n },\n importAnnotations(data, opts = { mode: 'replace' }) {\n const plan = planImport(store, data, opts)\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 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 store.destroy()\n pageCache?.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\n/** Runs `task(0..count-1)` with at most `limit` in flight; results come back in index order. */\nasync 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\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","import type { AnnotationStore } from './store'\nimport type { Annotation } from './types'\n\n/**\n * Keeps a suggested redaction as the user's own: `origin` becomes `'user'` and the colour\n * goes from the confidence colour to the store's default redaction colour, so an accepted\n * mark looks like any other. The suggestion details stay on it. Returns the updated\n * annotation, or undefined (changing nothing) when `id` is not a suggested redaction or is\n * locked.\n */\nexport function acceptSuggestion(\n store: AnnotationStore,\n id: string\n): Annotation | undefined {\n // Pending-aware: a controlled host may not have echoed the suggestion back yet.\n const a = store._getProposed(id)\n if (a?.type !== 'redact' || a.origin !== 'suggested' || a.locked) return undefined\n return store.update(id, { origin: 'user', color: store.defaults.color('redact') })\n}\n","import type { Annotation, NoteAnnotation } from './types'\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 note's thread: follows `inReplyTo` up through notes, stopping at a missing\n * parent, a parent that is not a note, or a cycle.\n */\nexport function threadRoot(\n list: readonly Annotation[],\n start: NoteAnnotation\n): NoteAnnotation {\n const seen = new Set([start.id])\n let current = start\n while (current.inReplyTo) {\n const parent = list.find((a) => a.id === current.inReplyTo)\n if (parent?.type !== 'text' || 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(\n list: readonly Annotation[],\n root: NoteAnnotation\n): 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/** An unlocked root note with no text and no replies: nothing a reader would miss. */\nexport function isAbandonedNote(list: readonly Annotation[], id: string): boolean {\n const a = list.find((x) => x.id === id)\n if (a?.type !== 'text' || a.locked || a.inReplyTo || a.contents?.trim()) return false\n return repliesTo(list, id).length === 0\n}\n"],"mappings":";;;AAWA,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;;;ACjCA,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,CAAC,KAAK;AAC5B;AAEA,SAAgB,eAAe,GAAU,GAAgB;CAGvD,OAAO;EAAE,GAFC,KAAK,IAAI,EAAE,GAAG,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