@embedpdf/plugin-stamp 2.14.4 → 3.0.0-next.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +192 -21
- package/dist/index.cjs +591 -2
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +187 -0
- package/dist/index.d.ts +187 -1
- package/dist/index.js +584 -975
- package/dist/index.js.map +1 -1
- package/package.json +23 -61
- package/dist/lib/actions.d.ts +0 -14
- package/dist/lib/defaults/name-map.d.ts +0 -2
- package/dist/lib/handlers/rubber-stamp.handler.d.ts +0 -4
- package/dist/lib/index.d.ts +0 -11
- package/dist/lib/manifest.d.ts +0 -4
- package/dist/lib/reducer.d.ts +0 -5
- package/dist/lib/stamp-plugin.d.ts +0 -54
- package/dist/lib/tools.d.ts +0 -58
- package/dist/lib/types.d.ts +0 -130
- package/dist/preact/adapter.d.ts +0 -5
- package/dist/preact/annotation.d.ts +0 -1
- package/dist/preact/core.d.ts +0 -1
- package/dist/preact/index.cjs +0 -2
- package/dist/preact/index.cjs.map +0 -1
- package/dist/preact/index.d.ts +0 -1
- package/dist/preact/index.js +0 -116
- package/dist/preact/index.js.map +0 -1
- package/dist/react/adapter.d.ts +0 -2
- package/dist/react/annotation.d.ts +0 -1
- package/dist/react/core.d.ts +0 -1
- package/dist/react/index.cjs +0 -2
- package/dist/react/index.cjs.map +0 -1
- package/dist/react/index.d.ts +0 -1
- package/dist/react/index.js +0 -115
- package/dist/react/index.js.map +0 -1
- package/dist/shared/components/index.d.ts +0 -1
- package/dist/shared/components/stamp-img.d.ts +0 -10
- package/dist/shared/hooks/index.d.ts +0 -1
- package/dist/shared/hooks/use-stamp.d.ts +0 -18
- package/dist/shared/index.d.ts +0 -4
- package/dist/shared-preact/components/index.d.ts +0 -1
- package/dist/shared-preact/components/stamp-img.d.ts +0 -10
- package/dist/shared-preact/hooks/index.d.ts +0 -1
- package/dist/shared-preact/hooks/use-stamp.d.ts +0 -18
- package/dist/shared-preact/index.d.ts +0 -4
- package/dist/shared-react/components/index.d.ts +0 -1
- package/dist/shared-react/components/stamp-img.d.ts +0 -10
- package/dist/shared-react/hooks/index.d.ts +0 -1
- package/dist/shared-react/hooks/use-stamp.d.ts +0 -18
- package/dist/shared-react/index.d.ts +0 -4
- package/dist/svelte/components/StampImg.svelte.d.ts +0 -10
- package/dist/svelte/components/index.d.ts +0 -1
- package/dist/svelte/hooks/index.d.ts +0 -1
- package/dist/svelte/hooks/use-stamp.svelte.d.ts +0 -23
- package/dist/svelte/index.cjs +0 -2
- package/dist/svelte/index.cjs.map +0 -1
- package/dist/svelte/index.d.ts +0 -4
- package/dist/svelte/index.js +0 -182
- package/dist/svelte/index.js.map +0 -1
- package/dist/vue/components/index.d.ts +0 -1
- package/dist/vue/components/stamp-img.vue.d.ts +0 -9
- package/dist/vue/hooks/index.d.ts +0 -1
- package/dist/vue/hooks/use-stamp.d.ts +0 -460
- package/dist/vue/index.cjs +0 -2
- package/dist/vue/index.cjs.map +0 -1
- package/dist/vue/index.d.ts +0 -4
- package/dist/vue/index.js +0 -189
- package/dist/vue/index.js.map +0 -1
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","sources":["../src/lib/manifest.ts","../src/lib/actions.ts","../src/lib/handlers/rubber-stamp.handler.ts","../src/lib/tools.ts","../src/lib/defaults/name-map.ts","../src/lib/stamp-plugin.ts","../src/lib/reducer.ts","../src/lib/index.ts"],"sourcesContent":["import { PluginManifest } from '@embedpdf/core';\nimport { StampPluginConfig } from './types';\n\nexport const STAMP_PLUGIN_ID = 'stamp';\n\nexport const manifest: PluginManifest<StampPluginConfig> = {\n id: STAMP_PLUGIN_ID,\n name: 'Stamp Plugin',\n version: '1.0.0',\n provides: ['stamp'],\n requires: ['annotation'],\n optional: ['i18n'],\n defaultConfig: {\n defaultLibrary: {\n id: 'custom',\n name: 'Custom Stamps',\n nameKey: 'stamp.library.custom',\n categories: ['custom', 'sidebar'],\n },\n manifests: [\n {\n url: 'https://cdn.jsdelivr.net/npm/@embedpdf/default-stamps/{locale}/manifest.json',\n fallbackLocale: 'en',\n },\n ],\n },\n};\n","import { Action } from '@embedpdf/core';\n\nexport const ADD_STAMP_LIBRARY = 'STAMP/ADD_LIBRARY';\nexport const REMOVE_STAMP_LIBRARY = 'STAMP/REMOVE_LIBRARY';\n\nexport interface AddStampLibraryAction extends Action {\n type: typeof ADD_STAMP_LIBRARY;\n payload: string;\n}\n\nexport interface RemoveStampLibraryAction extends Action {\n type: typeof REMOVE_STAMP_LIBRARY;\n payload: string;\n}\n\nexport type StampAction = AddStampLibraryAction | RemoveStampLibraryAction;\n\nexport function addStampLibrary(id: string): AddStampLibraryAction {\n return { type: ADD_STAMP_LIBRARY, payload: id };\n}\n\nexport function removeStampLibrary(id: string): RemoveStampLibraryAction {\n return { type: REMOVE_STAMP_LIBRARY, payload: id };\n}\n","import {\n PdfAnnotationName,\n PdfAnnotationSubtype,\n PdfStampAnnoObject,\n Rect,\n uuidV4,\n} from '@embedpdf/models';\nimport { HandlerFactory } from '@embedpdf/plugin-annotation';\nimport { applyInsertUpright, clampAnnotationToPage } from '@embedpdf/plugin-annotation';\nimport { RUBBER_STAMP_TOOL_ID } from '../tools';\n\nexport const rubberStampHandlerFactory: HandlerFactory<\n PdfStampAnnoObject,\n typeof RUBBER_STAMP_TOOL_ID\n> = {\n annotationType: PdfAnnotationSubtype.STAMP,\n create(context) {\n const { onPreview, onCommit, getTool, pageSize, pageRotation, getToolContext } = context;\n\n return {\n onPointerMove: (pos) => {\n const ctx = getToolContext();\n if (!ctx?.stampSize) return;\n const { width, height } = ctx.stampSize;\n onPreview({\n type: PdfAnnotationSubtype.STAMP,\n bounds: {\n origin: { x: pos.x - width / 2, y: pos.y - height / 2 },\n size: { width, height },\n },\n data: {\n rect: {\n origin: { x: pos.x - width / 2, y: pos.y - height / 2 },\n size: { width, height },\n },\n ghostUrl: ctx.ghostUrl,\n pageRotation,\n },\n });\n },\n\n onPointerDown: (pos) => {\n const tool = getTool();\n const ctx = getToolContext();\n if (!tool || !ctx?.stampSize) return;\n\n const { width, height } = ctx.stampSize;\n const rect: Rect = {\n origin: { x: pos.x - width / 2, y: pos.y - height / 2 },\n size: { width, height },\n };\n\n let anno: PdfStampAnnoObject = {\n ...tool.defaults,\n rect,\n type: PdfAnnotationSubtype.STAMP,\n name: ctx.stamp.name ?? tool.defaults.name ?? PdfAnnotationName.Custom,\n subject: ctx.stamp.subject ?? tool.defaults.subject ?? 'Custom Stamp',\n flags: tool.defaults.flags ?? ['print'],\n pageIndex: context.pageIndex,\n id: uuidV4(),\n created: new Date(),\n };\n\n if (tool.behavior?.insertUpright) {\n anno = applyInsertUpright(anno, pageRotation, false);\n }\n anno = clampAnnotationToPage(anno, pageSize);\n\n onCommit(anno, { appearance: ctx.appearance });\n onPreview(null);\n },\n\n onPointerLeave: () => {\n onPreview(null);\n },\n };\n },\n};\n","import { PdfAnnotationSubtype } from '@embedpdf/models';\nimport { defineAnnotationTool } from '@embedpdf/plugin-annotation';\nimport { rubberStampHandlerFactory } from './handlers/rubber-stamp.handler';\n\nexport const RUBBER_STAMP_TOOL_ID = 'rubberStamp' as const;\n\nexport const rubberStampTool = defineAnnotationTool({\n id: RUBBER_STAMP_TOOL_ID,\n name: 'Rubber Stamp',\n labelKey: 'stamp.rubberStamp',\n categories: ['annotation', 'stamp', 'insert'],\n matchScore: () => 0,\n interaction: {\n exclusive: true,\n cursor: 'copy',\n isDraggable: true,\n isResizable: true,\n isRotatable: false,\n lockAspectRatio: true,\n isGroupDraggable: true,\n isGroupResizable: false,\n isGroupRotatable: false,\n },\n defaults: {\n type: PdfAnnotationSubtype.STAMP,\n },\n behavior: {\n deactivateToolAfterCreate: true,\n selectAfterCreate: true,\n insertUpright: true,\n useAppearanceStream: true,\n },\n pointerHandler: rubberStampHandlerFactory,\n});\n\nexport const stampTools = [rubberStampTool];\n","import { PdfAnnotationName } from '@embedpdf/models';\n\nconst ANNOTATION_NAME_MAP: Record<string, PdfAnnotationName> = {\n Approved: PdfAnnotationName.Approved,\n Experimental: PdfAnnotationName.Experimental,\n NotApproved: PdfAnnotationName.NotApproved,\n AsIs: PdfAnnotationName.AsIs,\n Expired: PdfAnnotationName.Expired,\n NotForPublicRelease: PdfAnnotationName.NotForPublicRelease,\n Confidential: PdfAnnotationName.Confidential,\n Final: PdfAnnotationName.Final,\n Sold: PdfAnnotationName.Sold,\n Departmental: PdfAnnotationName.Departmental,\n ForComment: PdfAnnotationName.ForComment,\n TopSecret: PdfAnnotationName.TopSecret,\n Draft: PdfAnnotationName.Draft,\n ForPublicRelease: PdfAnnotationName.ForPublicRelease,\n Completed: PdfAnnotationName.Completed,\n Void: PdfAnnotationName.Void,\n PreliminaryResults: PdfAnnotationName.PreliminaryResults,\n InformationOnly: PdfAnnotationName.InformationOnly,\n Rejected: PdfAnnotationName.Rejected,\n Witness: PdfAnnotationName.Witness,\n InitialHere: PdfAnnotationName.InitialHere,\n SignHere: PdfAnnotationName.SignHere,\n Accepted: PdfAnnotationName.Accepted,\n Custom: PdfAnnotationName.Custom,\n Image: PdfAnnotationName.Image,\n};\n\nexport function parseAnnotationName(name?: string): PdfAnnotationName {\n if (!name) return PdfAnnotationName.Custom;\n return ANNOTATION_NAME_MAP[name] ?? PdfAnnotationName.Custom;\n}\n","import { BasePlugin, createEmitter, createScopedEmitter, PluginRegistry } from '@embedpdf/core';\nimport { Task, PdfErrorReason, PdfErrorCode, PdfAnnotationObject, uuidV4 } from '@embedpdf/models';\nimport { AnnotationCapability, AnnotationPlugin } from '@embedpdf/plugin-annotation';\nimport { I18nCapability, I18nPlugin } from '@embedpdf/plugin-i18n';\nimport {\n StampCapability,\n StampScope,\n ActiveStampChangeEvent,\n ActiveStampInfo,\n StampDefinition,\n StampDefinitionUpdate,\n StampLibrary,\n StampLibraryConfig,\n StampLibraryUpdate,\n StampManifest,\n StampManifestSource,\n StampPluginConfig,\n StampState,\n ExportedStampLibrary,\n ResolvedStamp,\n} from './types';\nimport { addStampLibrary, removeStampLibrary, StampAction } from './actions';\nimport { STAMP_PLUGIN_ID } from './manifest';\nimport { RUBBER_STAMP_TOOL_ID, stampTools } from './tools';\nimport { parseAnnotationName } from './defaults/name-map';\n\ninterface ManagedManifest {\n source: StampManifestSource;\n localeAware: boolean;\n currentLocale: string;\n libraryId: string | null;\n}\n\nexport class StampPlugin extends BasePlugin<\n StampPluginConfig,\n StampCapability,\n StampState,\n StampAction\n> {\n static readonly id = STAMP_PLUGIN_ID;\n\n private readonly instanceId = uuidV4();\n private readonly libraries = new Map<string, StampLibrary>();\n private readonly libraryChange$ = createEmitter<StampLibrary[]>();\n private readonly activeStamp$ = createScopedEmitter<\n ActiveStampInfo | null,\n ActiveStampChangeEvent,\n string\n >((documentId, activeStamp) => ({ documentId, activeStamp }));\n private readonly managedManifests: ManagedManifest[] = [];\n private annotation: AnnotationCapability | null = null;\n private i18n: I18nCapability | null = null;\n private localeUnsubscribe: (() => void) | null = null;\n private toolChangeUnsubscribe: (() => void) | null = null;\n private currentGhostUrl: string | null = null;\n\n constructor(\n id: string,\n registry: PluginRegistry,\n private config: StampPluginConfig,\n ) {\n super(id, registry);\n\n this.annotation = registry.getPlugin<AnnotationPlugin>('annotation')?.provides() ?? null;\n if (this.annotation) {\n for (const tool of stampTools) {\n this.annotation.addTool(tool);\n }\n this.toolChangeUnsubscribe = this.annotation.onActiveToolChange(({ documentId, tool }) => {\n if (tool?.id !== RUBBER_STAMP_TOOL_ID) {\n if (this.currentGhostUrl) {\n URL.revokeObjectURL(this.currentGhostUrl);\n this.currentGhostUrl = null;\n }\n this.activeStamp$.emit(documentId, null);\n }\n });\n }\n\n this.i18n = registry.getPlugin<I18nPlugin>('i18n')?.provides() ?? null;\n }\n\n async initialize(): Promise<void> {\n if (this.config.libraries) {\n for (const libConfig of this.config.libraries) {\n await this.loadLibraryInternal(libConfig).toPromise();\n }\n }\n\n if (this.config.manifests && this.config.manifests.length > 0) {\n await this.initializeManifests();\n }\n }\n\n protected buildCapability(): StampCapability {\n return {\n getLibraries: () => this.getLibraries(),\n getStampsByCategory: (category) => this.getStampsByCategory(category),\n renderStamp: (libraryId, pageIndex, width, dpr) =>\n this.renderStamp(libraryId, pageIndex, width, dpr),\n loadLibrary: (config) => this.loadLibrary(config),\n loadLibraryFromManifest: (url) => this.loadLibraryFromManifest(url),\n createNewLibrary: (name, options) => this.createNewLibrary(name, options),\n addStampToLibrary: (libraryId, stamp, pdf) => this.addStampToLibrary(libraryId, stamp, pdf),\n removeStampFromLibrary: (libraryId, stampId) =>\n this.removeStampFromLibrary(libraryId, stampId),\n updateStamp: (libraryId, stampId, updates) => this.updateStamp(libraryId, stampId, updates),\n updateLibrary: (libraryId, updates) => this.updateLibrary(libraryId, updates),\n removeLibrary: (id) => this.removeLibrary(id),\n exportLibrary: (id) => this.exportLibrary(id),\n forDocument: (documentId) => this.createStampScope(documentId),\n onActiveStampChange: this.activeStamp$.onGlobal,\n onLibraryChange: this.libraryChange$.on,\n };\n }\n\n getLibraries(): StampLibrary[] {\n return Array.from(this.libraries.values());\n }\n\n getStampsByCategory(category: string): ResolvedStamp[] {\n const results: ResolvedStamp[] = [];\n\n for (const library of this.libraries.values()) {\n const libraryMatches = library.categories?.includes(category) ?? false;\n\n for (const stamp of library.stamps) {\n const stampMatches = stamp.categories?.includes(category) ?? false;\n if (libraryMatches || stampMatches) {\n results.push({ library, stamp });\n }\n }\n }\n\n return results;\n }\n\n renderStamp(\n libraryId: string,\n pageIndex: number,\n width: number,\n dpr?: number,\n ): Task<Blob, PdfErrorReason> {\n const library = this.libraries.get(libraryId);\n if (!library) {\n const task = new Task<Blob, PdfErrorReason>();\n task.reject({\n code: PdfErrorCode.NotFound,\n message: `Stamp library not found: ${libraryId}`,\n });\n return task;\n }\n\n const page = library.document.pages[pageIndex];\n if (!page) {\n const task = new Task<Blob, PdfErrorReason>();\n task.reject({\n code: PdfErrorCode.NotFound,\n message: `Page ${pageIndex} not found in stamp library: ${libraryId}`,\n });\n return task;\n }\n\n const scaleFactor = width / page.size.width;\n\n return this.engine.renderPageRect(\n library.document,\n page,\n { origin: { x: 0, y: 0 }, size: page.size },\n {\n scaleFactor,\n dpr: dpr ?? 1,\n withAnnotations: true,\n rotation: page.rotation,\n transparentBackground: true,\n },\n );\n }\n\n loadLibrary(config: StampLibraryConfig): Task<string, PdfErrorReason> {\n return this.loadLibraryInternal(config);\n }\n\n createNewLibrary(\n name: string,\n options?: { categories?: string[]; id?: string; nameKey?: string; readonly?: boolean },\n ): Task<string, PdfErrorReason> {\n const task = new Task<string, PdfErrorReason>();\n const libraryId = options?.id ?? this.generateLibraryId();\n const documentId = this.getLibraryDocumentId(libraryId);\n\n this.engine.createDocument(documentId).wait(\n (doc) => {\n const library: StampLibrary = {\n id: libraryId,\n name,\n nameKey: options?.nameKey,\n document: doc,\n stamps: [],\n categories: options?.categories,\n readonly: options?.readonly ?? false,\n };\n\n this.libraries.set(libraryId, library);\n this.dispatch(addStampLibrary(libraryId));\n this.emitLibraryChange();\n task.resolve(libraryId);\n },\n (error) => {\n this.logger.error(\n 'StampPlugin',\n 'CreateNewLibrary',\n `Failed to create library: ${name}`,\n error,\n );\n task.fail(error);\n },\n );\n\n return task;\n }\n\n addStampToLibrary(\n libraryId: string,\n stamp: Omit<StampDefinition, 'id' | 'pageIndex'>,\n pdf: ArrayBuffer,\n ): Task<void, PdfErrorReason> {\n const task = new Task<void, PdfErrorReason>();\n\n const library = this.libraries.get(libraryId);\n if (!library) {\n task.reject({\n code: PdfErrorCode.NotFound,\n message: `Stamp library not found: ${libraryId}`,\n });\n return task;\n }\n\n if (library.readonly) {\n task.reject({\n code: PdfErrorCode.NotSupport,\n message: `Cannot add stamps to readonly library: ${libraryId}`,\n });\n return task;\n }\n\n const tempDocId = `stamp-temp-${Date.now()}`;\n\n this.engine.openDocumentBuffer({ id: tempDocId, content: pdf }).wait(\n (tempDoc) => {\n this.engine.importPages(library.document, tempDoc, [0]).wait(\n (newPages) => {\n const newPage = newPages[0];\n library.document.pages.push(newPage);\n library.document.pageCount = library.document.pages.length;\n\n const stampDef: StampDefinition = {\n ...stamp,\n id: uuidV4(),\n pageIndex: newPage.index,\n };\n library.stamps.push(stampDef);\n\n this.engine.closeDocument(tempDoc).wait(\n () => {\n this.emitLibraryChange();\n task.resolve();\n },\n () => {\n this.emitLibraryChange();\n task.resolve();\n },\n );\n },\n (error) => {\n this.logger.error('StampPlugin', 'AddStampToLibrary', 'Failed to import page', error);\n this.engine.closeDocument(tempDoc).wait(\n () => task.fail(error),\n () => task.fail(error),\n );\n },\n );\n },\n (error) => {\n this.logger.error(\n 'StampPlugin',\n 'AddStampToLibrary',\n 'Failed to open temp document',\n error,\n );\n task.fail(error);\n },\n );\n\n return task;\n }\n\n private createStampScope(documentId: string): StampScope {\n return {\n createStampFromAnnotation: (annotation, stamp, libraryId) =>\n this.createStampFromAnnotation(documentId, annotation, stamp, libraryId),\n createStampFromAnnotations: (annotations, stamp, libraryId) =>\n this.createStampFromAnnotations(documentId, annotations, stamp, libraryId),\n activateStampPlacement: (libraryId, stamp) =>\n this.activateStampPlacement(documentId, libraryId, stamp),\n activateStampPlacementById: (libraryId, stampId) =>\n this.activateStampPlacementById(documentId, libraryId, stampId),\n getActiveStamp: () => this.getActiveStamp(documentId),\n onActiveStampChange: this.activeStamp$.forScope(documentId),\n };\n }\n\n private activateStampPlacementById(\n documentId: string,\n libraryId: string,\n stampId: string,\n ): Task<void, PdfErrorReason> {\n const task = new Task<void, PdfErrorReason>();\n\n const library = this.libraries.get(libraryId);\n if (!library) {\n task.reject({\n code: PdfErrorCode.NotFound,\n message: `Stamp library not found: ${libraryId}`,\n });\n return task;\n }\n\n const stamp = library.stamps.find((s) => s.id === stampId);\n if (!stamp) {\n task.reject({\n code: PdfErrorCode.NotFound,\n message: `Stamp ${stampId} not found in library: ${libraryId}`,\n });\n return task;\n }\n\n return this.activateStampPlacement(documentId, libraryId, stamp);\n }\n\n private getActiveStamp(documentId: string): ActiveStampInfo | null {\n return this.activeStamp$.getValue(documentId) ?? null;\n }\n\n private activateStampPlacement(\n documentId: string,\n libraryId: string,\n stamp: StampDefinition,\n ): Task<void, PdfErrorReason> {\n const task = new Task<void, PdfErrorReason>();\n\n const library = this.libraries.get(libraryId);\n if (!library) {\n task.reject({\n code: PdfErrorCode.NotFound,\n message: `Stamp library not found: ${libraryId}`,\n });\n return task;\n }\n\n const page = library.document.pages[stamp.pageIndex];\n if (!page) {\n task.reject({\n code: PdfErrorCode.NotFound,\n message: `Page ${stamp.pageIndex} not found in library`,\n });\n return task;\n }\n\n const stampSize = page.size;\n\n this.engine.extractPages(library.document, [stamp.pageIndex]).wait(\n (appearance) => {\n this.renderStamp(libraryId, stamp.pageIndex, stampSize.width, 2).wait(\n (blob) => {\n if (this.currentGhostUrl) {\n URL.revokeObjectURL(this.currentGhostUrl);\n }\n const ghostUrl = URL.createObjectURL(blob);\n this.currentGhostUrl = ghostUrl;\n this.annotation?.setActiveTool(RUBBER_STAMP_TOOL_ID, {\n appearance,\n ghostUrl,\n stampSize,\n libraryId,\n stamp,\n });\n this.activeStamp$.emit(documentId, { libraryId, stamp });\n task.resolve();\n },\n (error) => {\n this.logger.error(\n 'StampPlugin',\n 'ActivateStampPlacement',\n 'Failed to render stamp preview',\n error,\n );\n task.fail(error);\n },\n );\n },\n (error) => {\n this.logger.error(\n 'StampPlugin',\n 'ActivateStampPlacement',\n 'Failed to extract stamp page',\n error,\n );\n task.fail(error);\n },\n );\n\n return task;\n }\n\n private createStampFromAnnotation(\n documentId: string,\n annotation: PdfAnnotationObject,\n stamp: Omit<StampDefinition, 'id' | 'pageIndex'>,\n libraryId?: string,\n ): Task<void, PdfErrorReason> {\n const task = new Task<void, PdfErrorReason>();\n\n const docState = this.getCoreDocument(documentId);\n if (!docState?.document) {\n task.reject({ code: PdfErrorCode.DocNotOpen, message: 'document is not open' });\n return task;\n }\n\n const doc = docState.document;\n const page = doc.pages[annotation.pageIndex];\n if (!page) {\n task.reject({\n code: PdfErrorCode.NotFound,\n message: `page ${annotation.pageIndex} not found`,\n });\n return task;\n }\n\n this.resolveTargetLibrary(libraryId).wait(\n (targetId) => {\n this.engine.exportAnnotationAppearanceAsPdf(doc, page, annotation).wait(\n (pdf) => {\n this.addStampToLibrary(targetId, stamp, pdf).wait(\n () => task.resolve(),\n (error) => task.fail(error),\n );\n },\n (error) => {\n this.logger.error(\n 'StampPlugin',\n 'CreateStampFromAnnotation',\n 'Failed to export annotation',\n error,\n );\n task.fail(error);\n },\n );\n },\n (error) => task.fail(error),\n );\n\n return task;\n }\n\n private createStampFromAnnotations(\n documentId: string,\n annotations: PdfAnnotationObject[],\n stamp: Omit<StampDefinition, 'id' | 'pageIndex'>,\n libraryId?: string,\n ): Task<void, PdfErrorReason> {\n const task = new Task<void, PdfErrorReason>();\n\n if (annotations.length === 0) {\n task.reject({ code: PdfErrorCode.NotFound, message: 'no annotations provided' });\n return task;\n }\n\n const docState = this.getCoreDocument(documentId);\n if (!docState?.document) {\n task.reject({ code: PdfErrorCode.DocNotOpen, message: 'document is not open' });\n return task;\n }\n\n const doc = docState.document;\n const page = doc.pages[annotations[0].pageIndex];\n if (!page) {\n task.reject({\n code: PdfErrorCode.NotFound,\n message: `page ${annotations[0].pageIndex} not found`,\n });\n return task;\n }\n\n this.resolveTargetLibrary(libraryId).wait(\n (targetId) => {\n this.engine.exportAnnotationsAppearanceAsPdf(doc, page, annotations).wait(\n (pdf) => {\n this.addStampToLibrary(targetId, stamp, pdf).wait(\n () => task.resolve(),\n (error) => task.fail(error),\n );\n },\n (error) => {\n this.logger.error(\n 'StampPlugin',\n 'CreateStampFromAnnotations',\n 'Failed to export annotations',\n error,\n );\n task.fail(error);\n },\n );\n },\n (error) => task.fail(error),\n );\n\n return task;\n }\n\n private resolveTargetLibrary(libraryId?: string): Task<string, PdfErrorReason> {\n if (libraryId && this.libraries.has(libraryId)) {\n const task = new Task<string, PdfErrorReason>();\n task.resolve(libraryId);\n return task;\n }\n\n const defaults = this.config.defaultLibrary;\n if (this.config.defaultLibrary === false || !defaults) {\n const task = new Task<string, PdfErrorReason>();\n task.reject({\n code: PdfErrorCode.NotSupport,\n message: 'Default library creation is disabled',\n });\n return task;\n }\n\n const defaultId = defaults.id ?? 'custom';\n\n if (this.libraries.has(defaultId)) {\n const task = new Task<string, PdfErrorReason>();\n task.resolve(defaultId);\n return task;\n }\n\n return this.createNewLibrary(defaults.name ?? 'Custom Stamps', {\n id: defaultId,\n nameKey: defaults.nameKey,\n categories: defaults.categories,\n });\n }\n\n removeLibrary(id: string): Task<void, PdfErrorReason> {\n const task = new Task<void, PdfErrorReason>();\n\n const library = this.libraries.get(id);\n if (!library) {\n task.resolve();\n return task;\n }\n\n this.engine.closeDocument(library.document).wait(\n () => {\n this.libraries.delete(id);\n this.dispatch(removeStampLibrary(id));\n this.emitLibraryChange();\n task.resolve();\n },\n () => {\n this.logger.warn(\n 'StampPlugin',\n 'RemoveLibrary',\n `Failed to close document for library: ${id}`,\n );\n this.libraries.delete(id);\n this.dispatch(removeStampLibrary(id));\n this.emitLibraryChange();\n task.resolve();\n },\n );\n\n return task;\n }\n\n exportLibrary(id: string): Task<ExportedStampLibrary, PdfErrorReason> {\n const task = new Task<ExportedStampLibrary, PdfErrorReason>();\n\n const library = this.libraries.get(id);\n if (!library) {\n task.reject({\n code: PdfErrorCode.NotFound,\n message: `Stamp library not found: ${id}`,\n });\n return task;\n }\n\n this.engine.saveAsCopy(library.document).wait(\n (pdf) => {\n task.resolve({\n name: library.name,\n pdf,\n stamps: library.stamps,\n categories: library.categories,\n });\n },\n (error) => {\n this.logger.error('StampPlugin', 'ExportLibrary', `Failed to export library: ${id}`, error);\n task.fail(error);\n },\n );\n\n return task;\n }\n\n private loadLibraryInternal(config: StampLibraryConfig): Task<string, PdfErrorReason> {\n const task = new Task<string, PdfErrorReason>();\n const libraryId = config.id ?? this.generateLibraryId();\n const documentId = this.getLibraryDocumentId(libraryId);\n\n const engineTask =\n typeof config.pdf === 'string'\n ? this.engine.openDocumentUrl({ id: documentId, url: config.pdf })\n : this.engine.openDocumentBuffer({ id: documentId, content: config.pdf });\n\n engineTask.wait(\n (doc) => {\n const stamps = config.stamps.map((s) => (s.id ? s : { ...s, id: uuidV4() }));\n\n const library: StampLibrary = {\n id: libraryId,\n name: config.name,\n nameKey: config.nameKey,\n document: doc,\n stamps,\n categories: config.categories,\n readonly: config.readonly ?? false,\n };\n\n this.libraries.set(libraryId, library);\n this.dispatch(addStampLibrary(libraryId));\n this.emitLibraryChange();\n\n task.resolve(libraryId);\n },\n (error) => {\n this.logger.error(\n 'StampPlugin',\n 'LoadLibrary',\n `Failed to load stamp library: ${config.name}`,\n error,\n );\n task.fail(error);\n },\n );\n\n return task;\n }\n\n removeStampFromLibrary(libraryId: string, stampId: string): Task<void, PdfErrorReason> {\n const task = new Task<void, PdfErrorReason>();\n\n const library = this.libraries.get(libraryId);\n if (!library) {\n task.reject({\n code: PdfErrorCode.NotFound,\n message: `Stamp library not found: ${libraryId}`,\n });\n return task;\n }\n\n if (library.readonly) {\n task.reject({\n code: PdfErrorCode.NotSupport,\n message: `Cannot remove stamps from readonly library: ${libraryId}`,\n });\n return task;\n }\n\n const stampIdx = library.stamps.findIndex((s) => s.id === stampId);\n if (stampIdx === -1) {\n task.reject({\n code: PdfErrorCode.NotFound,\n message: `Stamp ${stampId} not found in library: ${libraryId}`,\n });\n return task;\n }\n\n const pageIndex = library.stamps[stampIdx].pageIndex;\n\n this.engine.deletePage(library.document, pageIndex).wait(\n () => {\n library.stamps.splice(stampIdx, 1);\n library.document.pages.splice(pageIndex, 1);\n library.document.pageCount = library.document.pages.length;\n\n for (const s of library.stamps) {\n if (s.pageIndex > pageIndex) {\n s.pageIndex--;\n }\n }\n for (let i = 0; i < library.document.pages.length; i++) {\n library.document.pages[i].index = i;\n }\n\n this.emitLibraryChange();\n task.resolve();\n },\n (error) => {\n this.logger.error(\n 'StampPlugin',\n 'RemoveStampFromLibrary',\n `Failed to delete page for stamp ${stampId}`,\n error,\n );\n task.fail(error);\n },\n );\n\n return task;\n }\n\n updateStamp(\n libraryId: string,\n stampId: string,\n updates: StampDefinitionUpdate,\n ): Task<void, PdfErrorReason> {\n const task = new Task<void, PdfErrorReason>();\n\n const library = this.libraries.get(libraryId);\n if (!library) {\n task.reject({\n code: PdfErrorCode.NotFound,\n message: `Stamp library not found: ${libraryId}`,\n });\n return task;\n }\n\n if (library.readonly) {\n task.reject({\n code: PdfErrorCode.NotSupport,\n message: `Cannot update stamps in readonly library: ${libraryId}`,\n });\n return task;\n }\n\n const stamp = library.stamps.find((s) => s.id === stampId);\n if (!stamp) {\n task.reject({\n code: PdfErrorCode.NotFound,\n message: `Stamp ${stampId} not found in library: ${libraryId}`,\n });\n return task;\n }\n\n Object.assign(stamp, updates);\n this.emitLibraryChange();\n task.resolve();\n\n return task;\n }\n\n updateLibrary(libraryId: string, updates: StampLibraryUpdate): Task<void, PdfErrorReason> {\n const task = new Task<void, PdfErrorReason>();\n\n const library = this.libraries.get(libraryId);\n if (!library) {\n task.reject({\n code: PdfErrorCode.NotFound,\n message: `Stamp library not found: ${libraryId}`,\n });\n return task;\n }\n\n if (library.readonly) {\n task.reject({\n code: PdfErrorCode.NotSupport,\n message: `Cannot update readonly library: ${libraryId}`,\n });\n return task;\n }\n\n if (updates.name !== undefined) library.name = updates.name;\n if (updates.nameKey !== undefined) library.nameKey = updates.nameKey;\n if (updates.categories !== undefined) library.categories = updates.categories;\n if (updates.readonly !== undefined) library.readonly = updates.readonly;\n\n this.emitLibraryChange();\n task.resolve();\n\n return task;\n }\n\n loadLibraryFromManifest(url: string): Task<string, PdfErrorReason> {\n return this.loadManifestUrl(url, true);\n }\n\n private async initializeManifests(): Promise<void> {\n const currentLocale = this.i18n?.getLocale() ?? 'en';\n\n for (const source of this.config.manifests!) {\n const localeAware = source.url.includes('{locale}');\n const locale = localeAware ? currentLocale : '';\n const resolvedUrl = source.url.replace('{locale}', locale || currentLocale);\n\n const managed: ManagedManifest = {\n source,\n localeAware,\n currentLocale: localeAware ? currentLocale : '',\n libraryId: null,\n };\n this.managedManifests.push(managed);\n\n try {\n const libraryId = await this.loadManifestUrl(resolvedUrl, true).toPromise();\n managed.libraryId = libraryId;\n } catch {\n if (localeAware && source.fallbackLocale && source.fallbackLocale !== currentLocale) {\n const fallbackUrl = source.url.replace('{locale}', source.fallbackLocale);\n try {\n const libraryId = await this.loadManifestUrl(fallbackUrl, true).toPromise();\n managed.libraryId = libraryId;\n managed.currentLocale = source.fallbackLocale;\n } catch {\n this.logger.warn(\n 'StampPlugin',\n 'InitManifests',\n `Failed to load manifest (including fallback): ${source.url}`,\n );\n }\n } else {\n this.logger.warn(\n 'StampPlugin',\n 'InitManifests',\n `Failed to load manifest: ${resolvedUrl}`,\n );\n }\n }\n }\n\n if (this.i18n) {\n this.localeUnsubscribe = this.i18n.onLocaleChange((event) => {\n this.handleLocaleChange(event.currentLocale);\n });\n }\n }\n\n private async handleLocaleChange(newLocale: string): Promise<void> {\n for (const managed of this.managedManifests) {\n if (!managed.localeAware || managed.currentLocale === newLocale) {\n continue;\n }\n\n if (managed.libraryId) {\n try {\n await this.removeLibrary(managed.libraryId).toPromise();\n } catch {\n // Best effort removal\n }\n managed.libraryId = null;\n }\n\n const resolvedUrl = managed.source.url.replace('{locale}', newLocale);\n\n try {\n const libraryId = await this.loadManifestUrl(resolvedUrl, true).toPromise();\n managed.libraryId = libraryId;\n managed.currentLocale = newLocale;\n } catch {\n const fallback = managed.source.fallbackLocale ?? 'en';\n if (fallback !== newLocale) {\n const fallbackUrl = managed.source.url.replace('{locale}', fallback);\n try {\n const libraryId = await this.loadManifestUrl(fallbackUrl, true).toPromise();\n managed.libraryId = libraryId;\n managed.currentLocale = fallback;\n } catch {\n this.logger.warn(\n 'StampPlugin',\n 'LocaleChange',\n `Failed to load manifest for locale ${newLocale} (including fallback): ${managed.source.url}`,\n );\n }\n } else {\n this.logger.warn(\n 'StampPlugin',\n 'LocaleChange',\n `Failed to load manifest for locale ${newLocale}: ${managed.source.url}`,\n );\n }\n }\n }\n }\n\n private loadManifestUrl(url: string, readonly: boolean): Task<string, PdfErrorReason> {\n const task = new Task<string, PdfErrorReason>();\n\n fetch(url)\n .then((response) => {\n if (!response.ok) {\n throw new Error(`HTTP ${response.status}: ${response.statusText}`);\n }\n return response.json() as Promise<StampManifest>;\n })\n .then((manifest) => {\n const pdfUrl = this.resolveManifestPdfUrl(url, manifest.pdf);\n\n const stamps: StampDefinition[] = manifest.stamps.map((entry) => ({\n id: entry.id ?? uuidV4(),\n pageIndex: entry.pageIndex,\n name: parseAnnotationName(entry.name),\n subject: entry.subject,\n subjectKey: entry.subjectKey,\n label: entry.label,\n categories: entry.categories,\n }));\n\n const config: StampLibraryConfig = {\n id: manifest.id,\n name: manifest.name,\n nameKey: manifest.nameKey,\n pdf: pdfUrl,\n stamps,\n categories: manifest.categories,\n readonly,\n };\n\n this.loadLibraryInternal(config).wait(\n (libraryId) => task.resolve(libraryId),\n (error) => task.fail(error),\n );\n })\n .catch((error) => {\n this.logger.error('StampPlugin', 'LoadManifest', `Failed to fetch manifest: ${url}`, error);\n task.reject({\n code: PdfErrorCode.NotFound,\n message: `Failed to load stamp manifest: ${url}`,\n });\n });\n\n return task;\n }\n\n private resolveManifestPdfUrl(manifestUrl: string, pdfPath: string): string {\n if (\n pdfPath.startsWith('http://') ||\n pdfPath.startsWith('https://') ||\n pdfPath.startsWith('/')\n ) {\n return pdfPath;\n }\n const base = manifestUrl.substring(0, manifestUrl.lastIndexOf('/') + 1);\n return base + pdfPath;\n }\n\n private generateLibraryId(): string {\n return uuidV4();\n }\n\n private getLibraryDocumentId(libraryId: string): string {\n return `stamp-doc-${this.instanceId}-${libraryId}`;\n }\n\n private emitLibraryChange(): void {\n this.libraryChange$.emit(this.getLibraries());\n }\n\n override async destroy(): Promise<void> {\n if (this.currentGhostUrl) {\n URL.revokeObjectURL(this.currentGhostUrl);\n this.currentGhostUrl = null;\n }\n if (this.toolChangeUnsubscribe) {\n this.toolChangeUnsubscribe();\n this.toolChangeUnsubscribe = null;\n }\n if (this.localeUnsubscribe) {\n this.localeUnsubscribe();\n this.localeUnsubscribe = null;\n }\n this.activeStamp$.clear();\n const libs = Array.from(this.libraries.values());\n for (const library of libs) {\n try {\n await this.engine.closeDocument(library.document).toPromise();\n } catch {\n // Best effort cleanup\n }\n }\n this.libraries.clear();\n this.managedManifests.length = 0;\n super.destroy();\n }\n}\n","import { Reducer } from '@embedpdf/core';\nimport { StampAction, ADD_STAMP_LIBRARY, REMOVE_STAMP_LIBRARY } from './actions';\nimport { StampState } from './types';\n\nexport const initialState: StampState = {\n libraryIds: [],\n};\n\nexport const stampReducer: Reducer<StampState, StampAction> = (state = initialState, action) => {\n switch (action.type) {\n case ADD_STAMP_LIBRARY:\n return {\n ...state,\n libraryIds: [...state.libraryIds, action.payload],\n };\n\n case REMOVE_STAMP_LIBRARY:\n return {\n ...state,\n libraryIds: state.libraryIds.filter((id) => id !== action.payload),\n };\n\n default:\n return state;\n }\n};\n","import { PluginPackage } from '@embedpdf/core';\nimport { manifest, STAMP_PLUGIN_ID } from './manifest';\nimport { StampPluginConfig, StampState } from './types';\nimport { StampPlugin } from './stamp-plugin';\nimport { stampReducer, initialState } from './reducer';\nimport { StampAction } from './actions';\n\nexport const StampPluginPackage: PluginPackage<\n StampPlugin,\n StampPluginConfig,\n StampState,\n StampAction\n> = {\n manifest,\n create: (registry, config) => new StampPlugin(STAMP_PLUGIN_ID, registry, config),\n reducer: stampReducer,\n initialState,\n};\n\nexport * from './stamp-plugin';\nexport * from './types';\nexport * from './manifest';\nexport * from './actions';\nexport * from './reducer';\nexport { RUBBER_STAMP_TOOL_ID } from './tools';\n"],"names":["STAMP_PLUGIN_ID","manifest","id","name","version","provides","requires","optional","defaultConfig","defaultLibrary","nameKey","categories","manifests","url","fallbackLocale","ADD_STAMP_LIBRARY","REMOVE_STAMP_LIBRARY","addStampLibrary","type","payload","removeStampLibrary","rubberStampHandlerFactory","annotationType","PdfAnnotationSubtype","STAMP","create","context","onPreview","onCommit","getTool","pageSize","pageRotation","getToolContext","onPointerMove","pos","ctx","stampSize","width","height","bounds","origin","x","y","size","data","rect","ghostUrl","onPointerDown","tool","anno","defaults","stamp","PdfAnnotationName","Custom","subject","flags","pageIndex","uuidV4","created","Date","_a","behavior","insertUpright","applyInsertUpright","clampAnnotationToPage","appearance","onPointerLeave","RUBBER_STAMP_TOOL_ID","stampTools","defineAnnotationTool","labelKey","matchScore","interaction","exclusive","cursor","isDraggable","isResizable","isRotatable","lockAspectRatio","isGroupDraggable","isGroupResizable","isGroupRotatable","deactivateToolAfterCreate","selectAfterCreate","useAppearanceStream","pointerHandler","ANNOTATION_NAME_MAP","Approved","Experimental","NotApproved","AsIs","Expired","NotForPublicRelease","Confidential","Final","Sold","Departmental","ForComment","TopSecret","Draft","ForPublicRelease","Completed","Void","PreliminaryResults","InformationOnly","Rejected","Witness","InitialHere","SignHere","Accepted","Image","_StampPlugin","BasePlugin","constructor","registry","config","super","this","instanceId","libraries","Map","libraryChange$","createEmitter","activeStamp$","createScopedEmitter","documentId","activeStamp","managedManifests","annotation","i18n","localeUnsubscribe","toolChangeUnsubscribe","currentGhostUrl","getPlugin","addTool","onActiveToolChange","URL","revokeObjectURL","emit","_b","initialize","libConfig","loadLibraryInternal","toPromise","length","initializeManifests","buildCapability","getLibraries","getStampsByCategory","category","renderStamp","libraryId","dpr","loadLibrary","loadLibraryFromManifest","createNewLibrary","options","addStampToLibrary","pdf","removeStampFromLibrary","stampId","updateStamp","updates","updateLibrary","removeLibrary","exportLibrary","forDocument","createStampScope","onActiveStampChange","onGlobal","onLibraryChange","on","Array","from","values","results","library","libraryMatches","includes","stamps","stampMatches","push","get","task","Task","reject","code","PdfErrorCode","NotFound","message","page","document","pages","scaleFactor","engine","renderPageRect","withAnnotations","rotation","transparentBackground","generateLibraryId","getLibraryDocumentId","createDocument","wait","doc","readonly","set","dispatch","emitLibraryChange","resolve","error","logger","fail","NotSupport","tempDocId","now","openDocumentBuffer","content","tempDoc","importPages","newPages","newPage","pageCount","stampDef","index","closeDocument","createStampFromAnnotation","createStampFromAnnotations","annotations","activateStampPlacement","activateStampPlacementById","getActiveStamp","forScope","find","s","getValue","extractPages","blob","createObjectURL","setActiveTool","docState","getCoreDocument","DocNotOpen","resolveTargetLibrary","targetId","exportAnnotationAppearanceAsPdf","exportAnnotationsAppearanceAsPdf","has","defaultId","delete","warn","saveAsCopy","openDocumentUrl","map","stampIdx","findIndex","deletePage","splice","i","Object","assign","loadManifestUrl","currentLocale","getLocale","source","localeAware","locale","resolvedUrl","replace","managed","fallbackUrl","onLocaleChange","event","handleLocaleChange","newLocale","fallback","fetch","then","response","ok","Error","status","statusText","json","pdfUrl","resolveManifestPdfUrl","entry","subjectKey","label","catch","manifestUrl","pdfPath","startsWith","substring","lastIndexOf","destroy","clear","libs","StampPlugin","initialState","libraryIds","stampReducer","state","action","filter","StampPluginPackage","reducer"],"mappings":"yLAGaA,EAAkB,QAElBC,EAA8C,CACzDC,GAAIF,EACJG,KAAM,eACNC,QAAS,QACTC,SAAU,CAAC,SACXC,SAAU,CAAC,cACXC,SAAU,CAAC,QACXC,cAAe,CACbC,eAAgB,CACdP,GAAI,SACJC,KAAM,gBACNO,QAAS,uBACTC,WAAY,CAAC,SAAU,YAEzBC,UAAW,CACT,CACEC,IAAK,+EACLC,eAAgB,SCpBXC,EAAoB,oBACpBC,EAAuB,uBAc7B,SAASC,EAAgBf,GAC9B,MAAO,CAAEgB,KAAMH,EAAmBI,QAASjB,EAC7C,CAEO,SAASkB,EAAmBlB,GACjC,MAAO,CAAEgB,KAAMF,EAAsBG,QAASjB,EAChD,CCZO,MAAMmB,EAGT,CACFC,eAAgBC,EAAAA,qBAAqBC,MACrC,MAAAC,CAAOC,GACL,MAAMC,UAAEA,EAAAC,SAAWA,EAAAC,QAAUA,WAASC,EAAAC,aAAUA,EAAAC,eAAcA,GAAmBN,EAEjF,MAAO,CACLO,cAAgBC,IACd,MAAMC,EA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IAAW,IAAIsL,EAAYzS,EAAiBkH,EAAUC,GACzE8L,QAASL,EACTF"}
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["EngineError","EngineErrorCode","AnnotationToken"],"sources":["../src/capability.ts","../src/reducer.ts","../src/types.ts","../src/stamp.plugin.ts"],"sourcesContent":["import {\n EngineError,\n EngineErrorCode,\n resolveBinarySource,\n sniffBinaryMetadata,\n type BinarySource,\n type DocumentHandle,\n type Engine,\n type PageImageHandle,\n type PieceInfoEntry,\n type PieceInfoPatch,\n} from '@embedpdf/engine-core/runtime';\nimport { type PluginContext } from '@embedpdf/core';\nimport { AnnotationToken } from '@embedpdf/plugin-annotation';\nimport { createFormScriptingController, type FormCommitResult } from '@embedpdf/plugin-form';\n\nimport type {\n AddAssetInput,\n ImportLibraryOptions,\n StampAction,\n StampAsset,\n StampAssetPreview,\n StampCapability,\n StampConfig,\n StampLibrary,\n StampAssetKind,\n StampState,\n} from './types';\n\nconst DEFAULT_PREVIEW_WIDTH = 256;\nconst LIBRARY_PIECEINFO_APP = 'EMBD_StampLibrary';\nconst STAMP_PIECEINFO_APP = 'EMBD_Stamp';\nconst STAMP_SCHEMA_VERSION = 1;\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 kindToPdfName = (kind: StampAssetKind): string =>\n kind === 'signature' ? 'Signature' : kind === 'initials' ? 'Initials' : 'Stamp';\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 metadataPatch = (\n id: string,\n name: string,\n kind: StampAssetKind,\n subject?: string,\n categories?: readonly string[],\n): PieceInfoPatch => ({\n Version: STAMP_SCHEMA_VERSION,\n Id: id,\n Name: name,\n Kind: { name: kindToPdfName(kind) },\n Subject: subject ?? null,\n Categories: categories ?? null,\n});\n\nconst libraryMetadataPatch = (\n id: string,\n name: string,\n categories?: readonly string[],\n): PieceInfoPatch => ({\n Version: STAMP_SCHEMA_VERSION,\n Id: id,\n Name: name,\n Kind: { name: 'StampLibrary' },\n Categories: categories ?? null,\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 (\n bytes: Uint8Array,\n identity?: DocumentHandle['security']['identity'],\n ): Promise<DocumentHandle> => {\n try {\n return await (\n await assetEngine()\n ).open(\n { kind: 'bytes', id: uid('stamp-import'), bytes },\n { scope: ['*'], ...(identity ? { identity } : {}) },\n );\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 createLooseLibrary = (name: string): string => {\n const id = uid('stamp-lib');\n ctx.dispatch({\n type: 'LIBRARY_ADDED',\n library: { id, name, storage: 'loose', assetIds: [] },\n });\n return id;\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 if (!doc.pieceInfo || !doc.pages.extract) {\n throw new EngineError(\n EngineErrorCode.NotImplemented,\n '[stamp] canonical PDF libraries need an asset engine with pieceInfo and pages.extract',\n );\n }\n const snapshot = await doc.pages.list();\n if (snapshot.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\n // Discover and validate every required service before the first write.\n const pages = snapshot.pages.map((layout) => {\n const handle = doc.page(layout.pageObjectNumber);\n if (!handle.pieceInfo) {\n throw new EngineError(\n EngineErrorCode.NotImplemented,\n '[stamp] canonical PDF libraries need page pieceInfo support',\n );\n }\n return {\n layout,\n handle,\n metadata: null as Awaited<ReturnType<typeof handle.pieceInfo.read>>,\n };\n });\n\n const catalogMetadata = await doc.pieceInfo.read(LIBRARY_PIECEINFO_APP);\n for (const page of pages) {\n page.metadata = await page.handle.pieceInfo!.read(STAMP_PIECEINFO_APP);\n }\n\n const state = ctx.getState();\n const takenLibraryIds = new Set(Object.keys(state.libraries));\n const takenAssetIds = new Set(Object.keys(state.assets));\n const catalogEntries = catalogMetadata?.entries ?? {};\n const libraryId = allocateId(entryString(catalogEntries, 'Id'), 'stamp-lib', takenLibraryIds);\n const libraryName = opts?.name ?? entryString(catalogEntries, 'Name') ?? 'Stamps';\n const libraryCategories = opts?.categories ?? entryStringArray(catalogEntries, 'Categories');\n\n const descriptors = pages.map(({ layout, handle, metadata: pageMetadata }) => {\n const entries = pageMetadata?.entries ?? {};\n const id = allocateId(entryString(entries, 'Id'), 'stamp', takenAssetIds);\n const kind = opts?.kind ?? kindFromPdfName(entryName(entries, 'Kind')) ?? 'stamp';\n return {\n handle,\n asset: {\n id,\n libraryId,\n kind,\n name:\n opts?.assetName?.(layout.index) ??\n entryString(entries, 'Name') ??\n `Stamp ${layout.index + 1}`,\n size: { width: layout.size.width, height: layout.size.height },\n format: 'pdf' as const,\n pageObjectNumber: layout.pageObjectNumber,\n subject: entryString(entries, 'Subject'),\n categories: entryStringArray(entries, 'Categories'),\n },\n };\n });\n\n await doc.pieceInfo.update(\n LIBRARY_PIECEINFO_APP,\n libraryMetadataPatch(libraryId, libraryName, libraryCategories),\n );\n\n const assets: NonNullable<typeof imported>['assets'] = [];\n for (const descriptor of descriptors) {\n const { asset, handle } = descriptor;\n await handle.pieceInfo!.update(\n STAMP_PIECEINFO_APP,\n metadataPatch(asset.id, asset.name, asset.kind, asset.subject, asset.categories),\n );\n // One canonical page → one derived placement PDF plus a transparent\n // preview. Extract after metadata so the cache carries the same id.\n const bytes = await doc.pages.extract([asset.pageObjectNumber!]);\n const image = 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 assets.push({ asset, bytes, preview: imageToPreview(image) });\n }\n\n imported = {\n library: {\n id: libraryId,\n name: libraryName,\n storage: 'canonical-pdf',\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 return imported.library.id;\n };\n\n const addAsset = async (input: AddAssetInput): Promise<string> => {\n const targetLibrary = input.libraryId\n ? (ctx.getState().libraries[input.libraryId] ?? null)\n : null;\n if (input.libraryId && !targetLibrary) {\n throw new EngineError(\n EngineErrorCode.NotFound,\n `[stamp] unknown library '${input.libraryId}'`,\n );\n }\n const resolved = await resolveBinarySource(input.source);\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\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 if (targetLibrary?.storage === 'canonical-pdf') {\n if (!isPdf) {\n throw new EngineError(\n EngineErrorCode.InvalidArg,\n '[stamp] raster assets cannot be appended to a canonical PDF library',\n );\n }\n return mutateLibrary(targetLibrary.id, async () => {\n const liveLibrary = ctx.getState().libraries[targetLibrary.id];\n if (liveLibrary?.storage !== 'canonical-pdf') {\n throw new EngineError(\n EngineErrorCode.NotFound,\n `[stamp] canonical library '${targetLibrary.id}' no longer exists`,\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 assetId = uid('stamp');\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 if (!doc.pages.insert || !doc.pages.extract) {\n throw new EngineError(\n EngineErrorCode.NotImplemented,\n '[stamp] appending to a canonical library needs pages.insert and pages.extract',\n );\n }\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 canonical library asset must be a single-page PDF',\n );\n }\n const pageObjectNumber = result.insertedPageObjectNumbers[0];\n const layout = result.layout.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 const asset: StampAsset = {\n id: assetId,\n libraryId: liveLibrary.id,\n kind: input.kind ?? 'stamp',\n name: input.name,\n size: { width: layout.size.width, height: layout.size.height },\n format: 'pdf',\n pageObjectNumber,\n subject: input.subject,\n categories: input.categories,\n };\n await page.pieceInfo.update(\n STAMP_PIECEINFO_APP,\n metadataPatch(asset.id, asset.name, asset.kind, asset.subject, asset.categories),\n );\n const bytes = await doc.pages.extract([pageObjectNumber]);\n let preview = suppliedPreview;\n if (!preview) {\n preview = imageToPreview(\n await page.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 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 return appended.asset.id;\n });\n }\n\n const size =\n input.size ?? ('width' in meta ? { width: meta.width, height: meta.height } : null);\n if (!size) {\n throw new EngineError(\n EngineErrorCode.InvalidArg,\n '[stamp] a PDF asset needs `size` (its page size in points) — PDF bytes carry no sniffable dimensions',\n );\n }\n let preview = suppliedPreview;\n if (!preview && !isPdf) {\n preview = { bytes: new Uint8Array(resolved.bytes), mimeType: meta.mimeType };\n }\n const commitLooseAsset = (libraryId: string): string => {\n const asset: StampAsset = {\n id: uid('stamp'),\n libraryId,\n kind: input.kind ?? 'stamp',\n name: input.name,\n size,\n format: isPdf ? 'pdf' : meta.mimeType === 'image/png' ? 'png' : 'jpeg',\n subject: input.subject,\n categories: input.categories,\n };\n binaries.set(asset.id, { bytes: new Uint8Array(resolved.bytes), preview });\n ctx.dispatch({ type: 'ASSET_ADDED', asset });\n return asset.id;\n };\n if (!targetLibrary) return commitLooseAsset(createLooseLibrary(input.name));\n return mutateLibrary(targetLibrary.id, async () => {\n const liveLibrary = ctx.getState().libraries[targetLibrary.id];\n if (liveLibrary?.storage !== 'loose') {\n throw new EngineError(\n EngineErrorCode.NotFound,\n `[stamp] loose library '${targetLibrary.id}' no longer exists`,\n );\n }\n return commitLooseAsset(liveLibrary.id);\n });\n };\n\n const dropLibrary = (id: string): void => {\n const library = ctx.getState().libraries[id];\n if (library) for (const assetId of library.assetIds) binaries.delete(assetId);\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?.storage === 'canonical-pdf') {\n if (library.assetIds.length === 1) {\n dropLibrary(library.id);\n return;\n }\n if (asset.pageObjectNumber === undefined) {\n throw new EngineError(\n EngineErrorCode.Unknown,\n `[stamp] canonical asset '${id}' has no page object number`,\n );\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 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 }\n binaries.delete(id);\n ctx.dispatch({ type: 'ASSET_REMOVED', assetId: id });\n });\n };\n\n const removeLibrary = (id: string): Promise<void> =>\n mutateLibrary(id, async () => dropLibrary(id));\n\n const surfaceScriptingResult = (result: FormCommitResult): void => {\n try {\n for (const effect of result.uiEffects) config.scripting?.onUiEffect?.(effect);\n for (const diagnostic of result.diagnostics) {\n config.scripting?.onDiagnostic?.(diagnostic);\n }\n if (result.error) config.scripting?.onError?.(result.error);\n } catch (error) {\n globalThis.console?.error('[stamp] scripting observer failed:', error);\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 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 (asset.format !== 'pdf' || !config.scripting?.enabled) return bin;\n\n const targetDoc = ctx.documentHandle(documentId);\n const targetMeta = ctx.core().documents[documentId] ?? null;\n if (!targetDoc || !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), targetDoc.security.identity);\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 const scriptingConfig = config.scripting;\n scripting = createFormScriptingController({\n doc,\n document: () => targetMeta,\n config: scriptingConfig,\n sandboxFactory:\n scriptingConfig.sandboxFactory ??\n (() =>\n import('@embedpdf/core-js-sandbox').then(({ createQuickJsSandbox }) =>\n createQuickJsSandbox(),\n )),\n });\n const result = await scripting.recalculate(snapshot);\n surfaceScriptingResult(result);\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 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 source: placement.bytes,\n preview: placement.preview\n ? { data: placement.preview.bytes, mimeType: placement.preview.mimeType }\n : undefined,\n intrinsicSize: asset.size,\n targetWidth: opts?.targetWidth,\n });\n };\n\n ctx.cleanup(() => {\n binaries.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: () => {\n const s = ctx.getState();\n return s.libraryOrder.map((id) => s.libraries[id]).filter((l) => l != null);\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 libraryBytes: (id) => libraryBinaries.get(id) ?? null,\n importLibraryPdf,\n addAsset,\n removeAsset,\n removeLibrary,\n armAsset,\n disarm: (documentId) => ctx.forDocument(AnnotationToken, documentId).disarmStamp(),\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_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_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 type { BinarySource, Engine } from '@embedpdf/engine-core/runtime';\nimport { createCapabilityToken } from '@embedpdf/core';\nimport type { FormScriptingOptions } from '@embedpdf/plugin-form';\n\n/**\n * The stamp plugin: a workspace-scoped ASSET substrate.\n *\n * The design law (\"documents have a home; assets ride the wire\"): imported\n * PDF libraries retain one canonical PDF whose catalog/page `/PieceInfo`\n * carries their metadata. Per-asset PDFs and previews are derived caches used\n * for placement. Standalone PNG/JPEG assets remain loose because the engine\n * intentionally has no raster-to-PDF-page authoring primitive.\n */\n\nexport type StampAssetKind = 'stamp' | 'signature' | 'initials';\n\n/**\n * One asset's SERIALIZABLE descriptor. The bytes and the cached preview are\n * deliberately NOT here — the reducer state stays pure/serializable (kernel\n * rule 1); binary lives in the capability and crosses only as call\n * arguments/returns, mirroring the engine's own BinarySource rule.\n */\nexport interface StampAsset {\n id: string;\n libraryId: string;\n kind: StampAssetKind;\n name: string;\n /** Intrinsic size in PDF points (the source page's crop box / image pixels 1:1). */\n size: { width: number; height: number };\n /** What the asset bytes are: a single-page vector PDF, or a raster image. */\n format: 'pdf' | 'png' | 'jpeg';\n /** Canonical library page identity; present for PDF-backed libraries. */\n pageObjectNumber?: number;\n subject?: string;\n categories?: string[];\n}\n\n/** A named group of assets — one imported PDF becomes one library. */\nexport interface StampLibrary {\n id: string;\n name: string;\n /** PDF-backed libraries own canonical bytes; loose libraries are raster/pre-sliced conveniences. */\n storage: 'canonical-pdf' | 'loose';\n categories?: string[];\n /** Asset ids in display order. */\n assetIds: string[];\n}\n\nexport interface StampState {\n libraries: Record<string, StampLibrary>;\n /** Library display order (insertion order). */\n libraryOrder: string[];\n assets: Record<string, StampAsset>;\n}\n\nexport type StampAction =\n | { type: 'LIBRARY_ADDED'; library: StampLibrary }\n | { type: 'LIBRARY_REMOVED'; libraryId: string }\n | { type: 'ASSET_ADDED'; asset: StampAsset }\n | { type: 'ASSET_REMOVED'; assetId: string };\n\nexport interface StampConfig {\n /**\n * The ASSET ENGINE port: any `Engine` that can open `{ kind: 'bytes' }` —\n * used only to slice an imported library PDF into per-page assets and\n * render their previews.\n *\n * Omitted → the kernel's own engine is used, which is exactly right for a\n * local deployment (same WASM instance, zero extra cost). In a CLOUD\n * deployment the kernel engine cannot open local bytes, so pass a factory —\n * it is called (and memoized) on the first import, never at viewer boot:\n *\n * ```ts\n * stampPlugin({\n * assetEngine: () => import('@embedpdf/engine').then((m) => m.createLocalEngine()),\n * })\n * ```\n */\n assetEngine?: Engine | (() => Engine | Promise<Engine>);\n /** Cached preview width in device px (import-time render). Default 256. */\n previewWidth?: number;\n /**\n * Opt-in Acrobat JavaScript evaluation for form-backed PDF stamp assets.\n * On arm, the plugin recalculates a temporary copy using the target\n * document's identity/name/clock, flattens it, and arms the resulting\n * static page. Canonical library and derived base bytes stay unchanged.\n */\n scripting?: FormScriptingOptions;\n}\n\nexport interface ImportLibraryOptions {\n /** Library display name. Default `'Stamps'`. */\n name?: string;\n /** Library categories written to catalog `/PieceInfo`. */\n categories?: string[];\n /** Kind stamped onto every imported asset. Default `'stamp'`. */\n kind?: StampAssetKind;\n /** Per-page asset names; default `Stamp <n>`. */\n assetName?: (pageIndex: number) => string;\n}\n\nexport interface AddAssetInput {\n /** Target library; omitted → a new single-asset library named after the asset. */\n libraryId?: string;\n name: string;\n kind?: StampAssetKind;\n subject?: string;\n categories?: string[];\n /** Single-page PDF (vector) or PNG/JPEG bytes. */\n source: BinarySource;\n /**\n * Paintable preview for pickers + the hover ghost. Loose PDF assets cannot\n * derive one without opening the PDF; canonical libraries render it after\n * insertion. Raster sources default to their own bytes.\n */\n preview?: BinarySource;\n /** Intrinsic size in PDF points. Required for PDF sources; rasters are sniffed. */\n size?: { width: number; height: number };\n}\n\n/** A cached, browser-paintable render of an asset (PNG from import; raster assets as-is). */\nexport interface StampAssetPreview {\n bytes: Uint8Array;\n mimeType: string;\n}\n\nexport interface StampCapability {\n // ── selectors (pure reads over serializable state) ──\n libraries(): StampLibrary[];\n library(id: string): StampLibrary | null;\n /** Assets of one library, in library order — or every asset when omitted. */\n assets(libraryId?: string): StampAsset[];\n asset(id: string): StampAsset | null;\n // ── binary reads (capability-held, never store state) ──\n /** The asset's paintable preview, or null while none is cached. */\n assetPreview(id: string): StampAssetPreview | null;\n /** Placement bytes; derived from the canonical page for PDF-backed libraries. */\n assetBytes(id: string): Uint8Array | null;\n /** Canonical library PDF bytes, or null for a loose library/unknown id. */\n libraryBytes(id: string): Uint8Array | null;\n // ── library intents ──\n /**\n * Import a PDF as a stamp library: every page becomes one vector asset\n * (single-page PDF bytes + a cached preview render). Uses the asset\n * engine; in a cloud deployment without one configured this rejects with\n * an actionable error. Resolves to the new library id.\n */\n importLibraryPdf(source: BinarySource, opts?: ImportLibraryOptions): Promise<string>;\n /**\n * Add a single asset. A PDF added to a canonical library is inserted as a\n * page and receives `/PieceInfo`; loose assets keep their bytes directly.\n * Raster input cannot be appended to a canonical PDF library.\n */\n addAsset(input: AddAssetInput): Promise<string>;\n /** Remove an asset, deleting its canonical page before state changes when PDF-backed. */\n removeAsset(id: string): Promise<void>;\n /** Remove a library and every asset in it, ordered with in-flight library mutations. */\n removeLibrary(id: string): Promise<void>;\n // ── placement (delegates to the annotation plugin of the named document) ──\n /**\n * Arm an asset on a document: the next click on that document's pages\n * places it (and the hover ghost previews the exact placement). With\n * scripting enabled, form-backed PDFs are evaluated against that target\n * document and flattened first. Rides `annotation.armStamp` — bytes,\n * preview, and intrinsic size all travel along, so vector stamps keep\n * their true aspect.\n */\n armAsset(documentId: string, assetId: string, opts?: { targetWidth?: number }): Promise<void>;\n /** Disarm the stamp tool on a document. */\n disarm(documentId: string): void;\n}\n\nexport const StampToken = createCapabilityToken<StampCapability>('stamp');\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"],"mappings":";;;;;;AA6BA,MAAM,wBAAwB;AAC9B,MAAM,wBAAwB;AAC9B,MAAM,sBAAsB;AAC5B,MAAM,uBAAuB;;;AAI7B,IAAI,MAAM;AACV,MAAM,OAAO,WACX,GAAG,OAAO,GAAG,KAAK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+1,187 @@
|
|
|
1
|
+
import { BinarySource, Engine } from "@embedpdf/engine-core/runtime";
|
|
2
|
+
import { FormScriptingOptions } from "@embedpdf/plugin-form";
|
|
3
|
+
//#region src/types.d.ts
|
|
4
|
+
/**
|
|
5
|
+
* The stamp plugin: a workspace-scoped ASSET substrate.
|
|
6
|
+
*
|
|
7
|
+
* The design law ("documents have a home; assets ride the wire"): imported
|
|
8
|
+
* PDF libraries retain one canonical PDF whose catalog/page `/PieceInfo`
|
|
9
|
+
* carries their metadata. Per-asset PDFs and previews are derived caches used
|
|
10
|
+
* for placement. Standalone PNG/JPEG assets remain loose because the engine
|
|
11
|
+
* intentionally has no raster-to-PDF-page authoring primitive.
|
|
12
|
+
*/
|
|
13
|
+
type StampAssetKind = 'stamp' | 'signature' | 'initials';
|
|
14
|
+
/**
|
|
15
|
+
* One asset's SERIALIZABLE descriptor. The bytes and the cached preview are
|
|
16
|
+
* deliberately NOT here — the reducer state stays pure/serializable (kernel
|
|
17
|
+
* rule 1); binary lives in the capability and crosses only as call
|
|
18
|
+
* arguments/returns, mirroring the engine's own BinarySource rule.
|
|
19
|
+
*/
|
|
20
|
+
interface StampAsset {
|
|
21
|
+
id: string;
|
|
22
|
+
libraryId: string;
|
|
23
|
+
kind: StampAssetKind;
|
|
24
|
+
name: string;
|
|
25
|
+
/** Intrinsic size in PDF points (the source page's crop box / image pixels 1:1). */
|
|
26
|
+
size: {
|
|
27
|
+
width: number;
|
|
28
|
+
height: number;
|
|
29
|
+
};
|
|
30
|
+
/** What the asset bytes are: a single-page vector PDF, or a raster image. */
|
|
31
|
+
format: 'pdf' | 'png' | 'jpeg';
|
|
32
|
+
/** Canonical library page identity; present for PDF-backed libraries. */
|
|
33
|
+
pageObjectNumber?: number;
|
|
34
|
+
subject?: string;
|
|
35
|
+
categories?: string[];
|
|
36
|
+
}
|
|
37
|
+
/** A named group of assets — one imported PDF becomes one library. */
|
|
38
|
+
interface StampLibrary {
|
|
39
|
+
id: string;
|
|
40
|
+
name: string;
|
|
41
|
+
/** PDF-backed libraries own canonical bytes; loose libraries are raster/pre-sliced conveniences. */
|
|
42
|
+
storage: 'canonical-pdf' | 'loose';
|
|
43
|
+
categories?: string[];
|
|
44
|
+
/** Asset ids in display order. */
|
|
45
|
+
assetIds: string[];
|
|
46
|
+
}
|
|
47
|
+
interface StampState {
|
|
48
|
+
libraries: Record<string, StampLibrary>;
|
|
49
|
+
/** Library display order (insertion order). */
|
|
50
|
+
libraryOrder: string[];
|
|
51
|
+
assets: Record<string, StampAsset>;
|
|
52
|
+
}
|
|
53
|
+
type StampAction = {
|
|
54
|
+
type: 'LIBRARY_ADDED';
|
|
55
|
+
library: StampLibrary;
|
|
56
|
+
} | {
|
|
57
|
+
type: 'LIBRARY_REMOVED';
|
|
58
|
+
libraryId: string;
|
|
59
|
+
} | {
|
|
60
|
+
type: 'ASSET_ADDED';
|
|
61
|
+
asset: StampAsset;
|
|
62
|
+
} | {
|
|
63
|
+
type: 'ASSET_REMOVED';
|
|
64
|
+
assetId: string;
|
|
65
|
+
};
|
|
66
|
+
interface StampConfig {
|
|
67
|
+
/**
|
|
68
|
+
* The ASSET ENGINE port: any `Engine` that can open `{ kind: 'bytes' }` —
|
|
69
|
+
* used only to slice an imported library PDF into per-page assets and
|
|
70
|
+
* render their previews.
|
|
71
|
+
*
|
|
72
|
+
* Omitted → the kernel's own engine is used, which is exactly right for a
|
|
73
|
+
* local deployment (same WASM instance, zero extra cost). In a CLOUD
|
|
74
|
+
* deployment the kernel engine cannot open local bytes, so pass a factory —
|
|
75
|
+
* it is called (and memoized) on the first import, never at viewer boot:
|
|
76
|
+
*
|
|
77
|
+
* ```ts
|
|
78
|
+
* stampPlugin({
|
|
79
|
+
* assetEngine: () => import('@embedpdf/engine').then((m) => m.createLocalEngine()),
|
|
80
|
+
* })
|
|
81
|
+
* ```
|
|
82
|
+
*/
|
|
83
|
+
assetEngine?: Engine | (() => Engine | Promise<Engine>);
|
|
84
|
+
/** Cached preview width in device px (import-time render). Default 256. */
|
|
85
|
+
previewWidth?: number;
|
|
86
|
+
/**
|
|
87
|
+
* Opt-in Acrobat JavaScript evaluation for form-backed PDF stamp assets.
|
|
88
|
+
* On arm, the plugin recalculates a temporary copy using the target
|
|
89
|
+
* document's identity/name/clock, flattens it, and arms the resulting
|
|
90
|
+
* static page. Canonical library and derived base bytes stay unchanged.
|
|
91
|
+
*/
|
|
92
|
+
scripting?: FormScriptingOptions;
|
|
93
|
+
}
|
|
94
|
+
interface ImportLibraryOptions {
|
|
95
|
+
/** Library display name. Default `'Stamps'`. */
|
|
96
|
+
name?: string;
|
|
97
|
+
/** Library categories written to catalog `/PieceInfo`. */
|
|
98
|
+
categories?: string[];
|
|
99
|
+
/** Kind stamped onto every imported asset. Default `'stamp'`. */
|
|
100
|
+
kind?: StampAssetKind;
|
|
101
|
+
/** Per-page asset names; default `Stamp <n>`. */
|
|
102
|
+
assetName?: (pageIndex: number) => string;
|
|
103
|
+
}
|
|
104
|
+
interface AddAssetInput {
|
|
105
|
+
/** Target library; omitted → a new single-asset library named after the asset. */
|
|
106
|
+
libraryId?: string;
|
|
107
|
+
name: string;
|
|
108
|
+
kind?: StampAssetKind;
|
|
109
|
+
subject?: string;
|
|
110
|
+
categories?: string[];
|
|
111
|
+
/** Single-page PDF (vector) or PNG/JPEG bytes. */
|
|
112
|
+
source: BinarySource;
|
|
113
|
+
/**
|
|
114
|
+
* Paintable preview for pickers + the hover ghost. Loose PDF assets cannot
|
|
115
|
+
* derive one without opening the PDF; canonical libraries render it after
|
|
116
|
+
* insertion. Raster sources default to their own bytes.
|
|
117
|
+
*/
|
|
118
|
+
preview?: BinarySource;
|
|
119
|
+
/** Intrinsic size in PDF points. Required for PDF sources; rasters are sniffed. */
|
|
120
|
+
size?: {
|
|
121
|
+
width: number;
|
|
122
|
+
height: number;
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
/** A cached, browser-paintable render of an asset (PNG from import; raster assets as-is). */
|
|
126
|
+
interface StampAssetPreview {
|
|
127
|
+
bytes: Uint8Array;
|
|
128
|
+
mimeType: string;
|
|
129
|
+
}
|
|
130
|
+
interface StampCapability {
|
|
131
|
+
libraries(): StampLibrary[];
|
|
132
|
+
library(id: string): StampLibrary | null;
|
|
133
|
+
/** Assets of one library, in library order — or every asset when omitted. */
|
|
134
|
+
assets(libraryId?: string): StampAsset[];
|
|
135
|
+
asset(id: string): StampAsset | null;
|
|
136
|
+
/** The asset's paintable preview, or null while none is cached. */
|
|
137
|
+
assetPreview(id: string): StampAssetPreview | null;
|
|
138
|
+
/** Placement bytes; derived from the canonical page for PDF-backed libraries. */
|
|
139
|
+
assetBytes(id: string): Uint8Array | null;
|
|
140
|
+
/** Canonical library PDF bytes, or null for a loose library/unknown id. */
|
|
141
|
+
libraryBytes(id: string): Uint8Array | null;
|
|
142
|
+
/**
|
|
143
|
+
* Import a PDF as a stamp library: every page becomes one vector asset
|
|
144
|
+
* (single-page PDF bytes + a cached preview render). Uses the asset
|
|
145
|
+
* engine; in a cloud deployment without one configured this rejects with
|
|
146
|
+
* an actionable error. Resolves to the new library id.
|
|
147
|
+
*/
|
|
148
|
+
importLibraryPdf(source: BinarySource, opts?: ImportLibraryOptions): Promise<string>;
|
|
149
|
+
/**
|
|
150
|
+
* Add a single asset. A PDF added to a canonical library is inserted as a
|
|
151
|
+
* page and receives `/PieceInfo`; loose assets keep their bytes directly.
|
|
152
|
+
* Raster input cannot be appended to a canonical PDF library.
|
|
153
|
+
*/
|
|
154
|
+
addAsset(input: AddAssetInput): Promise<string>;
|
|
155
|
+
/** Remove an asset, deleting its canonical page before state changes when PDF-backed. */
|
|
156
|
+
removeAsset(id: string): Promise<void>;
|
|
157
|
+
/** Remove a library and every asset in it, ordered with in-flight library mutations. */
|
|
158
|
+
removeLibrary(id: string): Promise<void>;
|
|
159
|
+
/**
|
|
160
|
+
* Arm an asset on a document: the next click on that document's pages
|
|
161
|
+
* places it (and the hover ghost previews the exact placement). With
|
|
162
|
+
* scripting enabled, form-backed PDFs are evaluated against that target
|
|
163
|
+
* document and flattened first. Rides `annotation.armStamp` — bytes,
|
|
164
|
+
* preview, and intrinsic size all travel along, so vector stamps keep
|
|
165
|
+
* their true aspect.
|
|
166
|
+
*/
|
|
167
|
+
armAsset(documentId: string, assetId: string, opts?: {
|
|
168
|
+
targetWidth?: number;
|
|
169
|
+
}): Promise<void>;
|
|
170
|
+
/** Disarm the stamp tool on a document. */
|
|
171
|
+
disarm(documentId: string): void;
|
|
172
|
+
}
|
|
173
|
+
declare const StampToken: import("@embedpdf/core").CapabilityToken<StampCapability>;
|
|
174
|
+
//#endregion
|
|
175
|
+
//#region src/stamp.plugin.d.ts
|
|
176
|
+
/**
|
|
177
|
+
* The stamp plugin. WORKSPACE-scoped: libraries are shared across every open
|
|
178
|
+
* document; placement names its document explicitly (`armAsset(documentId, …)`)
|
|
179
|
+
* and delegates to that document's annotation plugin — no hard `requires`,
|
|
180
|
+
* because the annotation token is document-scoped and resolved lazily per
|
|
181
|
+
* placement (a viewer without the annotation plugin fails at the arm call,
|
|
182
|
+
* with the kernel's own missing-capability error).
|
|
183
|
+
*/
|
|
184
|
+
declare const stampPlugin: (config?: StampConfig) => import("@embedpdf/core").PluginDef<StampState, StampAction, StampCapability>;
|
|
185
|
+
//#endregion
|
|
186
|
+
export { type AddAssetInput, type ImportLibraryOptions, type StampAsset, type StampAssetKind, type StampAssetPreview, type StampCapability, type StampConfig, type StampLibrary, type StampState, StampToken, stampPlugin };
|
|
187
|
+
//# sourceMappingURL=index.d.cts.map
|