@embedpdf/plugin-stamp 3.0.0-next.13 → 3.0.0-next.15
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/contract-CEeBOug9.d.cts +431 -0
- package/dist/{contract-B79Onij2.js → contract-CJBvneyw.js} +23 -16
- package/dist/contract-CJBvneyw.js.map +1 -0
- package/dist/contract-CjGXUUDJ.d.ts +431 -0
- package/dist/{contract-T-v5KaYd.cjs → contract-lDLkRDYV.cjs} +28 -34
- package/dist/contract-lDLkRDYV.cjs.map +1 -0
- package/dist/contract.cjs +2 -13
- package/dist/contract.d.cts +2 -2
- package/dist/contract.d.ts +2 -2
- package/dist/contract.js +2 -2
- package/dist/index.cjs +1200 -765
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +21 -9
- package/dist/index.d.ts +21 -9
- package/dist/index.js +1203 -758
- package/dist/index.js.map +1 -1
- package/package.json +10 -10
- package/dist/contract-B79Onij2.js.map +0 -1
- package/dist/contract-BS3m51Au.d.cts +0 -384
- package/dist/contract-T-v5KaYd.cjs.map +0 -1
- package/dist/contract-VuCLK5Sr.d.ts +0 -384
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["EngineError","EngineErrorCode","STAMP_LIBRARY_PIECEINFO_APP","stampLibraryPieceInfo","libraryKindFromPdfName","parseStampKey","STAMP_PIECEINFO_APP","stampKey","assetIdFor","stampPieceInfo","customStampName","ActionsHostToken","AnnotationToken","AnnotationHostToken","StampToken"],"sources":["../src/blank-library.ts","../src/capability.ts","../src/reducer.ts","../src/stamp.plugin.ts","../src/persistence.ts"],"sourcesContent":["/**\n * The seed of a new library: a one-page PDF whose page is UNREGISTERED — the\n * shape Acrobat itself gives a fresh stamp library (its first page is a\n * blank starter that no `/Names /Pages` key points at). A library must be a\n * PDF from the moment it exists, and a PDF must have a page; the unregistered\n * blank is that page. It is never an asset, never placed, never listed.\n */\nconst BLANK_OBJECTS = [\n '<< /Type /Catalog /Pages 2 0 R >>',\n '<< /Type /Pages /Kids [3 0 R] /Count 1 >>',\n '<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>',\n];\n\nlet cached: Uint8Array | null = null;\n\nexport function blankLibraryPdf(): Uint8Array {\n if (cached) return new Uint8Array(cached);\n let body = '%PDF-1.7\\n';\n const offsets: number[] = [];\n BLANK_OBJECTS.forEach((object, index) => {\n offsets.push(body.length);\n body += `${index + 1} 0 obj\\n${object}\\nendobj\\n`;\n });\n const xref = body.length;\n body += `xref\\n0 ${BLANK_OBJECTS.length + 1}\\n0000000000 65535 f \\n`;\n for (const offset of offsets) body += `${String(offset).padStart(10, '0')} 00000 n \\n`;\n body += `trailer\\n<< /Size ${BLANK_OBJECTS.length + 1} /Root 1 0 R >>\\nstartxref\\n${xref}\\n%%EOF\\n`;\n cached = new TextEncoder().encode(body);\n return new Uint8Array(cached);\n}\n","import {\n EngineError,\n EngineErrorCode,\n resolveBinarySource,\n sniffBinaryMetadata,\n type BinarySource,\n type AnnotationRef,\n type DocumentHandle,\n type Engine,\n type PageImageHandle,\n type PieceInfoEntry,\n} from '@embedpdf/engine-core/runtime';\nimport { createEventHook, type PluginContext } from '@embedpdf/core';\nimport { javaScriptProgramFromActionTree } from '@embedpdf/core-acrojs';\nimport { ActionsToken as ActionsHostToken } from '@embedpdf/plugin-actions/contract/host';\nimport {\n AnnotationToken,\n type StampPlacement,\n type StampPreviewProvider,\n} from '@embedpdf/plugin-annotation/contract';\nimport { AnnotationToken as AnnotationHostToken } from '@embedpdf/plugin-annotation/contract/host';\nimport { createFormScriptingController } from '@embedpdf/plugin-form/scripting';\n\nimport { blankLibraryPdf } from './blank-library';\nimport {\n assetIdFor,\n customStampName,\n DEFAULT_LIBRARY_KIND,\n libraryKindFromPdfName,\n parseStampKey,\n stampKey,\n stampLibraryPieceInfo,\n stampPieceInfo,\n STAMP_LIBRARY_PIECEINFO_APP,\n STAMP_PIECEINFO_APP,\n} from './convention';\nimport type {\n AddAssetInput,\n ImportLibraryOptions,\n MarkSource,\n StampAction,\n StampAsset,\n StampAssetPreview,\n StampCapability,\n StampConfig,\n StampLibrary,\n StampLibraryChange,\n StampLibraryQuery,\n StampAssetKind,\n StampState,\n} from './types';\n\nconst DEFAULT_PREVIEW_WIDTH = 256;\n\n/** `#rrggbb` → the engine's sRGB triplet. */\nconst hexColor = (hex: string): { r: number; g: number; b: number } => {\n const m = /^#?([0-9a-f]{6})$/i.exec(hex.trim());\n if (!m) throw new EngineError(EngineErrorCode.InvalidArg, `[stamp] mark color must be #rrggbb, got '${hex}'`);\n const n = parseInt(m[1], 16);\n return { r: (n >> 16) & 0xff, g: (n >> 8) & 0xff, b: n & 0xff };\n};\n\n/** An exact ArrayBuffer over a view (the engine's binary idiom). */\nconst toArrayBuffer = (bytes: Uint8Array): ArrayBuffer => {\n const out = new ArrayBuffer(bytes.byteLength);\n new Uint8Array(out).set(bytes);\n return out;\n};\n\n/** The rect an ink mark occupies, padded by its stroke. */\nconst inkBounds = (\n strokes: ReadonlyArray<ReadonlyArray<{ x: number; y: number }>>,\n strokeWidth: number,\n): { left: number; bottom: number; right: number; top: number } => {\n let left = Infinity;\n let bottom = Infinity;\n let right = -Infinity;\n let top = -Infinity;\n for (const stroke of strokes) {\n for (const { x, y } of stroke) {\n if (x < left) left = x;\n if (x > right) right = x;\n if (y < bottom) bottom = y;\n if (y > top) top = y;\n }\n }\n if (!Number.isFinite(left)) {\n throw new EngineError(EngineErrorCode.InvalidArg, '[stamp] an ink mark needs at least one point');\n }\n const pad = strokeWidth;\n return { left: left - pad, bottom: bottom - pad, right: right + pad, top: top + pad };\n};\n\n/** A generous box for typed text; the export crops to the glyphs. */\nconst textBounds = (\n text: string,\n fontSize: number,\n): { left: number; bottom: number; right: number; top: number } => ({\n left: 0,\n bottom: 0,\n right: Math.max(1, text.length) * fontSize * 0.75 + fontSize,\n top: fontSize * 1.6,\n});\n\n/** Session-unique ids. Assets are session-scoped for now (no persistence),\n * so a timestamp + counter is enough — durable ids come with the store port. */\nlet seq = 0;\nconst uid = (prefix: string): string =>\n `${prefix}-${Date.now().toString(36)}-${(seq++).toString(36)}`;\n\nconst entryString = (entries: Record<string, PieceInfoEntry>, key: string): string | undefined => {\n const entry = entries[key];\n return entry?.type === 'string' && entry.value.length > 0 ? entry.value : undefined;\n};\n\nconst entryName = (entries: Record<string, PieceInfoEntry>, key: string): string | undefined => {\n const entry = entries[key];\n return entry?.type === 'name' && entry.value.length > 0 ? entry.value : undefined;\n};\n\nconst entryStringArray = (\n entries: Record<string, PieceInfoEntry>,\n key: string,\n): string[] | undefined => {\n const entry = entries[key];\n return entry?.type === 'string-array' ? [...entry.value] : undefined;\n};\n\nconst kindFromPdfName = (name: string | undefined): StampAssetKind | undefined => {\n switch (name?.toLowerCase()) {\n case 'stamp':\n return 'stamp';\n case 'signature':\n return 'signature';\n case 'initials':\n return 'initials';\n default:\n return undefined;\n }\n};\n\nexport function createStampCapability(\n ctx: PluginContext<StampState, StampAction>,\n config: StampConfig = {},\n): StampCapability {\n /** Binary sidecar of the serializable store: asset bytes + cached preview,\n * keyed by asset id. The reducer never sees these (kernel rule 1). */\n const binaries = new Map<string, { bytes: Uint8Array; preview: StampAssetPreview | null }>();\n /** The durable source of truth for a canonical library. Asset PDFs above\n * are derived page extractions; this map owns the rewritten whole PDF. */\n const libraryBinaries = new Map<string, Uint8Array>();\n /** Whole-PDF rewrites must be serialized per library or two concurrent\n * appends could both start from the same bytes and lose one page. */\n const libraryMutationTails = new Map<string, Promise<void>>();\n\n const mutateLibrary = <T>(libraryId: string, mutation: () => Promise<T>): Promise<T> => {\n const previous = libraryMutationTails.get(libraryId) ?? Promise.resolve();\n const result = previous.then(mutation);\n const tail = result.then(\n () => undefined,\n () => undefined,\n );\n libraryMutationTails.set(libraryId, tail);\n return result.finally(() => {\n if (libraryMutationTails.get(libraryId) === tail) libraryMutationTails.delete(libraryId);\n });\n };\n\n // The ASSET ENGINE port. A configured factory is called (and memoized) on\n // the first import, not at viewer start; a configured instance is used\n // as-is; nothing configured falls back to the kernel's engine — correct for\n // local deployments, and rejected with an actionable error by cloud engines\n // at the first `open({ kind: 'bytes' })`.\n let assetEngineRef: Engine | Promise<Engine> | null = null;\n const assetEngine = (): Engine | Promise<Engine> => {\n if (!assetEngineRef) {\n const cfg = config.assetEngine;\n assetEngineRef = !cfg ? ctx.engine : typeof cfg === 'function' ? cfg() : cfg;\n }\n return assetEngineRef;\n };\n\n const openAssetDocument = async (bytes: Uint8Array): Promise<DocumentHandle> => {\n try {\n return await (\n await assetEngine()\n ).open({ kind: 'bytes', id: uid('stamp-import'), bytes }, { scope: ['*'] });\n } catch (err) {\n // A cloud kernel engine rejects 'bytes' with InvalidArg — turn the\n // generic contract error into the configuration fix.\n if (!config.assetEngine && EngineError.is(err, EngineErrorCode.InvalidArg)) {\n throw new EngineError(\n EngineErrorCode.NotImplemented,\n \"[stamp] importing a library PDF needs an engine that can open local bytes, and this viewer's engine cannot (cloud). Pass stampPlugin({ assetEngine: () => import('@embedpdf/engine').then((m) => m.createLocalEngine()) }) — it loads lazily, on first import.\",\n );\n }\n throw err;\n }\n };\n\n /** Import-time preview render → bytes. The asset engine is local by\n * definition, so the image source is always inline bytes. */\n const imageToPreview = (image: PageImageHandle): StampAssetPreview => {\n if (image.source.kind !== 'bytes') {\n throw new EngineError(\n EngineErrorCode.NotImplemented,\n '[stamp] asset engine returned a URL-sourced render; asset engines must be local',\n );\n }\n return { bytes: image.source.bytes, mimeType: image.contentType };\n };\n\n const allocateId = (\n preferred: string | undefined,\n prefix: string,\n taken: Set<string>,\n ): string => {\n let id = preferred;\n if (!id || taken.has(id)) {\n do id = uid(prefix);\n while (taken.has(id));\n }\n taken.add(id);\n return id;\n };\n\n const libraryChanged = createEventHook<StampLibraryChange>((error) =>\n globalThis.console?.error('[stamp] onLibraryChanged observer failed:', error),\n );\n\n /** Thumbnail render of one library page (the small picker image). */\n const renderThumbnail = async (\n handle: ReturnType<DocumentHandle['page']>,\n ): Promise<StampAssetPreview> =>\n imageToPreview(\n await handle.render.image({\n viewport: { kind: 'width', width: config.previewWidth ?? DEFAULT_PREVIEW_WIDTH },\n background: 'transparent',\n includeAnnotations: true,\n format: 'png',\n }),\n );\n\n const createLibrary = async (\n name: string,\n opts?: { id?: string; kind?: string; categories?: string[] },\n ): Promise<string> => {\n const kind = opts?.kind ?? DEFAULT_LIBRARY_KIND;\n const taken = new Set(Object.keys(ctx.getState().libraries));\n const id = allocateId(opts?.id, 'stamp-lib', taken);\n const doc = await openAssetDocument(blankLibraryPdf());\n let bytes: Uint8Array;\n try {\n requireCanonicalServices(doc);\n await doc.metadata.update({ title: name });\n await doc.pieceInfo!.update(\n STAMP_LIBRARY_PIECEINFO_APP,\n stampLibraryPieceInfo(id, { kind, categories: opts?.categories }),\n );\n bytes = await doc.download();\n } finally {\n await doc.close();\n }\n libraryBinaries.set(id, bytes);\n ctx.dispatch({\n type: 'LIBRARY_ADDED',\n library: {\n id,\n name,\n kind,\n assetIds: [],\n ...(opts?.categories ? { categories: opts.categories } : {}),\n },\n });\n libraryChanged.emit({ libraryId: id, reason: 'created' });\n return id;\n };\n\n const requireCanonicalServices = (doc: DocumentHandle): void => {\n if (!doc.pieceInfo) {\n throw new EngineError(\n EngineErrorCode.NotImplemented,\n '[stamp] canonical PDF libraries need an asset engine with pieceInfo',\n );\n }\n if (!doc.pages.setName || !doc.pages.removeName) {\n throw new EngineError(\n EngineErrorCode.NotImplemented,\n '[stamp] canonical PDF libraries need an asset engine with named pages (pages.setName)',\n );\n }\n };\n\n const importLibraryPdf = async (\n source: BinarySource,\n opts?: ImportLibraryOptions,\n ): Promise<string> => {\n const resolved = await resolveBinarySource(source);\n const meta = sniffBinaryMetadata(resolved.bytes);\n if (meta?.mimeType !== 'application/pdf') {\n throw new EngineError(\n EngineErrorCode.InvalidArg,\n '[stamp] importLibraryPdf needs PDF bytes (use addAsset for a raster image)',\n );\n }\n const doc = await openAssetDocument(new Uint8Array(resolved.bytes));\n let imported:\n | {\n library: StampLibrary;\n canonicalBytes: Uint8Array;\n assets: Array<{\n asset: StampAsset;\n bytes: Uint8Array;\n preview: StampAssetPreview;\n }>;\n }\n | undefined;\n try {\n requireCanonicalServices(doc);\n const layout = await doc.pages.list();\n if (layout.pageCount === 0) {\n throw new EngineError(\n EngineErrorCode.InvalidArg,\n '[stamp] a canonical stamp library PDF must contain at least one page',\n );\n }\n const byPon = new Map(layout.pages.map((page) => [page.pageObjectNumber, page]));\n\n // ── library identity: /Title (Acrobat) → v1 PieceInfo → caller fallback ──\n const catalogEntries =\n (await doc.pieceInfo!.read(STAMP_LIBRARY_PIECEINFO_APP))?.entries ?? {};\n const state = ctx.getState();\n const takenLibraryIds = new Set(Object.keys(state.libraries));\n const libraryId = allocateId(entryString(catalogEntries, 'Id'), 'stamp-lib', takenLibraryIds);\n const docMeta = await doc.metadata.read();\n const libraryName =\n (docMeta.title && docMeta.title.length > 0 ? docMeta.title : undefined) ??\n entryString(catalogEntries, 'Name') ??\n opts?.name ??\n 'Stamps';\n if (!docMeta.title) await doc.metadata.update({ title: libraryName });\n const libraryCategories = opts?.categories ?? entryStringArray(catalogEntries, 'Categories');\n const libraryLocale = entryString(catalogEntries, 'Locale');\n // What the file is for: the caller's word, else the file's, else a plain stamp library.\n const libraryKind =\n opts?.libraryKind ?? libraryKindFromPdfName(entryName(catalogEntries, 'Kind'));\n\n // ── the registry: /Names /Pages keys `identifier=label` → pages ──\n const registry = (layout.namedPages ?? []).filter(\n (entry): entry is typeof entry & { target: { kind: 'page' } } =>\n entry.target.kind === 'page',\n );\n const hidden = (layout.namedPages ?? []).filter((entry) => entry.target.kind !== 'page');\n if (hidden.length > 0) {\n globalThis.console?.warn(\n `[stamp] library '${libraryName}' carries ${hidden.length} hidden-template or dangling registration(s); they are not stamps and were ignored`,\n );\n }\n\n type Descriptor = { pageObjectNumber: number; index: number; name: string; label: string };\n let descriptors: Descriptor[];\n if (registry.length > 0) {\n const seen = new Set<string>();\n descriptors = registry.map((entry) => {\n const { name, label } = parseStampKey(entry.name);\n if (!name) {\n throw new EngineError(\n EngineErrorCode.InvalidArg,\n `[stamp] library '${libraryName}': empty stamp identifier in key '${entry.name}'`,\n );\n }\n if (seen.has(name)) {\n throw new EngineError(\n EngineErrorCode.InvalidArg,\n `[stamp] library '${libraryName}': duplicate stamp identifier '${name}'`,\n );\n }\n seen.add(name);\n const page = byPon.get(entry.target.pageObjectNumber)!;\n return { pageObjectNumber: page.pageObjectNumber, index: page.index, name, label };\n });\n // Display order is PAGE order, never the tree's key-sorted order.\n descriptors.sort((a, b) => a.index - b.index);\n } else if (layout.namedPages === undefined) {\n throw new EngineError(\n EngineErrorCode.NotImplemented,\n '[stamp] the asset engine reports no named-page registry (an older engine); upgrade it to import libraries',\n );\n } else {\n // A plain PDF: every page is a stamp. Register it so the canonical\n // copy is Acrobat-readable on export. v1 PieceInfo keys are honoured\n // as a fallback for libraries written before the registry.\n descriptors = [];\n for (const page of layout.pages) {\n const v1 = (await doc.page(page.pageObjectNumber).pieceInfo?.read(STAMP_PIECEINFO_APP))\n ?.entries;\n const name = (v1 && entryString(v1, 'Name')) ?? `Stamp${page.index + 1}`;\n const label = (v1 && entryString(v1, 'Subject')) ?? opts?.assetName?.(page.index) ?? name;\n descriptors.push({\n pageObjectNumber: page.pageObjectNumber,\n index: page.index,\n name,\n label,\n });\n }\n for (const d of descriptors) {\n await doc.pages.setName!({\n name: stampKey(d.name, d.label),\n pageObjectNumber: d.pageObjectNumber,\n });\n }\n }\n\n await doc.pieceInfo!.update(\n STAMP_LIBRARY_PIECEINFO_APP,\n stampLibraryPieceInfo(libraryId, {\n kind: libraryKind,\n categories: libraryCategories,\n locale: libraryLocale,\n }),\n );\n\n const assets: NonNullable<typeof imported>['assets'] = [];\n for (const d of descriptors) {\n const handle = doc.page(d.pageObjectNumber);\n if (!handle.pieceInfo) {\n throw new EngineError(\n EngineErrorCode.NotImplemented,\n '[stamp] canonical PDF libraries need page pieceInfo support',\n );\n }\n const entries = (await handle.pieceInfo.read(STAMP_PIECEINFO_APP))?.entries ?? {};\n const kind = opts?.kind ?? kindFromPdfName(entryName(entries, 'Kind')) ?? 'stamp';\n const subject = entryString(entries, 'SubjectOverride');\n const categories = entryStringArray(entries, 'Categories');\n const page = byPon.get(d.pageObjectNumber)!;\n const asset: StampAsset = {\n id: assetIdFor(libraryId, d.name),\n libraryId,\n kind,\n name: d.name,\n label: d.label,\n size: { width: page.size.width, height: page.size.height },\n pageObjectNumber: d.pageObjectNumber,\n ...(subject !== undefined ? { subject } : {}),\n ...(categories !== undefined ? { categories } : {}),\n };\n await handle.pieceInfo.update(\n STAMP_PIECEINFO_APP,\n stampPieceInfo(kind, { subject, categories }),\n );\n // One canonical page → one derived placement PDF plus a thumbnail.\n const bytes = await doc.pages.extract([d.pageObjectNumber]);\n assets.push({ asset, bytes, preview: await renderThumbnail(handle) });\n }\n\n imported = {\n library: {\n id: libraryId,\n name: libraryName,\n kind: libraryKind,\n ...(libraryLocale ? { locale: libraryLocale } : {}),\n categories: libraryCategories,\n assetIds: [],\n },\n canonicalBytes: await doc.download(),\n assets,\n };\n } finally {\n await doc.close();\n }\n\n libraryBinaries.set(imported.library.id, imported.canonicalBytes);\n ctx.dispatch({ type: 'LIBRARY_ADDED', library: imported.library });\n for (const { asset, bytes, preview } of imported.assets) {\n binaries.set(asset.id, { bytes, preview });\n ctx.dispatch({ type: 'ASSET_ADDED', asset });\n }\n libraryChanged.emit({ libraryId: imported.library.id, reason: 'imported' });\n return imported.library.id;\n };\n\n /**\n * A drawn or typed mark rendered to a one-page PDF: the annotation is\n * authored on a scratch page and exported the way \"stamp from selection\"\n * exports — a fresh page the size of the mark, paths kept as paths, the\n * font subset-embedded. Self-contained and Acrobat-readable.\n */\n const renderMark = async (\n mark: Extract<MarkSource, { kind: 'ink' | 'text' }>,\n ): Promise<Uint8Array> => {\n const doc = await openAssetDocument(blankLibraryPdf());\n try {\n const layout = await doc.pages.list();\n const scratch = layout.pages[0];\n if (!scratch) throw new EngineError(EngineErrorCode.Unknown, '[stamp] no scratch page');\n const page = doc.page(scratch.pageObjectNumber);\n if (!page.annotations.exportAppearance) {\n throw new EngineError(\n EngineErrorCode.NotImplemented,\n '[stamp] authoring a mark needs an asset engine that can export annotation appearances',\n );\n }\n const color = hexColor(mark.color ?? '#1d2b53');\n const created =\n mark.kind === 'ink'\n ? await page.annotations.create({\n subtype: 'ink',\n inkList: mark.strokes.map((stroke) => stroke.map(({ x, y }) => ({ x, y }))),\n rect: inkBounds(mark.strokes, mark.strokeWidth ?? 2),\n color,\n strokeWidth: mark.strokeWidth ?? 2,\n })\n : await page.annotations.create({\n subtype: 'free-text',\n intent: 'free-text',\n contents: mark.text,\n fontFamily: mark.fontFamily,\n fontSize: mark.fontSize ?? 36,\n textAlign: 'left',\n rect: textBounds(mark.text, mark.fontSize ?? 36),\n fontColor: color,\n strokeWidth: 0,\n });\n return new Uint8Array(await page.annotations.exportAppearance([created.created.ref]));\n } finally {\n await doc.close();\n }\n };\n\n /** One page of a PDF as a single-page PDF (a `pdf` mark with `pageIndex`). */\n const extractPage = async (bytes: Uint8Array, pageIndex: number): Promise<Uint8Array> => {\n const doc = await openAssetDocument(bytes);\n try {\n const layout = await doc.pages.list();\n const page = layout.pages[pageIndex];\n if (!page) {\n throw new EngineError(\n EngineErrorCode.InvalidArg,\n `[stamp] the PDF has no page ${pageIndex} (${layout.pageCount} pages)`,\n );\n }\n return await doc.pages.extract([page.pageObjectNumber]);\n } finally {\n await doc.close();\n }\n };\n\n /** The bytes an asset is made from: the caller's `source`, or its `mark` authored into one. */\n const resolveAssetSource = async (\n input: AddAssetInput,\n ): Promise<{ bytes: ArrayBuffer; mimeType?: string }> => {\n if ((input.source === undefined) === (input.mark === undefined)) {\n throw new EngineError(\n EngineErrorCode.InvalidArg,\n '[stamp] addAsset takes exactly one of `source` / `mark`',\n );\n }\n if (input.source !== undefined) return resolveBinarySource(input.source);\n const mark = input.mark!;\n switch (mark.kind) {\n case 'image':\n return resolveBinarySource(mark.source);\n case 'pdf': {\n const resolved = await resolveBinarySource(mark.source);\n if (mark.pageIndex === undefined) return resolved;\n return { bytes: toArrayBuffer(await extractPage(new Uint8Array(resolved.bytes), mark.pageIndex)) };\n }\n case 'ink':\n case 'text':\n return { bytes: toArrayBuffer(await renderMark(mark)) };\n }\n };\n\n const addAsset = async (input: AddAssetInput): Promise<string> => {\n if (input.libraryId && !ctx.getState().libraries[input.libraryId]) {\n throw new EngineError(\n EngineErrorCode.NotFound,\n `[stamp] unknown library '${input.libraryId}'`,\n );\n }\n const resolved = await resolveAssetSource(input);\n const meta = sniffBinaryMetadata(resolved.bytes);\n if (!meta) {\n throw new EngineError(\n EngineErrorCode.InvalidArg,\n '[stamp] asset source must be PNG, JPEG, or single-page PDF bytes',\n );\n }\n const isPdf = meta.mimeType === 'application/pdf';\n const name = input.name ?? customStampName();\n const label = input.label ?? name;\n if (name.length === 0 || name.includes('=')) {\n throw new EngineError(\n EngineErrorCode.InvalidArg,\n `[stamp] invalid stamp identifier '${name}': must be non-empty and contain no '='`,\n );\n }\n const rasterSize =\n input.size ?? ('width' in meta ? { width: meta.width, height: meta.height } : null);\n if (!isPdf && (!rasterSize || rasterSize.width <= 0 || rasterSize.height <= 0)) {\n throw new EngineError(\n EngineErrorCode.InvalidArg,\n '[stamp] a raster asset needs a positive `size` (its page size in points)',\n );\n }\n\n let suppliedPreview: StampAssetPreview | null = null;\n if (input.preview) {\n const preview = await resolveBinarySource(input.preview);\n suppliedPreview = {\n bytes: new Uint8Array(preview.bytes),\n mimeType: preview.mimeType ?? 'image/png',\n };\n }\n\n // No library named → one of its own, named after the label.\n const libraryId = input.libraryId ?? (await createLibrary(label));\n\n return mutateLibrary(libraryId, async () => {\n const liveLibrary = ctx.getState().libraries[libraryId];\n if (!liveLibrary) {\n throw new EngineError(\n EngineErrorCode.NotFound,\n `[stamp] library '${libraryId}' no longer exists`,\n );\n }\n const assetId = assetIdFor(liveLibrary.id, name);\n if (ctx.getState().assets[assetId]) {\n throw new EngineError(\n EngineErrorCode.InvalidArg,\n `[stamp] library '${liveLibrary.name}' already has a stamp named '${name}'`,\n );\n }\n const canonicalBytes = libraryBinaries.get(liveLibrary.id);\n if (!canonicalBytes) {\n throw new EngineError(\n EngineErrorCode.Unknown,\n `[stamp] canonical bytes are missing for library '${liveLibrary.id}'`,\n );\n }\n\n const doc = await openAssetDocument(canonicalBytes);\n let appended:\n | {\n asset: StampAsset;\n bytes: Uint8Array;\n preview: StampAssetPreview;\n canonical: Uint8Array;\n }\n | undefined;\n try {\n requireCanonicalServices(doc);\n let pageObjectNumber: number;\n if (isPdf) {\n const result = await doc.pages.insert(new Uint8Array(resolved.bytes));\n if (result.insertedPageObjectNumbers.length !== 1) {\n throw new EngineError(\n EngineErrorCode.InvalidArg,\n '[stamp] a library asset must be a single-page PDF',\n );\n }\n pageObjectNumber = result.insertedPageObjectNumbers[0];\n } else {\n // Raster → page: a blank page the image's size, the image placed\n // to fill it, flattened into content. From here on it is a page\n // like any other — exportable, persistable, Acrobat-readable.\n if (!doc.pages.flatten) {\n throw new EngineError(\n EngineErrorCode.NotImplemented,\n '[stamp] raster assets need an asset engine with pages.flatten',\n );\n }\n const blank = await doc.pages.insertBlank({ size: rasterSize! });\n pageObjectNumber = blank.insertedPageObjectNumbers[0];\n await doc.page(pageObjectNumber).annotations.create({\n subtype: 'stamp',\n rect: { left: 0, bottom: 0, right: rasterSize!.width, top: rasterSize!.height },\n source: new Uint8Array(resolved.bytes),\n fit: 'fill',\n });\n const flattened = await doc.pages.flatten([pageObjectNumber], 'display');\n if (flattened.results.some(({ status }) => status !== 'applied')) {\n throw new EngineError(\n EngineErrorCode.Unknown,\n '[stamp] flattening the raster into its page failed',\n );\n }\n }\n const layout = (await doc.pages.list()).pages.find(\n (candidate) => candidate.pageObjectNumber === pageObjectNumber,\n );\n const page = doc.page(pageObjectNumber);\n if (!layout || !page.pieceInfo) {\n throw new EngineError(\n EngineErrorCode.NotImplemented,\n '[stamp] canonical PDF libraries need page layout and pieceInfo support',\n );\n }\n // Insert copies the page only — register it in the same mutation.\n await doc.pages.setName!({ name: stampKey(name, label), pageObjectNumber });\n const asset: StampAsset = {\n id: assetId,\n libraryId: liveLibrary.id,\n kind: input.kind ?? 'stamp',\n name,\n label,\n size: { width: layout.size.width, height: layout.size.height },\n pageObjectNumber,\n ...(input.subject !== undefined ? { subject: input.subject } : {}),\n ...(input.categories !== undefined ? { categories: input.categories } : {}),\n };\n await page.pieceInfo.update(\n STAMP_PIECEINFO_APP,\n stampPieceInfo(asset.kind, { subject: asset.subject, categories: asset.categories }),\n );\n const bytes = await doc.pages.extract([pageObjectNumber]);\n const preview = suppliedPreview ?? (await renderThumbnail(page));\n appended = { asset, bytes, preview, canonical: await doc.download() };\n } finally {\n await doc.close();\n }\n\n libraryBinaries.set(liveLibrary.id, appended.canonical);\n binaries.set(appended.asset.id, { bytes: appended.bytes, preview: appended.preview });\n ctx.dispatch({ type: 'ASSET_ADDED', asset: appended.asset });\n libraryChanged.emit({ libraryId: liveLibrary.id, reason: 'asset-added' });\n return appended.asset.id;\n });\n };\n\n const addAssetFromAnnotations = async (\n documentId: string,\n pageObjectNumber: number,\n refs: AnnotationRef[],\n input: Omit<AddAssetInput, 'source' | 'size'>,\n ): Promise<string> => {\n const doc = ctx.documentHandle(documentId);\n if (!doc) {\n throw new EngineError(\n EngineErrorCode.NotFound,\n `[stamp] target document '${documentId}' is not open`,\n );\n }\n const page = doc.page(pageObjectNumber);\n if (!page.annotations.exportAppearance) {\n throw new EngineError(\n EngineErrorCode.NotImplemented,\n \"[stamp] this document's engine cannot export annotation appearances\",\n );\n }\n // The engine flattens the selection into a fresh single-page PDF —\n // the same placement whole-page flatten uses, aimed at a new page.\n const source = await page.annotations.exportAppearance(refs);\n return addAsset({ ...input, source });\n };\n\n const dropLibrary = (id: string): void => {\n const library = ctx.getState().libraries[id];\n if (library) {\n for (const assetId of library.assetIds) {\n binaries.delete(assetId);\n ghostRenders.delete(assetId);\n }\n }\n libraryBinaries.delete(id);\n ctx.dispatch({ type: 'LIBRARY_REMOVED', libraryId: id });\n };\n\n const removeAsset = async (id: string): Promise<void> => {\n const initialAsset = ctx.getState().assets[id];\n if (!initialAsset) return;\n return mutateLibrary(initialAsset.libraryId, async () => {\n const asset = ctx.getState().assets[id];\n if (!asset) return;\n const library = ctx.getState().libraries[asset.libraryId];\n if (!library) return;\n const canonicalBytes = libraryBinaries.get(library.id);\n if (!canonicalBytes) {\n throw new EngineError(\n EngineErrorCode.Unknown,\n `[stamp] canonical bytes are missing for library '${library.id}'`,\n );\n }\n // The page goes; the engine drops its registry entry inside the\n // delete. The unregistered blank keeps the file valid when this was\n // the last stamp — a library with no stamps is still a library.\n const doc = await openAssetDocument(canonicalBytes);\n let rewritten: Uint8Array | undefined;\n try {\n await doc.pages.delete([asset.pageObjectNumber]);\n rewritten = await doc.download();\n } finally {\n await doc.close();\n }\n libraryBinaries.set(library.id, rewritten);\n binaries.delete(id);\n ghostRenders.delete(id);\n ctx.dispatch({ type: 'ASSET_REMOVED', assetId: id });\n libraryChanged.emit({ libraryId: library.id, reason: 'asset-removed' });\n });\n };\n\n const removeLibrary = (id: string): Promise<void> =>\n mutateLibrary(id, async () => {\n const existed = ctx.getState().libraries[id] !== undefined;\n dropLibrary(id);\n if (existed) libraryChanged.emit({ libraryId: id, reason: 'removed' });\n });\n\n const updateAsset = async (\n id: string,\n patch: { label?: string; subject?: string | null; categories?: string[] },\n ): Promise<void> => {\n const initial = ctx.getState().assets[id];\n if (!initial) throw new EngineError(EngineErrorCode.NotFound, `[stamp] unknown asset '${id}'`);\n return mutateLibrary(initial.libraryId, async () => {\n const asset = ctx.getState().assets[id];\n const library = asset ? ctx.getState().libraries[asset.libraryId] : undefined;\n if (!asset || !library) {\n throw new EngineError(EngineErrorCode.NotFound, `[stamp] unknown asset '${id}'`);\n }\n const next: StampAsset = {\n ...asset,\n ...(patch.label !== undefined ? { label: patch.label } : {}),\n ...(patch.categories !== undefined ? { categories: patch.categories } : {}),\n };\n if (patch.subject === null) delete next.subject;\n else if (patch.subject !== undefined) next.subject = patch.subject;\n\n const canonicalBytes = libraryBinaries.get(library.id);\n if (!canonicalBytes) {\n throw new EngineError(\n EngineErrorCode.Unknown,\n `[stamp] canonical bytes are missing for library '${library.id}'`,\n );\n }\n const doc = await openAssetDocument(canonicalBytes);\n let rewritten: Uint8Array | undefined;\n try {\n requireCanonicalServices(doc);\n if (next.label !== asset.label) {\n // A relabel is a registry rename — one job, the identifier untouched.\n await doc.pages.setName!({\n name: stampKey(asset.name, next.label),\n pageObjectNumber: asset.pageObjectNumber,\n replace: stampKey(asset.name, asset.label),\n });\n }\n const page = doc.page(asset.pageObjectNumber);\n await page.pieceInfo?.update(\n STAMP_PIECEINFO_APP,\n stampPieceInfo(next.kind, { subject: next.subject, categories: next.categories }),\n );\n rewritten = await doc.download();\n } finally {\n await doc.close();\n }\n libraryBinaries.set(library.id, rewritten);\n ctx.dispatch({ type: 'ASSET_UPDATED', asset: next });\n libraryChanged.emit({ libraryId: library.id, reason: 'asset-updated' });\n });\n };\n\n const updateLibrary = async (\n id: string,\n patch: { name?: string; categories?: string[] },\n ): Promise<void> => {\n if (!ctx.getState().libraries[id]) {\n throw new EngineError(EngineErrorCode.NotFound, `[stamp] unknown library '${id}'`);\n }\n return mutateLibrary(id, async () => {\n const library = ctx.getState().libraries[id];\n if (!library) {\n throw new EngineError(EngineErrorCode.NotFound, `[stamp] unknown library '${id}'`);\n }\n const canonicalBytes = libraryBinaries.get(id);\n if (!canonicalBytes) {\n throw new EngineError(\n EngineErrorCode.Unknown,\n `[stamp] canonical bytes are missing for library '${id}'`,\n );\n }\n const next: StampLibrary = {\n ...library,\n ...(patch.name !== undefined ? { name: patch.name } : {}),\n ...(patch.categories !== undefined ? { categories: patch.categories } : {}),\n };\n const doc = await openAssetDocument(canonicalBytes);\n let rewritten: Uint8Array | undefined;\n try {\n requireCanonicalServices(doc);\n // The name is the PDF's /Title; kind, id, categories, locale ride PieceInfo.\n if (next.name !== library.name) await doc.metadata.update({ title: next.name });\n await doc.pieceInfo!.update(\n STAMP_LIBRARY_PIECEINFO_APP,\n stampLibraryPieceInfo(id, {\n kind: next.kind,\n categories: next.categories,\n locale: next.locale,\n }),\n );\n rewritten = await doc.download();\n } finally {\n await doc.close();\n }\n libraryBinaries.set(id, rewritten);\n ctx.dispatch({ type: 'LIBRARY_UPDATED', library: next });\n libraryChanged.emit({ libraryId: id, reason: 'updated' });\n });\n };\n\n /**\n * Form-backed stamps are executable templates only until placement. Work\n * on an isolated copy so neither the canonical library nor its reusable\n * per-page extraction becomes target/user/time specific.\n *\n * The realm comes from the TARGET document's actions plugin — a detached\n * realm under that document's policy and environment (WP4: its own\n * sandbox, none of the viewer realm's globals). No actions plugin, or\n * scripting off, or `dynamic: false` → the template is armed as-is.\n */\n const materializeForPlacement = async (\n documentId: string,\n asset: StampAsset,\n bin: { bytes: Uint8Array; preview: StampAssetPreview | null },\n ): Promise<{ bytes: Uint8Array; preview: StampAssetPreview | null }> => {\n if (config.dynamic === false) return bin;\n const actions = ctx.tryForDocument(ActionsHostToken, documentId);\n const mintRealm = actions?.createDetachedScriptRealm;\n if (!actions || !mintRealm) return bin;\n\n const targetMeta = ctx.core().documents[documentId] ?? null;\n if (!targetMeta) {\n throw new EngineError(\n EngineErrorCode.NotFound,\n `[stamp] target document '${documentId}' is not open`,\n );\n }\n\n // A page extraction intentionally does not retain catalog-owned AcroForm\n // and action structures. Canonical assets therefore evaluate from the\n // whole library PDF, then extract only their selected page after flatten.\n const canonicalBytes = libraryBinaries.get(asset.libraryId);\n const sourceBytes = canonicalBytes ?? bin.bytes;\n const doc = await openAssetDocument(new Uint8Array(sourceBytes));\n // Cleanup protection starts the moment the temporary document exists:\n // realm/controller construction failures must not leak it.\n let realm: ReturnType<typeof mintRealm> | null = null;\n let scripting: ReturnType<typeof createFormScriptingController> | null = null;\n try {\n const layout = await doc.pages.list();\n const selectedPage =\n asset.pageObjectNumber === undefined\n ? layout.pageCount === 1\n ? layout.pages[0]\n : undefined\n : layout.pages.find(\n ({ pageObjectNumber }) => pageObjectNumber === asset.pageObjectNumber,\n );\n if (!selectedPage) {\n throw new EngineError(\n EngineErrorCode.InvalidArg,\n canonicalBytes\n ? `[stamp] canonical page ${asset.pageObjectNumber ?? 'unknown'} no longer exists`\n : '[stamp] a loose dynamic stamp asset must contain exactly one page',\n );\n }\n const snapshot = await doc.forms.list();\n const hasSelectedPageField = snapshot.fields.some((field) =>\n field.widgets.some(\n ({ pageObjectNumber }) => pageObjectNumber === selectedPage.pageObjectNumber,\n ),\n );\n if (!hasSelectedPageField) return bin;\n if (!doc.pages.flatten || !doc.pages.extract) {\n throw new EngineError(\n EngineErrorCode.NotImplemented,\n '[stamp] dynamic PDF stamps need an asset engine with pages.flatten and pages.extract',\n );\n }\n\n // Scripts observe the TARGET document's metadata (Acrobat's dynamic\n // stamp contract: `documentFileName` is the document being stamped)\n // and boot from the asset document's own name tree.\n realm = mintRealm.call(actions, {\n doc,\n document: () => targetMeta,\n bootSources: async () => {\n const tree = doc.actions ? await doc.actions.read() : null;\n return (\n tree?.nameTreeScripts.map(({ action }) => javaScriptProgramFromActionTree(action)) ?? []\n );\n },\n });\n scripting = createFormScriptingController({\n doc,\n document: () => targetMeta,\n transaction: realm.transaction.bind(realm),\n budget: realm.budget,\n });\n const result = await scripting.recalculate();\n actions.surfaceScriptCommit(result, { origin: 'user', realm: 'detached' });\n if (result.status === 'failed') {\n throw new EngineError(\n EngineErrorCode.Unknown,\n `[stamp] dynamic stamp scripting failed: ${result.error?.message ?? 'native form effect failed'}`,\n );\n }\n\n const pageObjectNumber = selectedPage.pageObjectNumber;\n const flattened = await doc.pages.flatten([pageObjectNumber], 'display');\n const failed = flattened.results.find(\n ({ status }) => status === 'failed' || status === 'skipped',\n );\n if (failed) {\n throw new EngineError(\n EngineErrorCode.Unknown,\n `[stamp] dynamic stamp flatten failed for page ${failed.pageObjectNumber}`,\n );\n }\n\n const bytes = await doc.pages.extract([pageObjectNumber]);\n const image = await doc.page(pageObjectNumber).render.image({\n viewport: { kind: 'width', width: config.previewWidth ?? DEFAULT_PREVIEW_WIDTH },\n background: 'transparent',\n includeAnnotations: false,\n format: 'png',\n });\n return { bytes, preview: imageToPreview(image) };\n } finally {\n scripting?.dispose();\n realm?.dispose();\n await doc.close();\n }\n };\n\n const armAsset = async (\n documentId: string,\n assetId: string,\n opts?: { targetWidth?: number },\n ): Promise<void> => {\n const asset = ctx.getState().assets[assetId];\n const bin = binaries.get(assetId);\n if (!asset || !bin) {\n throw new EngineError(EngineErrorCode.NotFound, `[stamp] unknown asset '${assetId}'`);\n }\n const placement = await materializeForPlacement(documentId, asset, bin);\n // The placement itself remains one armStamp call. Dynamic evaluation,\n // when enabled and applicable, has already produced an ephemeral static\n // page and matching preview at this boundary.\n const annotation = ctx.forDocument(AnnotationToken, documentId);\n await annotation.armStamp({\n ...stampPayload(asset, placement, placement !== bin),\n targetWidth: opts?.targetWidth,\n });\n armedByDocument.set(documentId, assetId);\n };\n\n /** Which asset this plugin armed per document. The annotation plugin owns\n * the arm itself (a tool switch disarms it), so the answer is checked\n * against it and forgotten once it no longer holds one. */\n const armedByDocument = new Map<string, string>();\n const armedAsset = (documentId: string): StampAsset | null => {\n const assetId = armedByDocument.get(documentId);\n if (assetId === undefined) return null;\n const annotation = ctx.tryForDocument(AnnotationHostToken, documentId);\n if (!annotation?.hasArmedStamp()) {\n armedByDocument.delete(documentId);\n return null;\n }\n return ctx.getState().assets[assetId] ?? null;\n };\n\n /**\n * Ghost renders, one per size bucket per asset, rendered lazily on the\n * asset engine the first time the ghost is shown at that size and kept\n * until the asset goes away. Materialized (dynamic) placements are\n * user/time specific and cache only for their own arm (`cacheKey` null).\n */\n const ghostRenders = new Map<string, Map<number, Promise<StampAssetPreview | null>>>();\n\n const renderGhost = async (bytes: Uint8Array, devicePixelWidth: number) => {\n const doc = await openAssetDocument(new Uint8Array(bytes));\n try {\n const layout = await doc.pages.list();\n const page = layout.pages[0];\n if (!page) return null;\n return imageToPreview(\n await doc.page(page.pageObjectNumber).render.image({\n viewport: { kind: 'width', width: devicePixelWidth },\n background: 'transparent',\n includeAnnotations: true,\n format: 'png',\n }),\n );\n } finally {\n await doc.close();\n }\n };\n\n /** A resolution-aware ghost source for placement bytes: the page renders\n * at the requested width, cached per bucket under `cacheKey` when given. */\n const ghostProvider = (\n bytes: Uint8Array,\n fallback: StampAssetPreview | null,\n cacheKey: string | null,\n ): StampPreviewProvider => {\n const local = cacheKey ? (ghostRenders.get(cacheKey) ?? new Map()) : new Map();\n if (cacheKey) ghostRenders.set(cacheKey, local);\n return (devicePixelWidth) => {\n let pending = local.get(devicePixelWidth);\n if (!pending) {\n pending = renderGhost(bytes, devicePixelWidth).catch((error) => {\n globalThis.console?.warn('[stamp] ghost render failed, using the thumbnail:', error);\n return fallback;\n });\n local.set(devicePixelWidth, pending);\n }\n return pending;\n };\n };\n\n /** The one payload both entry points hand the annotation plugin: artwork,\n * a resolution-aware ghost, true size, and the identity a placement\n * writes (`/Name` = identifier, `/Subj` = the subject override or label). */\n const stampPayload = (\n asset: StampAsset,\n placement: { bytes: Uint8Array; preview: StampAssetPreview | null },\n materialized: boolean,\n ) => ({\n source: placement.bytes,\n preview: ghostProvider(placement.bytes, placement.preview, materialized ? null : asset.id),\n intrinsicSize: asset.size,\n name: asset.name,\n subject: asset.subject ?? asset.label,\n });\n\n const placeAsset = async (\n documentId: string,\n assetId: string,\n placement: StampPlacement,\n ): Promise<AnnotationRef> => {\n const asset = ctx.getState().assets[assetId];\n const bin = binaries.get(assetId);\n if (!asset || !bin) {\n throw new EngineError(EngineErrorCode.NotFound, `[stamp] unknown asset '${assetId}'`);\n }\n const materialized = await materializeForPlacement(documentId, asset, bin);\n const annotation = ctx.forDocument(AnnotationToken, documentId);\n return annotation.placeStamp(\n stampPayload(asset, materialized, materialized !== bin),\n placement,\n );\n };\n\n ctx.cleanup(() => {\n binaries.clear();\n ghostRenders.clear();\n libraryBinaries.clear();\n libraryMutationTails.clear();\n const ownedAssetEngine = typeof config.assetEngine === 'function' ? assetEngineRef : null;\n assetEngineRef = null;\n if (ownedAssetEngine) {\n void Promise.resolve(ownedAssetEngine)\n .then((engine) => engine.destroy())\n .catch(() => {});\n }\n });\n\n return {\n libraries: (query?: StampLibraryQuery) => {\n const s = ctx.getState();\n const kinds =\n query?.kind === undefined\n ? null\n : new Set(typeof query.kind === 'string' ? [query.kind] : query.kind);\n return s.libraryOrder\n .map((id) => s.libraries[id])\n .filter((l): l is StampLibrary => l != null && (kinds === null || kinds.has(l.kind)));\n },\n library: (id) => ctx.getState().libraries[id] ?? null,\n assets: (libraryId) => {\n const s = ctx.getState();\n if (libraryId) {\n const library = s.libraries[libraryId];\n return library ? library.assetIds.map((id) => s.assets[id]).filter((a) => a != null) : [];\n }\n return s.libraryOrder.flatMap((lid) =>\n (s.libraries[lid]?.assetIds ?? []).map((id) => s.assets[id]).filter((a) => a != null),\n );\n },\n asset: (id) => ctx.getState().assets[id] ?? null,\n assetPreview: (id) => binaries.get(id)?.preview ?? null,\n assetBytes: (id) => binaries.get(id)?.bytes ?? null,\n exportLibrary: (id) => libraryBinaries.get(id) ?? null,\n onLibraryChanged: libraryChanged.on,\n createLibrary,\n updateLibrary,\n importLibraryPdf,\n addAsset,\n addAssetFromAnnotations,\n updateAsset,\n removeAsset,\n removeLibrary,\n armAsset,\n placeAsset,\n disarm: (documentId) => {\n armedByDocument.delete(documentId);\n ctx.forDocument(AnnotationToken, documentId).disarmStamp();\n },\n armedAsset,\n };\n}\n","import type { StampAction, StampState } from './types';\n\nexport const initialStampState = (): StampState => ({\n libraries: {},\n libraryOrder: [],\n assets: {},\n});\n\n/** Pure and serializable (kernel rule 1) — descriptors only; the bytes and\n * previews live in the capability and never enter the store. */\nexport const stampReducer = (state: StampState, action: StampAction): StampState => {\n switch (action.type) {\n case 'LIBRARY_ADDED':\n return {\n ...state,\n libraries: { ...state.libraries, [action.library.id]: action.library },\n libraryOrder: [...state.libraryOrder, action.library.id],\n };\n case 'LIBRARY_UPDATED':\n return state.libraries[action.library.id]\n ? { ...state, libraries: { ...state.libraries, [action.library.id]: action.library } }\n : state;\n case 'LIBRARY_REMOVED': {\n const library = state.libraries[action.libraryId];\n if (!library) return state;\n const libraries = { ...state.libraries };\n delete libraries[action.libraryId];\n const assets = { ...state.assets };\n for (const id of library.assetIds) delete assets[id];\n return {\n ...state,\n libraries,\n libraryOrder: state.libraryOrder.filter((id) => id !== action.libraryId),\n assets,\n };\n }\n case 'ASSET_ADDED': {\n const library = state.libraries[action.asset.libraryId];\n if (!library) return state;\n return {\n ...state,\n assets: { ...state.assets, [action.asset.id]: action.asset },\n libraries: {\n ...state.libraries,\n [library.id]: { ...library, assetIds: [...library.assetIds, action.asset.id] },\n },\n };\n }\n case 'ASSET_UPDATED':\n return state.assets[action.asset.id]\n ? { ...state, assets: { ...state.assets, [action.asset.id]: action.asset } }\n : state;\n case 'ASSET_REMOVED': {\n const asset = state.assets[action.assetId];\n if (!asset) return state;\n const assets = { ...state.assets };\n delete assets[action.assetId];\n const library = state.libraries[asset.libraryId];\n return {\n ...state,\n assets,\n libraries: library\n ? {\n ...state.libraries,\n [library.id]: {\n ...library,\n assetIds: library.assetIds.filter((id) => id !== action.assetId),\n },\n }\n : state.libraries,\n };\n }\n default:\n return state;\n }\n};\n","import { definePlugin } from '@embedpdf/core';\nimport { createStampCapability } from './capability';\nimport { initialStampState, stampReducer } from './reducer';\nimport { StampToken } from './types';\nimport type { StampAction, StampCapability, StampConfig, StampState } from './types';\n\n/**\n * The stamp plugin. WORKSPACE-scoped: libraries are shared across every open\n * document; placement names its document explicitly (`armAsset(documentId, …)`)\n * and delegates to that document's annotation plugin — no hard `requires`,\n * because the annotation token is document-scoped and resolved lazily per\n * placement (a viewer without the annotation plugin fails at the arm call,\n * with the kernel's own missing-capability error).\n */\nexport const stampPlugin = (config: StampConfig = {}) =>\n definePlugin<StampState, StampAction, StampCapability>({\n id: 'stamp',\n token: StampToken,\n scope: 'workspace',\n initialState: initialStampState,\n reduce: stampReducer,\n capability: (ctx) => createStampCapability(ctx, config),\n });\n","/**\n * Keeping custom libraries — over the plugin's public API, in any environment.\n *\n * The plugin knows WHEN a library changes (`onLibraryChanged`) and WHAT its\n * canonical bytes are (`exportLibrary`, a complete PDF). WHERE those bytes\n * live is the embedder's decision: {@link StampLibraryStore} is the port,\n * declared here DOM-free like every plugin port. The browser adapter is\n * `indexedDbByteStore` in `@embedpdf/web` (structurally this port), wired by\n * the framework layer; an embedder with its own backend implements the three\n * calls once. These helpers are the proof that the two capability calls are\n * all a store needs.\n */\nimport type { StampCapability } from './types';\n\n/** The persistence port: bytes by library id. */\nexport interface StampLibraryStore {\n list(): Promise<Array<{ id: string; bytes: Uint8Array }>>;\n put(id: string, bytes: Uint8Array): Promise<void>;\n delete(id: string): Promise<void>;\n}\n\n/** An in-memory store — tests and SSR. */\nexport function memoryStampStore(): StampLibraryStore {\n const rows = new Map<string, Uint8Array>();\n return {\n list: async () => [...rows.entries()].map(([id, bytes]) => ({ id, bytes })),\n put: async (id, bytes) => {\n rows.set(id, new Uint8Array(bytes));\n },\n delete: async (id) => {\n rows.delete(id);\n },\n };\n}\n\n/**\n * Bring every stored library back: each PDF is imported as-is (its title,\n * registry, and PieceInfo id come from the file — the store's key is only a\n * hint). Call once at boot, before seeding defaults, so \"already has\n * libraries\" means the user's own.\n */\nexport async function restoreStampLibraries(\n stamp: StampCapability,\n store: StampLibraryStore,\n): Promise<string[]> {\n const restored: string[] = [];\n for (const { id, bytes } of await store.list()) {\n try {\n restored.push(await stamp.importLibraryPdf(bytes));\n } catch (error) {\n globalThis.console?.warn(`[stamp] stored library '${id}' could not be restored:`, error);\n }\n }\n return restored;\n}\n\n/**\n * Keep the store in sync from now on: every canonical change writes the\n * library's PDF (coalesced per library so a burst of edits saves once),\n * a removal deletes it. `except` names libraries never to persist — the\n * bundled default set, typically. Returns the unsubscribe.\n */\nexport function persistStampLibraries(\n stamp: StampCapability,\n store: StampLibraryStore,\n opts: { except?: readonly string[]; debounceMs?: number } = {},\n): () => void {\n const except = new Set(opts.except ?? []);\n const timers = new Map<string, ReturnType<typeof setTimeout>>();\n const write = (libraryId: string) => {\n timers.delete(libraryId);\n const bytes = stamp.exportLibrary(libraryId);\n if (!bytes) return;\n store.put(libraryId, bytes).catch((error) => {\n globalThis.console?.warn(`[stamp] persisting library '${libraryId}' failed:`, error);\n });\n };\n const off = stamp.onLibraryChanged(({ libraryId, reason }) => {\n if (except.has(libraryId)) return;\n const pending = timers.get(libraryId);\n if (pending) clearTimeout(pending);\n if (reason === 'removed') {\n timers.delete(libraryId);\n store.delete(libraryId).catch((error) => {\n globalThis.console?.warn(`[stamp] deleting stored library '${libraryId}' failed:`, error);\n });\n return;\n }\n timers.set(\n libraryId,\n setTimeout(() => write(libraryId), opts.debounceMs ?? 250),\n );\n });\n return () => {\n off();\n for (const [libraryId, timer] of timers) {\n clearTimeout(timer);\n write(libraryId);\n }\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAOA,MAAM,gBAAgB;CACpB;CACA;CACA;AACF;AAEA,IAAI,SAA4B;AAEhC,SAAgB,kBAA8B;CAC5C,IAAI,QAAQ,OAAO,IAAI,WAAW,MAAM;CACxC,IAAI,OAAO;CACX,MAAM,UAAoB,CAAC;CAC3B,cAAc,SAAS,QAAQ,UAAU;EACvC,QAAQ,KAAK,KAAK,MAAM;EACxB,QAAQ,GAAG,QAAQ,EAAE,UAAU,OAAO;CACxC,CAAC;CACD,MAAM,OAAO,KAAK;CAClB,QAAQ,WAAW,cAAc,SAAS,EAAE;CAC5C,KAAK,MAAM,UAAU,SAAS,QAAQ,GAAG,OAAO,MAAM,CAAC,CAAC,SAAS,IAAI,GAAG,EAAE;CAC1E,QAAQ,qBAAqB,cAAc,SAAS,EAAE,8BAA8B,KAAK;CACzF,SAAS,IAAI,YAAY,CAAC,CAAC,OAAO,IAAI;CACtC,OAAO,IAAI,WAAW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,WAAW,SAAS,KAAK,oCAAoC,UAAU,YAAY,KAAK;GAC1F,CAAC;GACD;EACF;EACA,OAAO,IACL,WACA,iBAAiB,MAAM,SAAS,GAAG,KAAK,cAAc,GAAG,CAC3D;CACF,CAAC;CACD,aAAa;EACX,IAAI;EACJ,KAAK,MAAM,CAAC,WAAW,UAAU,QAAQ;GACvC,aAAa,KAAK;GAClB,MAAM,SAAS;EACjB;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["PluginError","AnnotationToken","DocumentsToken","DocumentsToken","customStampName","assetIdFor","stampKey","STAMP_PIECEINFO_APP","stampPieceInfo","STAMP_LIBRARY_PIECEINFO_APP","stampLibraryPieceInfo","libraryKindFromPdfName","parseStampKey","STAMP_PIECEINFO_APP","stampKey","assetIdFor","stampPieceInfo","AnnotationHostToken","ActionsHostToken","DocumentsToken","armAsset","AnnotationToken","rememberArm","StampToken","AnnotationToken","ActionsToken","STAMP_DEFAULTS","StampToken"],"sources":["../src/services/errors.ts","../src/read/catalog.ts","../src/services/asset-engine.ts","../src/services/binaries.ts","../src/services/documents.ts","../src/services/events.ts","../src/services/ghosts.ts","../src/services/index.ts","../src/model.ts","../src/write/assets.ts","../src/blank-library.ts","../src/write/libraries.ts","../src/write/marks.ts","../src/write/placement.ts","../src/controller.ts","../src/stamp.plugin.ts","../src/state.ts","../src/persistence.ts"],"sourcesContent":["import { PluginError, toPluginError, type PluginErrorCode } from '@embedpdf/core';\n\n/** A `PluginError` raised by the stamp plugin. */\nexport const stampError = (code: PluginErrorCode, message: string): PluginError =>\n new PluginError(code, 'stamp', message);\n\nexport const notFound = (what: string, id: string): PluginError =>\n stampError('not-found', `unknown ${what} '${id}'`);\n\n/**\n * A refusal that names the missing permission. The stamp plugin acts on a\n * document it isn't bound to, so it asks that document's checks instead of\n * `ctx.assertAllowed`, and refuses with the same error.\n */\nexport const permissionDenied = (permission: string, operation: string): PluginError =>\n new PluginError('permission-denied', 'stamp', `${operation} requires ${permission}`, {\n permission,\n });\n\n/** Stop before the next step, or before anything is kept, once the caller cancelled. */\nexport const throwIfCancelled = (signal: AbortSignal | undefined): void => {\n if (signal?.aborted) {\n throw new PluginError('operation-cancelled', 'stamp', 'operation cancelled', {\n cause: signal.reason,\n });\n }\n};\n\n/**\n * A capability verb: whatever the asset engine, a sibling plugin or a binary\n * source rejects with reaches the caller as a `PluginError`.\n */\nexport const verb =\n <Args extends unknown[], Result>(run: (...args: Args) => Promise<Result>) =>\n async (...args: Args): Promise<Result> => {\n try {\n return await run(...args);\n } catch (error) {\n throw toPluginError('stamp', error);\n }\n };\n","/** Reads over the state and the binaries resource: libraries, assets,\n * previews, the library's PDF, and the checks. */\nimport { DocumentsToken, type OperationOptions } from '@embedpdf/core';\nimport { AnnotationToken } from '@embedpdf/plugin-annotation/contract';\n\nimport type {\n StampAsset,\n StampAssetFilter,\n StampCapability,\n StampLibrary,\n StampLibraryFilter,\n} from '../contract';\nimport type { StampContext, StampServices } from '../services';\nimport { notFound, throwIfCancelled, verb } from '../services/errors';\n\nexport function createCatalog(\n ctx: StampContext,\n {\n binaries,\n assetEngine,\n ghosts,\n targets,\n }: Pick<StampServices, 'binaries' | 'assetEngine' | 'ghosts' | 'targets'>,\n) {\n const { binaries: assetBinaries, libraryBinaries } = binaries;\n const { ghostProvider } = ghosts;\n const { documentIdOf } = targets;\n\n const listAssets = (filter?: StampAssetFilter): readonly StampAsset[] => {\n const state = ctx.state.get();\n const libraryIds = filter?.libraryId ? [filter.libraryId] : state.libraryOrder;\n return libraryIds\n .flatMap((libraryId) =>\n (state.libraries[libraryId]?.assetIds ?? []).map((id) => state.assets[id]),\n )\n .filter(\n (asset): asset is StampAsset =>\n asset != null &&\n (!filter?.kind || asset.kind === filter.kind) &&\n (!filter?.category || (asset.categories ?? []).includes(filter.category)),\n );\n };\n\n /** Placing is annotation work: the document's annotation plugin answers. */\n const canPlace = (documentId?: string): boolean => {\n const id = documentIdOf(documentId);\n if (!id) return false;\n return ctx.tryForDocument(AnnotationToken, id)?.canCreate() ?? false;\n };\n\n /** A stamp made from annotations copies them out of the document, as a download does. */\n const canCreateFromAnnotations = (documentId?: string): boolean => {\n const id = documentIdOf(documentId);\n return id !== null && ctx.get(DocumentsToken).canDownload(id);\n };\n\n return {\n canPlace,\n canCreateFromAnnotations,\n api: {\n listLibraries: (filter?: StampLibraryFilter) => {\n const state = ctx.state.get();\n const kinds =\n filter?.kind === undefined\n ? null\n : new Set(typeof filter.kind === 'string' ? [filter.kind] : filter.kind);\n return state.libraryOrder\n .map((id) => state.libraries[id])\n .filter(\n (library): library is StampLibrary =>\n library != null && (kinds === null || kinds.has(library.kind)),\n );\n },\n getLibrary: (libraryId) => ctx.state.get().libraries[libraryId] ?? null,\n listAssets,\n getAsset: (assetId) => ctx.state.get().assets[assetId] ?? null,\n getAssetPreview: (assetId) => assetBinaries.get(assetId)?.preview ?? null,\n renderAssetPreview: verb(\n async (assetId: string, { width, signal }: { width: number } & OperationOptions) => {\n throwIfCancelled(signal);\n const binary = assetBinaries.get(assetId);\n if (!binary) throw notFound('asset', assetId);\n const preview = await ctx.cancellable(\n signal,\n ghostProvider(binary.bytes, binary.preview, assetId)(width),\n );\n return preview\n ? { bytes: preview.bytes, mimeType: preview.mimeType ?? 'image/png' }\n : null;\n },\n ),\n readAssetBytes: (assetId) => {\n const bytes = assetBinaries.get(assetId)?.bytes;\n return bytes ? new Uint8Array(bytes) : null;\n },\n exportLibrary: async (libraryId, options) => {\n throwIfCancelled(options?.signal);\n const bytes = libraryBinaries.get(libraryId);\n if (!bytes) throw notFound('library', libraryId);\n return new Uint8Array(bytes);\n },\n canPlace,\n canCreateFromAnnotations,\n canImport: assetEngine.canImport,\n } satisfies Partial<StampCapability>,\n };\n}\nexport type StampCatalog = ReturnType<typeof createCatalog>;\n","/**\n * The asset engine port and the canonical-library services every write\n * needs: opening library bytes as a document on a local engine, import-time\n * previews, and the import-support fact learned from the first import.\n */\nimport { isLocalEngine } from '@embedpdf/engine-core/runtime';\nimport type {\n Engine,\n LocalDocumentHandle,\n LocalPageHandle,\n PageImageHandle,\n} from '@embedpdf/engine-core/runtime';\n\nimport type { StampAssetEngine, StampAssetPreview } from '../contract';\nimport type { StampContext } from './context';\nimport { stampError } from './errors';\n\n/** Session-unique ids (scratch documents, library ids a file does not carry):\n * a timestamp plus a counter. */\nlet idCounter = 0;\nexport const uid = (prefix: string): string =>\n `${prefix}-${Date.now().toString(36)}-${(idCounter++).toString(36)}`;\n\nexport function createAssetEngine(ctx: StampContext) {\n const settings = ctx.settings();\n /** Set once an import finds the asset engine is not local (cloud). */\n let importSupported: boolean | null = null;\n\n // The asset engine port, read from the setting. A configured function is\n // called (and memoized) on the first import, not at viewer start; a\n // configured engine is used as it is; none falls back to the kernel's\n // engine: right for local deployments, and refused with an actionable\n // error at the first import when it is a cloud engine. A change of the\n // setting takes effect at the next library operation.\n let resolved: { from: StampAssetEngine | null; engine: Engine | Promise<Engine> } | null = null;\n /** Engines this plugin made through a configured function: destroyed with it. */\n const owned: Array<Engine | Promise<Engine>> = [];\n const assetEngine = (): Engine | Promise<Engine> => {\n const configured = settings.get().assetEngine;\n if (resolved?.from !== configured) {\n const engine = !configured\n ? ctx.engine\n : typeof configured === 'function'\n ? configured()\n : configured;\n if (typeof configured === 'function') owned.push(engine);\n resolved = { from: configured, engine };\n importSupported = null;\n }\n return resolved.engine;\n };\n\n /** Library PDFs are sliced and tagged (`/PieceInfo`) on a local engine only. */\n const openAssetDocument = async (bytes: Uint8Array): Promise<LocalDocumentHandle> => {\n const engine = await assetEngine();\n if (!isLocalEngine(engine)) {\n if (importSupported !== false) {\n importSupported = false;\n ctx.notify();\n }\n throw stampError(\n 'unsupported',\n settings.get().assetEngine\n ? \"the stamp plugin's assetEngine must be a local engine (createLocalEngine())\"\n : \"importing a library PDF needs a local engine, and this viewer's engine is a cloud engine. Pass stampPlugin({ assetEngine: () => import('@embedpdf/engine').then((module) => module.createLocalEngine()) }): it loads lazily, on first import.\",\n );\n }\n return engine.open({ kind: 'bytes', id: uid('stamp-import'), bytes }, { scope: ['*'] });\n };\n\n /** Import-time preview render to bytes. The asset engine is local by\n * definition, so the image source is always inline bytes. */\n const imageToPreview = (image: PageImageHandle): StampAssetPreview => {\n if (image.source.kind !== 'bytes') {\n throw stampError(\n 'unsupported',\n 'the asset engine returned a URL-sourced render; asset engines must be local',\n );\n }\n return { bytes: image.source.bytes, mimeType: image.contentType };\n };\n\n /** Thumbnail render of one library page (the small picker image). */\n const renderThumbnail = async (handle: LocalPageHandle): Promise<StampAssetPreview> =>\n imageToPreview(\n await handle.render.image({\n viewport: { kind: 'width', width: settings.get().previewWidth },\n background: 'transparent',\n includeAnnotations: true,\n format: 'png',\n }),\n );\n\n ctx.cleanup(() => {\n resolved = null;\n for (const engine of owned.splice(0)) {\n void Promise.resolve(engine)\n .then((made) => made.destroy())\n .catch(() => {});\n }\n });\n\n return {\n openAssetDocument,\n imageToPreview,\n renderThumbnail,\n /** Optimistic until an import finds the asset engine is not local (cloud). */\n canImport: (): boolean => {\n // Reading the setting re-resolves after a change, which makes imports possible again.\n if (resolved && resolved.from !== settings.get().assetEngine) return true;\n return importSupported !== false;\n },\n };\n}\nexport type StampAssetEngineService = ReturnType<typeof createAssetEngine>;\n","/**\n * The binaries resource: asset bytes and cached previews, the canonical\n * library PDFs, and the ghost render caches. State holds only the\n * serializable descriptors; everything binary lives here, next to the\n * per-library mutation queue that orders whole-PDF rewrites.\n */\nimport type { StampAssetPreview } from '../contract';\nimport type { StampContext } from './context';\n\nexport function createBinaries(ctx: StampContext) {\n /** Asset bytes (a one-page placement PDF) and the cached preview, by asset id. */\n const binaries = new Map<string, { bytes: Uint8Array; preview: StampAssetPreview | null }>();\n /** The durable source of truth for a canonical library. Asset PDFs above\n * are derived page extractions; this map owns the rewritten whole PDF. */\n const libraryBinaries = new Map<string, Uint8Array>();\n\n /** Whole-PDF rewrites are serialized per library, or two concurrent\n * appends could both start from the same bytes and lose one page. A\n * mutation whose signal fired while it waited never starts. */\n const mutateLibrary = <T>(\n libraryId: string,\n mutation: () => Promise<T>,\n signal?: AbortSignal,\n ): Promise<T> => ctx.serialQueue(`library:${libraryId}`)(mutation, { signal });\n\n /**\n * Ghost renders, one per size bucket per asset, rendered lazily on the\n * asset engine the first time the ghost is shown at that size and kept\n * until the asset goes away. Materialized (dynamic) placements are\n * user/time specific and cache only for their own arm (`cacheKey` null).\n */\n const ghostRenders = new Map<string, Map<number, Promise<StampAssetPreview | null>>>();\n\n ctx.cleanup(() => {\n binaries.clear();\n ghostRenders.clear();\n libraryBinaries.clear();\n });\n\n return { binaries, libraryBinaries, ghostRenders, mutateLibrary };\n}\nexport type StampBinaries = ReturnType<typeof createBinaries>;\n","/**\n * The document a placing verb acts on: the one its options name, else the\n * active one (a document's scope fills `documentId` in through the plugin's\n * `inScope`), and the page arguments resolved in it.\n */\nimport { DocumentsToken, type PageInfo, type PageRef } from '@embedpdf/core';\n\nimport type { StampDocumentOptions } from '../contract';\nimport type { StampContext } from './context';\nimport { stampError } from './errors';\n\nexport function createTargets(ctx: StampContext) {\n const documents = () => ctx.get(DocumentsToken);\n\n /** The document's id, or null with no document open. */\n const documentIdOf = (documentId: string | undefined): string | null =>\n documentId ?? documents().getActiveId();\n\n /** The document a verb acts on. Rejects `not-ready` with no document open. */\n const targetOf = (options: StampDocumentOptions | undefined): string => {\n const documentId = documentIdOf(options?.documentId);\n if (!documentId) throw stampError('not-ready', 'no document is open');\n return documentId;\n };\n\n /** A page argument of the document, as a ref or an index. Rejects `not-found`. */\n const pageOf = (documentId: string, page: PageRef | number): PageInfo => {\n const found = documents().getPage(page, documentId);\n if (!found) {\n throw stampError(\n 'not-found',\n `no page ${typeof page === 'number' ? page : page.objectNumber} in document '${documentId}'`,\n );\n }\n return found;\n };\n\n return { documentIdOf, targetOf, pageOf };\n}\nexport type StampTargets = ReturnType<typeof createTargets>;\n","/** The capability's events, minted on the instance so they are disposed with it. */\nimport type {\n StampArmChangedEvent,\n StampAssetCreatedEvent,\n StampAssetDeletedEvent,\n StampAssetUpdatedEvent,\n StampLibraryChangedEvent,\n StampLibraryCreatedEvent,\n StampLibraryDeletedEvent,\n StampLibraryUpdatedEvent,\n} from '../contract';\nimport type { StampContext } from './context';\n\nexport function createEvents(ctx: StampContext) {\n return {\n libraryChanged: ctx.events.source<StampLibraryChangedEvent>(),\n libraryCreated: ctx.events.source<StampLibraryCreatedEvent>(),\n libraryUpdated: ctx.events.source<StampLibraryUpdatedEvent>(),\n libraryDeleted: ctx.events.source<StampLibraryDeletedEvent>(),\n assetCreated: ctx.events.source<StampAssetCreatedEvent>(),\n assetUpdated: ctx.events.source<StampAssetUpdatedEvent>(),\n assetDeleted: ctx.events.source<StampAssetDeletedEvent>(),\n armChanged: ctx.events.source<StampArmChangedEvent>(),\n };\n}\nexport type StampEvents = ReturnType<typeof createEvents>;\n","/**\n * Ghost renders, one per size bucket per asset, rendered lazily on the asset\n * engine the first time the ghost is shown at that size and kept until the\n * asset goes away. Materialized (dynamic) placements are user/time specific\n * and cache only for their own arm (`cacheKey` null).\n */\nimport type { StampPreviewProvider } from '@embedpdf/plugin-annotation/contract';\n\nimport type { StampAssetPreview } from '../contract';\nimport type { StampAssetEngineService } from './asset-engine';\nimport type { StampBinaries } from './binaries';\n\nexport function createGhosts(\n {\n openAssetDocument,\n imageToPreview,\n }: Pick<StampAssetEngineService, 'openAssetDocument' | 'imageToPreview'>,\n { ghostRenders }: Pick<StampBinaries, 'ghostRenders'>,\n) {\n const renderGhost = async (bytes: Uint8Array, devicePixelWidth: number) => {\n const doc = await openAssetDocument(new Uint8Array(bytes));\n try {\n const layout = await doc.pages.list();\n const page = layout.pages[0];\n if (!page) return null;\n return imageToPreview(\n await doc.page(page.ref).render.image({\n viewport: { kind: 'width', width: devicePixelWidth },\n background: 'transparent',\n includeAnnotations: true,\n format: 'png',\n }),\n );\n } finally {\n await doc.close();\n }\n };\n\n /** A resolution-aware ghost source for placement bytes: the page renders\n * at the requested width, cached per bucket under `cacheKey` when given. */\n const ghostProvider = (\n bytes: Uint8Array,\n fallback: StampAssetPreview | null,\n cacheKey: string | null,\n ): StampPreviewProvider => {\n const local = cacheKey ? (ghostRenders.get(cacheKey) ?? new Map()) : new Map();\n if (cacheKey) ghostRenders.set(cacheKey, local);\n return (devicePixelWidth) => {\n let pending = local.get(devicePixelWidth);\n if (!pending) {\n pending = renderGhost(bytes, devicePixelWidth).catch((error) => {\n globalThis.console?.warn('[stamp] ghost render failed, using the thumbnail:', error);\n return fallback;\n });\n local.set(devicePixelWidth, pending);\n }\n return pending;\n };\n };\n\n return { ghostProvider };\n}\nexport type StampGhosts = ReturnType<typeof createGhosts>;\n","/**\n * Plugin-private services every area is built on (not the kernel): the\n * events, the binaries resource, the asset engine port, the ghost renderer\n * and the document a placing verb acts on.\n */\nimport { createAssetEngine, type StampAssetEngineService } from './asset-engine';\nimport { createBinaries, type StampBinaries } from './binaries';\nimport type { StampContext } from './context';\nimport { createTargets, type StampTargets } from './documents';\nimport { createEvents, type StampEvents } from './events';\nimport { createGhosts, type StampGhosts } from './ghosts';\n\nexport type { StampContext } from './context';\n\nexport interface StampServices {\n readonly events: StampEvents;\n readonly binaries: StampBinaries;\n readonly assetEngine: StampAssetEngineService;\n readonly ghosts: StampGhosts;\n readonly targets: StampTargets;\n}\n\nexport function createServices(ctx: StampContext): StampServices {\n const binaries = createBinaries(ctx);\n const assetEngine = createAssetEngine(ctx);\n return {\n events: createEvents(ctx),\n binaries,\n assetEngine,\n ghosts: createGhosts(assetEngine, binaries),\n targets: createTargets(ctx),\n };\n}\n","/**\n * The stamp plugin's session state: libraries, their display order and\n * assets, as serializable descriptors, and the asset armed on each document.\n * The bytes and previews they describe live in the binaries resource\n * (`services/binaries.ts`) and never enter state. Every function below is a\n * pure transition; the areas apply them with `ctx.state.update`.\n */\nimport type { StampAsset, StampLibrary } from './contract';\n\nexport interface StampState {\n readonly libraries: Readonly<Record<string, StampLibrary>>;\n /** Library display order (insertion order). */\n readonly libraryOrder: readonly string[];\n readonly assets: Readonly<Record<string, StampAsset>>;\n /** Document id → the id of the asset armed there. */\n readonly armed: Readonly<Record<string, string>>;\n}\n\nexport const initialStampState = (): StampState => ({\n libraries: {},\n libraryOrder: [],\n assets: {},\n armed: {},\n});\n\n/** Remember the asset armed on a document. */\nexport function armAsset(state: StampState, documentId: string, assetId: string): StampState {\n if (state.armed[documentId] === assetId) return state;\n return { ...state, armed: { ...state.armed, [documentId]: assetId } };\n}\n\n/** Forget what was armed on these documents. */\nexport function disarmDocuments(state: StampState, documentIds: readonly string[]): StampState {\n if (!documentIds.some((documentId) => documentId in state.armed)) return state;\n const armed = { ...state.armed };\n for (const documentId of documentIds) delete armed[documentId];\n return { ...state, armed };\n}\n\n/** Append a library to the display order. */\nexport function addLibrary(state: StampState, library: StampLibrary): StampState {\n return {\n ...state,\n libraries: { ...state.libraries, [library.id]: library },\n libraryOrder: [...state.libraryOrder, library.id],\n };\n}\n\n/** Replace a known library's descriptor; an unknown id changes nothing. */\nexport function setLibrary(state: StampState, library: StampLibrary): StampState {\n if (!state.libraries[library.id]) return state;\n return { ...state, libraries: { ...state.libraries, [library.id]: library } };\n}\n\n/** Remove a library together with its assets. */\nexport function removeLibrary(state: StampState, libraryId: string): StampState {\n const library = state.libraries[libraryId];\n if (!library) return state;\n const { [libraryId]: _removed, ...libraries } = state.libraries;\n const assets = { ...state.assets };\n for (const id of library.assetIds) delete assets[id];\n return {\n ...state,\n libraries,\n libraryOrder: state.libraryOrder.filter((id) => id !== libraryId),\n assets,\n };\n}\n\n/** Add an asset to the end of its library; an asset of an unknown library changes nothing. */\nexport function addAsset(state: StampState, asset: StampAsset): StampState {\n const library = state.libraries[asset.libraryId];\n if (!library) return state;\n return {\n ...state,\n assets: { ...state.assets, [asset.id]: asset },\n libraries: {\n ...state.libraries,\n [library.id]: { ...library, assetIds: [...library.assetIds, asset.id] },\n },\n };\n}\n\n/** Replace a known asset's descriptor; an unknown id changes nothing. */\nexport function setAsset(state: StampState, asset: StampAsset): StampState {\n if (!state.assets[asset.id]) return state;\n return { ...state, assets: { ...state.assets, [asset.id]: asset } };\n}\n\n/** Remove an asset and its entry in its library's order. */\nexport function removeAsset(state: StampState, assetId: string): StampState {\n const asset = state.assets[assetId];\n if (!asset) return state;\n const { [assetId]: _removed, ...assets } = state.assets;\n const library = state.libraries[asset.libraryId];\n return {\n ...state,\n assets,\n libraries: library\n ? {\n ...state.libraries,\n [library.id]: {\n ...library,\n assetIds: library.assetIds.filter((id) => id !== assetId),\n },\n }\n : state.libraries,\n };\n}\n","/**\n * Asset writes: every asset is a page of its library's PDF — a single-page\n * PDF is inserted, a raster becomes a page with the image flattened into it.\n * Removal deletes the page; relabel renames the registry entry. All through\n * the per-library mutation queue.\n */\nimport type { OperationOptions } from '@embedpdf/core';\nimport { resolveBinarySource, sniffBinaryMetadata } from '@embedpdf/engine-core/runtime';\nimport type { AnnotationRef, PageRef } from '@embedpdf/engine-core/runtime';\n\nimport type {\n AddAssetInput,\n AssetFromAnnotationsInput,\n StampAsset,\n StampAssetPatch,\n StampAssetPreview,\n StampCapability,\n StampDocumentOptions,\n} from '../contract';\nimport {\n assetIdFor,\n customStampName,\n stampKey,\n stampPieceInfo,\n STAMP_PIECEINFO_APP,\n} from '../convention';\nimport { addAsset, removeAsset, setAsset } from '../model';\nimport type { StampContext, StampServices } from '../services';\nimport { notFound, permissionDenied, stampError, throwIfCancelled, verb } from '../services/errors';\nimport type { StampLibraryWrites } from './libraries';\nimport type { StampMarks } from './marks';\nimport type { StampCatalog } from '../read/catalog';\n\nexport function createAssetWrites(\n ctx: StampContext,\n {\n events,\n binaries,\n assetEngine,\n targets,\n }: Pick<StampServices, 'events' | 'binaries' | 'assetEngine' | 'targets'>,\n { resolveAssetSource }: StampMarks,\n { createLibrary }: Pick<StampLibraryWrites, 'createLibrary'>,\n { canCreateFromAnnotations }: Pick<StampCatalog, 'canCreateFromAnnotations'>,\n) {\n const { libraryChanged, assetCreated, assetUpdated, assetDeleted } = events;\n const { binaries: assetBinaries, libraryBinaries, ghostRenders, mutateLibrary } = binaries;\n const { openAssetDocument, renderThumbnail } = assetEngine;\n const { targetOf, pageOf } = targets;\n\n const createAsset = async (\n input: AddAssetInput,\n options?: OperationOptions,\n ): Promise<{ asset: StampAsset }> => {\n const signal = options?.signal;\n throwIfCancelled(signal);\n if (input.libraryId && !ctx.state.get().libraries[input.libraryId]) {\n throw notFound('library', input.libraryId);\n }\n const resolved = await ctx.cancellable(signal, resolveAssetSource(input));\n const meta = sniffBinaryMetadata(resolved.bytes);\n if (!meta) {\n throw stampError('invalid-input', 'asset source must be PNG, JPEG, or single-page PDF bytes');\n }\n const isPdf = meta.mimeType === 'application/pdf';\n const name = input.name ?? customStampName();\n const label = input.label ?? name;\n if (name.length === 0 || name.includes('=')) {\n throw stampError(\n 'invalid-input',\n `invalid stamp identifier '${name}': must be non-empty and contain no '='`,\n );\n }\n const rasterSize =\n input.size ?? ('width' in meta ? { width: meta.width, height: meta.height } : null);\n if (!isPdf && (!rasterSize || rasterSize.width <= 0 || rasterSize.height <= 0)) {\n throw stampError(\n 'invalid-input',\n 'a raster asset needs a positive `size` (its page size in points)',\n );\n }\n\n let suppliedPreview: StampAssetPreview | null = null;\n if (input.preview) {\n const preview = await resolveBinarySource(input.preview);\n suppliedPreview = {\n bytes: new Uint8Array(preview.bytes),\n mimeType: preview.mimeType ?? 'image/png',\n };\n }\n\n // No library named: one of its own, named after the label.\n const libraryId = input.libraryId ?? (await createLibrary(label, { signal })).library.id;\n\n return mutateLibrary(\n libraryId,\n async () => {\n const liveLibrary = ctx.state.get().libraries[libraryId];\n if (!liveLibrary) {\n throw stampError('not-found', `library '${libraryId}' no longer exists`);\n }\n const assetId = assetIdFor(liveLibrary.id, name);\n if (ctx.state.get().assets[assetId]) {\n throw stampError(\n 'invalid-input',\n `library '${liveLibrary.name}' already has a stamp named '${name}'`,\n );\n }\n const canonicalBytes = libraryBinaries.get(liveLibrary.id);\n if (!canonicalBytes) {\n throw stampError(\n 'operation-failed',\n `canonical bytes are missing for library '${liveLibrary.id}'`,\n );\n }\n\n const doc = await ctx.cancellable(signal, openAssetDocument(canonicalBytes));\n let appended:\n | {\n asset: StampAsset;\n bytes: Uint8Array;\n preview: StampAssetPreview;\n canonical: Uint8Array;\n }\n | undefined;\n try {\n let page: PageRef;\n if (isPdf) {\n const result = await doc.pages.insert(new Uint8Array(resolved.bytes));\n if (result.insertedPages.length !== 1) {\n throw stampError('invalid-input', 'a library asset must be a single-page PDF');\n }\n page = result.insertedPages[0];\n } else {\n // A raster becomes a page: a blank page the image's size, the image\n // placed to fill it, flattened into content. From here on it is a\n // page like any other: exportable, persistable, Acrobat-readable.\n if (!doc.pages.flatten) {\n throw stampError(\n 'unsupported',\n 'raster assets need an asset engine with pages.flatten',\n );\n }\n const blank = await doc.pages.insertBlank({ size: rasterSize! });\n page = blank.insertedPages[0];\n await doc.page(page).annotations.create(\n {\n subtype: 'stamp',\n box: { x: 0, y: 0, width: rasterSize!.width, height: rasterSize!.height },\n fit: 'fill',\n },\n { resources: { appearance: new Uint8Array(resolved.bytes) } },\n );\n const flattened = await doc.pages.flatten([page], { usage: 'display' });\n if (flattened.results.some(({ status }) => status !== 'applied')) {\n throw stampError('operation-failed', 'flattening the raster into its page failed');\n }\n }\n const layout = (await doc.pages.list()).pages.find(\n (candidate) => candidate.ref.objectNumber === page.objectNumber,\n );\n const handle = doc.page(page);\n if (!layout) {\n throw stampError('operation-failed', 'the new page is missing from the library layout');\n }\n // Insert copies the page only: register it in the same mutation.\n await doc.pages.setName({ name: stampKey(name, label), page });\n const asset: StampAsset = {\n id: assetId,\n libraryId: liveLibrary.id,\n kind: input.kind ?? 'stamp',\n name,\n label,\n size: { width: layout.size.width, height: layout.size.height },\n page,\n ...(input.subject !== undefined ? { subject: input.subject } : {}),\n ...(input.categories !== undefined ? { categories: input.categories } : {}),\n };\n await handle.pieceInfo.update(\n STAMP_PIECEINFO_APP,\n stampPieceInfo(asset.kind, { subject: asset.subject, categories: asset.categories }),\n );\n const bytes = await doc.pages.extract([page]);\n const preview = suppliedPreview ?? (await renderThumbnail(handle));\n appended = { asset, bytes, preview, canonical: await doc.download() };\n } finally {\n await doc.close();\n }\n\n throwIfCancelled(signal);\n libraryBinaries.set(liveLibrary.id, appended.canonical);\n assetBinaries.set(appended.asset.id, { bytes: appended.bytes, preview: appended.preview });\n ctx.state.update(addAsset, appended.asset);\n libraryChanged.emit({ libraryId: liveLibrary.id, reason: 'asset-added' });\n assetCreated.emit({\n assetId: appended.asset.id,\n libraryId: liveLibrary.id,\n asset: appended.asset,\n });\n return { asset: appended.asset };\n },\n signal,\n );\n };\n\n const createAssetFromAnnotations = async (\n page: PageRef | number,\n refs: readonly AnnotationRef[],\n input: AssetFromAnnotationsInput,\n options?: StampDocumentOptions,\n ): Promise<{ asset: StampAsset }> => {\n const signal = options?.signal;\n throwIfCancelled(signal);\n const documentId = targetOf(options);\n if (!canCreateFromAnnotations(documentId)) {\n throw permissionDenied('doc.download', 'stamp.createAssetFromAnnotations');\n }\n const doc = ctx.documentHandle(documentId);\n if (!doc) throw stampError('not-found', `document '${documentId}' is not open`);\n const handle = doc.page(pageOf(documentId, page).ref);\n // The engine flattens the selection into a fresh single-page PDF: the\n // same placement whole-page flatten uses, aimed at a new page.\n const source = await ctx.cancellable(signal, handle.annotations.exportAppearance([...refs]));\n return createAsset({ ...input, source }, { signal });\n };\n\n const deleteAsset = async (id: string, options?: OperationOptions): Promise<void> => {\n const signal = options?.signal;\n throwIfCancelled(signal);\n const initialAsset = ctx.state.get().assets[id];\n if (!initialAsset) return;\n return mutateLibrary(\n initialAsset.libraryId,\n async () => {\n const asset = ctx.state.get().assets[id];\n if (!asset) return;\n const library = ctx.state.get().libraries[asset.libraryId];\n if (!library) return;\n const canonicalBytes = libraryBinaries.get(library.id);\n if (!canonicalBytes) {\n throw stampError(\n 'operation-failed',\n `canonical bytes are missing for library '${library.id}'`,\n );\n }\n // The page goes; the engine drops its registry entry inside the\n // delete. The unregistered blank keeps the file valid when this was\n // the last stamp: a library with no stamps is still a library.\n const doc = await ctx.cancellable(signal, openAssetDocument(canonicalBytes));\n let rewritten: Uint8Array | undefined;\n try {\n await doc.pages.delete([asset.page]);\n rewritten = await doc.download();\n } finally {\n await doc.close();\n }\n throwIfCancelled(signal);\n libraryBinaries.set(library.id, rewritten);\n assetBinaries.delete(id);\n ghostRenders.delete(id);\n ctx.state.update(removeAsset, id);\n libraryChanged.emit({ libraryId: library.id, reason: 'asset-removed' });\n assetDeleted.emit({ assetId: id, libraryId: library.id, asset: null });\n },\n signal,\n );\n };\n\n const updateAsset = async (\n id: string,\n patch: StampAssetPatch,\n options?: OperationOptions,\n ): Promise<{ asset: StampAsset }> => {\n const signal = options?.signal;\n throwIfCancelled(signal);\n const initial = ctx.state.get().assets[id];\n if (!initial) throw notFound('asset', id);\n return mutateLibrary(\n initial.libraryId,\n async () => {\n const asset = ctx.state.get().assets[id];\n const library = asset ? ctx.state.get().libraries[asset.libraryId] : undefined;\n if (!asset || !library) throw notFound('asset', id);\n const next: StampAsset = {\n ...asset,\n ...(patch.label !== undefined ? { label: patch.label } : {}),\n ...(patch.categories !== undefined ? { categories: patch.categories } : {}),\n };\n if (patch.subject === null) delete next.subject;\n else if (patch.subject !== undefined) next.subject = patch.subject;\n\n const canonicalBytes = libraryBinaries.get(library.id);\n if (!canonicalBytes) {\n throw stampError(\n 'operation-failed',\n `canonical bytes are missing for library '${library.id}'`,\n );\n }\n const doc = await ctx.cancellable(signal, openAssetDocument(canonicalBytes));\n let rewritten: Uint8Array | undefined;\n try {\n if (next.label !== asset.label) {\n // A relabel is a registry rename: one job, the identifier untouched.\n await doc.pages.setName({\n name: stampKey(asset.name, next.label),\n page: asset.page,\n replace: stampKey(asset.name, asset.label),\n });\n }\n const page = doc.page(asset.page);\n await page.pieceInfo.update(\n STAMP_PIECEINFO_APP,\n stampPieceInfo(next.kind, { subject: next.subject, categories: next.categories }),\n );\n rewritten = await doc.download();\n } finally {\n await doc.close();\n }\n throwIfCancelled(signal);\n libraryBinaries.set(library.id, rewritten);\n ctx.state.update(setAsset, next);\n libraryChanged.emit({ libraryId: library.id, reason: 'asset-updated' });\n assetUpdated.emit({ assetId: next.id, libraryId: library.id, asset: next });\n return { asset: next };\n },\n signal,\n );\n };\n\n const moveAsset = async (\n id: string,\n to: { libraryId: string },\n options?: OperationOptions,\n ): Promise<{ asset: StampAsset }> => {\n const signal = options?.signal;\n throwIfCancelled(signal);\n const asset = ctx.state.get().assets[id];\n const binary = assetBinaries.get(id);\n if (!asset || !binary) throw notFound('asset', id);\n if (to.libraryId === asset.libraryId) return { asset };\n const copy = await createAsset(\n {\n libraryId: to.libraryId,\n source: new Uint8Array(binary.bytes),\n kind: asset.kind,\n label: asset.label,\n ...(asset.subject !== undefined ? { subject: asset.subject } : {}),\n ...(asset.categories ? { categories: [...asset.categories] } : {}),\n ...(binary.preview ? { preview: binary.preview.bytes } : {}),\n },\n { signal },\n );\n // The copy is in place: the original goes even if the caller cancels now.\n await deleteAsset(id);\n return copy;\n };\n\n const duplicateAsset = async (\n id: string,\n options?: { label?: string } & OperationOptions,\n ): Promise<{ asset: StampAsset }> => {\n throwIfCancelled(options?.signal);\n const asset = ctx.state.get().assets[id];\n const binary = assetBinaries.get(id);\n if (!asset || !binary) throw notFound('asset', id);\n return createAsset(\n {\n libraryId: asset.libraryId,\n source: new Uint8Array(binary.bytes),\n kind: asset.kind,\n label: options?.label ?? `${asset.label} copy`,\n ...(asset.subject !== undefined ? { subject: asset.subject } : {}),\n ...(asset.categories ? { categories: [...asset.categories] } : {}),\n ...(binary.preview ? { preview: binary.preview.bytes } : {}),\n },\n { signal: options?.signal },\n );\n };\n\n return {\n api: {\n createAsset: verb(createAsset),\n createAssetFromAnnotations: verb(createAssetFromAnnotations),\n updateAsset: verb(updateAsset),\n deleteAsset: verb(deleteAsset),\n moveAsset: verb(moveAsset),\n duplicateAsset: verb(duplicateAsset),\n } satisfies Partial<StampCapability>,\n };\n}\n","/**\n * The seed of a new library: a one-page PDF whose page is unregistered, the\n * shape Acrobat itself gives a fresh stamp library (its first page is a\n * blank starter that no `/Names /Pages` key points at). A library must be a\n * PDF from the moment it exists, and a PDF must have a page; the unregistered\n * blank is that page. It is never an asset, never placed, never listed.\n */\nconst BLANK_OBJECTS = [\n '<< /Type /Catalog /Pages 2 0 R >>',\n '<< /Type /Pages /Kids [3 0 R] /Count 1 >>',\n '<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>',\n];\n\nlet cached: Uint8Array | null = null;\n\nexport function blankLibraryPdf(): Uint8Array {\n if (cached) return new Uint8Array(cached);\n let body = '%PDF-1.7\\n';\n const offsets: number[] = [];\n BLANK_OBJECTS.forEach((object, index) => {\n offsets.push(body.length);\n body += `${index + 1} 0 obj\\n${object}\\nendobj\\n`;\n });\n const xref = body.length;\n body += `xref\\n0 ${BLANK_OBJECTS.length + 1}\\n0000000000 65535 f \\n`;\n for (const offset of offsets) body += `${String(offset).padStart(10, '0')} 00000 n \\n`;\n body += `trailer\\n<< /Size ${BLANK_OBJECTS.length + 1} /Root 1 0 R >>\\nstartxref\\n${xref}\\n%%EOF\\n`;\n cached = new TextEncoder().encode(body);\n return new Uint8Array(cached);\n}\n","/**\n * Library writes. A library is a PDF: its `/Title` is the name, its\n * `/Names /Pages` registry the assets, its pages the artwork, PieceInfo only\n * what has no standard home. Every whole-PDF rewrite rides the per-library\n * mutation queue.\n */\nimport { resolveBinarySource, sniffBinaryMetadata } from '@embedpdf/engine-core/runtime';\nimport type { BinarySource, PageRef, PieceInfoEntry } from '@embedpdf/engine-core/runtime';\n\nimport { blankLibraryPdf } from '../blank-library';\nimport type { OperationOptions } from '@embedpdf/core';\n\nimport type {\n CreateLibraryOptions,\n ImportLibraryOptions,\n StampAsset,\n StampAssetKind,\n StampAssetPreview,\n StampCapability,\n StampLibrary,\n StampLibraryPatch,\n} from '../contract';\nimport {\n assetIdFor,\n DEFAULT_LIBRARY_KIND,\n libraryKindFromPdfName,\n parseStampKey,\n stampKey,\n stampLibraryPieceInfo,\n stampPieceInfo,\n STAMP_LIBRARY_PIECEINFO_APP,\n STAMP_PIECEINFO_APP,\n} from '../convention';\nimport { addAsset, addLibrary, removeLibrary, setLibrary } from '../model';\nimport type { StampContext, StampServices } from '../services';\nimport { uid } from '../services/asset-engine';\nimport { notFound, stampError, throwIfCancelled, verb } from '../services/errors';\n\nconst entryString = (entries: Record<string, PieceInfoEntry>, key: string): string | undefined => {\n const entry = entries[key];\n return entry?.type === 'string' && entry.value.length > 0 ? entry.value : undefined;\n};\n\nconst entryName = (entries: Record<string, PieceInfoEntry>, key: string): string | undefined => {\n const entry = entries[key];\n return entry?.type === 'name' && entry.value.length > 0 ? entry.value : undefined;\n};\n\nconst entryStringArray = (\n entries: Record<string, PieceInfoEntry>,\n key: string,\n): string[] | undefined => {\n const entry = entries[key];\n return entry?.type === 'string-array' ? [...entry.value] : undefined;\n};\n\nconst kindFromPdfName = (name: string | undefined): StampAssetKind | undefined => {\n switch (name?.toLowerCase()) {\n case 'stamp':\n return 'stamp';\n case 'signature':\n return 'signature';\n case 'initials':\n return 'initials';\n default:\n return undefined;\n }\n};\n\nconst allocateId = (preferred: string | undefined, prefix: string, taken: Set<string>): string => {\n let id = preferred;\n if (!id || taken.has(id)) {\n do id = uid(prefix);\n while (taken.has(id));\n }\n taken.add(id);\n return id;\n};\n\nexport function createLibraryWrites(\n ctx: StampContext,\n { events, binaries, assetEngine }: Pick<StampServices, 'events' | 'binaries' | 'assetEngine'>,\n) {\n const { libraryChanged, libraryCreated, libraryUpdated, libraryDeleted, assetCreated } = events;\n const { binaries: assetBinaries, libraryBinaries, ghostRenders, mutateLibrary } = binaries;\n const { openAssetDocument, renderThumbnail } = assetEngine;\n\n const createLibrary = async (\n name: string,\n options?: CreateLibraryOptions,\n ): Promise<{ library: StampLibrary }> => {\n const signal = options?.signal;\n throwIfCancelled(signal);\n const kind = options?.kind ?? DEFAULT_LIBRARY_KIND;\n const taken = new Set(Object.keys(ctx.state.get().libraries));\n const id = allocateId(options?.id, 'stamp-lib', taken);\n const doc = await ctx.cancellable(signal, openAssetDocument(blankLibraryPdf()));\n let bytes: Uint8Array;\n try {\n await doc.metadata.update({ title: name });\n await doc.pieceInfo.update(\n STAMP_LIBRARY_PIECEINFO_APP,\n stampLibraryPieceInfo(id, { kind, categories: options?.categories }),\n );\n bytes = await doc.download();\n } finally {\n await doc.close();\n }\n throwIfCancelled(signal);\n const library: StampLibrary = {\n id,\n name,\n kind,\n assetIds: [],\n ...(options?.categories ? { categories: options.categories } : {}),\n };\n libraryBinaries.set(id, bytes);\n ctx.state.update(addLibrary, library);\n libraryChanged.emit({ libraryId: id, reason: 'created' });\n libraryCreated.emit({ libraryId: id, library });\n return { library };\n };\n\n const importLibrary = async (\n source: BinarySource,\n options?: ImportLibraryOptions,\n ): Promise<{ library: StampLibrary }> => {\n const signal = options?.signal;\n throwIfCancelled(signal);\n const resolved = await ctx.cancellable(signal, resolveBinarySource(source));\n const meta = sniffBinaryMetadata(resolved.bytes);\n if (meta?.mimeType !== 'application/pdf') {\n throw stampError(\n 'invalid-input',\n 'importLibrary needs PDF bytes (use createAsset for a raster image)',\n );\n }\n const doc = await ctx.cancellable(signal, openAssetDocument(new Uint8Array(resolved.bytes)));\n let imported:\n | {\n library: StampLibrary;\n canonicalBytes: Uint8Array;\n assets: Array<{\n asset: StampAsset;\n bytes: Uint8Array;\n preview: StampAssetPreview;\n }>;\n }\n | undefined;\n try {\n const layout = await doc.pages.list();\n if (layout.pageCount === 0) {\n throw stampError(\n 'invalid-input',\n 'a canonical stamp library PDF must contain at least one page',\n );\n }\n const pagesByObjectNumber = new Map(\n layout.pages.map((page) => [page.ref.objectNumber, page]),\n );\n\n // Library identity: /Title (Acrobat), then format version 1 PieceInfo, then the caller's fallback.\n const catalogEntries = (await doc.pieceInfo.get(STAMP_LIBRARY_PIECEINFO_APP))?.entries ?? {};\n const takenLibraryIds = new Set(Object.keys(ctx.state.get().libraries));\n const libraryId = allocateId(entryString(catalogEntries, 'Id'), 'stamp-lib', takenLibraryIds);\n const docMeta = await doc.metadata.get();\n const libraryName =\n (docMeta.title && docMeta.title.length > 0 ? docMeta.title : undefined) ??\n entryString(catalogEntries, 'Name') ??\n options?.name ??\n 'Stamps';\n if (!docMeta.title) await doc.metadata.update({ title: libraryName });\n const libraryCategories =\n options?.categories ?? entryStringArray(catalogEntries, 'Categories');\n const libraryLocale = entryString(catalogEntries, 'Locale');\n // What the file is for: the caller's word, else the file's, else a plain stamp library.\n const libraryKind =\n options?.libraryKind ?? libraryKindFromPdfName(entryName(catalogEntries, 'Kind'));\n\n // The registry: /Names /Pages keys `identifier=label` naming pages.\n const registry = (layout.namedPages ?? []).filter(\n (entry): entry is typeof entry & { target: { kind: 'page' } } =>\n entry.target.kind === 'page',\n );\n const hidden = (layout.namedPages ?? []).filter((entry) => entry.target.kind !== 'page');\n if (hidden.length > 0) {\n globalThis.console?.warn(\n `[stamp] library '${libraryName}' carries ${hidden.length} hidden-template or dangling registration(s); they are not stamps and were ignored`,\n );\n }\n\n type Descriptor = { page: PageRef; index: number; name: string; label: string };\n let descriptors: Descriptor[];\n if (registry.length > 0) {\n const seen = new Set<string>();\n descriptors = registry.map((entry) => {\n const { name, label } = parseStampKey(entry.name);\n if (!name) {\n throw stampError(\n 'invalid-input',\n `library '${libraryName}': empty stamp identifier in key '${entry.name}'`,\n );\n }\n if (seen.has(name)) {\n throw stampError(\n 'invalid-input',\n `library '${libraryName}': duplicate stamp identifier '${name}'`,\n );\n }\n seen.add(name);\n const page = pagesByObjectNumber.get(entry.target.page.objectNumber)!;\n return { page: page.ref, index: page.index, name, label };\n });\n // Display order is page order, never the tree's key-sorted order.\n descriptors.sort((left, right) => left.index - right.index);\n } else if (layout.namedPages === undefined) {\n throw stampError(\n 'unsupported',\n 'the asset engine reports no named-page registry; an engine with named pages is needed to import libraries',\n );\n } else {\n // A plain PDF: every page is a stamp. Register it so the canonical\n // copy is Acrobat-readable on export. Format version 1 PieceInfo keys\n // (`Name`, `Subject`) name the stamps of a library without a registry.\n descriptors = [];\n for (const page of layout.pages) {\n const version1Entries = (await doc.page(page.ref).pieceInfo.get(STAMP_PIECEINFO_APP))\n ?.entries;\n const name =\n (version1Entries && entryString(version1Entries, 'Name')) ?? `Stamp${page.index + 1}`;\n const label =\n (version1Entries && entryString(version1Entries, 'Subject')) ??\n options?.assetName?.(page.index) ??\n name;\n descriptors.push({ page: page.ref, index: page.index, name, label });\n }\n for (const descriptor of descriptors) {\n await doc.pages.setName({\n name: stampKey(descriptor.name, descriptor.label),\n page: descriptor.page,\n });\n }\n }\n\n await doc.pieceInfo.update(\n STAMP_LIBRARY_PIECEINFO_APP,\n stampLibraryPieceInfo(libraryId, {\n kind: libraryKind,\n categories: libraryCategories,\n locale: libraryLocale,\n }),\n );\n\n const assets: NonNullable<typeof imported>['assets'] = [];\n for (const descriptor of descriptors) {\n const handle = doc.page(descriptor.page);\n const entries = (await handle.pieceInfo.get(STAMP_PIECEINFO_APP))?.entries ?? {};\n const kind = options?.kind ?? kindFromPdfName(entryName(entries, 'Kind')) ?? 'stamp';\n const subject = entryString(entries, 'SubjectOverride');\n const categories = entryStringArray(entries, 'Categories');\n const page = pagesByObjectNumber.get(descriptor.page.objectNumber)!;\n const asset: StampAsset = {\n id: assetIdFor(libraryId, descriptor.name),\n libraryId,\n kind,\n name: descriptor.name,\n label: descriptor.label,\n size: { width: page.size.width, height: page.size.height },\n page: descriptor.page,\n ...(subject !== undefined ? { subject } : {}),\n ...(categories !== undefined ? { categories } : {}),\n };\n await handle.pieceInfo.update(\n STAMP_PIECEINFO_APP,\n stampPieceInfo(kind, { subject, categories }),\n );\n // One canonical page → one derived placement PDF plus a thumbnail.\n const bytes = await doc.pages.extract([descriptor.page]);\n assets.push({ asset, bytes, preview: await renderThumbnail(handle) });\n }\n\n imported = {\n library: {\n id: libraryId,\n name: libraryName,\n kind: libraryKind,\n ...(libraryLocale ? { locale: libraryLocale } : {}),\n categories: libraryCategories,\n assetIds: [],\n },\n canonicalBytes: await doc.download(),\n assets,\n };\n } finally {\n await doc.close();\n }\n\n throwIfCancelled(signal);\n libraryBinaries.set(imported.library.id, imported.canonicalBytes);\n ctx.state.update(addLibrary, imported.library);\n for (const { asset, bytes, preview } of imported.assets) {\n assetBinaries.set(asset.id, { bytes, preview });\n ctx.state.update(addAsset, asset);\n }\n libraryChanged.emit({ libraryId: imported.library.id, reason: 'imported' });\n libraryCreated.emit({ libraryId: imported.library.id, library: imported.library });\n for (const { asset } of imported.assets) {\n assetCreated.emit({ assetId: asset.id, libraryId: imported.library.id, asset });\n }\n return { library: ctx.state.get().libraries[imported.library.id] ?? imported.library };\n };\n\n const dropLibrary = (id: string): void => {\n const library = ctx.state.get().libraries[id];\n if (library) {\n for (const assetId of library.assetIds) {\n assetBinaries.delete(assetId);\n ghostRenders.delete(assetId);\n }\n }\n libraryBinaries.delete(id);\n ctx.state.update(removeLibrary, id);\n };\n\n const deleteLibrary = (id: string, options?: OperationOptions): Promise<void> =>\n mutateLibrary(\n id,\n async () => {\n const existed = ctx.state.get().libraries[id] !== undefined;\n dropLibrary(id);\n if (existed) {\n libraryChanged.emit({ libraryId: id, reason: 'removed' });\n libraryDeleted.emit({ libraryId: id, library: null });\n }\n },\n options?.signal,\n );\n\n const updateLibrary = async (\n id: string,\n patch: StampLibraryPatch,\n options?: OperationOptions,\n ): Promise<{ library: StampLibrary }> => {\n const signal = options?.signal;\n throwIfCancelled(signal);\n if (!ctx.state.get().libraries[id]) throw notFound('library', id);\n return mutateLibrary(\n id,\n async () => {\n const library = ctx.state.get().libraries[id];\n if (!library) throw notFound('library', id);\n const canonicalBytes = libraryBinaries.get(id);\n if (!canonicalBytes) {\n throw stampError('operation-failed', `canonical bytes are missing for library '${id}'`);\n }\n const next: StampLibrary = {\n ...library,\n ...(patch.name !== undefined ? { name: patch.name } : {}),\n ...(patch.categories !== undefined ? { categories: patch.categories } : {}),\n };\n const doc = await ctx.cancellable(signal, openAssetDocument(canonicalBytes));\n let rewritten: Uint8Array | undefined;\n try {\n // The name is the PDF's /Title; kind, id, categories, locale ride PieceInfo.\n if (next.name !== library.name) await doc.metadata.update({ title: next.name });\n await doc.pieceInfo.update(\n STAMP_LIBRARY_PIECEINFO_APP,\n stampLibraryPieceInfo(id, {\n kind: next.kind,\n categories: next.categories,\n locale: next.locale,\n }),\n );\n rewritten = await doc.download();\n } finally {\n await doc.close();\n }\n throwIfCancelled(signal);\n libraryBinaries.set(id, rewritten);\n ctx.state.update(setLibrary, next);\n libraryChanged.emit({ libraryId: id, reason: 'updated' });\n libraryUpdated.emit({ libraryId: id, library: next });\n return { library: next };\n },\n signal,\n );\n };\n\n return {\n createLibrary,\n api: {\n createLibrary: verb(createLibrary),\n updateLibrary: verb(updateLibrary),\n importLibrary: verb(importLibrary),\n deleteLibrary: verb(deleteLibrary),\n } satisfies Partial<StampCapability>,\n };\n}\nexport type StampLibraryWrites = ReturnType<typeof createLibraryWrites>;\n","/**\n * Authoring: a drawn or typed mark rendered to a one-page PDF (the\n * annotation is authored on a scratch page and exported the way \"stamp from\n * selection\" exports), a page of a PDF as a single-page PDF, and the bytes\n * an asset is made from.\n */\nimport { resolveBinarySource } from '@embedpdf/engine-core/runtime';\n\nimport { blankLibraryPdf } from '../blank-library';\nimport type { AddAssetInput, MarkSource } from '../contract';\nimport type { StampServices } from '../services';\nimport { stampError } from '../services/errors';\n\n/** A mark's `#rrggbb` color, checked before anything is drawn. */\nconst hexColor = (hex: string): string => {\n const color = hex.trim();\n if (!/^#[0-9a-f]{6}$/i.test(color)) {\n throw stampError('invalid-input', `mark color must be #rrggbb, got '${hex}'`);\n }\n return color;\n};\n\n/** An exact ArrayBuffer over a view (the engine's binary idiom). */\nconst toArrayBuffer = (bytes: Uint8Array): ArrayBuffer => {\n const buffer = new ArrayBuffer(bytes.byteLength);\n new Uint8Array(buffer).set(bytes);\n return buffer;\n};\n\n/** An ink mark's strokes, as the engine takes them; a mark needs at least one point. */\nconst inkListOf = (\n strokes: ReadonlyArray<ReadonlyArray<{ x: number; y: number }>>,\n): { x: number; y: number }[][] => {\n if (!strokes.some((stroke) => stroke.length > 0))\n throw stampError('invalid-input', 'an ink mark needs at least one point');\n return strokes.map((stroke) => stroke.map(({ x, y }) => ({ x, y })));\n};\n\n/**\n * A generous box for typed text. The export keeps the whole box, so the\n * text is centered in it: the mark then sits in the middle of a preview\n * or a signature field.\n */\nconst textBounds = (\n text: string,\n fontSize: number,\n): { x: number; y: number; width: number; height: number } => ({\n x: 0,\n y: 0,\n width: Math.max(1, text.length) * fontSize * 0.75 + fontSize,\n height: fontSize * 1.6,\n});\n\nexport function createMarks({ assetEngine }: Pick<StampServices, 'assetEngine'>) {\n const { openAssetDocument } = assetEngine;\n\n /**\n * A drawn or typed mark rendered to a one-page PDF: the annotation is\n * authored on a scratch page and exported the way \"stamp from selection\"\n * exports — a fresh page the size of the mark, paths kept as paths, the\n * font subset-embedded. Self-contained and Acrobat-readable.\n */\n const renderMark = async (\n mark: Extract<MarkSource, { kind: 'ink' | 'text' }>,\n ): Promise<Uint8Array> => {\n const doc = await openAssetDocument(blankLibraryPdf());\n try {\n const layout = await doc.pages.list();\n const scratch = layout.pages[0];\n if (!scratch) throw stampError('operation-failed', 'the scratch document has no page');\n const page = doc.page(scratch.ref);\n const color = hexColor(mark.color ?? '#1d2b53');\n const created =\n mark.kind === 'ink'\n ? await page.annotations.create({\n subtype: 'ink',\n inkList: inkListOf(mark.strokes),\n color,\n strokeWidth: mark.strokeWidth ?? 2,\n })\n : await page.annotations.create({\n subtype: 'free-text',\n intent: 'free-text',\n contents: mark.text,\n fontFamily: mark.fontFamily,\n fontSize: mark.fontSize ?? 36,\n textAlign: 'center',\n verticalAlign: 'middle',\n box: textBounds(mark.text, mark.fontSize ?? 36),\n fontColor: color,\n strokeWidth: 0,\n });\n return new Uint8Array(await page.annotations.exportAppearance([created.annotation.ref]));\n } finally {\n await doc.close();\n }\n };\n\n /** One page of a PDF as a single-page PDF (a `pdf` mark with `pageIndex`). */\n const extractPage = async (bytes: Uint8Array, pageIndex: number): Promise<Uint8Array> => {\n const doc = await openAssetDocument(bytes);\n try {\n const layout = await doc.pages.list();\n const page = layout.pages[pageIndex];\n if (!page) {\n throw stampError(\n 'invalid-input',\n `the PDF has no page ${pageIndex} (${layout.pageCount} pages)`,\n );\n }\n return await doc.pages.extract([page.ref]);\n } finally {\n await doc.close();\n }\n };\n\n /** The bytes an asset is made from: the caller's `source`, or its `mark` authored into one. */\n const resolveAssetSource = async (\n input: AddAssetInput,\n ): Promise<{ bytes: ArrayBuffer; mimeType?: string }> => {\n if ((input.source === undefined) === (input.mark === undefined)) {\n throw stampError('invalid-input', 'createAsset takes exactly one of `source` / `mark`');\n }\n if (input.source !== undefined) return resolveBinarySource(input.source);\n const mark = input.mark!;\n switch (mark.kind) {\n case 'image':\n return resolveBinarySource(mark.source);\n case 'pdf': {\n const resolved = await resolveBinarySource(mark.source);\n if (mark.pageIndex === undefined) return resolved;\n return {\n bytes: toArrayBuffer(await extractPage(new Uint8Array(resolved.bytes), mark.pageIndex)),\n };\n }\n case 'ink':\n case 'text':\n return { bytes: toArrayBuffer(await renderMark(mark)) };\n }\n };\n\n return { resolveAssetSource };\n}\nexport type StampMarks = ReturnType<typeof createMarks>;\n","/**\n * Placement: arm an asset on a document (the next click places) or place it\n * without the pointer. Form-backed stamps are executable templates only\n * until placement — they are evaluated on an isolated copy under the target\n * document's detached script realm, so neither the canonical library nor\n * its reusable per-page extraction becomes target/user/time specific.\n */\nimport {\n DocumentsToken,\n toPluginError,\n toPluginErrorInfo,\n type BatchResult,\n type PageRef,\n} from '@embedpdf/core';\nimport { javaScriptProgramFromActionTree } from '@embedpdf/core-acrojs';\nimport { formEffectOps, type Annotation } from '@embedpdf/engine-core/runtime';\nimport { ActionsToken as ActionsHostToken } from '@embedpdf/plugin-actions/contract/host';\nimport { AnnotationToken, type StampPlacement } from '@embedpdf/plugin-annotation/contract';\nimport { AnnotationToken as AnnotationHostToken } from '@embedpdf/plugin-annotation/contract/host';\nimport { createFormScriptingController } from '@embedpdf/plugin-form/scripting';\n\nimport type {\n StampArmOptions,\n StampAsset,\n StampAssetPreview,\n StampCapability,\n StampDocumentOptions,\n} from '../contract';\nimport { armAsset as rememberArm, disarmDocuments } from '../model';\nimport type { StampCatalog } from '../read/catalog';\nimport type { StampContext, StampServices } from '../services';\nimport { notFound, permissionDenied, stampError, throwIfCancelled, verb } from '../services/errors';\n\nexport function createPlacement(\n ctx: StampContext,\n {\n binaries,\n assetEngine,\n ghosts,\n targets,\n }: Pick<StampServices, 'binaries' | 'assetEngine' | 'ghosts' | 'targets'>,\n { canPlace }: Pick<StampCatalog, 'canPlace'>,\n) {\n const { binaries: assetBinaries, libraryBinaries } = binaries;\n const { openAssetDocument, imageToPreview } = assetEngine;\n const { ghostProvider } = ghosts;\n const { documentIdOf, targetOf, pageOf } = targets;\n const settings = ctx.settings();\n\n // The annotation plugin owns the arm itself and drops it on its own (a\n // tool switch, a closed document). Forget those arms here too, so\n // `getArmedAsset` and `onArmChanged` follow.\n const droppedArms = (): string =>\n Object.keys(ctx.state.get().armed)\n .filter(\n (documentId) => !ctx.tryForDocument(AnnotationHostToken, documentId)?.stamps.isArmed(),\n )\n .join('\\n');\n ctx.watch(droppedArms, (dropped) => {\n if (dropped) ctx.state.update(disarmDocuments, dropped.split('\\n'));\n });\n\n /** The one payload both entry points hand the annotation plugin: artwork,\n * a resolution-aware ghost, true size, and the identity a placement\n * writes (`/Name` = identifier, `/Subj` = the subject override or label). */\n const stampPayload = (\n asset: StampAsset,\n placement: { bytes: Uint8Array; preview: StampAssetPreview | null },\n materialized: boolean,\n ) => ({\n source: placement.bytes,\n preview: ghostProvider(placement.bytes, placement.preview, materialized ? null : asset.id),\n intrinsicSize: asset.size,\n name: asset.name,\n subject: asset.subject ?? asset.label,\n });\n\n /**\n * Form-backed stamps are executable templates only until placement. Work\n * on an isolated copy so neither the canonical library nor its reusable\n * per-page extraction becomes target/user/time specific.\n *\n * The realm comes from the target document's actions plugin: a detached\n * realm under that document's policy and environment, with its own\n * sandbox and none of the viewer realm's globals. No actions plugin,\n * scripting off, or `dynamic: false`: the template is armed as-is.\n */\n const materializeForPlacement = async (\n documentId: string,\n asset: StampAsset,\n binary: { bytes: Uint8Array; preview: StampAssetPreview | null },\n ): Promise<{ bytes: Uint8Array; preview: StampAssetPreview | null }> => {\n if (!settings.get().dynamic) return binary;\n const actions = ctx.tryForDocument(ActionsHostToken, documentId);\n const mintRealm = actions?.createDetachedScriptRealm;\n if (!actions || !mintRealm) return binary;\n\n const documents = ctx.get(DocumentsToken);\n const target = documents.get(documentId);\n if (target?.status !== 'ready') {\n throw stampError('not-found', `document '${documentId}' is not open`);\n }\n const targetDocument = {\n name: target.name,\n pageCount: target.pageCount,\n pages: documents.listPages(documentId),\n };\n\n // A page extraction intentionally does not retain catalog-owned AcroForm\n // and action structures. Canonical assets therefore evaluate from the\n // whole library PDF, then extract only their selected page after flatten.\n const canonicalBytes = libraryBinaries.get(asset.libraryId);\n const sourceBytes = canonicalBytes ?? binary.bytes;\n const doc = await openAssetDocument(new Uint8Array(sourceBytes));\n // Cleanup protection starts the moment the temporary document exists:\n // realm/controller construction failures must not leak it.\n let realm: ReturnType<typeof mintRealm> | null = null;\n let scripting: ReturnType<typeof createFormScriptingController> | null = null;\n try {\n const layout = await doc.pages.list();\n const selectedPage =\n asset.page === undefined\n ? layout.pageCount === 1\n ? layout.pages[0]\n : undefined\n : layout.pages.find(({ ref }) => ref.objectNumber === asset.page.objectNumber);\n if (!selectedPage) {\n throw stampError(\n 'invalid-input',\n canonicalBytes\n ? `canonical page ${asset.page?.objectNumber ?? 'unknown'} no longer exists`\n : 'a loose dynamic stamp asset must contain exactly one page',\n );\n }\n const snapshot = await doc.forms.list();\n const hasSelectedPageField = snapshot.fields.some((field) =>\n field.widgets.some(({ page }) => page?.objectNumber === selectedPage.ref.objectNumber),\n );\n if (!hasSelectedPageField) return binary;\n if (!doc.pages.flatten || !doc.pages.extract) {\n throw stampError(\n 'unsupported',\n 'dynamic PDF stamps need an asset engine with pages.flatten and pages.extract',\n );\n }\n\n // Scripts observe the target document's metadata (Acrobat's dynamic\n // stamp contract: `documentFileName` is the document being stamped)\n // and boot from the asset document's own name tree.\n realm = mintRealm.call(actions, {\n doc,\n document: () => targetDocument,\n bootSources: async () => {\n const tree = doc.actions ? await doc.actions.get() : null;\n return (\n tree?.nameTreeScripts.map(({ action }) => javaScriptProgramFromActionTree(action)) ?? []\n );\n },\n });\n scripting = createFormScriptingController({\n document: () => targetDocument,\n transaction: realm.transaction.bind(realm),\n budget: realm.budget,\n });\n // The copy is the stamp's own: what its scripts calculate is written to it, in the same\n // transaction, before it is flattened.\n const result = await scripting.transaction(async (scripts) => {\n const calculated = await scripts.recalculate(snapshot);\n if (calculated.status === 'accepted' && calculated.effects.length > 0) {\n await doc.apply({ ops: formEffectOps(calculated.effects) });\n }\n return calculated;\n });\n actions.surfaceScriptCommit(result, { origin: 'user', realm: 'detached' });\n if (result.status === 'failed') {\n throw stampError(\n 'operation-failed',\n `dynamic stamp scripting failed: ${result.error?.message ?? 'native form effect failed'}`,\n );\n }\n\n const page = selectedPage.ref;\n // All or nothing: a page that fails to flatten throws.\n await doc.pages.flatten([page], { usage: 'display' });\n\n const bytes = await doc.pages.extract([page]);\n const image = await doc.page(page).render.image({\n viewport: { kind: 'width', width: settings.get().previewWidth },\n background: 'transparent',\n includeAnnotations: false,\n format: 'png',\n });\n return { bytes, preview: imageToPreview(image) };\n } finally {\n scripting?.dispose();\n realm?.dispose();\n await doc.close();\n }\n };\n\n /** An asset and its bytes, or `not-found`. */\n const assetOf = (assetId: string) => {\n const asset = ctx.state.get().assets[assetId];\n const binary = assetBinaries.get(assetId);\n if (!asset || !binary) throw notFound('asset', assetId);\n return { asset, binary };\n };\n\n /** Placing is annotation work: refused where the document's annotation plugin refuses a create. */\n const assertMayPlace = (documentId: string, operation: string): void => {\n if (!canPlace(documentId)) throw permissionDenied('annotations:create', operation);\n };\n\n const armAsset = async (assetId: string, options?: StampArmOptions): Promise<void> => {\n const signal = options?.signal;\n throwIfCancelled(signal);\n const documentId = targetOf(options);\n const { asset, binary } = assetOf(assetId);\n assertMayPlace(documentId, 'stamp.armAsset');\n const placement = await ctx.cancellable(\n signal,\n materializeForPlacement(documentId, asset, binary),\n );\n throwIfCancelled(signal);\n // The placement itself remains one `stamps.arm` call. Dynamic evaluation,\n // when enabled and applicable, has already produced an ephemeral static\n // page and matching preview at this boundary.\n const annotation = ctx.forDocument(AnnotationToken, documentId);\n await annotation.stamps.arm(\n {\n ...stampPayload(asset, placement, placement !== binary),\n targetWidth: options?.targetWidth,\n },\n { signal },\n );\n ctx.state.update(rememberArm, documentId, assetId);\n };\n\n const getArmedAsset = (documentId?: string): StampAsset | null => {\n const id = documentIdOf(documentId);\n const assetId = id === null ? undefined : ctx.state.get().armed[id];\n if (id === null || assetId === undefined) return null;\n // An arm the annotation plugin just dropped reads as nothing armed, even\n // for a reader that runs before the watch above forgets it.\n if (!ctx.tryForDocument(AnnotationHostToken, id)?.stamps.isArmed()) return null;\n return ctx.state.get().assets[assetId] ?? null;\n };\n\n const disarm = (documentId?: string): void => {\n const id = documentIdOf(documentId);\n if (id === null) return;\n ctx.tryForDocument(AnnotationToken, id)?.stamps.disarm();\n ctx.state.update(disarmDocuments, [id]);\n };\n\n /** Place on one document, its permission already checked. */\n const placeOn = async (\n documentId: string,\n assetId: string,\n placement: StampPlacement,\n signal: AbortSignal | undefined,\n ): Promise<{ annotation: Annotation }> => {\n const { asset, binary } = assetOf(assetId);\n const materialized = await ctx.cancellable(\n signal,\n materializeForPlacement(documentId, asset, binary),\n );\n throwIfCancelled(signal);\n const annotation = ctx.forDocument(AnnotationToken, documentId);\n return annotation.stamps.place(\n stampPayload(asset, materialized, materialized !== binary),\n placement,\n { signal },\n );\n };\n\n const placeAsset = async (\n assetId: string,\n placement: StampPlacement,\n options?: StampDocumentOptions,\n ): Promise<{ annotation: Annotation }> => {\n throwIfCancelled(options?.signal);\n const documentId = targetOf(options);\n assetOf(assetId);\n assertMayPlace(documentId, 'stamp.placeAsset');\n return placeOn(documentId, assetId, placement, options?.signal);\n };\n\n const placeAssetOnPages = async (\n assetId: string,\n pages: readonly (PageRef | number)[] | 'all',\n placement: Omit<StampPlacement, 'page'>,\n options?: StampDocumentOptions,\n ): Promise<BatchResult<Annotation, PageRef>> => {\n const signal = options?.signal;\n throwIfCancelled(signal);\n const documentId = targetOf(options);\n assetOf(assetId);\n assertMayPlace(documentId, 'stamp.placeAssetOnPages');\n // Every page is resolved before the first placement: a page that isn't\n // there refuses the call, and nothing is placed.\n const targetPages =\n pages === 'all'\n ? ctx\n .get(DocumentsToken)\n .listPages(documentId)\n .map((page) => page.ref)\n : pages.map((page) => pageOf(documentId, page).ref);\n const applied: Annotation[] = [];\n const failed: { ref: PageRef; error: ReturnType<typeof toPluginErrorInfo> }[] = [];\n for (const page of targetPages) {\n try {\n const placed = await placeOn(documentId, assetId, { ...placement, page }, signal);\n applied.push(placed.annotation);\n } catch (error) {\n const refused = toPluginError('stamp', error);\n // A cancel stops the whole batch: what was placed stays placed.\n if (refused.code === 'operation-cancelled') throw refused;\n failed.push({ ref: page, error: toPluginErrorInfo(refused) });\n }\n }\n return { applied, skipped: [], failed };\n };\n\n return {\n api: {\n armAsset: verb(armAsset),\n disarm,\n getArmedAsset,\n placeAsset: verb(placeAsset),\n placeAssetOnPages: verb(placeAssetOnPages),\n } satisfies Partial<StampCapability>,\n };\n}\n","/**\n * The stamp controller: the composition root. It builds the plugin's\n * services once, wires each area with the services it declares, and\n * assembles the capability from the areas' API slices. Every verb and read\n * has a home in `read/` or `write/`; the one state-change event is derived\n * here.\n */\nimport { composeApi } from '@embedpdf/core';\n\nimport type { StampCapability } from './contract';\nimport { createCatalog } from './read/catalog';\nimport { createServices, type StampContext } from './services';\nimport { createAssetWrites } from './write/assets';\nimport { createLibraryWrites } from './write/libraries';\nimport { createMarks } from './write/marks';\nimport { createPlacement } from './write/placement';\n\nexport function createStampController(ctx: StampContext) {\n const services = createServices(ctx);\n const { events } = services;\n const settings = ctx.settings();\n\n // What is armed on a document is state: the event follows it, whichever\n // verb, tool switch or closed document changed it.\n ctx.state.onChange(({ previous, next }) => {\n if (previous.armed === next.armed) return;\n const documentIds = new Set([...Object.keys(previous.armed), ...Object.keys(next.armed)]);\n for (const documentId of documentIds) {\n const assetId = next.armed[documentId];\n if (previous.armed[documentId] === assetId) continue;\n events.armChanged.emit({\n documentId,\n asset: assetId === undefined ? null : (next.assets[assetId] ?? null),\n });\n }\n });\n\n // Reads: pure projections of the state and the binaries resource.\n const catalog = createCatalog(ctx, services);\n\n // Writes: every durable change, through the per-library mutation queue.\n const marks = createMarks(services);\n const libraries = createLibraryWrites(ctx, services);\n const assets = createAssetWrites(ctx, services, marks, libraries, catalog);\n const placement = createPlacement(ctx, services, catalog);\n\n const api: StampCapability = composeApi('stamp', [\n settings.api,\n catalog.api,\n libraries.api,\n assets.api,\n placement.api,\n {\n // The events are services, not areas.\n onLibraryChanged: events.libraryChanged.on,\n onLibraryCreated: events.libraryCreated.on,\n onLibraryUpdated: events.libraryUpdated.on,\n onLibraryDeleted: events.libraryDeleted.on,\n onAssetCreated: events.assetCreated.on,\n onAssetUpdated: events.assetUpdated.on,\n onAssetDeleted: events.assetDeleted.on,\n onArmChanged: events.armChanged.on,\n },\n ]);\n return { api };\n}\n","import { definePlugin } from '@embedpdf/core';\nimport { ActionsToken } from '@embedpdf/plugin-actions/contract';\nimport { AnnotationToken } from '@embedpdf/plugin-annotation/contract';\n\nimport { STAMP_DEFAULTS, StampToken, type StampConfig } from './contract';\nimport { createStampController } from './controller';\nimport { initialStampState } from './model';\n\n/**\n * Stamp libraries and assets. Workspace-scoped: libraries outlive any one\n * document; placement targets a document through its annotation plugin.\n * `config` is the settings the app registers, over {@link STAMP_DEFAULTS}.\n */\nexport const stampPlugin = (config?: StampConfig) =>\n definePlugin({\n id: 'stamp',\n token: StampToken,\n scope: 'workspace',\n optional: [AnnotationToken, ActionsToken],\n state: initialStampState,\n // An engine is one value: a change replaces it, never merges into it.\n settings: { defaults: STAMP_DEFAULTS, registered: config, whole: ['assetEngine'] },\n create: createStampController,\n // Inside a document's scope, a placing call that leaves out the document is for that one.\n inScope: (stamp, documentId) => {\n const scoped = <Options extends { documentId?: string }>(options?: Options) => ({\n ...options,\n documentId: options?.documentId ?? documentId,\n });\n return {\n ...stamp,\n createAssetFromAnnotations: (page, refs, input, options) =>\n stamp.createAssetFromAnnotations(page, refs, input, scoped(options)),\n armAsset: (assetId, options) => stamp.armAsset(assetId, scoped(options)),\n disarm: (target = documentId) => stamp.disarm(target),\n getArmedAsset: (target = documentId) => stamp.getArmedAsset(target),\n placeAsset: (assetId, placement, options) =>\n stamp.placeAsset(assetId, placement, scoped(options)),\n placeAssetOnPages: (assetId, pages, placement, options) =>\n stamp.placeAssetOnPages(assetId, pages, placement, scoped(options)),\n canPlace: (target = documentId) => stamp.canPlace(target),\n canCreateFromAnnotations: (target = documentId) => stamp.canCreateFromAnnotations(target),\n };\n },\n });\n","/**\n * The stamps page's State table as code: what `useStampState()` returns, and\n * the same fields in every other framework. It reads the document in scope,\n * else the active one. The libraries and their stamps are not here:\n * `useStampLibraries()` and `useStampAssets()` read them, so a component that\n * only shows the armed stamp doesn't re-render when a library changes.\n */\nimport { defineState } from '@embedpdf/core';\n\nimport { StampToken } from './contract';\n\nexport const stampState = defineState(StampToken, {\n read: (stamp) => ({\n armedAsset: stamp.getArmedAsset(),\n }),\n empty: {\n armedAsset: null,\n },\n});\n","/**\n * Keeping custom libraries, over the plugin's public API, in any environment.\n *\n * The plugin knows when a library changes (`onLibraryChanged`) and what its\n * canonical bytes are (`exportLibrary`, a complete PDF). Where those bytes\n * live is the embedder's decision: {@link StampLibraryStore} is the port,\n * declared here DOM-free like every plugin port. The browser adapter is\n * `indexedDbByteStore` in `@embedpdf/web` (structurally this port), wired by\n * the framework layer; an embedder with its own backend implements the three\n * calls once. These helpers are the proof that the two capability calls are\n * all a store needs: each takes only the members it uses, so a framework's\n * own service of the plugin works as well as the capability.\n */\nimport type { StampCapability } from './contract';\n\n/** The persistence port: bytes by library id. */\nexport interface StampLibraryStore {\n list(): Promise<Array<{ id: string; bytes: Uint8Array }>>;\n put(id: string, bytes: Uint8Array): Promise<void>;\n delete(id: string): Promise<void>;\n}\n\n/** An in-memory store, for tests and SSR. */\nexport function memoryStampStore(): StampLibraryStore {\n const rows = new Map<string, Uint8Array>();\n return {\n list: async () => [...rows.entries()].map(([id, bytes]) => ({ id, bytes })),\n put: async (id, bytes) => {\n rows.set(id, new Uint8Array(bytes));\n },\n delete: async (id) => {\n rows.delete(id);\n },\n };\n}\n\n/**\n * Bring every stored library back: each PDF is imported as-is (its title,\n * registry, and PieceInfo id come from the file; the store's key is only a\n * hint). Call once at boot, before seeding defaults, so \"already has\n * libraries\" means the user's own.\n */\nexport async function restoreStampLibraries(\n stamp: Pick<StampCapability, 'importLibrary'>,\n store: StampLibraryStore,\n): Promise<string[]> {\n const restored: string[] = [];\n for (const { id, bytes } of await store.list()) {\n try {\n restored.push((await stamp.importLibrary(bytes)).library.id);\n } catch (error) {\n globalThis.console?.warn(`[stamp] stored library '${id}' could not be restored:`, error);\n }\n }\n return restored;\n}\n\n/**\n * Keep the store in sync from now on: every canonical change saves the\n * library's PDF, a removal deletes it. `except` names libraries never to\n * persist (the bundled default set, typically). Returns the unsubscribe;\n * work already asked for still finishes.\n *\n * Each library has one line of store work, so saves never overlap and a\n * delete never lands under a late save. The changes of one burst (one call\n * into the plugin) are one save; the changes made while a save runs are one\n * more after it.\n */\nexport function persistStampLibraries(\n stamp: Pick<StampCapability, 'exportLibrary' | 'onLibraryChanged'>,\n store: StampLibraryStore,\n options: { except?: readonly string[] } = {},\n): () => void {\n const except = new Set(options.except ?? []);\n /** Per library: the store step waiting or running, and the one to follow it. */\n const lines = new Map<string, { step: Step; started: boolean; next: Step | null }>();\n\n const run = (libraryId: string, step: Step): void => {\n const line = lines.get(libraryId);\n if (line) {\n // Not started yet: it does the latest wish. Running: the latest wish follows it.\n if (line.started) line.next = step;\n else line.step = step;\n return;\n }\n const fresh = { step, started: false, next: null as Step | null };\n lines.set(libraryId, fresh);\n // Starts once the current burst of changes is over, so the burst is one step.\n void Promise.resolve().then(async () => {\n fresh.started = true;\n try {\n if (fresh.step === 'save') await store.put(libraryId, await stamp.exportLibrary(libraryId));\n else await store.delete(libraryId);\n } catch (error) {\n const doing = fresh.step === 'save' ? 'persisting' : 'deleting stored';\n globalThis.console?.warn(`[stamp] ${doing} library '${libraryId}' failed:`, error);\n }\n lines.delete(libraryId);\n if (fresh.next) run(libraryId, fresh.next);\n });\n };\n\n return stamp.onLibraryChanged(({ libraryId, reason }) => {\n if (except.has(libraryId)) return;\n run(libraryId, reason === 'removed' ? 'delete' : 'save');\n });\n}\n\n/** What a library's line does next in the store. */\ntype Step = 'save' | 'delete';\n"],"mappings":";;;;;;;;;;;;AAGA,MAAa,cAAc,MAAuB,YAChD,IAAIA,eAAAA,YAAY,MAAM,SAAS,OAAO;AAExC,MAAa,YAAY,MAAc,OACrC,WAAW,aAAa,WAAW,KAAK,IAAI,GAAG,EAAE;;;;;;AAOnD,MAAa,oBAAoB,YAAoB,cACnD,IAAIA,eAAAA,YAAY,qBAAqB,SAAS,GAAG,UAAU,YAAY,cAAc,EACnF,WACF,CAAC;;AAGH,MAAa,oBAAoB,WAA0C;CACzE,IAAI,QAAQ,SACV,MAAM,IAAIA,eAAAA,YAAY,uBAAuB,SAAS,uBAAuB,EAC3E,OAAO,OAAO,OAChB,CAAC;AAEL;;;;;AAMA,MAAa,QACsB,QACjC,OAAO,GAAG,SAAgC;CACxC,IAAI;EACF,OAAO,MAAM,IAAI,GAAG,IAAI;CAC1B,SAAS,OAAO;EACd,OAAA,GAAA,eAAA,cAAA,CAAoB,SAAS,KAAK;CACpC;AACF;;;;;ACzBF,SAAgB,cACd,KACA,EACE,UACA,aACA,QACA,WAEF;CACA,MAAM,EAAE,UAAU,eAAe,oBAAoB;CACrD,MAA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AM,QAAQ;GAAE;GAAM,SAAS;GAAO,MAAM;EAAoB;EAChE,MAAM,IAAI,WAAW,KAAK;EAE1B,QAAa,QAAQ,CAAC,CAAC,KAAK,YAAY;GACtC,MAAM,UAAU;GAChB,IAAI;IACF,IAAI,MAAM,SAAS,QAAQ,MAAM,MAAM,IAAI,WAAW,MAAM,MAAM,cAAc,SAAS,CAAC;SACrF,MAAM,MAAM,OAAO,SAAS;GACnC,SAAS,OAAO;IACd,MAAM,QAAQ,MAAM,SAAS,SAAS,eAAe;IACrD,WAAW,SAAS,KAAK,WAAW,MAAM,YAAY,UAAU,YAAY,KAAK;GACnF;GACA,MAAM,OAAO,SAAS;GACtB,IAAI,MAAM,MAAM,IAAI,WAAW,MAAM,IAAI;EAC3C,CAAC;CACH;CAEA,OAAO,MAAM,kBAAkB,EAAE,WAAW,aAAa;EACvD,IAAI,OAAO,IAAI,SAAS,GAAG;EAC3B,IAAI,WAAW,WAAW,YAAY,WAAW,MAAM;CACzD,CAAC;AACH"}
|
package/dist/index.d.cts
CHANGED
|
@@ -1,14 +1,26 @@
|
|
|
1
|
-
import { A as
|
|
1
|
+
import { A as StampSettings, C as StampLibraryCreatedEvent, D as StampLibraryPatch, E as StampLibraryKind, F as DEFAULT_LIBRARY_KIND, I as StampToken, M as memoryStampStore, N as persistStampLibraries, O as StampLibraryUpdatedEvent, P as restoreStampLibraries, S as StampLibraryChangedEvent, T as StampLibraryFilter, _ as StampAssetUpdatedEvent, a as MarkSource, b as StampDocumentOptions, c as StampArmOptions, d as StampAssetDeletedEvent, f as StampAssetEngine, g as StampAssetPreview, h as StampAssetPatch, i as ImportLibraryOptions, j as StampLibraryStore, k as StampPlacement, l as StampAsset, m as StampAssetKind, n as AssetFromAnnotationsInput, o as STAMP_DEFAULTS, p as StampAssetFilter, r as CreateLibraryOptions, s as StampArmChangedEvent, t as AddAssetInput, u as StampAssetCreatedEvent, v as StampCapability, w as StampLibraryDeletedEvent, x as StampLibrary, y as StampConfig } from "./contract-CEeBOug9.cjs";
|
|
2
|
+
//#region src/model.d.ts
|
|
3
|
+
interface StampState {
|
|
4
|
+
readonly libraries: Readonly<Record<string, StampLibrary>>;
|
|
5
|
+
/** Library display order (insertion order). */
|
|
6
|
+
readonly libraryOrder: readonly string[];
|
|
7
|
+
readonly assets: Readonly<Record<string, StampAsset>>;
|
|
8
|
+
/** Document id → the id of the asset armed there. */
|
|
9
|
+
readonly armed: Readonly<Record<string, string>>;
|
|
10
|
+
}
|
|
11
|
+
//#endregion
|
|
2
12
|
//#region src/stamp.plugin.d.ts
|
|
3
13
|
/**
|
|
4
|
-
*
|
|
5
|
-
* document; placement
|
|
6
|
-
*
|
|
7
|
-
* because the annotation token is document-scoped and resolved lazily per
|
|
8
|
-
* placement (a viewer without the annotation plugin fails at the arm call,
|
|
9
|
-
* with the kernel's own missing-capability error).
|
|
14
|
+
* Stamp libraries and assets. Workspace-scoped: libraries outlive any one
|
|
15
|
+
* document; placement targets a document through its annotation plugin.
|
|
16
|
+
* `config` is the settings the app registers, over {@link STAMP_DEFAULTS}.
|
|
10
17
|
*/
|
|
11
|
-
declare const stampPlugin: (config?: StampConfig) => import("@embedpdf/core").PluginDef<StampState,
|
|
18
|
+
declare const stampPlugin: (config?: StampConfig) => import("@embedpdf/core").PluginDef<StampState, StampCapability, StampSettings>;
|
|
19
|
+
//#endregion
|
|
20
|
+
//#region src/state.d.ts
|
|
21
|
+
declare const stampState: import("@embedpdf/core").StateDeclaration<StampCapability, {
|
|
22
|
+
armedAsset: StampAsset | null;
|
|
23
|
+
}>;
|
|
12
24
|
//#endregion
|
|
13
|
-
export {
|
|
25
|
+
export { AddAssetInput, AssetFromAnnotationsInput, CreateLibraryOptions, DEFAULT_LIBRARY_KIND, ImportLibraryOptions, MarkSource, STAMP_DEFAULTS, StampArmChangedEvent, StampArmOptions, StampAsset, StampAssetCreatedEvent, StampAssetDeletedEvent, StampAssetEngine, StampAssetFilter, StampAssetKind, StampAssetPatch, StampAssetPreview, StampAssetUpdatedEvent, StampCapability, StampConfig, StampDocumentOptions, StampLibrary, StampLibraryChangedEvent, StampLibraryCreatedEvent, StampLibraryDeletedEvent, StampLibraryFilter, StampLibraryKind, StampLibraryPatch, type StampLibraryStore, StampLibraryUpdatedEvent, type StampPlacement, StampSettings, StampToken, memoryStampStore, persistStampLibraries, restoreStampLibraries, stampPlugin, stampState };
|
|
14
26
|
//# sourceMappingURL=index.d.cts.map
|
package/dist/index.d.ts
CHANGED
|
@@ -1,14 +1,26 @@
|
|
|
1
|
-
import { A as
|
|
1
|
+
import { A as StampSettings, C as StampLibraryCreatedEvent, D as StampLibraryPatch, E as StampLibraryKind, F as DEFAULT_LIBRARY_KIND, I as StampToken, M as memoryStampStore, N as persistStampLibraries, O as StampLibraryUpdatedEvent, P as restoreStampLibraries, S as StampLibraryChangedEvent, T as StampLibraryFilter, _ as StampAssetUpdatedEvent, a as MarkSource, b as StampDocumentOptions, c as StampArmOptions, d as StampAssetDeletedEvent, f as StampAssetEngine, g as StampAssetPreview, h as StampAssetPatch, i as ImportLibraryOptions, j as StampLibraryStore, k as StampPlacement, l as StampAsset, m as StampAssetKind, n as AssetFromAnnotationsInput, o as STAMP_DEFAULTS, p as StampAssetFilter, r as CreateLibraryOptions, s as StampArmChangedEvent, t as AddAssetInput, u as StampAssetCreatedEvent, v as StampCapability, w as StampLibraryDeletedEvent, x as StampLibrary, y as StampConfig } from "./contract-CjGXUUDJ.js";
|
|
2
|
+
//#region src/model.d.ts
|
|
3
|
+
interface StampState {
|
|
4
|
+
readonly libraries: Readonly<Record<string, StampLibrary>>;
|
|
5
|
+
/** Library display order (insertion order). */
|
|
6
|
+
readonly libraryOrder: readonly string[];
|
|
7
|
+
readonly assets: Readonly<Record<string, StampAsset>>;
|
|
8
|
+
/** Document id → the id of the asset armed there. */
|
|
9
|
+
readonly armed: Readonly<Record<string, string>>;
|
|
10
|
+
}
|
|
11
|
+
//#endregion
|
|
2
12
|
//#region src/stamp.plugin.d.ts
|
|
3
13
|
/**
|
|
4
|
-
*
|
|
5
|
-
* document; placement
|
|
6
|
-
*
|
|
7
|
-
* because the annotation token is document-scoped and resolved lazily per
|
|
8
|
-
* placement (a viewer without the annotation plugin fails at the arm call,
|
|
9
|
-
* with the kernel's own missing-capability error).
|
|
14
|
+
* Stamp libraries and assets. Workspace-scoped: libraries outlive any one
|
|
15
|
+
* document; placement targets a document through its annotation plugin.
|
|
16
|
+
* `config` is the settings the app registers, over {@link STAMP_DEFAULTS}.
|
|
10
17
|
*/
|
|
11
|
-
declare const stampPlugin: (config?: StampConfig) => import("@embedpdf/core").PluginDef<StampState,
|
|
18
|
+
declare const stampPlugin: (config?: StampConfig) => import("@embedpdf/core").PluginDef<StampState, StampCapability, StampSettings>;
|
|
19
|
+
//#endregion
|
|
20
|
+
//#region src/state.d.ts
|
|
21
|
+
declare const stampState: import("@embedpdf/core").StateDeclaration<StampCapability, {
|
|
22
|
+
armedAsset: StampAsset | null;
|
|
23
|
+
}>;
|
|
12
24
|
//#endregion
|
|
13
|
-
export {
|
|
25
|
+
export { AddAssetInput, AssetFromAnnotationsInput, CreateLibraryOptions, DEFAULT_LIBRARY_KIND, ImportLibraryOptions, MarkSource, STAMP_DEFAULTS, StampArmChangedEvent, StampArmOptions, StampAsset, StampAssetCreatedEvent, StampAssetDeletedEvent, StampAssetEngine, StampAssetFilter, StampAssetKind, StampAssetPatch, StampAssetPreview, StampAssetUpdatedEvent, StampCapability, StampConfig, StampDocumentOptions, StampLibrary, StampLibraryChangedEvent, StampLibraryCreatedEvent, StampLibraryDeletedEvent, StampLibraryFilter, StampLibraryKind, StampLibraryPatch, type StampLibraryStore, StampLibraryUpdatedEvent, type StampPlacement, StampSettings, StampToken, memoryStampStore, persistStampLibraries, restoreStampLibraries, stampPlugin, stampState };
|
|
14
26
|
//# sourceMappingURL=index.d.ts.map
|