{"version":3,"file":"index.cjs","names":["abortReason","RENDER_SCOPE","SNAPSHOT_MAX_PIXELS","InteractionToken","SNAPSHOT_TOOL","EMPTY_TILE_PLAN","resolveRenderOptions","PluginError","CONTINUOUS_RENDER_POLICY","EMPTY_TILE_PLAN","RenderToken","InteractionToken","RENDER_DEFAULTS"],"sources":["../src/appearance-store.ts","../src/invalidation.ts","../src/model.ts","../src/pictures.ts","../src/raster-store.ts","../src/snapshot.ts","../src/strategy.ts","../src/tiles.ts","../src/tile-manager.ts","../src/controller.ts","../src/render.plugin.ts"],"sourcesContent":["/**\n * The engine's pictures of a page's annotations or form widgets, shared\n * between the views and plugins that draw them. One ask is one key (the\n * page, the family, the scale and the owner's items at their versions):\n * asks with the same key share one fetch.\n *\n * Consumer aborts are refcounted, as in the raster store: a view that leaves\n * detaches without stopping the fetch for the others; the fetch stops only\n * when the last one leaves before it resolved.\n *\n * Kept for undo:\n * - the last {@link SETS_KEPT} sets of each page and family: an undo that\n *   brings a page back to an earlier set asks the engine for nothing;\n * - each item's last pictures ({@link RecentPictures}), a while after it left\n *   its page: an undo that brings it back shows them at once.\n */\nexport class AppearanceStore<Picture> {\n  private readonly entries = new Map<string, Entry<Picture>>();\n  /** The keys of the resolved sets kept for each page and family, newest last. */\n  private readonly kept = new Map<string, string[]>();\n\n  /** `group` names the page and family; `key` the whole ask. */\n  acquire(\n    group: string,\n    key: string,\n    fetch: (signal: AbortSignal) => Promise<readonly Picture[]>,\n    signal?: AbortSignal,\n  ): Promise<readonly Picture[]> {\n    const existing = this.entries.get(key);\n    if (existing) {\n      if (existing.resolved) this.keep(group, key);\n      return this.attach(key, existing, signal);\n    }\n\n    const entry: Entry<Picture> = {\n      group,\n      promise: undefined as unknown as Promise<readonly Picture[]>,\n      refs: 0,\n      abort: new AbortController(),\n      resolved: false,\n    };\n    entry.promise = fetch(entry.abort.signal).then(\n      (pictures) => {\n        entry.resolved = true;\n        this.keep(group, key);\n        return pictures;\n      },\n      (error) => {\n        // A failed fetch isn't kept: the next ask tries again.\n        this.drop(key, entry);\n        throw error;\n      },\n    );\n    // Each consumer sees the rejection through its own attachment.\n    entry.promise.catch(() => {});\n    this.entries.set(key, entry);\n    return this.attach(key, entry, signal);\n  }\n\n  /** Keep `key` as the group's newest set, letting go of the oldest beyond the few kept. */\n  private keep(group: string, key: string): void {\n    const kept = (this.kept.get(group) ?? []).filter((each) => each !== key);\n    kept.push(key);\n    const gone = kept.splice(0, Math.max(0, kept.length - SETS_KEPT));\n    this.kept.set(group, kept);\n    for (const old of gone) {\n      const entry = this.entries.get(old);\n      if (entry && entry.refs <= 0) this.entries.delete(old);\n    }\n  }\n\n  private isKept(group: string, key: string): boolean {\n    return this.kept.get(group)?.includes(key) ?? false;\n  }\n\n  private attach(\n    key: string,\n    entry: Entry<Picture>,\n    signal?: AbortSignal,\n  ): Promise<readonly Picture[]> {\n    if (signal?.aborted) return Promise.reject(abortReason(signal));\n    entry.refs += 1;\n    if (!signal) {\n      const release = () => this.release(key, entry);\n      entry.promise.then(release, release);\n      return entry.promise;\n    }\n    let settled = false;\n    return new Promise<readonly Picture[]>((resolve, reject) => {\n      const onAbort = () => {\n        if (settled) return;\n        settled = true;\n        entry.refs -= 1;\n        if (entry.refs <= 0 && !entry.resolved) {\n          entry.abort.abort(abortReason(signal));\n          this.drop(key, entry);\n        }\n        reject(abortReason(signal));\n      };\n      signal.addEventListener('abort', onAbort, { once: true });\n      entry.promise.then(\n        (pictures) => {\n          if (settled) return;\n          settled = true;\n          this.release(key, entry);\n          signal.removeEventListener('abort', onAbort);\n          resolve(pictures);\n        },\n        (error) => {\n          if (settled) return;\n          settled = true;\n          this.release(key, entry);\n          signal.removeEventListener('abort', onAbort);\n          reject(error);\n        },\n      );\n    });\n  }\n\n  /** A consumer let go: a set no longer kept goes with the last one. */\n  private release(key: string, entry: Entry<Picture>): void {\n    entry.refs -= 1;\n    if (entry.refs <= 0 && entry.resolved && !this.isKept(entry.group, key)) {\n      this.drop(key, entry);\n    }\n  }\n\n  private drop(key: string, entry: Entry<Picture>): void {\n    if (this.entries.get(key) === entry) this.entries.delete(key);\n  }\n}\n\n/** How many of each page's latest sets are kept, per family: an undo goes back to one. */\nexport const SETS_KEPT = 4;\n\n/** How many items' last pictures are kept, per family, for an undo that brings one back. */\nexport const ITEMS_KEPT = 200;\n\n/**\n * The last pictures of each item (all its states), the newest {@link ITEMS_KEPT}\n * items per family, kept after the item left its page.\n */\nexport class RecentPictures<Picture> {\n  private readonly families = new Map<string, Map<string, readonly Picture[]>>();\n\n  /** A fetch's pictures, grouped by item: each replaces what its item had. */\n  remember(family: string, pictures: readonly Picture[], keyOf: (picture: Picture) => string) {\n    const items = this.families.get(family) ?? new Map<string, readonly Picture[]>();\n    const byItem = new Map<string, Picture[]>();\n    for (const picture of pictures) {\n      const key = keyOf(picture);\n      byItem.set(key, [...(byItem.get(key) ?? []), picture]);\n    }\n    for (const [key, itemPictures] of byItem) {\n      items.delete(key);\n      items.set(key, itemPictures);\n    }\n    while (items.size > ITEMS_KEPT) items.delete(items.keys().next().value!);\n    this.families.set(family, items);\n  }\n\n  of(family: string, key: string): readonly Picture[] {\n    return this.families.get(family)?.get(key) ?? [];\n  }\n}\n\ninterface Entry<Picture> {\n  group: string;\n  promise: Promise<readonly Picture[]>;\n  refs: number;\n  abort: AbortController;\n  resolved: boolean;\n}\n\nfunction abortReason(signal: AbortSignal): unknown {\n  return signal.reason ?? new DOMException('aborted', 'AbortError');\n}\n","/**\n * The built-in event → pixels map: which pages' pictures a confirmed fact\n * repaints, and at which scope. `annotations` scope repaints the pictures\n * that draw annotations, `fields` the ones that draw form fields, and\n * `content` every picture (a redaction or a flatten rewrites the content\n * stream). Over-invalidation is acceptable (a z-order move that changes\n * nothing repaints one thumbnail); under-invalidation is the bug.\n *\n * The map ignores whose change it is: a baked raster is stale whether this\n * session moved the highlight or a collaborator did. Events fire only for confirmed\n * mutations, so a drag invalidates once at commit; optimistic previews live\n * in the overlay, never here.\n */\nimport type { DocumentEvent, PageObjectNumber, PageRef } from '@embedpdf/core';\n\nimport type { InvalidateScope } from './contract';\n\nexport interface PixelChange {\n  readonly pages: readonly PageObjectNumber[];\n  readonly scope: InvalidateScope;\n}\n\nconst placedPages = (widgets: ReadonlyArray<{ page: PageRef | null }>): PageObjectNumber[] =>\n  widgets.flatMap((widget) => (widget.page ? [widget.page.objectNumber] : []));\n\nconst changeOf = (\n  pages: readonly PageObjectNumber[],\n  scope: InvalidateScope,\n): PixelChange | null => (pages.length ? { pages: [...new Set(pages)], scope } : null);\n\n/**\n * The pages a form fact repaints. Every form fact names the widgets whose\n * look changed or that went (`meta.changedWidgets`), each with its page; the\n * widget rows it carries, and a deleted widget's page, are counted too. An\n * unplaced widget (`page: null`) has no pixels to repaint.\n */\nfunction formPagesOf(\n  event: Extract<DocumentEvent, { meta: { changedWidgets: unknown } }>,\n): PageObjectNumber[] {\n  const pages = placedPages(event.meta.changedWidgets);\n  if ('widgets' in event) pages.push(...placedPages(event.widgets));\n  if ('page' in event && event.page) pages.push(event.page.objectNumber);\n  return pages;\n}\n\nexport function pixelChangeOf(\n  event: DocumentEvent,\n  allPageObjectNumbers: () => PageObjectNumber[],\n): PixelChange | null {\n  switch (event.type) {\n    case 'annotations.created':\n    case 'annotations.updated':\n    case 'annotations.deleted':\n    case 'annotations.restored':\n    case 'annotations.reordered': // z-order: baked stacking can change\n      return changeOf([event.page.objectNumber], 'annotations');\n    case 'forms.valueSet':\n    case 'forms.created':\n    case 'forms.updated':\n    case 'forms.deleted':\n    case 'forms.restored':\n    case 'forms.widgetAdded':\n    case 'forms.widgetRemoved':\n    case 'forms.widgetDeleted':\n    case 'forms.widgetRestored':\n    case 'forms.widgetUpdated':\n    case 'forms.widgetsReordered':\n      return changeOf(formPagesOf(event), 'fields');\n    // A coarse result (counts only, no per-widget detail): repaint every page.\n    case 'forms.repaired':\n      return changeOf(allPageObjectNumbers(), 'fields');\n    // Sealing bakes the signature into its widget's appearance.\n    case 'signatures.completed':\n      return changeOf(\n        event.signature.widget ? placedPages([event.signature.widget]) : [],\n        'fields',\n      );\n    // These rewrite the page content itself.\n    case 'redaction.applied':\n    case 'pages.flattened':\n      return changeOf(\n        event.results\n          .filter((result) => result.status === 'applied')\n          .map((result) => result.page.objectNumber),\n        'content',\n      );\n    case 'annotations.flattened':\n      return changeOf(\n        event.results.some((result) => result.status === 'applied')\n          ? [event.page.objectNumber]\n          : [],\n        'content',\n      );\n    // The stream lost events that will never arrive: any page may be stale.\n    case 'stream.desynced':\n      return changeOf(allPageObjectNumbers(), 'content');\n    // The engine's own fonts changed, with no write behind it (a font\n    // registered after the first pages were drawn): a page's text draws a\n    // glyph its font lacks from a fallback, so any page may be stale. A\n    // write's `fonts.changed` carries its `transaction`; that write's own events\n    // repaint what it changed.\n    case 'fonts.changed':\n      return event.origin.transaction ? null : changeOf(allPageObjectNumbers(), 'content');\n    // pages.* replace the page registry: the kernel's `pagesSequence` bump already\n    // re-keys every layout, and metadata never touches pixels. A new saved\n    // version changes no pixels beyond the signature it seals. The\n    // calculation order changes no pixels.\n    default:\n      return null;\n  }\n}\n","/**\n * The render ledger: per-page raster versions, and the snapshot tool's box.\n * Every function below is a pure transition or projection; the controller\n * applies the transitions with `ctx.state.update`.\n */\nimport type { PageObjectNumber, PageRef, PageRenderLayers } from '@embedpdf/core';\nimport type { Rotation, Point } from '@embedpdf/core-geometry';\nimport type { InvalidateScope } from './contract';\n\n/**\n * Per-page versions of what a page picture can draw: the page content, its\n * annotations and its form fields. Fed by the document event stream and by\n * the `invalidate` verb: a confirmed pixel-changing fact, own or remote,\n * bumps the touched pages, and anything holding a rendered bitmap refetches.\n * A picture's version is the sum of the parts it draws, and is part of every\n * raster and tile key.\n */\nexport interface RenderState {\n  /** Content versions, bumped by content facts (redaction, flatten). */\n  readonly contentEpochs: Readonly<Record<PageObjectNumber, number>>;\n  /** Annotation versions, bumped by annotation facts (widgets excepted). */\n  readonly annotationEpochs: Readonly<Record<PageObjectNumber, number>>;\n  /** Form field versions, bumped by form facts: a fill, a widget's move or look, a signing. */\n  readonly fieldEpochs: Readonly<Record<PageObjectNumber, number>>;\n  /** The snapshot tool's box, while it is dragged or held. */\n  readonly snapshot: SnapshotBox | null;\n}\n\n/**\n * The snapshot tool's box: two corners on the page the press was on, in page\n * space. Dragged until the release; held from then on, as the snapshot.\n */\nexport interface SnapshotBox {\n  readonly page: PageRef;\n  /** Where the press was. */\n  readonly from: Point;\n  /** Where the pointer is, kept on the page. */\n  readonly to: Point;\n  /** View px per page unit at the press, which tells a box from a click. */\n  readonly scale: number;\n  /** The page's turn on screen at the press: the picture turns with it. */\n  readonly rotation: Rotation;\n  /** Released: the box is the snapshot. */\n  readonly held: boolean;\n}\n\nexport const initialRenderState = (): RenderState => ({\n  contentEpochs: {},\n  annotationEpochs: {},\n  fieldEpochs: {},\n  snapshot: null,\n});\n\nexport function setSnapshotBox(state: RenderState, snapshot: SnapshotBox | null): RenderState {\n  return state.snapshot === snapshot ? state : { ...state, snapshot };\n}\n\nconst bump = (\n  epochs: Readonly<Record<PageObjectNumber, number>>,\n  pageObjectNumbers: readonly PageObjectNumber[],\n): Record<PageObjectNumber, number> => {\n  const next: Record<PageObjectNumber, number> = { ...epochs };\n  for (const pageObjectNumber of pageObjectNumbers) {\n    next[pageObjectNumber] = (next[pageObjectNumber] ?? 0) + 1;\n  }\n  return next;\n};\n\n/**\n * Bump the pages' versions in the ledger the scope names. A content fact\n * bumps only the content ledger; every picture counts content (see\n * {@link renderEpochOf}), which is how content invalidation reaches them all.\n */\nexport function invalidatePages(\n  state: RenderState,\n  pageObjectNumbers: readonly PageObjectNumber[],\n  scope: InvalidateScope,\n): RenderState {\n  if (pageObjectNumbers.length === 0) return state;\n  switch (scope) {\n    case 'content':\n      return { ...state, contentEpochs: bump(state.contentEpochs, pageObjectNumbers) };\n    case 'annotations':\n      return { ...state, annotationEpochs: bump(state.annotationEpochs, pageObjectNumbers) };\n    case 'fields':\n      return { ...state, fieldEpochs: bump(state.fieldEpochs, pageObjectNumbers) };\n  }\n}\n\n/** The version of one picture of a page: its content, plus the annotations and form fields it draws. */\nexport function renderEpochOf(\n  state: RenderState,\n  pageObjectNumber: PageObjectNumber,\n  layers: PageRenderLayers,\n): number {\n  return (\n    (state.contentEpochs[pageObjectNumber] ?? 0) +\n    (layers.includeAnnotations ? (state.annotationEpochs[pageObjectNumber] ?? 0) : 0) +\n    (layers.includeFormFields ? (state.fieldEpochs[pageObjectNumber] ?? 0) : 0)\n  );\n}\n\n/** What a picture draws, as one key part: `a1f0` draws annotations and no form fields. */\nexport const layersKeyOf = (layers: PageRenderLayers): string =>\n  `a${layers.includeAnnotations ? 1 : 0}f${layers.includeFormFields ? 1 : 0}`;\n","/**\n * Whether each page's picture is on screen: the reports the page layers keep, folded into one\n * state per page and view.\n *\n * A layer that paints a page opens a report on it when it mounts (`reportPicture`), and the page\n * is `loading` in that view from then on. It turns `ready` once a report says `shown()`, and\n * stays so: a later picture of the page replaces the one on screen only once it's there. A\n * failure before that makes it `forbidden` or `error`. `slow` turns on when it has been loading\n * for `slowAfterMs`, on the plugin's clock, and the page goes back to `idle` once every report on\n * it closed (its layers unmounted).\n *\n * Like the tile plans, the states live here and not in the plugin's state: they follow the\n * layers, which unmount while the document closes, after the plugin's state stopped taking\n * writes. A change wakes the readers with `ctx.notify()`, which does nothing by then.\n */\nimport {\n  isPluginError,\n  type Cancel,\n  type PageObjectNumber,\n  type PageRef,\n  type PluginContext,\n  type ResourceStatus,\n} from '@embedpdf/core';\nimport type { PictureState, PictureStateChangedEvent, RenderSettings } from './contract';\nimport type { OpenPictureReport } from './host-contract';\nimport type { RenderState } from './model';\n\nconst pictureState = (status: ResourceStatus, slow = false): PictureState =>\n  Object.freeze({ status, slow });\n\n/** Every picture state there is, one object each, so the same state is the same object. */\nexport const PICTURE_STATES = {\n  idle: pictureState('idle'),\n  loading: pictureState('loading'),\n  slow: pictureState('loading', true),\n  ready: pictureState('ready'),\n  forbidden: pictureState('forbidden'),\n  error: pictureState('error'),\n} as const;\n\n/** What one report said: its picture showed, or why it can't. */\ninterface Report {\n  shown: boolean;\n  failure: 'forbidden' | 'error' | null;\n}\n\n/** A page some view shows, and the reports on it. */\ninterface ShownPage {\n  readonly page: PageRef;\n  readonly reports: Set<Report>;\n  slow: boolean;\n  /** The pending turn to `slow`, while it waits. */\n  cancelSlow: Cancel | null;\n  /** What it reads now. */\n  state: PictureState;\n}\n\n/** A refusal for want of a permission, as a `PluginError` or its plain info. */\nconst isRefusal = (error: unknown): boolean =>\n  isPluginError(error, 'permission-denied') ||\n  (typeof error === 'object' &&\n    error !== null &&\n    (error as { code?: unknown }).code === 'permission-denied');\n\n/** One picture shown is enough; otherwise a failure, or still loading. */\nfunction statusOf(shown: ShownPage): ResourceStatus {\n  let failure: Report['failure'] = null;\n  for (const report of shown.reports) {\n    if (report.shown) return 'ready';\n    if (report.failure === 'forbidden' || (report.failure && !failure)) failure = report.failure;\n  }\n  return failure ?? 'loading';\n}\n\nfunction stateOf(status: ResourceStatus, slow: boolean): PictureState {\n  if (status === 'loading') return slow ? PICTURE_STATES.slow : PICTURE_STATES.loading;\n  return PICTURE_STATES[status];\n}\n\nexport function createPictureReports(\n  ctx: PluginContext<RenderState, RenderSettings>,\n  changed: (event: PictureStateChangedEvent) => void,\n) {\n  const views = new Map<string, Map<PageObjectNumber, ShownPage>>();\n  // Layers unmount after the document closed: their last reports change nothing then.\n  let closed = false;\n  ctx.cleanup(() => {\n    closed = true;\n    for (const pages of views.values()) for (const shown of pages.values()) shown.cancelSlow?.();\n    views.clear();\n  });\n\n  /** Fold a page's reports into its state, and tell the readers when that changed. */\n  function publish(view: string, shown: ShownPage): void {\n    const status = shown.reports.size === 0 ? 'idle' : statusOf(shown);\n    if (status !== 'loading') {\n      shown.cancelSlow?.();\n      shown.cancelSlow = null;\n      shown.slow = false;\n    } else if (!shown.slow && !shown.cancelSlow) {\n      const delay = ctx.settings().get().slowAfterMs;\n      if (delay <= 0) {\n        shown.slow = true;\n      } else {\n        shown.cancelSlow = ctx.clock.after(delay, () => {\n          shown.cancelSlow = null;\n          shown.slow = true;\n          publish(view, shown);\n        });\n      }\n    }\n    const next = stateOf(status, shown.slow);\n    if (shown.state === next) return;\n    shown.state = next;\n    ctx.notify();\n    changed({ page: shown.page, view, ...next });\n  }\n\n  /** A page's state in a view: `idle` when the view doesn't show it. */\n  function stateIn(view: string, pageObjectNumber: PageObjectNumber): PictureState {\n    return views.get(view)?.get(pageObjectNumber)?.state ?? PICTURE_STATES.idle;\n  }\n\n  function open(view: string, page: PageRef): OpenPictureReport {\n    const report: Report = { shown: false, failure: null };\n    if (closed) return { shown() {}, failed() {}, close() {} };\n    let pages = views.get(view);\n    if (!pages) views.set(view, (pages = new Map()));\n    let shown = pages.get(page.objectNumber);\n    if (!shown) {\n      shown = {\n        page,\n        reports: new Set(),\n        slow: false,\n        cancelSlow: null,\n        state: PICTURE_STATES.idle,\n      };\n      pages.set(page.objectNumber, shown);\n    }\n    const target = shown;\n    target.reports.add(report);\n    publish(view, target);\n    let open = true;\n    return {\n      shown() {\n        if (!open || closed || report.shown) return;\n        report.shown = true;\n        report.failure = null;\n        publish(view, target);\n      },\n      failed(error) {\n        if (!open || closed || report.shown) return;\n        report.failure = isRefusal(error) ? 'forbidden' : 'error';\n        publish(view, target);\n      },\n      close() {\n        if (!open || closed) return;\n        open = false;\n        target.reports.delete(report);\n        if (target.reports.size === 0 && views.get(view)?.get(page.objectNumber) === target) {\n          views.get(view)!.delete(page.objectNumber);\n        }\n        publish(view, target);\n      },\n    };\n  }\n\n  return { open, stateIn };\n}\n","import type { PageImageHandle } from '@embedpdf/core';\n\n/**\n * The client-side counterpart of the server's read-through cache: per-key\n * singleflight + cost-budgeted LRU over encoded page images.\n *\n * The key is the raster's canonical identity (for page rasters: width,\n * annotations flag, epoch and format, built by `rasterKey` in the\n * controller; for tiles: `TileManager`'s tile key), so the render points do\n * the caching work: every ask at one point is the same key, and\n * re-crossings (zoom 1280 → 2560 → back) resolve instantly from the LRU\n * instead of re-rendering. Epoch bumps mint new keys; stale-epoch entries\n * age out through the LRU (they are never re-requested).\n *\n * The budget is cost, approximately bytes: an entry costs its encoded byte\n * length when the handle carries bytes (local), its pixel count as a\n * decoded-order estimate otherwise (URL-backed cloud handles), and 1 when\n * neither is known. Entry counts lie — a 512² webp tile and a BMP full page\n * differ by 100× — and long deep-zoom sessions cycle hundreds of tile keys,\n * so the budget is what actually bounds memory.\n *\n * Consumer aborts are refcounted: a caller abandoning a fetch (camera moved,\n * layer unmounted) detaches without killing it for other consumers; the\n * underlying engine call aborts only when the last in-flight consumer leaves.\n * Resolved entries are kept (evictable by LRU) — an abort after resolution\n * is a no-op by design.\n */\nexport class RasterStore {\n  private readonly entries = new Map<string, Entry>();\n  private tick = 0;\n  private total = 0;\n\n  constructor(private readonly maxCost = 128 * 1024 * 1024) {}\n\n  acquire(\n    key: string,\n    fetch: (signal: AbortSignal) => Promise<PageImageHandle>,\n    signal?: AbortSignal,\n  ): Promise<PageImageHandle> {\n    const existing = this.entries.get(key);\n    if (existing) {\n      existing.used = ++this.tick;\n      return this.attach(key, existing, signal);\n    }\n\n    const abort = new AbortController();\n    const entry: Entry = {\n      promise: undefined as unknown as Promise<PageImageHandle>,\n      refs: 0,\n      abort,\n      used: ++this.tick,\n    };\n    entry.promise = fetch(abort.signal).then(\n      (handle) => {\n        entry.handle = handle;\n        entry.cost = costOf(handle);\n        this.total += entry.cost;\n        this.evict(); // cost is known only now — budget check at resolution\n        return handle;\n      },\n      (error) => {\n        // Failed fetches must not be sticky — drop so the next ask retries.\n        this.drop(key, entry);\n        throw error;\n      },\n    );\n    // Swallow the shared promise's rejection when no consumer is attached\n    // (everyone aborted) — each consumer observes it via its own attachment.\n    entry.promise.catch(() => {});\n    this.entries.set(key, entry);\n    this.evict();\n    return this.attach(key, entry, signal);\n  }\n\n  /** Resolved handle if present — synchronous peek for paint-time reuse. */\n  peek(key: string): PageImageHandle | undefined {\n    const entry = this.entries.get(key);\n    if (entry?.handle) entry.used = ++this.tick;\n    return entry?.handle;\n  }\n\n  get size(): number {\n    return this.entries.size;\n  }\n\n  /** Total cost (~bytes) of resolved entries — the budgeted quantity. */\n  get costUsed(): number {\n    return this.total;\n  }\n\n  private attach(key: string, entry: Entry, signal?: AbortSignal): Promise<PageImageHandle> {\n    if (signal?.aborted) return Promise.reject(abortReason(signal));\n    // Every consumer holds a ref while the fetch is in flight — including\n    // signal-less ones (\"I never abandon\"), otherwise a signal-bearing\n    // sibling's abort could kill a fetch someone else is still awaiting.\n    entry.refs += 1;\n    if (!signal) {\n      const release = () => {\n        entry.refs -= 1;\n      };\n      entry.promise.then(release, release);\n      return entry.promise;\n    }\n    let settled = false;\n    return new Promise<PageImageHandle>((resolve, reject) => {\n      const onAbort = () => {\n        if (settled) return;\n        settled = true;\n        entry.refs -= 1;\n        // Last live consumer walking away from an unresolved fetch kills it;\n        // resolved entries stay for the LRU (that's the cache).\n        if (entry.refs <= 0 && entry.handle === undefined) {\n          entry.abort.abort(abortReason(signal));\n          this.drop(key, entry);\n        }\n        reject(abortReason(signal));\n      };\n      signal.addEventListener('abort', onAbort, { once: true });\n      entry.promise.then(\n        (handle) => {\n          if (settled) return;\n          settled = true;\n          entry.refs -= 1;\n          signal.removeEventListener('abort', onAbort);\n          resolve(handle);\n        },\n        (error) => {\n          if (settled) return;\n          settled = true;\n          entry.refs -= 1;\n          signal.removeEventListener('abort', onAbort);\n          reject(error);\n        },\n      );\n    });\n  }\n\n  /** Remove an entry, keeping the cost ledger honest. */\n  private drop(key: string, entry: Entry): void {\n    if (this.entries.get(key) !== entry) return;\n    this.entries.delete(key);\n    if (entry.cost !== undefined) this.total -= entry.cost;\n  }\n\n  private evict(): void {\n    if (this.total <= this.maxCost) return;\n    // Oldest-first over evictable entries: resolved and consumer-free.\n    const candidates = [...this.entries.entries()]\n      .filter(([, entry]) => entry.refs <= 0 && entry.handle !== undefined)\n      .sort((left, right) => left[1].used - right[1].used);\n    for (const [key, entry] of candidates) {\n      if (this.total <= this.maxCost) return;\n      this.drop(key, entry);\n    }\n  }\n}\n\ninterface Entry {\n  promise: Promise<PageImageHandle>;\n  handle?: PageImageHandle;\n  /** Approximate bytes; set at resolution (see class doc). */\n  cost?: number;\n  refs: number;\n  abort: AbortController;\n  used: number;\n}\n\n/** Approximate memory cost: encoded bytes when known, pixel count as a\n *  decoded-order estimate for URL handles, 1 when nothing is known. */\nfunction costOf(handle: PageImageHandle): number {\n  if (handle.source?.kind === 'bytes') return handle.source.bytes.byteLength;\n  if (handle.width !== undefined && handle.height !== undefined) {\n    return handle.width * handle.height;\n  }\n  return 1;\n}\n\nfunction abortReason(signal: AbortSignal): unknown {\n  return signal.reason ?? new DOMException('aborted', 'AbortError');\n}\n","/**\n * The snapshot tool: drag a box on a page, or click for the whole page, and\n * the box becomes the snapshot, part of the page as a picture to copy or\n * save. The box is state, in page space on the page the press was on; its\n * picture is a one-off render of it (`renderPage` with a `rect`), kept beside\n * the state, since a promise is no data. The pointer comes from the\n * interaction hub when there is one: `connect` registers the tool and its\n * handler.\n */\nimport {\n  memo,\n  type DocCapability,\n  type EngineRenderPolicy,\n  type PageRef,\n  type PluginContext,\n} from '@embedpdf/core';\nimport { rectFromCorners, type Rotation, type Point, type Rect } from '@embedpdf/core-geometry';\nimport {\n  InteractionToken,\n  samplePointOn,\n  type InteractionHandler,\n} from '@embedpdf/plugin-interaction/contract/host';\n\nimport {\n  SNAPSHOT_MAX_PIXELS,\n  SNAPSHOT_TOOL,\n  type RenderCapability,\n  type RenderSettings,\n  type Snapshot,\n  type SnapshotChangedEvent,\n  type SnapshotSettings,\n} from './contract';\nimport type { RenderHostCapability } from './host-contract';\nimport { setSnapshotBox, type RenderState, type SnapshotBox } from './model';\n\nconst RENDER_SCOPE: DocCapability = 'doc.render';\nconst CONTENT_COPY_SCOPE: DocCapability = 'doc.content.copy';\n\n/** The behavior tag the snapshot tool turns on, which its handler answers to. */\nconst SNAPSHOT_BOX_TAG = 'snapshot-box';\n\n/** A drag shorter than this on both axes, in view px, is a click (the zoom tool's threshold). */\nconst BOX_THRESHOLD_PX = 4;\n\nconst clamp = (value: number, min: number, max: number): number =>\n  Math.min(max, Math.max(min, value));\n\n/** Whether a drag is big enough on screen to be a box, not a click. */\nconst isBox = (box: SnapshotBox): boolean =>\n  Math.abs(box.to.x - box.from.x) * box.scale >= BOX_THRESHOLD_PX ||\n  Math.abs(box.to.y - box.from.y) * box.scale >= BOX_THRESHOLD_PX;\n\n/** The rect a box spans; a side dragged flat is one view pixel, so there's a picture to take. */\nfunction rectOf(box: SnapshotBox): Rect {\n  const rect = rectFromCorners(box.from, box.to);\n  const least = 1 / box.scale;\n  return {\n    ...rect,\n    width: Math.max(rect.width, least),\n    height: Math.max(rect.height, least),\n  };\n}\n\n/**\n * The scale of a snapshot's picture: the setting, lowered until the picture\n * fits {@link SNAPSHOT_MAX_PIXELS} and the deployment's budget, counting its\n * sides in whole pixels.\n */\nexport function snapshotScale(rect: Rect, wanted: number, policy: EngineRenderPolicy): number {\n  const deployment = policy.kind === 'lattice' ? (policy.maxRenderPixels ?? Infinity) : Infinity;\n  const budget = Math.min(SNAPSHOT_MAX_PIXELS, deployment);\n  const pixelsAt = (scale: number) =>\n    Math.ceil(rect.width * scale) * Math.ceil(rect.height * scale);\n  let scale = Math.min(wanted, Math.sqrt(budget / (rect.width * rect.height)));\n  while (pixelsAt(scale) > budget) scale *= 0.999;\n  return scale;\n}\n\nexport function createSnapshots(\n  ctx: PluginContext<RenderState, RenderSettings>,\n  {\n    renderPage,\n    renderPolicy,\n    settings,\n  }: {\n    renderPage: RenderCapability['renderPage'];\n    renderPolicy: () => EngineRenderPolicy;\n    settings: () => SnapshotSettings;\n  },\n) {\n  const changed = ctx.events.source<SnapshotChangedEvent>();\n  const box = (): SnapshotBox | null => ctx.state.get().snapshot;\n  const canSnapshot = (): boolean => ctx.allows(RENDER_SCOPE) && ctx.allows(CONTENT_COPY_SCOPE);\n\n  // The snapshot held now, and the way to stop its picture: set before the\n  // box turns held, so a reader woken by the state finds it.\n  let held: Snapshot | null = null;\n  let stopPicture: AbortController | null = null;\n\n  function clearSnapshot(): void {\n    stopPicture?.abort();\n    stopPicture = null;\n    const letGo = held;\n    held = null;\n    ctx.state.update(setSnapshotBox, null);\n    if (letGo) changed.emit({ snapshot: null });\n  }\n\n  /** Hold `rect` of the box's page as the snapshot, and render its picture. */\n  function take(dragged: SnapshotBox, rect: Rect): void {\n    const stop = new AbortController();\n    stopPicture = stop;\n    const scale = snapshotScale(rect, settings().scale, renderPolicy());\n    // Every change made before the snapshot is in its picture, a stamp placed\n    // a moment ago too: the engine has them all first.\n    const image = ctx.cancellable(stop.signal, ctx.changes.whenSettled()).then(() =>\n      renderPage(dragged.page, {\n        rect,\n        scale,\n        rotation: dragged.rotation,\n        format: 'png',\n        signal: stop.signal,\n      }),\n    );\n    image.catch(() => {}); // nobody may ever ask for it\n    held = { page: dragged.page, rect, image };\n    ctx.state.update(setSnapshotBox, {\n      ...dragged,\n      from: { x: rect.x, y: rect.y },\n      to: { x: rect.x + rect.width, y: rect.y + rect.height },\n      held: true,\n    });\n    changed.emit({ snapshot: held });\n  }\n\n  // ── the gesture, in page space on the page the press was on ──\n\n  function begin(page: PageRef, point: Point, scale: number, rotation: Rotation): boolean {\n    if (!canSnapshot() || !ctx.getPage(page)) return false;\n    clearSnapshot();\n    ctx.state.update(setSnapshotBox, {\n      page,\n      from: point,\n      to: point,\n      scale,\n      rotation,\n      held: false,\n    });\n    return true;\n  }\n\n  function move(point: Point): void {\n    const dragged = box();\n    const size = dragged && !dragged.held ? ctx.getPage(dragged.page)?.size : undefined;\n    if (!dragged || !size) return;\n    const to = { x: clamp(point.x, 0, size.width), y: clamp(point.y, 0, size.height) };\n    ctx.state.update(setSnapshotBox, { ...dragged, to });\n  }\n\n  function end(): void {\n    const dragged = box();\n    if (!dragged || dragged.held) return;\n    const size = ctx.getPage(dragged.page)?.size;\n    if (!size) {\n      ctx.state.update(setSnapshotBox, null);\n      return;\n    }\n    // A click takes the whole page.\n    take(dragged, isBox(dragged) ? rectOf(dragged) : { x: 0, y: 0, ...size });\n  }\n\n  function cancel(): void {\n    const dragged = box();\n    if (dragged && !dragged.held) ctx.state.update(setSnapshotBox, null);\n  }\n\n  const handler: InteractionHandler = {\n    id: 'render-snapshot',\n    priority: 10,\n    enabledFor: (tool) => tool.enables.has(SNAPSHOT_BOX_TAG),\n    // A press between pages does nothing: a box lives on one page.\n    onPointerDown: (sample) =>\n      sample.page\n        ? begin(\n            sample.page.ref,\n            sample.page.point,\n            sample.page.scale ?? 1,\n            sample.page.rotation ?? 0,\n          )\n        : false,\n    onPointerMove: (sample) => {\n      const dragged = box();\n      const point = dragged && samplePointOn(sample, dragged.page);\n      if (point) move(point);\n    },\n    onPointerUp: (sample) => {\n      const dragged = box();\n      const point = dragged && samplePointOn(sample, dragged.page);\n      if (point) move(point);\n      end();\n    },\n    onPointerCancel: cancel,\n  };\n\n  // The box as a page layer draws it: the same object while the box is the same.\n  const shown = memo(\n    () => [box()] as const,\n    (current): { page: PageRef; rect: Rect } | null =>\n      current && (current.held || isBox(current))\n        ? { page: current.page, rect: rectOf(current) }\n        : null,\n  );\n\n  return {\n    api: {\n      canSnapshot,\n      // A snapshot of a page that left the document is gone with it.\n      getSnapshot: () => (held && ctx.getPage(held.page) ? held : null),\n      clearSnapshot,\n      onSnapshotChanged: changed.on,\n      getSnapshotBox: (page) => {\n        const current = shown();\n        return current && current.page.objectNumber === page.objectNumber ? current.rect : null;\n      },\n    } satisfies Partial<RenderHostCapability>,\n\n    /** Register the tool and its handler with the interaction hub, when there is one. */\n    connect(): void {\n      const interaction = ctx.tryGet(InteractionToken);\n      if (!interaction) return;\n      ctx.cleanup(\n        interaction.registerTool({\n          id: SNAPSHOT_TOOL,\n          cursor: 'crosshair',\n          touch: 'draw',\n          enables: new Set([SNAPSHOT_BOX_TAG]),\n        }),\n      );\n      ctx.cleanup(interaction.registerHandler(handler));\n      // Another tool lets the snapshot go.\n      ctx.listen(interaction.onToolChanged, ({ toolId }) => {\n        if (toolId !== SNAPSHOT_TOOL) clearSnapshot();\n      });\n    },\n  };\n}\n","import type { EngineRenderPolicy, PageImageOptions } from '@embedpdf/core';\n\nimport type { ResolvedRenderOptions } from './paint-plan';\n\n/** Encoded formats the strategy may request (the engine's own union). */\nexport type RenderFormat = NonNullable<PageImageOptions['format']>;\n\n/**\n * The render points a document actually uses — policy ∧ strategy, resolved\n * once per (policy, options) pair.\n *\n * Policy is an engine fact (what the deployment serves and caches); strategy\n * is a plugin decision (what the viewer spends, and which points it renders\n * when the engine permits anything). The one rule, applied three times:\n * a strategy value applies as written under `continuous`, and conforms to\n * the advertised lattice when there is one — so `quantize: 'exact'` or\n * `format: 'bmp'` run unchanged against cloud with no branches in client\n * code.\n *\n *   - `widths: null`  → base renders the exact settled demand, capped at\n *     `maxWidth` (the local default — resting pixels are never resampled,\n *     which is the only way ~1px text stems stay crisp on dpr-1 screens).\n *   - `widths: [...]` → base snaps up the rung list (an advertised lattice,\n *     or the opt-in client ladder), capped by `maxWidth`.\n *   - `pyramid` mirrors the same split for tile levels.\n */\nexport interface ResolvedStrategy {\n  /** Base render points; null = exact-up-to-budget. */\n  readonly widths: readonly number[] | null;\n  /** The budget: no full-page raster is ever wider (device px). */\n  readonly maxWidth: number;\n  /** Tile levels (device px per point); null = exact scale at rest. */\n  readonly pyramid: readonly number[] | null;\n  /** Tile edge in device px (policy tileSizes win when advertised). */\n  readonly tileSize: number;\n  /** Sharpness deficit above which tiles engage. Resolved default: 1.0 when\n   *  the base is exact (nothing may rest stretched), 1.25 under a lattice\n   *  (rungs make the band cheap and CSS ≤1.25× upscale reads fine). */\n  readonly engageRatio: number;\n  /** Exact-mode tile-level safety clamp (device px per point). */\n  readonly tileMaxScale: number;\n  /** Encode format for both planes, policy-conformed. Undefined = engine default. */\n  readonly format?: RenderFormat;\n  readonly quality?: number;\n}\n\nconst ascending = (values: readonly number[]): number[] =>\n  [...values].sort((left, right) => left - right);\n\n/** Rung list capped by the budget — always keeps at least the smallest rung. */\nconst capWidths = (widths: readonly number[], maxWidth: number): readonly number[] => {\n  const sorted = ascending(widths);\n  const kept = sorted.filter((width) => width <= maxWidth);\n  return kept.length ? kept : sorted.slice(0, 1);\n};\n\nexport function resolveStrategy(\n  policy: EngineRenderPolicy,\n  options: ResolvedRenderOptions,\n): ResolvedStrategy {\n  const lattice = policy.kind === 'lattice';\n\n  // An advertised ladder is the deployment's intent — the default budget\n  // never second-guesses it; an explicit maxWidth filters it (every rung is\n  // CDN-valid, so choosing lower ones is always safe — the mobile knob).\n  const widths = lattice\n    ? options.fullPage.maxWidthExplicit\n      ? capWidths(policy.fullPage.widths, options.fullPage.maxWidth)\n      : ascending(policy.fullPage.widths)\n    : options.fullPage.quantize === 'exact'\n      ? null\n      : capWidths(options.fullPage.quantize, options.fullPage.maxWidth);\n\n  // Tile levels: an advertised tiles block always wins; otherwise the client\n  // quantizer — exact on continuous by default, and the ×2 client pyramid as\n  // the fallback for lattice deployments that don't advertise tiles yet.\n  const clientPyramid =\n    options.tiles.quantize === 'exact' ? null : ascending(options.tiles.quantize);\n  const pyramid = lattice\n    ? policy.tiles?.scales\n      ? ascending(policy.tiles.scales)\n      : (clientPyramid ?? options.tiles.fallbackPyramid)\n    : clientPyramid;\n\n  const tileSize =\n    lattice && policy.tiles?.tileSizes.length\n      ? policy.tiles.tileSizes.includes(options.tiles.size)\n        ? options.tiles.size\n        : policy.tiles.tileSizes[0]!\n      : options.tiles.size;\n\n  const engageRatio = options.tiles.engageRatio ?? (widths === null ? 1.0 : 1.25);\n\n  // Format conforms like everything else: valid under this policy or the\n  // deployment's preferred one. (BMP is local-only by the wire contract.)\n  const requested = options.format;\n  const format =\n    requested === undefined\n      ? undefined\n      : !lattice || (policy.formats as readonly string[]).includes(requested)\n        ? requested\n        : policy.formats[0];\n\n  return {\n    widths,\n    maxWidth: options.fullPage.maxWidth,\n    pyramid,\n    tileSize,\n    engageRatio,\n    tileMaxScale: options.tiles.maxScale,\n    format,\n    quality: options.quality,\n  };\n}\n\n/**\n * The one base-sizing function. Its callers: the controller's\n * `conformViewport` (which `renderSource` and `getSourceKey` go through)\n * and tile engagement in the tile manager. Exact mode\n * returns the (settled) demand itself up to the budget; ladder mode snaps\n * up and caps at the top rung.\n */\nexport function baseAskWidth(strategy: ResolvedStrategy, demandWidth: number): number {\n  const wanted = Math.max(1, Math.round(demandWidth));\n  if (strategy.widths === null) return Math.min(wanted, strategy.maxWidth);\n  return (\n    strategy.widths.find((width) => width >= wanted) ?? strategy.widths[strategy.widths.length - 1]!\n  );\n}\n","import type { Rect } from '@embedpdf/core-geometry';\n\n// One owner for space math: rect intersection lives in core-geometry\n// (the stage's visibility computation uses the same helper).\nexport { intersectRects } from '@embedpdf/core-geometry';\n\n/**\n * Pure tile-grid math.\n *\n * The pyramid is aligned: one origin (the page's top-left), a fixed tile\n * size in device pixels, and ×2 scale steps. Alignment is what makes the\n * retention bookkeeping index arithmetic instead of rectangle geometry —\n * a level-s tile is covered by exactly the level-2s tiles whose indices\n * fall in its doubled range, so occlusion/release checks are O(1).\n *\n * Spaces: tile coords live on the device grid at their level's scale\n * (tileSize² device px per tile, constant per-job cost by construction);\n * paint rects and engine render targets (`target: {kind:'rect'}`) are\n * page space, y-down page points (the layer multiplies by one container\n * transform).\n */\n\nexport interface PageSizePt {\n  width: number;\n  height: number;\n}\n\nexport interface TileCoord {\n  ix: number;\n  iy: number;\n}\n\nexport interface TileGrid {\n  /** Device px per PDF point at this pyramid level. */\n  scale: number;\n  /** Tile edge in device px. */\n  tileSize: number;\n  cols: number;\n  rows: number;\n}\n\nexport function tileGrid(page: PageSizePt, scale: number, tileSize: number): TileGrid {\n  return {\n    scale,\n    tileSize,\n    cols: Math.max(1, Math.ceil((page.width * scale) / tileSize)),\n    rows: Math.max(1, Math.ceil((page.height * scale) / tileSize)),\n  };\n}\n\n/** One tile's edge in page points at its level. */\nconst tileSpanPt = (grid: TileGrid): number => grid.tileSize / grid.scale;\n\n/**\n * The tiles of `grid` intersecting a y-down page-point rect, clamped to\n * the page. An empty intersection yields an empty list.\n */\nexport function tilesInRect(grid: TileGrid, page: PageSizePt, rect: Rect): TileCoord[] {\n  const span = tileSpanPt(grid);\n  const firstColumn = Math.max(0, Math.floor(rect.x / span));\n  const firstRow = Math.max(0, Math.floor(rect.y / span));\n  const lastColumn = Math.min(grid.cols - 1, Math.ceil((rect.x + rect.width) / span) - 1);\n  const lastRow = Math.min(grid.rows - 1, Math.ceil((rect.y + rect.height) / span) - 1);\n  const coords: TileCoord[] = [];\n  for (let iy = firstRow; iy <= lastRow; iy++) {\n    for (let ix = firstColumn; ix <= lastColumn; ix++) coords.push({ ix, iy });\n  }\n  return coords;\n}\n\n/** Paint rect: y-down page points, clamped to the page edge. */\nexport function tilePaintRect(grid: TileGrid, page: PageSizePt, coord: TileCoord): Rect {\n  const span = tileSpanPt(grid);\n  const x = coord.ix * span;\n  const y = coord.iy * span;\n  return {\n    x,\n    y,\n    width: Math.min(span, page.width - x),\n    height: Math.min(span, page.height - y),\n  };\n}\n\n/**\n * Expand a paint rect by `amountPt` page points per side, clamped to the page —\n * the tile bleed. Neighboring tiles rendered with bleed overlap by twice\n * this amount, and the overlapping strips contain identical content (same\n * page region, same scale), so every img edge composites over its\n * neighbor's duplicated pixels instead of the backdrop: no AA hairlines,\n * no bilinear edge smear, at any CSS stretch.\n */\nexport function bleedRect(rect: Rect, amountPt: number, page: PageSizePt): Rect {\n  const x = Math.max(0, rect.x - amountPt);\n  const y = Math.max(0, rect.y - amountPt);\n  return {\n    x,\n    y,\n    width: Math.min(page.width, rect.x + rect.width + amountPt) - x,\n    height: Math.min(page.height, rect.y + rect.height + amountPt) - y,\n  };\n}\n\n/**\n * Does a set of painted want-level tiles cover `region` (y-down points)?\n * The retention release check: a retained source may leave the paint list\n * once its visible footprint answers true here. Pure index arithmetic on\n * the aligned grid — the whole reason the pyramid is aligned.\n */\nexport function regionCovered(\n  grid: TileGrid,\n  page: PageSizePt,\n  region: Rect,\n  isPainted: (coord: TileCoord) => boolean,\n): boolean {\n  if (region.width <= 0 || region.height <= 0) return true;\n  for (const coord of tilesInRect(grid, page, region)) {\n    if (!isPainted(coord)) return false;\n  }\n  return true;\n}\n\n/**\n * Inflate a visible rect by a prefetch margin (fractions of the rect's own\n * size per side), optionally velocity-biased: the margin stretches toward\n * the direction of travel and shrinks behind it. Pure — the producer's\n * velocity is just data.\n */\nexport function inflateRect(\n  rect: Rect,\n  margin: number,\n  velocity?: { dx: number; dy: number },\n): Rect {\n  const marginX = rect.width * margin;\n  const marginY = rect.height * margin;\n  let left = marginX;\n  let right = marginX;\n  let up = marginY;\n  let down = marginY;\n  if (velocity) {\n    // Direction buckets only — raw magnitudes would make the want set\n    // churn with every pointer sample.\n    if (velocity.dx > 0) {\n      right = marginX * 2;\n      left = marginX / 2;\n    } else if (velocity.dx < 0) {\n      left = marginX * 2;\n      right = marginX / 2;\n    }\n    if (velocity.dy > 0) {\n      down = marginY * 2;\n      up = marginY / 2;\n    } else if (velocity.dy < 0) {\n      up = marginY * 2;\n      down = marginY / 2;\n    }\n  }\n  return {\n    x: rect.x - left,\n    y: rect.y - up,\n    width: rect.width + left + right,\n    height: rect.height + up + down,\n  };\n}\n\n/** Snap up through a pyramid's sorted scales; cap at the top. */\nexport function snapToPyramid(scales: readonly number[], needed: number): number {\n  const sorted = [...scales].sort((left, right) => left - right);\n  return sorted.find((scale) => scale >= needed) ?? sorted[sorted.length - 1]!;\n}\n","import {\n  memo,\n  type EngineRenderPolicy,\n  type PageImageHandle,\n  type PageRenderLayers,\n} from '@embedpdf/core';\nimport type { Rect } from '@embedpdf/core-geometry';\n\nimport {\n  EMPTY_TILE_PLAN,\n  type PageViewDemand,\n  type ResolvedRenderOptions,\n  type TilePaintPlan,\n  type TilePaintSource,\n} from './paint-plan';\nimport { layersKeyOf } from './model';\nimport type { RasterStore } from './raster-store';\nimport { baseAskWidth, resolveStrategy } from './strategy';\nimport {\n  bleedRect,\n  inflateRect,\n  intersectRects,\n  regionCovered,\n  snapToPyramid,\n  tileGrid,\n  tilesInRect,\n  tilePaintRect,\n  type PageSizePt,\n  type TileCoord,\n  type TileGrid,\n} from './tiles';\n\n/** One state entry per view of a page (see {@link TileManager}'s `pages`). */\nconst stateKey = (view: string, pageObjectNumber: number): string =>\n  `${view}\\u0000${pageObjectNumber}`;\n\n/** Backpressure: raw rasters in flight at once (render + encode transit). */\nconst MAX_IN_FLIGHT = 8;\n/** Stage-less (no visibleRect) demand is capped to this many whole-page tiles. */\nconst STAGELESS_TILE_CAP = 64;\n\n/**\n * The tile retention state machine. One instance per plugin instance (per\n * document), all levels and pages in one place, over the same RasterStore\n * the base renders use.\n *\n * Invariant it enforces: every screen region paints the sharpest painted\n * pixels available; quality per region only goes up until the want set\n * resolves. Mechanics:\n *   - want vs paint: `plan()` queues the want set (visible tiles first,\n *     center-out, then the prefetch ring once every visible tile resolved)\n *     and returns a paint list drawn only from resolved entries: the\n *     current level and retained older generations.\n *   - one line for every view and page: a transit slot goes to an on-screen\n *     tile of any page before a tile of any prefetch ring, so a ring never\n *     takes the slots an on-screen tile needs. The engine ranks the tiles it\n *     is given by where each one is on screen.\n *   - release-on-occlusion: when a want-level tile reports painted (after the\n *     layer's first presentation opportunity), retained sources whose\n *     visible footprint is covered by painted want tiles leave the paint\n *     list. Their bytes stay in the RasterStore (demotion, not eviction), so\n *     zooming back re-promotes from cache.\n *   - epoch exception: an invalidation bump means retained pixels are\n *     wrong, so everything of the old epoch drops immediately.\n *\n * Levels come from the resolved strategy (policy ∧ options): a pyramid\n * under a lattice (or the opt-in client ladder), the exact settled scale\n * under exact mode, where the level identity is the demand's device width\n * across the page, so keys stay integer and stable. The retention/coverage\n * math is generic over any mix of retained scales.\n *\n * `plan()` never wakes readers itself: its callers do, once, when the\n * returned plan changed. Fetch kickoff is idempotent (the store\n * singleflights); resolution handlers call `onAdvance`, which re-plans the\n * page and wakes subscribed layers, and hand the freed slot on.\n */\nexport class TileManager {\n  /**\n   * Tile state is per view-of-page, never per page: a document may be shown\n   * through several lenses at once (the main view, a thumbnail rail), each\n   * calling `plan` with its own demand. One shared entry would let the\n   * rail's below-engage demand hit the disengage branch and destroy the\n   * main view's tiles on every re-plan (the sidebar opens and the main view\n   * goes blurry). Keyed by {@link stateKey}; the RasterStore underneath\n   * stays shared — bytes dedupe across views by conformed width.\n   */\n  private readonly pages = new Map<string, PageTileState>();\n  /** The resolved strategy, recomputed when the policy or the settings change. */\n  private readonly strategy = memo(\n    () => [this.deps.getPolicy(), this.deps.getOptions()] as const,\n    (policy, options) => resolveStrategy(policy, options),\n  );\n  /** Live fetches across all pages — the backpressure counter. */\n  private inFlight = 0;\n  private warnedStageless = false;\n\n  constructor(\n    private readonly deps: {\n      store: RasterStore;\n      /** The render settings as they are now: read at every use, so a change applies at once. */\n      getOptions(): ResolvedRenderOptions;\n      /** The document fact off the kernel registry — never null: the kernel\n       *  materializes it (continuous fallback) before the doc publishes. */\n      getPolicy(): EngineRenderPolicy;\n      getPageSize(pageObjectNumber: number): PageSizePt | undefined;\n      getEpoch(pageObjectNumber: number, layers: PageRenderLayers): number;\n      /** Run `run` once, `ms` from now; returns its cancel (the plugin's `ctx.clock.after`). */\n      after(ms: number, run: () => void): () => void;\n      /**\n       * Render a page-space (y-down page points) region for `view`, whose\n       * pixels it is: the engine ranks it by where the region is in that view.\n       */\n      fetchTile(\n        view: string,\n        pageObjectNumber: number,\n        rect: Rect,\n        scale: number,\n        layers: PageRenderLayers,\n        signal: AbortSignal,\n      ): Promise<PageImageHandle>;\n      /** A page's plans changed outside `plan()`: re-plan it and wake subscribed layers. */\n      onAdvance(pageObjectNumber: number): void;\n      /** Diagnostic sink — scheduling and fetch outcomes; it logs while `debug` is set. */\n      debug?(message: string): void;\n    },\n  ) {}\n\n  plan(\n    view: string,\n    pageObjectNumber: number,\n    demand: PageViewDemand,\n    layers: PageRenderLayers,\n  ): TilePaintPlan {\n    const options = this.deps.getOptions();\n    if (!options.tiles.enabled) return EMPTY_TILE_PLAN;\n    const strategy = this.strategy();\n    const page = this.deps.getPageSize(pageObjectNumber);\n    if (!page) return EMPTY_TILE_PLAN;\n\n    const epoch = this.deps.getEpoch(pageObjectNumber, layers);\n    const state = this.pageState(pageObjectNumber, view);\n\n    // Epoch exception: old-epoch pixels are wrong, not blurry — drop all.\n    if (state.epoch !== epoch) {\n      this.abortAll(state);\n      state.entries.clear();\n      state.failedKeys.clear();\n      state.epoch = epoch;\n      state.wantScale = null;\n      state.wantWidth = null;\n      state.planCache = null;\n    }\n\n    // Engagement: deficit of what the base actually supplies vs demand —\n    // the same `baseAskWidth` the base layer sizes with, so local and cloud run\n    // the identical arithmetic. Exact mode engages at 1.0 (nothing may rest\n    // stretched past the budget); a lattice tolerates its band.\n    const supplied = baseAskWidth(strategy, demand.desiredDeviceWidth);\n    const deficit = demand.desiredDeviceWidth / supplied;\n    if (deficit <= strategy.engageRatio) {\n      // Disengage drops bookkeeping immediately; resolved bytes stay in the\n      // RasterStore, so a re-engage promotes from cache — and below the\n      // threshold the base itself is crisp, so nothing visible is lost.\n      if (state.entries.size || state.wantScale !== null) {\n        this.deps.debug?.(`disengage page=${pageObjectNumber} (deficit ${deficit.toFixed(2)})`);\n        this.abortAll(state);\n        state.entries.clear();\n        state.failedKeys.clear();\n        state.wantScale = null;\n        state.wantWidth = null;\n        state.planCache = null;\n        this.pump();\n      }\n      return EMPTY_TILE_PLAN;\n    }\n\n    // Level selection. Pyramid mode snaps up the ladder; exact mode renders\n    // the demand itself (clamped by the safety cap), with the level identity\n    // being the integer device width across the page.\n    let wantWidth: number;\n    let wantScale: number;\n    if (strategy.pyramid) {\n      wantScale = snapToPyramid(strategy.pyramid, demand.desiredDeviceWidth / page.width);\n      wantWidth = Math.round(wantScale * page.width);\n    } else {\n      wantWidth = Math.min(\n        Math.max(1, Math.round(demand.desiredDeviceWidth)),\n        Math.round(strategy.tileMaxScale * page.width),\n      );\n      wantScale = wantWidth / page.width;\n    }\n\n    // Stage-less demand (no visibleRect) means the whole page tiles at the\n    // want level — unbounded at deep zoom (a 4,650% page is ~28,000 tiles).\n    // Clamp the level so the whole-page tile count stays bounded: the lens\n    // degrades to bounded sharpness instead of unbounded memory, consistent\n    // with the budget philosophy everywhere else. Hosts that want true deep\n    // zoom supply a visibleRect (the Stage does).\n    if (!demand.visibleRect) {\n      const maxStagelessWidth = Math.max(\n        strategy.tileSize,\n        Math.floor(strategy.tileSize * Math.sqrt((STAGELESS_TILE_CAP * page.width) / page.height)),\n      );\n      if (wantWidth > maxStagelessWidth) {\n        if (!this.warnedStageless) {\n          this.warnedStageless = true;\n          console.warn(\n            `[render] stage-less tile demand of ${Math.round(demand.desiredDeviceWidth)} device px ` +\n              `would tile the whole page — clamped to ${maxStagelessWidth}. Supply a visibleRect ` +\n              `(host the page in a Stage) for sharp deep zoom.`,\n          );\n        }\n        if (strategy.pyramid) {\n          const fitting = strategy.pyramid.filter(\n            (scale) => Math.round(scale * page.width) <= maxStagelessWidth,\n          );\n          wantScale = fitting.length ? fitting[fitting.length - 1]! : strategy.pyramid[0]!;\n          wantWidth = Math.round(wantScale * page.width);\n        } else {\n          wantWidth = maxStagelessWidth;\n          wantScale = wantWidth / page.width;\n        }\n      }\n    }\n    const grid = tileGrid(page, wantScale, strategy.tileSize);\n\n    const visible = demand.visibleRect ?? { x: 0, y: 0, width: page.width, height: page.height };\n    state.lastVisible = visible;\n    const visibleCoords = tilesInRect(grid, page, visible);\n    const ring = inflateRect(\n      visible,\n      options.tiles.prefetchMargin,\n      options.tiles.velocityBias ? demand.velocity : undefined,\n    );\n    const visibleKeys = new Set(visibleCoords.map((coord) => coordKey(coord)));\n    const prefetchCoords = tilesInRect(grid, page, ring).filter(\n      (coord) => !visibleKeys.has(coordKey(coord)),\n    );\n\n    this.schedule(\n      pageObjectNumber,\n      state,\n      page,\n      grid,\n      wantScale,\n      wantWidth,\n      layers,\n      epoch,\n      visibleCoords,\n      prefetchCoords,\n      visible,\n    );\n\n    // Release retained generations covered by the current painted set —\n    // evaluated here, not only on painted reports, so release can never be\n    // stranded by report ordering.\n    if (this.releaseCovered(pageObjectNumber, state, page, layers)) {\n      state.version += 1;\n      state.planCache = null;\n    }\n\n    // Paint list: resolved entries intersecting the visible rect, coarser\n    // levels first (painter's algorithm — sharper occludes per region).\n    // The memo key holds the level identity (integer width) — zoom inside a\n    // pyramid rung is plan-stable by construction; exact mode re-plans per\n    // settled level, which the schedule gate keeps rare.\n    const demandKey = `w${wantWidth}|${rectKey(visible)}|e${epoch}`;\n    if (\n      state.planCache &&\n      state.planCache.demandKey === demandKey &&\n      state.planCache.version === state.version\n    ) {\n      return state.planCache.plan;\n    }\n    const paint: TilePaintSource[] = [];\n    const fetching: string[] = [];\n    const stale: string[] = [];\n    const bleedPx = this.deps.getOptions().tiles.bleedPx;\n    for (const entry of state.entries.values()) {\n      const visiblePart = intersectRects(entry.rect, visible);\n      if (entry.resolved) {\n        if (visiblePart.width > 0 && visiblePart.height > 0) {\n          // Ownership: bytes live in the RasterStore alone; the manager\n          // holds keys. Peek resolves the handle at paint time — an entry\n          // whose bytes were evicted is simply no longer resolved (dropped\n          // here; re-fetched on the next pass if still wanted).\n          const handle = this.deps.store.peek(entry.key);\n          if (!handle) {\n            stale.push(entry.key);\n            continue;\n          }\n          paint.push({\n            key: entry.key,\n            scale: entry.scale,\n            // The placement rect is the bled one — it matches the bitmap the\n            // fetch rendered. Retention/coverage math stays on the logical\n            // (unbled) `entry.rect`; the overlap strips duplicate the\n            // neighbor's content, so painting them is what kills the seams.\n            rect: bleedPx > 0 ? bleedRect(entry.rect, bleedPx / entry.scale, page) : entry.rect,\n            z: 0, // ranked below — stacking is scale order among present entries\n            handle,\n          });\n        }\n      } else if (entry.scale === wantScale) {\n        fetching.push(entry.key);\n      }\n    }\n    for (const key of stale) state.entries.delete(key);\n    // Stacking: rank the scales actually present (generic over exact levels\n    // and pyramid rungs alike) — coarse under fine.\n    const rank = new Map<number, number>();\n    const scales = [...new Set(paint.map((source) => source.scale))];\n    for (const scale of scales.sort((left, right) => left - right)) rank.set(scale, rank.size);\n    for (const source of paint) source.z = rank.get(source.scale)!;\n    paint.sort((left, right) => left.z - right.z || left.key.localeCompare(right.key));\n    const plan: TilePaintPlan = {\n      engaged: true,\n      paint,\n      fetching: fetching.sort(),\n      stamp: `${demandKey}|v${state.version}`,\n    };\n    state.planCache = { demandKey, version: state.version, plan };\n    return plan;\n  }\n\n  /** The layer's painted report: this key's pixels had a presentation opportunity. */\n  sourcePainted(view: string, pageObjectNumber: number, key: string): void {\n    const state = this.pages.get(stateKey(view, pageObjectNumber));\n    const entry = state?.entries.get(key);\n    if (!state || !entry || entry.painted) return;\n    entry.painted = true;\n    const page = this.deps.getPageSize(pageObjectNumber);\n    if (page) this.releaseCovered(pageObjectNumber, state, page, layersOfKey(key));\n    state.version += 1;\n    state.planCache = null;\n    this.deps.onAdvance(pageObjectNumber);\n  }\n\n  /**\n   * The inverse report: this key's <img> left the DOM (pan-away, plan drop),\n   * so its pixels are not currently compositable. Without this, a tile that\n   * unmounts and later remounts is still counted as painted while its new\n   * <img> re-decodes — and an adjacent fresh `sourcePainted` could release\n   * retained coarse coverage over a region that momentarily has no sharp\n   * pixels. Painted is a statement about the screen, so it follows the DOM.\n   */\n  sourceUnpainted(view: string, pageObjectNumber: number, key: string): void {\n    const entry = this.pages.get(stateKey(view, pageObjectNumber))?.entries.get(key);\n    if (entry) entry.painted = false;\n  }\n\n  /** A lens stopped painting tiles for the page (it left the view, or its\n   *  layer paints none): stop fetching, drop bookkeeping. Resolved bytes stay\n   *  in the RasterStore for a re-mount. */\n  releasePage(view: string, pageObjectNumber: number): void {\n    const state = this.pages.get(stateKey(view, pageObjectNumber));\n    if (!state) return;\n    this.abortAll(state);\n    this.pages.delete(stateKey(view, pageObjectNumber));\n    this.pump();\n  }\n\n  private pageState(pageObjectNumber: number, view: string): PageTileState {\n    let state = this.pages.get(stateKey(view, pageObjectNumber));\n    if (!state) {\n      state = {\n        view,\n        pageObjectNumber,\n        queue: null,\n        epoch: -1,\n        wantScale: null,\n        wantWidth: null,\n        entries: new Map(),\n        failedKeys: new Set(),\n        version: 0,\n        planCache: null,\n        cancelSettle: null,\n        pendingLevel: null,\n        lastVisible: null,\n      };\n      this.pages.set(stateKey(view, pageObjectNumber), state);\n    }\n    return state;\n  }\n\n  private schedule(\n    pageObjectNumber: number,\n    state: PageTileState,\n    page: PageSizePt,\n    grid: TileGrid,\n    wantScale: number,\n    wantWidth: number,\n    layers: PageRenderLayers,\n    epoch: number,\n    visibleCoords: TileCoord[],\n    prefetchCoords: TileCoord[],\n    visible: Rect,\n  ): void {\n    const options = this.deps.getOptions();\n    const firstEngage = state.wantWidth === null;\n    const levelChanged = state.wantWidth !== null && state.wantWidth !== wantWidth;\n    if (levelChanged) state.failedKeys.clear(); // a new level gets fresh chances\n    state.wantScale = wantScale;\n    state.wantWidth = wantWidth;\n\n    // Entries follow the want set. In-flight fetches that left it abort;\n    // resolved same-level tiles that left it are dropped — their bytes stay\n    // in the RasterStore's LRU, so a pan-back re-promotes from cache\n    // instead of re-rendering. Only cross-level retained entries stay, and\n    // those are the release rules' business. Without this, panning at deep\n    // zoom accumulates every tile ever visited.\n    const keyOf = (coord: TileCoord) =>\n      this.tileKey(pageObjectNumber, wantWidth, coord, layers, epoch);\n    const wanted = new Set([...visibleCoords, ...prefetchCoords].map(keyOf));\n    for (const [key, entry] of state.entries) {\n      if (wanted.has(key)) continue;\n      if (!entry.resolved) {\n        entry.abort?.abort();\n        // The transit slot frees now, synchronously — the rejection handler\n        // runs a microtask later, and fetches started in this plan must see\n        // the freed capacity.\n        this.releaseSlot(entry);\n        state.entries.delete(key);\n      } else if (entry.scale === wantScale) {\n        state.entries.delete(key);\n      }\n    }\n\n    // Center-out: the region under the user's gesture sharpens first.\n    const centerX = visible.x + visible.width / 2;\n    const centerY = visible.y + visible.height / 2;\n    const span = grid.tileSize / grid.scale;\n    const distanceToCenter = (coord: TileCoord): number => {\n      const dx = (coord.ix + 0.5) * span - centerX;\n      const dy = (coord.iy + 0.5) * span - centerY;\n      return dx * dx + dy * dy;\n    };\n    const orderedVisible = [...visibleCoords].sort(\n      (left, right) => distanceToCenter(left) - distanceToCenter(right),\n    );\n\n    const kickoff = () => {\n      // The prefetch ring strictly after the visible tiles: prefetch never\n      // competes with on-screen tiles. A tile that failed at this level counts\n      // as done; the base shows through its hole.\n      const allVisibleReady = orderedVisible.every((coord) => {\n        const key = keyOf(coord);\n        return state.failedKeys.has(key) || state.entries.get(key)?.resolved === true;\n      });\n      state.queue = {\n        coords: allVisibleReady ? [...orderedVisible, ...prefetchCoords] : orderedVisible,\n        ringFrom: orderedVisible.length,\n        next: 0,\n        page,\n        grid,\n        wantWidth,\n        layers,\n        epoch,\n      };\n      this.pump();\n    };\n\n    // Level-change settle: a zoom in motion shouldn't fetch each\n    // intermediate level (under exact mode every gesture frame is a new\n    // level — this gate is what makes exact affordable). First engagement\n    // fires immediately — there's nothing on screen above the base yet.\n    if (levelChanged && options.tiles.settleMs > 0) {\n      this.deps.debug?.(`arm settle page=${pageObjectNumber} level=${wantWidth}`);\n      // Nothing of the old level starts meanwhile.\n      state.queue = null;\n      state.pendingLevel = wantWidth;\n      state.cancelSettle?.();\n      state.cancelSettle = this.deps.after(options.tiles.settleMs, () => {\n        state.cancelSettle = null;\n        this.deps.debug?.(\n          `settle fired page=${pageObjectNumber} level=${wantWidth} ` +\n            `current=${state.pendingLevel === wantWidth}`,\n        );\n        if (state.pendingLevel === wantWidth) kickoff();\n      });\n      return;\n    }\n    if (state.cancelSettle !== null && !levelChanged && !firstEngage) {\n      // Same level again before the timer fired — the zoom came back;\n      // cancel the pending level fetch.\n      state.cancelSettle();\n      state.cancelSettle = null;\n      state.pendingLevel = null;\n    }\n    kickoff();\n  }\n\n  /**\n   * Starts queued tiles while transit slots are free: the first on-screen\n   * tile of any view and page, in the order their queues were set, before\n   * any tile of a prefetch ring. Within one view of a page, its queue's order\n   * holds. Backpressure bounds raw rasters in transit (render + encode); each\n   * resolution hands its slot on through here, so no other pump is needed.\n   */\n  private pump(): void {\n    const started = new Map<PageTileState, number>();\n    while (this.inFlight < MAX_IN_FLIGHT) {\n      let next: { state: PageTileState; coord: TileCoord } | null = null;\n      for (const state of this.pages.values()) {\n        const queued = this.nextToStart(state);\n        if (!queued || (next && queued.prefetch)) continue;\n        next = { state, coord: queued.coord };\n        if (!queued.prefetch) break;\n      }\n      if (!next) break;\n      this.start(next.state, next.coord);\n      started.set(next.state, (started.get(next.state) ?? 0) + 1);\n    }\n    for (const [state, count] of started) {\n      this.deps.debug?.(\n        `fetch page=${state.pageObjectNumber} level=${state.queue?.wantWidth} +${count} tiles`,\n      );\n    }\n  }\n\n  /** The first tile of the state's queue not started yet, nor failed at this level. */\n  private nextToStart(state: PageTileState): { coord: TileCoord; prefetch: boolean } | null {\n    const queue = state.queue;\n    if (!queue) return null;\n    for (; queue.next < queue.coords.length; queue.next += 1) {\n      const coord = queue.coords[queue.next]!;\n      const key = this.tileKey(\n        state.pageObjectNumber,\n        queue.wantWidth,\n        coord,\n        queue.layers,\n        queue.epoch,\n      );\n      // A key that failed (non-abort) at this level is not retried until the\n      // level or epoch changes — retrying every plan would loop on a\n      // permanent error. The base shows through the hole; degraded, honest.\n      if (state.failedKeys.has(key) || state.entries.has(key)) continue;\n      return { coord, prefetch: queue.next >= queue.ringFrom };\n    }\n    return null;\n  }\n\n  /** Starts one queued tile's fetch, in a transit slot. */\n  private start(state: PageTileState, coord: TileCoord): void {\n    const { page, grid, wantWidth, layers, epoch } = state.queue!;\n    const pageObjectNumber = state.pageObjectNumber;\n    const key = this.tileKey(pageObjectNumber, wantWidth, coord, layers, epoch);\n    const bleedPt = this.deps.getOptions().tiles.bleedPx / grid.scale;\n    this.inFlight += 1;\n    const abort = new AbortController();\n    const logical = tilePaintRect(grid, page, coord);\n    const entry: TileEntry = {\n      key,\n      scale: grid.scale,\n      coord,\n      rect: logical,\n      resolved: false,\n      painted: false,\n      charged: true,\n      abort,\n    };\n    state.entries.set(key, entry);\n    // The cached plan's `fetching` misses this tile now.\n    state.planCache = null;\n    this.deps.store\n      .acquire(\n        key,\n        (signal) =>\n          this.deps.fetchTile(\n            state.view,\n            pageObjectNumber,\n            // The rendered region is the bled rect — it matches the bled\n            // placement rect the paint list emits for this entry.\n            bleedPt > 0 ? bleedRect(logical, bleedPt, page) : logical,\n            grid.scale,\n            layers,\n            signal,\n          ),\n        abort.signal,\n      )\n      .then(\n        () => {\n          this.releaseSlot(entry);\n          // Unless aborted or superseded meanwhile. The handle stays in the\n          // store (single ownership) — the paint list peeks it back out;\n          // this entry just records success.\n          if (state.entries.get(key) === entry) {\n            entry.resolved = true;\n            state.version += 1;\n            state.planCache = null;\n            this.deps.onAdvance(pageObjectNumber);\n          }\n          this.pump();\n        },\n        (error) => {\n          this.releaseSlot(entry);\n          // Our own abort (pan-away, level change) is expected silence. A\n          // real failure marks the key and wakes the layers: the paint plan\n          // recomputes so the rest of the want set keeps making progress\n          // instead of waiting on a resolution that never comes.\n          if (state.entries.get(key) === entry) {\n            state.entries.delete(key);\n            if (!abort.signal.aborted) {\n              state.failedKeys.add(key);\n              this.deps.debug?.(`tile failed ${key}: ${String(error)}`);\n              state.version += 1;\n              state.planCache = null;\n              this.deps.onAdvance(pageObjectNumber);\n            }\n          }\n          this.pump();\n        },\n      );\n  }\n\n  /**\n   * The release rule, evaluated as a pure function of the current painted\n   * set: retained sources (any non-want level) whose visible footprint is\n   * covered by painted want-level tiles leave the paint list. Runs on every\n   * `plan()` and on every painted report — never only \"against the tile\n   * that just painted\": release must not depend on paint order (center-out\n   * scheduling means the report that completes a retained tile's coverage\n   * routinely lands far away from it), and re-evaluating from current state\n   * also self-heals any painted-flag transition the reports raced past.\n   * Coverage is index arithmetic over the want grid — generic over whatever\n   * mix of retained scales exists (exact levels included).\n   */\n  private releaseCovered(\n    pageObjectNumber: number,\n    state: PageTileState,\n    page: PageSizePt,\n    layers: PageRenderLayers,\n  ): boolean {\n    const { wantScale, wantWidth } = state;\n    if (wantScale === null || wantWidth === null) return false;\n    const grid = tileGrid(page, wantScale, this.strategy().tileSize);\n    const wantKeyOf = (coord: TileCoord) =>\n      this.tileKey(pageObjectNumber, wantWidth, coord, layers, state.epoch);\n    const paintedAt = (coord: TileCoord) => state.entries.get(wantKeyOf(coord))?.painted === true;\n    let released = false;\n    for (const [key, entry] of state.entries) {\n      if (entry.scale === wantScale || !entry.resolved) continue;\n      // Visible footprint only: an edge parent whose offscreen children\n      // were never fetched must still release once its on-screen region is\n      // covered, and its bytes stay in the store, so a pan that re-exposes\n      // the rest re-promotes from cache.\n      const region = state.lastVisible ? intersectRects(entry.rect, state.lastVisible) : entry.rect;\n      if (regionCovered(grid, page, region, paintedAt)) {\n        state.entries.delete(key);\n        released = true;\n      } else if (this.deps.debug && this.deps.getOptions().debug) {\n        const missing = tilesInRect(grid, page, region).filter((coord) => !paintedAt(coord));\n        const detail = missing.slice(0, 3).map((coord) => {\n          const missingEntry = state.entries.get(wantKeyOf(coord));\n          const status = !missingEntry\n            ? 'NO-ENTRY'\n            : !missingEntry.resolved\n              ? 'PENDING'\n              : 'RESOLVED-unpainted';\n          return `${coord.ix},${coord.iy}=${status}`;\n        });\n        this.deps.debug(\n          `retained ${key} blocked by: ${detail.join(' ')} (${missing.length} missing)`,\n        );\n      }\n    }\n    return released;\n  }\n\n  /** Test/diagnostic introspection: bookkeeping size for one page. */\n  stats(view: string, pageObjectNumber: number): { entries: number; inFlight: number } {\n    return {\n      entries: this.pages.get(stateKey(view, pageObjectNumber))?.entries.size ?? 0,\n      inFlight: this.inFlight,\n    };\n  }\n\n  /** Idempotent transit-slot release — the one place inFlight decrements. */\n  private releaseSlot(entry: TileEntry): void {\n    if (!entry.charged) return;\n    entry.charged = false;\n    this.inFlight -= 1;\n  }\n\n  private abortAll(state: PageTileState): void {\n    state.queue = null;\n    state.cancelSettle?.();\n    state.cancelSettle = null;\n    for (const entry of state.entries.values()) {\n      if (!entry.resolved) {\n        entry.abort?.abort();\n        this.releaseSlot(entry);\n      }\n    }\n  }\n\n  /** Level identity is the integer device width across the page — integer\n   *  and stable for pyramid rungs and exact levels alike. The key also\n   *  carries everything that determines the fetched bitmap for a coord\n   *  (tile size, bleed, encode format): a raster's identity must include\n   *  its geometry, or a cached handle from one configuration could be\n   *  stretched into another's rect. Format genuinely varies at runtime —\n   *  the cloud policy arrives async after open and can change the resolved\n   *  format under a live store. */\n  private tileKey(\n    pageObjectNumber: number,\n    levelWidth: number,\n    coord: TileCoord,\n    layers: PageRenderLayers,\n    epoch: number,\n  ): string {\n    const { tiles } = this.deps.getOptions();\n    const format = this.strategy().format;\n    const geometry = `g${tiles.size}.${tiles.bleedPx}${format ? `.${format}` : ''}`;\n    return (\n      `t:${pageObjectNumber}|w${levelWidth}|${coord.ix},${coord.iy}` +\n      `|${layersKeyOf(layers)}|e${epoch}|${geometry}`\n    );\n  }\n}\n\ninterface TileEntry {\n  key: string;\n  scale: number;\n  coord: TileCoord;\n  /** y-down page points. */\n  rect: Rect;\n  /** Fetch completed — the bytes live in the RasterStore (peeked at paint\n   *  time), never here: single ownership is what makes the store's budget\n   *  the actual bound on residency. */\n  resolved: boolean;\n  painted: boolean;\n  /** Holds an in-flight transit slot (see releaseSlot — idempotent). */\n  charged?: boolean;\n  abort?: AbortController;\n}\n\n/** The tiles one view of a page wants started, in order, with what starting one needs. */\ninterface TileQueue {\n  /** Visible tiles center-out, then the prefetch ring once every visible tile resolved. */\n  coords: TileCoord[];\n  /** Where the ring starts in `coords`. */\n  ringFrom: number;\n  /** Where the pump looks next: every coord before it is started or failed. */\n  next: number;\n  page: PageSizePt;\n  grid: TileGrid;\n  wantWidth: number;\n  layers: PageRenderLayers;\n  epoch: number;\n}\n\ninterface PageTileState {\n  view: string;\n  pageObjectNumber: number;\n  /** What the pump starts for this view of the page; null while nothing should start. */\n  queue: TileQueue | null;\n  epoch: number;\n  wantScale: number | null;\n  /** The want level's identity: integer device px across the page. */\n  wantWidth: number | null;\n  entries: Map<string, TileEntry>;\n  /** Keys that failed (non-abort) at the current level — not retried until\n   *  the level or epoch changes. */\n  failedKeys: Set<string>;\n  /** Bumped on ready/painted/drop; part of the paint-plan memo key. */\n  version: number;\n  planCache: { demandKey: string; version: number; plan: TilePaintPlan } | null;\n  /** Cancels the level-change settle wait while it runs. */\n  cancelSettle: (() => void) | null;\n  /** Pending level identity (wantWidth) while the settle gate runs. */\n  pendingLevel: number | null;\n  /** Last visible rect from plan() — the release rule's \"on screen\". */\n  lastVisible: Rect | null;\n}\n\nconst coordKey = (coord: TileCoord): string => `${coord.ix},${coord.iy}`;\nconst rectKey = (rect: Rect): string =>\n  `${Math.round(rect.x)},${Math.round(rect.y)},${Math.round(rect.width)},${Math.round(rect.height)}`;\n\n/** What a tile key's picture draws, as {@link layersKeyOf} wrote it into the key. */\nconst layersOfKey = (key: string): PageRenderLayers => {\n  const drawn = /\\|a([01])f([01])\\|/.exec(key);\n  return { includeAnnotations: drawn?.[1] === '1', includeFormFields: drawn?.[2] === '1' };\n};\n","import {\n  annotationKey,\n  CONTINUOUS_RENDER_POLICY,\n  isPluginError,\n  PluginError,\n  memo,\n  resolvePageLayers,\n  snapAppearanceScale,\n  toPageRef,\n  toPluginError,\n  toPluginErrorInfo,\n  type BatchResult,\n  type EventOrigin,\n  type PluginContext,\n  type DocCapability,\n  type EngineRenderPolicy,\n  type PageImageHandle,\n  type PageLayerRights,\n  type PageObjectNumber,\n  type PageRef,\n  type PageRenderLayers,\n  type PageRenderViewport,\n  type PluginErrorInfo,\n} from '@embedpdf/core';\nimport { intersectRects, type Rect } from '@embedpdf/core-geometry';\nimport { AppearanceStore, RecentPictures } from './appearance-store';\nimport type {\n  InvalidateOptions,\n  InvalidateScope,\n  PageLayerOptions,\n  PageRender,\n  PictureStateChangedEvent,\n  RenderFormat,\n  RenderInvalidatedEvent,\n  RenderPageOptions,\n  RenderPagesOptions,\n  RenderSettings,\n  PicturePainter,\n  RenderThumbnailOptions,\n} from './contract';\nimport type {\n  AppearancePicture,\n  AppearancesOptions,\n  PaintSettings,\n  RenderCompletedEvent,\n  RenderFailedEvent,\n  RenderHostCapability,\n  RenderSourceOptions,\n  ViewDemand,\n} from './host-contract';\nimport { pixelChangeOf } from './invalidation';\nimport { invalidatePages, layersKeyOf, renderEpochOf, type RenderState } from './model';\nimport {\n  EMPTY_TILE_PLAN,\n  resolveRenderOptions,\n  type PageViewDemand,\n  type ResolvedRenderOptions,\n  type TilePaintPlan,\n} from './paint-plan';\nimport { createPictureReports, PICTURE_STATES } from './pictures';\nimport { RasterStore } from './raster-store';\nimport { createSnapshots } from './snapshot';\nimport { baseAskWidth, resolveStrategy, type ResolvedStrategy } from './strategy';\nimport { TileManager } from './tile-manager';\n\nconst RENDER_SCOPE: DocCapability = 'doc.render';\nconst THUMBNAIL_SCOPE: DocCapability = 'doc.render.thumbnail';\nconst FORMS_SCOPE: DocCapability = 'doc.forms.read';\nconst ANNOTATIONS_SCOPE: DocCapability = 'doc.annotate.read';\n\n/** Every answer `getLayerRights()` gives, one object each, so the same rights are the same object. */\nconst LAYER_RIGHTS: readonly (readonly PageLayerRights[])[] = [false, true].map((annotations) =>\n  [false, true].map((formFields) => Object.freeze({ annotations, formFields })),\n);\n/** An abort reason the engine task accepts (signals carry `unknown`). */\nconst reasonOf = (signal: AbortSignal): string | undefined =>\n  typeof signal.reason === 'string' ? signal.reason : undefined;\nconst DEFAULT_BATCH_CONCURRENCY = 4;\n\n/** A view's live demand for one page, as last set through its handle. */\ninterface PageDemand {\n  demand: PageViewDemand;\n  layers: PageRenderLayers;\n  plan: TilePaintPlan;\n}\n\n/**\n * The render controller: the one place strategy (config: what the viewer\n * spends) composes with policy (the engine fact: what the deployment\n * serves). The engine never snaps and layers never see either; everything\n * between happens here: conforming demand to the resolved render points,\n * collapsing same-key asks in the raster store, exposing stable source keys,\n * and turning a view's demand into a retention-safe tile plan.\n *\n * Two doors for rasters: `renderPage` (public, exact size) and\n * `renderSource` (host, conformed). Both share the raster store, so a\n * developer's thumbnail and the rail's base plane never render twice.\n *\n * Every render it asks for is the picture of a page itself, so it asks the\n * engine with `priority: 'high'`, naming the view it's for when it knows it:\n * the engine runs it before anything else about the same place (annotation\n * appearances, form fields, text geometry, links).\n *\n * Two doors for staleness: confirmed document events (see `connect`) and\n * the `invalidate` verb. Both go through `publishInvalidation`, the one\n * place the ledger bumps and `onInvalidated` fires.\n *\n * The tile manager and the per-view plans live outside state (they hold\n * live handles and abort controllers); a re-plan wakes readers with\n * `ctx.notify()`.\n */\nexport function createRenderController(ctx: PluginContext<RenderState, RenderSettings>) {\n  const settings = ctx.settings();\n  // The settings as the strategy reads them, resolved again when they change.\n  const resolvedOptions: () => ResolvedRenderOptions = memo(\n    () => [settings.get()] as const,\n    (current) => resolveRenderOptions(current),\n  );\n  const store = new RasterStore();\n  const appearances = new AppearanceStore<AppearancePicture>();\n  const recentAppearances = new RecentPictures<AppearancePicture>();\n  const invalidated = ctx.events.source<RenderInvalidatedEvent>();\n  const renderCompleted = ctx.events.source<RenderCompletedEvent>();\n  const renderFailed = ctx.events.source<RenderFailedEvent>();\n  const pictureStateChanged = ctx.events.source<PictureStateChangedEvent>();\n  const pictures = createPictureReports(ctx, pictureStateChanged.emit);\n\n  const canRender = (): boolean => ctx.allows(RENDER_SCOPE);\n  const canRenderThumbnail = (): boolean => ctx.allows(THUMBNAIL_SCOPE);\n\n  // ── another plugin painting the pictures ──\n  // Kept out of state (a painter is behaviour, not data); `notify` tells the\n  // page layers, which read it through the capability.\n  let picturePainter: PicturePainter | null = null;\n  const handOverPictures = <Host>(painter: PicturePainter<Host>): (() => void) => {\n    if (picturePainter) {\n      throw new PluginError('conflict', 'render', 'another plugin paints the pictures already');\n    }\n    const held = painter as PicturePainter;\n    picturePainter = held;\n    ctx.notify();\n    let givenBack = false;\n    return () => {\n      if (givenBack) return;\n      givenBack = true;\n      if (picturePainter !== held) return;\n      picturePainter = null;\n      ctx.notify();\n    };\n  };\n\n  // ── what a picture draws ──\n  // The engine's rule (`resolvePageLayers`): each option as given, and one\n  // left out draws what the session may read. The doors refuse an explicit\n  // `true` the session may not read, as the engine would; reads (keys,\n  // epochs, plans) never throw, and count such an option as left out.\n  const rights = (): PageLayerRights =>\n    LAYER_RIGHTS[ctx.allows('doc.annotate.read') ? 1 : 0]![ctx.allows('doc.forms.read') ? 1 : 0]!;\n  const layersOf = (options: PageLayerOptions): PageRenderLayers => {\n    const may = rights();\n    return resolvePageLayers(\n      {\n        ...(options.includeAnnotations !== undefined &&\n        (may.annotations || !options.includeAnnotations)\n          ? { includeAnnotations: options.includeAnnotations }\n          : {}),\n        ...(options.includeFormFields !== undefined &&\n        (may.formFields || !options.includeFormFields)\n          ? { includeFormFields: options.includeFormFields }\n          : {}),\n      },\n      may,\n    );\n  };\n  const pictureLayers = (options: PageLayerOptions, operation: string): PageRenderLayers => {\n    if (options.includeAnnotations === true) ctx.assertAllowed('doc.annotate.read', operation);\n    if (options.includeFormFields === true) ctx.assertAllowed(FORMS_SCOPE, operation);\n    return layersOf(options);\n  };\n\n  // One-shot developer hints: misconfigurations, not errors.\n  let warnedFormat = false;\n  const warnDroppedFormat = (strategy: ResolvedStrategy, requested: RenderFormat | undefined) => {\n    if (warnedFormat || requested === undefined || strategy.format === requested) return;\n    warnedFormat = true;\n    console.warn(\n      `[render] format '${requested}' is not in the deployment's formats — using '${strategy.format}'.`,\n    );\n  };\n  let warnedBudget = false;\n  const warnPastBudgetNoTiles = (demandWidth: number, supplied: number) => {\n    if (warnedBudget || resolvedOptions().tiles.enabled || demandWidth <= supplied * 2) return;\n    warnedBudget = true;\n    console.warn(\n      `[render] demand is ${(demandWidth / supplied).toFixed(1)}× over the base budget and the ` +\n        `tile plane is disabled (tiles: false) — the page rests blurry. Raise fullPage.maxWidth ` +\n        `or re-enable tiles.`,\n    );\n  };\n\n  // ── strategy ∧ policy ──\n  // The policy is a document fact on the kernel's registry, materialized\n  // before publish. Composed with the strategy once per policy reference.\n  const renderPolicy = (): EngineRenderPolicy =>\n    ctx.document()?.renderPolicy ?? CONTINUOUS_RENDER_POLICY;\n  const currentStrategy = memo(\n    () => [renderPolicy(), resolvedOptions()] as const,\n    (policy, options) => {\n      const strategy = resolveStrategy(policy, options);\n      warnDroppedFormat(strategy, options.format);\n      return strategy;\n    },\n  );\n\n  // ── pages ──\n  const pageWidthOf = (page: PageRef): number => {\n    const info = ctx.getPage(page);\n    if (!info) ctx.assertPageRef(page); // throws not-found\n    return info!.size.width;\n  };\n  const allPageObjectNumbers = (): PageObjectNumber[] =>\n    (ctx.document()?.pages ?? []).map((info) => info.ref.objectNumber);\n\n  /**\n   * A page a change on its way makes (a blank insert, a copy, an undone\n   * delete) is in the page list before the engine has it. Until it lands\n   * nothing asks the engine for its pictures: a blank page shows its\n   * background, a page coming back the pictures still kept under its keys,\n   * and a copy the pictures of the page it copies.\n   */\n  const isPending = (page: PageRef): boolean =>\n    ctx.document()?.pendingPages.has(page.objectNumber) ?? false;\n  /** The page a pending copy copies; null for any other page. */\n  const copiedFrom = (page: PageRef): PageRef | null => {\n    const pending = ctx.document()?.pendingPages.get(page.objectNumber);\n    return pending?.kind === 'copy' ? pending.of : null;\n  };\n  /** Resolves once the engine has a pending page; rejects `not-found` when it went first. */\n  const whenHeld = async (page: PageRef, signal: AbortSignal | undefined): Promise<void> => {\n    await ctx.waitFor(() => !isPending(page), signal ? { signal } : undefined);\n    if (!ctx.getPage(page)) ctx.assertPageRef(page);\n  };\n\n  // The one base-sizing path: renderSource, getSourceKey, conformViewport,\n  // and (through the tile manager) engagement all go through baseAskWidth.\n  const conformViewport = (page: PageRef, scale: number): PageRenderViewport => {\n    const demandWidth = scale * pageWidthOf(page);\n    const width = baseAskWidth(currentStrategy(), demandWidth);\n    warnPastBudgetNoTiles(demandWidth, width);\n    return { kind: 'width', width };\n  };\n\n  const epochOf = (pageObjectNumber: PageObjectNumber, layers: PageRenderLayers): number =>\n    renderEpochOf(ctx.state.get(), pageObjectNumber, layers);\n\n  // A raster's identity includes its encode format: the cloud policy arrives\n  // asynchronously after open, so the resolved format can change under a\n  // live store, and the key must change with it. An absent format (the\n  // engine default) adds nothing.\n  const rasterKey = (\n    pageObjectNumber: PageObjectNumber,\n    width: number,\n    layers: PageRenderLayers,\n    format: RenderFormat | undefined,\n    quality: number | undefined,\n  ): string =>\n    `${pageObjectNumber}|w${width}|${layersKeyOf(layers)}|e${epochOf(pageObjectNumber, layers)}` +\n    `${format ? `|f${format}` : ''}${quality !== undefined ? `|q${quality}` : ''}`;\n  // A thumbnail is one picture per page, whatever the screen asks: its key\n  // has no width.\n  const thumbnailKey = (\n    pageObjectNumber: PageObjectNumber,\n    layers: PageRenderLayers,\n    format: RenderFormat | undefined,\n    quality: number | undefined,\n  ): string =>\n    `${pageObjectNumber}|thumbnail|${layersKeyOf(layers)}|e${epochOf(pageObjectNumber, layers)}` +\n    `${format ? `|f${format}` : ''}${quality !== undefined ? `|q${quality}` : ''}`;\n\n  // ── the raster store door (shared by both render doors and the tiles) ──\n  function acquireRaster(\n    page: PageRef,\n    key: string,\n    request: {\n      viewport: PageRenderViewport;\n      layers: PageRenderLayers;\n      format: RenderFormat | undefined;\n      quality: number | undefined;\n      /** The view whose picture it is, so the engine ranks it by where the page is there. */\n      view: string | undefined;\n    },\n    signal: AbortSignal | undefined,\n  ): Promise<PageImageHandle> {\n    const result = store.acquire(\n      key,\n      (storeSignal) => {\n        const draw = (drawn: PageRef): Promise<PageImageHandle> => {\n          const doc = ctx.doc.with({\n            priority: 'high',\n            ...(request.view !== undefined ? { view: request.view } : {}),\n          });\n          const task = doc.page(drawn).render.image({\n            viewport: request.viewport,\n            ...request.layers,\n            ...(request.format !== undefined ? { format: request.format } : {}),\n            ...(request.quality !== undefined ? { quality: request.quality } : {}),\n          });\n          if (storeSignal.aborted) task.abort(reasonOf(storeSignal));\n          else\n            storeSignal.addEventListener('abort', () => task.abort(reasonOf(storeSignal)), {\n              once: true,\n            });\n          return task; // AbortablePromise<PageImageHandle> is a Promise<PageImageHandle>\n        };\n        const drawnWhenHeld = (drawn: PageRef) =>\n          isPending(drawn) ? whenHeld(drawn, storeSignal).then(() => draw(drawn)) : draw(drawn);\n        // A copy draws as the page it copies, which the engine may not have yet either.\n        return drawnWhenHeld(copiedFrom(page) ?? page);\n      },\n      signal,\n    );\n    return result.then(\n      (image) => {\n        renderCompleted.emit({ page, key });\n        return image;\n      },\n      (error: unknown) => {\n        const mapped = toPluginError('render', error);\n        if (\n          !isPluginError(mapped, 'operation-cancelled') &&\n          !isPluginError(mapped, 'instance-closed')\n        ) {\n          renderFailed.emit({ page, key, error: toPluginErrorInfo(mapped) });\n        }\n        throw mapped;\n      },\n    );\n  }\n\n  /** The host door: conformed to the render points. Async so refusals reject. */\n  async function renderSource(\n    page: PageRef,\n    { scale, view, signal, thumbnail, ...options }: RenderSourceOptions & { signal?: AbortSignal },\n  ): Promise<PageImageHandle> {\n    if (thumbnail) return thumbnailOf(page, { ...options, view, signal }, 'render.renderSource');\n    ctx.assertAllowed(RENDER_SCOPE, 'render.renderSource');\n    const layers = pictureLayers(options, 'render.renderSource');\n    const viewport = conformViewport(page, scale);\n    const strategy = currentStrategy();\n    const key = rasterKey(\n      page.objectNumber,\n      viewport.kind === 'width' ? viewport.width : 0,\n      layers,\n      strategy.format,\n      undefined,\n    );\n    return acquireRaster(\n      page,\n      key,\n      {\n        viewport,\n        layers,\n        format: strategy.format,\n        quality: strategy.quality,\n        view,\n      },\n      signal,\n    );\n  }\n\n  /**\n   * A picture of part of a page, or a turned one, for its caller alone: no\n   * layer asks for it, so it skips the store. The rect is cut at the page's\n   * edge, and the size is the caller's, as the engine takes it.\n   */\n  function renderPart(\n    page: PageRef,\n    pageSize: { width: number; height: number },\n    options: RenderPageOptions,\n    layers: PageRenderLayers,\n    format: RenderFormat | undefined,\n    quality: number | undefined,\n  ): Promise<PageImageHandle> {\n    const rect = options.rect && intersectRects(options.rect, { x: 0, y: 0, ...pageSize });\n    if (rect && !(rect.width > 0 && rect.height > 0)) {\n      throw new PluginError('invalid-input', 'render', 'the rect misses the page', {\n        details: { field: 'rect' },\n      });\n    }\n    const signal = options.signal;\n    const draw = (drawn: PageRef): Promise<PageImageHandle> => {\n      const task = ctx.doc\n        .with({ priority: 'high' })\n        .page(drawn)\n        .render.image({\n          ...(rect ? { target: { kind: 'rect' as const, rect } } : {}),\n          viewport:\n            options.width !== undefined\n              ? { kind: 'width', width: Math.max(1, Math.round(options.width)) }\n              : { kind: 'scale', scale: options.scale ?? 1 },\n          ...(options.rotation ? { rotation: options.rotation } : {}),\n          ...layers,\n          ...(format !== undefined ? { format } : {}),\n          ...(quality !== undefined ? { quality } : {}),\n        });\n      if (signal?.aborted) task.abort(reasonOf(signal));\n      else signal?.addEventListener('abort', () => task.abort(reasonOf(signal)), { once: true });\n      return task;\n    };\n    // A copy draws as the page it copies, which the engine may not have yet either.\n    const drawn = copiedFrom(page) ?? page;\n    return isPending(drawn) ? whenHeld(drawn, signal).then(() => draw(drawn)) : draw(drawn);\n  }\n\n  /** The public door: the requested size, exactly. Async so refusals reject. */\n  async function renderPage(\n    pageArgument: PageRef | number,\n    options: RenderPageOptions = {},\n  ): Promise<PageImageHandle> {\n    ctx.assertAllowed(RENDER_SCOPE, 'render.renderPage');\n    const { ref: page, size } = ctx.pageOf(pageArgument);\n    const layers = pictureLayers(options, 'render.renderPage');\n    const strategy = currentStrategy();\n    const format = options.format ?? strategy.format;\n    const quality = options.quality ?? strategy.quality;\n    if (options.rect !== undefined || options.rotation) {\n      return ctx.cancellable(\n        options.signal,\n        renderPart(page, size, options, layers, format, quality),\n      );\n    }\n    const width = Math.max(1, Math.round(options.width ?? (options.scale ?? 1) * size.width));\n    // Exact-size renders share the store with the conformed door: a width\n    // that matches a conformed raster (same format, default quality) is the\n    // same key, so the cached image serves it.\n    const key = rasterKey(page.objectNumber, width, layers, format, options.quality);\n    return ctx.cancellable(\n      options.signal,\n      acquireRaster(\n        page,\n        key,\n        {\n          viewport: { kind: 'width', width },\n          layers,\n          format,\n          quality,\n          view: undefined,\n        },\n        options.signal,\n      ),\n    );\n  }\n\n  /** A page's thumbnail, by either door: one picture per page and layers. */\n  async function thumbnailOf(\n    page: PageRef,\n    {\n      view,\n      signal,\n      format: askedFormat,\n      quality: askedQuality,\n      ...options\n    }: RenderThumbnailOptions & { view?: string | undefined },\n    operation: string,\n  ): Promise<PageImageHandle> {\n    ctx.assertAllowed(THUMBNAIL_SCOPE, operation);\n    const layers = pictureLayers(options, operation);\n    const strategy = currentStrategy();\n    const format = askedFormat ?? strategy.format;\n    const quality = askedQuality ?? strategy.quality;\n    return acquireRaster(\n      page,\n      thumbnailKey(page.objectNumber, layers, format, askedQuality),\n      { viewport: { kind: 'thumbnail' }, layers, format, quality, view },\n      signal,\n    );\n  }\n\n  async function renderPages(\n    pages: readonly (PageRef | number)[],\n    options: RenderPagesOptions = {},\n  ): Promise<BatchResult<PageRender, PageRef | number>> {\n    ctx.assertAllowed(RENDER_SCOPE, 'render.renderPages');\n    const concurrency = Math.max(1, options.concurrency ?? DEFAULT_BATCH_CONCURRENCY);\n    // Each entry keeps its place in the input, so the result reads in the\n    // order given whatever order the renders finished in.\n    const applied: { index: number; render: PageRender }[] = [];\n    const failed: { index: number; ref: PageRef | number; error: PluginErrorInfo }[] = [];\n    const queue = pages.map((page, index) => ({ page, index }));\n    const worker = async () => {\n      for (let next = queue.shift(); next; next = queue.shift()) {\n        const { page, index } = next;\n        try {\n          const image = await renderPage(page, options);\n          applied.push({ index, render: { page: ctx.pageOf(page).ref, image } });\n        } catch (error) {\n          failed.push({\n            index,\n            ref: page,\n            error: toPluginErrorInfo(toPluginError('render', error)),\n          });\n        }\n      }\n    };\n    const batch = Promise.all(Array.from({ length: Math.min(concurrency, queue.length) }, worker));\n    await ctx.cancellable(options.signal, batch);\n    const byInput = (left: { index: number }, right: { index: number }) => left.index - right.index;\n    return {\n      applied: applied.sort(byInput).map(({ render }) => render),\n      skipped: [],\n      failed: failed.sort(byInput).map(({ ref, error }) => ({ ref, error })),\n    };\n  }\n\n  // ── appearance pictures: the owners' items, shared between their views ──\n  async function renderAppearances(\n    page: PageRef,\n    { family, scale, items, signal }: AppearancesOptions,\n  ): Promise<readonly AppearancePicture[]> {\n    ctx.assertAllowed(\n      family === 'widgets' ? FORMS_SCOPE : ANNOTATIONS_SCOPE,\n      'render.renderAppearances',\n    );\n    const pageObjectNumber = ctx.pageOf(page).ref.objectNumber;\n    const versions = new Map(items.map((item) => [annotationKey(item.ref), item.version]));\n    const asked = [...versions].map(([item, version]) => `${item}@${version}`).sort();\n    const group = `${family}|${pageObjectNumber}`;\n    const pictures = appearances.acquire(\n      group,\n      `${group}|s${scale}|${asked.join(',')}`,\n      async (fetchSignal) => {\n        if (isPending(page)) await whenHeld(page, fetchSignal);\n        // The look at rest only, in every state: a check box keeps both its\n        // pictures, and the looks under the pointer and pressed aren't drawn.\n        const pageHandle = ctx.doc.page(toPageRef(pageObjectNumber));\n        const options = { viewport: { kind: 'scale' as const, scale }, modes: ['normal' as const] };\n        const task =\n          family === 'widgets'\n            ? pageHandle.forms.renderAppearances(options)\n            : pageHandle.annotations.renderAppearances(options);\n        if (fetchSignal.aborted) task.abort(reasonOf(fetchSignal));\n        else\n          fetchSignal.addEventListener('abort', () => task.abort(reasonOf(fetchSignal)), {\n            once: true,\n          });\n        // The asked items' pictures, each tagged with the version it was asked at.\n        const drawn = (await task).appearances.flatMap((picture): AppearancePicture[] => {\n          const version = versions.get(annotationKey(picture.ref));\n          return version === undefined ? [] : [{ ...picture, version }];\n        });\n        recentAppearances.remember(family, drawn, (picture) => annotationKey(picture.ref));\n        return drawn;\n      },\n      signal,\n    );\n    return ctx.cancellable(\n      signal,\n      pictures.catch((error: unknown) => {\n        throw toPluginError('render', error);\n      }),\n    );\n  }\n\n  // ── invalidation: the one place the ledger bumps and onInvalidated fires ──\n  function publishInvalidation(\n    pageObjectNumbers: readonly PageObjectNumber[],\n    scope: InvalidateScope,\n    origin: EventOrigin | null,\n  ): void {\n    if (pageObjectNumbers.length === 0) return;\n    ctx.state.update(invalidatePages, pageObjectNumbers, scope);\n    // Every view's plan for these pages points at old-epoch pixels: re-plan\n    // now, so `getPlan` reads fresh on the subscribers' next look.\n    for (const pageObjectNumber of pageObjectNumbers) replanPage(pageObjectNumber);\n    invalidated.emit({\n      pages: pageObjectNumbers.map((pageObjectNumber) => toPageRef(pageObjectNumber)),\n      scope,\n      origin,\n    });\n  }\n\n  function invalidate({ pages, scope = 'content' }: InvalidateOptions = {}): void {\n    const named = pages?.flatMap((page) => ctx.getPage(page)?.ref.objectNumber ?? []);\n    publishInvalidation(named ?? allPageObjectNumbers(), scope, null);\n  }\n\n  // ── tiles: one manager, per-view demand handles with pure reads ──\n  // Tile resolutions arrive in bursts (a want set landing): coalesce the\n  // re-plans per frame, so N arrivals become one re-plan and one wake-up.\n  const pendingAdvance = new Set<PageObjectNumber>();\n  let advanceScheduled = false;\n  const wake = (pageObjectNumber: PageObjectNumber) => {\n    pendingAdvance.add(pageObjectNumber);\n    if (advanceScheduled) return;\n    advanceScheduled = true;\n    ctx.clock.nextFrame(() => {\n      advanceScheduled = false;\n      const advanced = [...pendingAdvance];\n      pendingAdvance.clear();\n      for (const advancedPage of advanced) replanPage(advancedPage);\n    });\n  };\n\n  const tiles = new TileManager({\n    store,\n    getOptions: resolvedOptions,\n    getPolicy: renderPolicy,\n    getPageSize: (pageObjectNumber) => ctx.getPage(toPageRef(pageObjectNumber))?.size,\n    getEpoch: epochOf,\n    after: ctx.clock.after,\n    fetchTile: async (view, pageObjectNumber, rect: Rect, scale, layers, signal) => {\n      // The same refusal the engine would send, without the round trip: a\n      // denied session's viewport would otherwise be refused once per tile.\n      ctx.assertAllowed(RENDER_SCOPE, 'render.tile');\n      const page = toPageRef(pageObjectNumber);\n      if (isPending(page)) await whenHeld(page, signal);\n      const strategy = currentStrategy();\n      const task = ctx.doc\n        .with({ priority: 'high', view })\n        .page(page)\n        .render.image({\n          target: { kind: 'rect', rect },\n          viewport: { kind: 'scale', scale },\n          ...layers,\n          ...(strategy.format !== undefined ? { format: strategy.format } : {}),\n          ...(strategy.quality !== undefined ? { quality: strategy.quality } : {}),\n        });\n      if (signal.aborted) task.abort(reasonOf(signal));\n      else signal.addEventListener('abort', () => task.abort(reasonOf(signal)), { once: true });\n      return task;\n    },\n    onAdvance: wake,\n    debug: (message: string) => {\n      if (resolvedOptions().debug) console.debug(`[render] ${message}`);\n    },\n  });\n\n  /** One handle per view id, reference-counted; demands and plans per page. */\n  const views = new Map<\n    string,\n    { handle: ViewDemand; refs: number; pages: Map<PageObjectNumber, PageDemand> }\n  >();\n\n  /** Re-plan a page for every view that wants it (schedules the next want\n   *  set), and wake readers once when any plan changed. */\n  function replanPage(pageObjectNumber: PageObjectNumber): void {\n    let changed = false;\n    for (const [viewId, view] of views) {\n      const entry = view.pages.get(pageObjectNumber);\n      if (!entry) continue;\n      const plan = tiles.plan(viewId, pageObjectNumber, entry.demand, entry.layers);\n      if (plan !== entry.plan) {\n        entry.plan = plan;\n        changed = true;\n      }\n    }\n    if (changed) ctx.notify();\n  }\n\n  function createViewDemand(viewId: string): ViewDemand {\n    const existing = views.get(viewId);\n    if (existing) {\n      existing.refs += 1;\n      return existing.handle;\n    }\n    const pages = new Map<PageObjectNumber, PageDemand>();\n    const handle: ViewDemand = {\n      setDemand: (page, demand, options) => {\n        const pageObjectNumber = page.objectNumber;\n        const layers = layersOf(options ?? {});\n        const previous = pages.get(pageObjectNumber);\n        const plan = tiles.plan(viewId, pageObjectNumber, demand, layers);\n        pages.set(pageObjectNumber, { demand, layers, plan });\n        if (plan !== previous?.plan) ctx.notify();\n      },\n      getPlan: (page) => pages.get(page.objectNumber)?.plan ?? EMPTY_TILE_PLAN,\n      markPainted: (page, key) => tiles.sourcePainted(viewId, page.objectNumber, key),\n      markUnpainted: (page, key) => tiles.sourceUnpainted(viewId, page.objectNumber, key),\n      release: (page) => {\n        pages.delete(page.objectNumber);\n        tiles.releasePage(viewId, page.objectNumber);\n      },\n      destroy: () => {\n        const view = views.get(viewId);\n        if (!view || view.refs === 0) return;\n        view.refs -= 1;\n        if (view.refs > 0) return;\n        // The last reference releases the view's pages. The entry itself stays\n        // (a few ids per document) so a handle that is re-acquired or reused\n        // after a dispose (React's development double-mount) keeps working.\n        for (const pageObjectNumber of [...view.pages.keys()]) {\n          tiles.releasePage(viewId, pageObjectNumber);\n        }\n        view.pages.clear();\n      },\n    };\n    views.set(viewId, { handle, refs: 1, pages });\n    return handle;\n  }\n\n  // What the layers paint with: the same object until a setting it reads changes.\n  const paintSettings = memo(\n    () => [resolvedOptions().tiles.enabled] as const,\n    (enabled): PaintSettings => Object.freeze({ tiles: enabled }),\n  );\n\n  // A settings change reaches every view's plans at once: re-plan what they show.\n  ctx.listen(settings.api.onSettingsChanged, () => {\n    const shown = new Set<PageObjectNumber>();\n    for (const view of views.values()) for (const page of view.pages.keys()) shown.add(page);\n    for (const page of shown) replanPage(page);\n  });\n\n  const snapshots = createSnapshots(ctx, {\n    renderPage,\n    renderPolicy,\n    settings: () => settings.get().snapshot,\n  });\n\n  const api: RenderHostCapability = {\n    // ── public lens ──\n    ...settings.api,\n    canRender,\n    canRenderThumbnail,\n    handOverPictures,\n    getPicturePainter: () => picturePainter,\n    renderPage,\n    renderThumbnail: async (pageArgument, options = {}) =>\n      ctx.cancellable(\n        options.signal,\n        thumbnailOf(ctx.pageOf(pageArgument).ref, options, 'render.renderThumbnail'),\n      ),\n    renderPages,\n    getRenderPolicy: renderPolicy,\n    getRenderEpoch: (page, layers = {}) => {\n      const info = ctx.getPage(page);\n      return info ? epochOf(info.ref.objectNumber, layersOf(layers)) : 0;\n    },\n    invalidate,\n    onInvalidated: invalidated.on,\n    getPictureState: (page, view) => {\n      const info = ctx.getPage(page);\n      return info ? pictures.stateIn(view, info.ref.objectNumber) : PICTURE_STATES.idle;\n    },\n    onPictureStateChanged: pictureStateChanged.on,\n\n    // ── host lens ──\n    renderSource,\n    getSourceKey: (page, { scale, view: _view, thumbnail, ...options }) => {\n      if (thumbnail) {\n        return thumbnailKey(\n          page.objectNumber,\n          layersOf(options),\n          currentStrategy().format,\n          undefined,\n        );\n      }\n      const viewport = conformViewport(page, scale);\n      return rasterKey(\n        page.objectNumber,\n        viewport.kind === 'width' ? viewport.width : 0,\n        layersOf(options),\n        currentStrategy().format,\n        undefined,\n      );\n    },\n    conformViewport,\n    getPaintSettings: paintSettings,\n    getLayerRights: rights,\n    createViewDemand,\n    reportPicture: pictures.open,\n    renderAppearances,\n    getKeptAppearances: (family, item) => recentAppearances.of(family, annotationKey(item)),\n    getAppearanceScale: (renderScale) => snapAppearanceScale(renderPolicy(), renderScale),\n    onRenderCompleted: renderCompleted.on,\n    onRenderFailed: renderFailed.on,\n\n    // ── snapshots, both lenses ──\n    ...snapshots.api,\n  };\n\n  return {\n    api,\n    connect() {\n      // Confirmed pixel-changing facts, own or remote, and the stream\n      // notice that some were lost.\n      ctx.listen(ctx.doc.events, (event) => {\n        const change = pixelChangeOf(event, allPageObjectNumbers);\n        if (!change) return;\n        publishInvalidation(change.pages, change.scope, 'origin' in event ? event.origin : null);\n      });\n      snapshots.connect();\n    },\n  };\n}\n","import { definePlugin } from '@embedpdf/core';\nimport { InteractionToken } from '@embedpdf/plugin-interaction/contract/host';\nimport { RENDER_DEFAULTS, type RenderConfig } from './contract';\nimport { createRenderController } from './controller';\nimport { RenderToken } from './host-contract';\nimport { initialRenderState } from './model';\n\n/**\n * Document-scoped page rasters. The only render-policy consumer in the\n * client stack: the kernel materializes the engine's advertised render\n * policy on the document, the controller conforms desired scales to it and\n * collapses same-key asks in its raster store, and the tile manager turns\n * host-supplied demand into a retention-safe paint plan over the same store.\n * State is the per-page raster-version ledger and the snapshot tool's box.\n * The interaction plugin is optional: with it, the plugin adds the\n * `snapshot` tool.\n */\nexport const renderPlugin = (config?: RenderConfig) =>\n  definePlugin({\n    id: 'render',\n    scope: 'document',\n    token: RenderToken,\n    optional: [InteractionToken],\n    state: initialRenderState,\n    settings: { defaults: RENDER_DEFAULTS, registered: config, whole: ['snapshot.box'] },\n    create: createRenderController,\n  });\n"],"mappings":";;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