@embedpdf/plugin-stamp 3.0.0-next.2 → 3.0.0-next.21

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/index.js CHANGED
@@ -1,16 +1,746 @@
1
- import { createCapabilityToken, definePlugin } from "@embedpdf/core";
2
- import { EngineError, EngineErrorCode, resolveBinarySource, sniffBinaryMetadata } from "@embedpdf/engine-core/runtime";
3
- import { AnnotationToken } from "@embedpdf/plugin-annotation";
4
- import { createFormScriptingController } from "@embedpdf/plugin-form";
5
- //#region src/capability.ts
6
- const DEFAULT_PREVIEW_WIDTH = 256;
7
- const LIBRARY_PIECEINFO_APP = "EMBD_StampLibrary";
8
- const STAMP_PIECEINFO_APP = "EMBD_Stamp";
9
- const STAMP_SCHEMA_VERSION = 1;
10
- /** Session-unique ids. Assets are session-scoped for now (no persistence),
11
- * so a timestamp + counter is enough — durable ids come with the store port. */
12
- let seq = 0;
13
- const uid = (prefix) => `${prefix}-${Date.now().toString(36)}-${(seq++).toString(36)}`;
1
+ import { a as assetIdFor, c as parseStampKey, d as stampPieceInfo, f as StampToken, i as STAMP_PIECEINFO_APP, l as stampKey, n as DEFAULT_LIBRARY_KIND, o as customStampName, r as STAMP_LIBRARY_PIECEINFO_APP, s as libraryKindFromPdfName, t as STAMP_DEFAULTS, u as stampLibraryPieceInfo } from "./contract-DHcn38S9.js";
2
+ import { DocumentsToken, PluginError, composeApi, definePlugin, defineState, toPluginError, toPluginErrorInfo } from "@embedpdf/core";
3
+ import { ActionsToken } from "@embedpdf/plugin-actions/contract";
4
+ import { AnnotationToken } from "@embedpdf/plugin-annotation/contract";
5
+ import { formEffectOps, isLocalEngine, resolveBinarySource, sniffBinaryMetadata } from "@embedpdf/engine-core/runtime";
6
+ import { javaScriptProgramFromActionTree } from "@embedpdf/core-acrojs";
7
+ import { ActionsToken as ActionsToken$1 } from "@embedpdf/plugin-actions/contract/host";
8
+ import { AnnotationToken as AnnotationToken$1 } from "@embedpdf/plugin-annotation/contract/host";
9
+ import { createFormScriptingController } from "@embedpdf/plugin-form/scripting";
10
+ //#region src/services/errors.ts
11
+ /** A `PluginError` raised by the stamp plugin. */
12
+ const stampError = (code, message) => new PluginError(code, "stamp", message);
13
+ const notFound = (what, id) => stampError("not-found", `unknown ${what} '${id}'`);
14
+ /**
15
+ * A refusal that names the missing permission. The stamp plugin acts on a
16
+ * document it isn't bound to, so it asks that document's checks instead of
17
+ * `ctx.assertAllowed`, and refuses with the same error.
18
+ */
19
+ const permissionDenied = (permission, operation) => new PluginError("permission-denied", "stamp", `${operation} requires ${permission}`, { permission });
20
+ /** Stop before the next step, or before anything is kept, once the caller cancelled. */
21
+ const throwIfCancelled = (signal) => {
22
+ if (signal?.aborted) throw new PluginError("operation-cancelled", "stamp", "operation cancelled", { cause: signal.reason });
23
+ };
24
+ /**
25
+ * A capability verb: whatever the asset engine, a sibling plugin or a binary
26
+ * source rejects with reaches the caller as a `PluginError`.
27
+ */
28
+ const verb = (run) => async (...args) => {
29
+ try {
30
+ return await run(...args);
31
+ } catch (error) {
32
+ throw toPluginError("stamp", error);
33
+ }
34
+ };
35
+ //#endregion
36
+ //#region src/read/catalog.ts
37
+ /** Reads over the state and the binaries resource: libraries, assets,
38
+ * previews, the library's PDF, and the checks. */
39
+ function createCatalog(ctx, { binaries, assetEngine, ghosts, targets }) {
40
+ const { binaries: assetBinaries, libraryBinaries } = binaries;
41
+ const { ghostProvider } = ghosts;
42
+ const { documentIdOf } = targets;
43
+ const listAssets = (filter) => {
44
+ const state = ctx.state.get();
45
+ return (filter?.libraryId ? [filter.libraryId] : state.libraryOrder).flatMap((libraryId) => (state.libraries[libraryId]?.assetIds ?? []).map((id) => state.assets[id])).filter((asset) => asset != null && (!filter?.kind || asset.kind === filter.kind) && (!filter?.category || (asset.categories ?? []).includes(filter.category)));
46
+ };
47
+ /** Placing is annotation work: the document's annotation plugin answers. */
48
+ const canPlace = (documentId) => {
49
+ const id = documentIdOf(documentId);
50
+ if (!id) return false;
51
+ return ctx.tryForDocument(AnnotationToken, id)?.canCreate() ?? false;
52
+ };
53
+ /** A stamp made from annotations copies them out of the document, as a download does. */
54
+ const canCreateFromAnnotations = (documentId) => {
55
+ const id = documentIdOf(documentId);
56
+ return id !== null && ctx.get(DocumentsToken).canDownload(id);
57
+ };
58
+ return {
59
+ canPlace,
60
+ canCreateFromAnnotations,
61
+ api: {
62
+ listLibraries: (filter) => {
63
+ const state = ctx.state.get();
64
+ const kinds = filter?.kind === void 0 ? null : new Set(typeof filter.kind === "string" ? [filter.kind] : filter.kind);
65
+ return state.libraryOrder.map((id) => state.libraries[id]).filter((library) => library != null && (kinds === null || kinds.has(library.kind)));
66
+ },
67
+ getLibrary: (libraryId) => ctx.state.get().libraries[libraryId] ?? null,
68
+ listAssets,
69
+ getAsset: (assetId) => ctx.state.get().assets[assetId] ?? null,
70
+ getAssetPreview: (assetId) => assetBinaries.get(assetId)?.preview ?? null,
71
+ renderAssetPreview: verb(async (assetId, { width, signal }) => {
72
+ throwIfCancelled(signal);
73
+ const binary = assetBinaries.get(assetId);
74
+ if (!binary) throw notFound("asset", assetId);
75
+ const preview = await ctx.cancellable(signal, ghostProvider(binary.bytes, binary.preview, assetId)(width));
76
+ return preview ? {
77
+ bytes: preview.bytes,
78
+ mimeType: preview.mimeType ?? "image/png"
79
+ } : null;
80
+ }),
81
+ readAssetBytes: (assetId) => {
82
+ const bytes = assetBinaries.get(assetId)?.bytes;
83
+ return bytes ? new Uint8Array(bytes) : null;
84
+ },
85
+ exportLibrary: async (libraryId, options) => {
86
+ throwIfCancelled(options?.signal);
87
+ const bytes = libraryBinaries.get(libraryId);
88
+ if (!bytes) throw notFound("library", libraryId);
89
+ return new Uint8Array(bytes);
90
+ },
91
+ canPlace,
92
+ canCreateFromAnnotations,
93
+ canImport: assetEngine.canImport
94
+ }
95
+ };
96
+ }
97
+ //#endregion
98
+ //#region src/services/asset-engine.ts
99
+ /**
100
+ * The asset engine port and the canonical-library services every write
101
+ * needs: opening library bytes as a document on a local engine, import-time
102
+ * previews, and the import-support fact learned from the first import.
103
+ */
104
+ /** Session-unique ids (scratch documents, library ids a file does not carry):
105
+ * a timestamp plus a counter. */
106
+ let idCounter = 0;
107
+ const uid = (prefix) => `${prefix}-${Date.now().toString(36)}-${(idCounter++).toString(36)}`;
108
+ function createAssetEngine(ctx) {
109
+ const settings = ctx.settings();
110
+ /** Set once an import finds the asset engine is not local (cloud). */
111
+ let importSupported = null;
112
+ let resolved = null;
113
+ /** Engines this plugin made through a configured function: destroyed with it. */
114
+ const owned = [];
115
+ const assetEngine = () => {
116
+ const configured = settings.get().assetEngine;
117
+ if (resolved?.from !== configured) {
118
+ const engine = !configured ? ctx.engine : typeof configured === "function" ? configured() : configured;
119
+ if (typeof configured === "function") owned.push(engine);
120
+ resolved = {
121
+ from: configured,
122
+ engine
123
+ };
124
+ importSupported = null;
125
+ }
126
+ return resolved.engine;
127
+ };
128
+ /** Each asset engine's fonts, by key: each read and registered once (a failed read is tried again). */
129
+ const registered = /* @__PURE__ */ new WeakMap();
130
+ /**
131
+ * Register the font a typed mark names on the asset engine, when it's one of the `fonts`
132
+ * setting's: a standard font, or one the engine has, needs nothing.
133
+ */
134
+ const registerFont = async (key) => {
135
+ const font = settings.get().fonts.find((each) => each.key === key);
136
+ if (!font) return;
137
+ const engine = await assetEngine();
138
+ if (!isLocalEngine(engine)) return;
139
+ let byKey = registered.get(engine);
140
+ if (!byKey) registered.set(engine, byKey = /* @__PURE__ */ new Map());
141
+ let registering = byKey.get(key);
142
+ if (!registering) {
143
+ const fonts = byKey;
144
+ registering = font.load().then((data) => engine.fonts.register({
145
+ key,
146
+ data
147
+ })).then(() => void 0);
148
+ fonts.set(key, registering);
149
+ registering.catch(() => fonts.delete(key));
150
+ }
151
+ return registering;
152
+ };
153
+ /** Library PDFs are sliced and tagged (`/PieceInfo`) on a local engine only. */
154
+ const openAssetDocument = async (bytes) => {
155
+ const engine = await assetEngine();
156
+ if (!isLocalEngine(engine)) {
157
+ if (importSupported !== false) {
158
+ importSupported = false;
159
+ ctx.notify();
160
+ }
161
+ throw stampError("unsupported", settings.get().assetEngine ? "the stamp plugin's assetEngine must be a local engine (createLocalEngine())" : "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.");
162
+ }
163
+ return engine.open({
164
+ kind: "bytes",
165
+ id: uid("stamp-import"),
166
+ bytes
167
+ }, { scope: ["*"] });
168
+ };
169
+ /** Import-time preview render to bytes. The asset engine is local by
170
+ * definition, so the image source is always inline bytes. */
171
+ const imageToPreview = (image) => {
172
+ if (image.source.kind !== "bytes") throw stampError("unsupported", "the asset engine returned a URL-sourced render; asset engines must be local");
173
+ return {
174
+ bytes: image.source.bytes,
175
+ mimeType: image.contentType
176
+ };
177
+ };
178
+ /** Thumbnail render of one library page (the small picker image). */
179
+ const renderThumbnail = async (handle) => imageToPreview(await handle.render.image({
180
+ viewport: {
181
+ kind: "width",
182
+ width: settings.get().previewWidth
183
+ },
184
+ background: "transparent",
185
+ includeAnnotations: true,
186
+ format: "png"
187
+ }));
188
+ ctx.cleanup(() => {
189
+ resolved = null;
190
+ for (const engine of owned.splice(0)) Promise.resolve(engine).then((made) => made.destroy()).catch(() => {});
191
+ });
192
+ return {
193
+ openAssetDocument,
194
+ registerFont,
195
+ imageToPreview,
196
+ renderThumbnail,
197
+ /** Optimistic until an import finds the asset engine is not local (cloud). */
198
+ canImport: () => {
199
+ if (resolved && resolved.from !== settings.get().assetEngine) return true;
200
+ return importSupported !== false;
201
+ }
202
+ };
203
+ }
204
+ //#endregion
205
+ //#region src/services/binaries.ts
206
+ function createBinaries(ctx) {
207
+ /** Asset bytes (a one-page placement PDF) and the cached preview, by asset id. */
208
+ const binaries = /* @__PURE__ */ new Map();
209
+ /** The durable source of truth for a canonical library. Asset PDFs above
210
+ * are derived page extractions; this map owns the rewritten whole PDF. */
211
+ const libraryBinaries = /* @__PURE__ */ new Map();
212
+ /** Whole-PDF rewrites are serialized per library, or two concurrent
213
+ * appends could both start from the same bytes and lose one page. A
214
+ * mutation whose signal fired while it waited never starts. */
215
+ const mutateLibrary = (libraryId, mutation, signal) => ctx.serialQueue(`library:${libraryId}`)(mutation, { signal });
216
+ /**
217
+ * Ghost renders, one per size bucket per asset, rendered lazily on the
218
+ * asset engine the first time the ghost is shown at that size and kept
219
+ * until the asset goes away. Materialized (dynamic) placements are
220
+ * user/time specific and cache only for their own arm (`cacheKey` null).
221
+ */
222
+ const ghostRenders = /* @__PURE__ */ new Map();
223
+ ctx.cleanup(() => {
224
+ binaries.clear();
225
+ ghostRenders.clear();
226
+ libraryBinaries.clear();
227
+ });
228
+ return {
229
+ binaries,
230
+ libraryBinaries,
231
+ ghostRenders,
232
+ mutateLibrary
233
+ };
234
+ }
235
+ //#endregion
236
+ //#region src/services/documents.ts
237
+ /**
238
+ * The document a placing verb acts on: the one its options name, else the
239
+ * active one (a document's scope fills `documentId` in through the plugin's
240
+ * `inScope`), and the page arguments resolved in it.
241
+ */
242
+ function createTargets(ctx) {
243
+ const documents = () => ctx.get(DocumentsToken);
244
+ /** The document's id, or null with no document open. */
245
+ const documentIdOf = (documentId) => documentId ?? documents().getActiveId();
246
+ /** The document a verb acts on. Rejects `not-ready` with no document open. */
247
+ const targetOf = (options) => {
248
+ const documentId = documentIdOf(options?.documentId);
249
+ if (!documentId) throw stampError("not-ready", "no document is open");
250
+ return documentId;
251
+ };
252
+ /** A page argument of the document, as a ref or an index. Rejects `not-found`. */
253
+ const pageOf = (documentId, page) => {
254
+ const found = documents().getPage(page, documentId);
255
+ if (!found) throw stampError("not-found", `no page ${typeof page === "number" ? page : page.objectNumber} in document '${documentId}'`);
256
+ return found;
257
+ };
258
+ return {
259
+ documentIdOf,
260
+ targetOf,
261
+ pageOf
262
+ };
263
+ }
264
+ //#endregion
265
+ //#region src/services/events.ts
266
+ function createEvents(ctx) {
267
+ return {
268
+ libraryChanged: ctx.events.source(),
269
+ libraryCreated: ctx.events.source(),
270
+ libraryUpdated: ctx.events.source(),
271
+ libraryDeleted: ctx.events.source(),
272
+ assetCreated: ctx.events.source(),
273
+ assetUpdated: ctx.events.source(),
274
+ assetDeleted: ctx.events.source(),
275
+ armChanged: ctx.events.source()
276
+ };
277
+ }
278
+ //#endregion
279
+ //#region src/services/ghosts.ts
280
+ function createGhosts({ openAssetDocument, imageToPreview }, { ghostRenders }) {
281
+ const renderGhost = async (bytes, devicePixelWidth) => {
282
+ const doc = await openAssetDocument(new Uint8Array(bytes));
283
+ try {
284
+ const page = (await doc.pages.list()).pages[0];
285
+ if (!page) return null;
286
+ return imageToPreview(await doc.page(page.ref).render.image({
287
+ viewport: {
288
+ kind: "width",
289
+ width: devicePixelWidth
290
+ },
291
+ background: "transparent",
292
+ includeAnnotations: true,
293
+ format: "png"
294
+ }));
295
+ } finally {
296
+ await doc.close();
297
+ }
298
+ };
299
+ /** A resolution-aware ghost source for placement bytes: the page renders
300
+ * at the requested width, cached per bucket under `cacheKey` when given. */
301
+ const ghostProvider = (bytes, fallback, cacheKey) => {
302
+ const local = cacheKey ? ghostRenders.get(cacheKey) ?? /* @__PURE__ */ new Map() : /* @__PURE__ */ new Map();
303
+ if (cacheKey) ghostRenders.set(cacheKey, local);
304
+ return (devicePixelWidth) => {
305
+ let pending = local.get(devicePixelWidth);
306
+ if (!pending) {
307
+ pending = renderGhost(bytes, devicePixelWidth).catch((error) => {
308
+ globalThis.console?.warn("[stamp] ghost render failed, using the thumbnail:", error);
309
+ return fallback;
310
+ });
311
+ local.set(devicePixelWidth, pending);
312
+ }
313
+ return pending;
314
+ };
315
+ };
316
+ return { ghostProvider };
317
+ }
318
+ //#endregion
319
+ //#region src/services/index.ts
320
+ /**
321
+ * Plugin-private services every area is built on (not the kernel): the
322
+ * events, the binaries resource, the asset engine port, the ghost renderer
323
+ * and the document a placing verb acts on.
324
+ */
325
+ function createServices(ctx) {
326
+ const binaries = createBinaries(ctx);
327
+ const assetEngine = createAssetEngine(ctx);
328
+ return {
329
+ events: createEvents(ctx),
330
+ binaries,
331
+ assetEngine,
332
+ ghosts: createGhosts(assetEngine, binaries),
333
+ targets: createTargets(ctx)
334
+ };
335
+ }
336
+ //#endregion
337
+ //#region src/model.ts
338
+ const initialStampModel = () => ({
339
+ libraries: {},
340
+ libraryOrder: [],
341
+ assets: {},
342
+ armed: {}
343
+ });
344
+ /** Remember the asset armed on a document. */
345
+ function armAsset(state, documentId, assetId) {
346
+ if (state.armed[documentId] === assetId) return state;
347
+ return {
348
+ ...state,
349
+ armed: {
350
+ ...state.armed,
351
+ [documentId]: assetId
352
+ }
353
+ };
354
+ }
355
+ /** Forget what was armed on these documents. */
356
+ function disarmDocuments(state, documentIds) {
357
+ if (!documentIds.some((documentId) => documentId in state.armed)) return state;
358
+ const armed = { ...state.armed };
359
+ for (const documentId of documentIds) delete armed[documentId];
360
+ return {
361
+ ...state,
362
+ armed
363
+ };
364
+ }
365
+ /** Append a library to the display order. */
366
+ function addLibrary(state, library) {
367
+ return {
368
+ ...state,
369
+ libraries: {
370
+ ...state.libraries,
371
+ [library.id]: library
372
+ },
373
+ libraryOrder: [...state.libraryOrder, library.id]
374
+ };
375
+ }
376
+ /** Replace a known library's descriptor; an unknown id changes nothing. */
377
+ function setLibrary(state, library) {
378
+ if (!state.libraries[library.id]) return state;
379
+ return {
380
+ ...state,
381
+ libraries: {
382
+ ...state.libraries,
383
+ [library.id]: library
384
+ }
385
+ };
386
+ }
387
+ /** Remove a library together with its assets. */
388
+ function removeLibrary(state, libraryId) {
389
+ const library = state.libraries[libraryId];
390
+ if (!library) return state;
391
+ const { [libraryId]: _removed, ...libraries } = state.libraries;
392
+ const assets = { ...state.assets };
393
+ for (const id of library.assetIds) delete assets[id];
394
+ return {
395
+ ...state,
396
+ libraries,
397
+ libraryOrder: state.libraryOrder.filter((id) => id !== libraryId),
398
+ assets
399
+ };
400
+ }
401
+ /** Add an asset to the end of its library; an asset of an unknown library changes nothing. */
402
+ function addAsset(state, asset) {
403
+ const library = state.libraries[asset.libraryId];
404
+ if (!library) return state;
405
+ return {
406
+ ...state,
407
+ assets: {
408
+ ...state.assets,
409
+ [asset.id]: asset
410
+ },
411
+ libraries: {
412
+ ...state.libraries,
413
+ [library.id]: {
414
+ ...library,
415
+ assetIds: [...library.assetIds, asset.id]
416
+ }
417
+ }
418
+ };
419
+ }
420
+ /** Replace a known asset's descriptor; an unknown id changes nothing. */
421
+ function setAsset(state, asset) {
422
+ if (!state.assets[asset.id]) return state;
423
+ return {
424
+ ...state,
425
+ assets: {
426
+ ...state.assets,
427
+ [asset.id]: asset
428
+ }
429
+ };
430
+ }
431
+ /** Remove an asset and its entry in its library's order. */
432
+ function removeAsset(state, assetId) {
433
+ const asset = state.assets[assetId];
434
+ if (!asset) return state;
435
+ const { [assetId]: _removed, ...assets } = state.assets;
436
+ const library = state.libraries[asset.libraryId];
437
+ return {
438
+ ...state,
439
+ assets,
440
+ libraries: library ? {
441
+ ...state.libraries,
442
+ [library.id]: {
443
+ ...library,
444
+ assetIds: library.assetIds.filter((id) => id !== assetId)
445
+ }
446
+ } : state.libraries
447
+ };
448
+ }
449
+ //#endregion
450
+ //#region src/write/assets.ts
451
+ function createAssetWrites(ctx, { events, binaries, assetEngine, targets }, { resolveAssetSource }, { createLibrary }, { canCreateFromAnnotations }) {
452
+ const { libraryChanged, assetCreated, assetUpdated, assetDeleted } = events;
453
+ const { binaries: assetBinaries, libraryBinaries, ghostRenders, mutateLibrary } = binaries;
454
+ const { openAssetDocument, renderThumbnail } = assetEngine;
455
+ const { targetOf, pageOf } = targets;
456
+ const createAsset = async (input, options) => {
457
+ const signal = options?.signal;
458
+ throwIfCancelled(signal);
459
+ if (input.libraryId && !ctx.state.get().libraries[input.libraryId]) throw notFound("library", input.libraryId);
460
+ const resolved = await ctx.cancellable(signal, resolveAssetSource(input));
461
+ const meta = sniffBinaryMetadata(resolved.bytes);
462
+ if (!meta) throw stampError("invalid-input", "asset source must be PNG, JPEG, or single-page PDF bytes");
463
+ const isPdf = meta.mimeType === "application/pdf";
464
+ const name = input.name ?? customStampName();
465
+ const label = input.label ?? name;
466
+ if (name.length === 0 || name.includes("=")) throw stampError("invalid-input", `invalid stamp identifier '${name}': must be non-empty and contain no '='`);
467
+ const rasterSize = input.size ?? ("width" in meta ? {
468
+ width: meta.width,
469
+ height: meta.height
470
+ } : null);
471
+ if (!isPdf && (!rasterSize || rasterSize.width <= 0 || rasterSize.height <= 0)) throw stampError("invalid-input", "a raster asset needs a positive `size` (its page size in points)");
472
+ let suppliedPreview = null;
473
+ if (input.preview) {
474
+ const preview = await resolveBinarySource(input.preview);
475
+ suppliedPreview = {
476
+ bytes: new Uint8Array(preview.bytes),
477
+ mimeType: preview.mimeType ?? "image/png"
478
+ };
479
+ }
480
+ const libraryId = input.libraryId ?? (await createLibrary(label, { signal })).library.id;
481
+ return mutateLibrary(libraryId, async () => {
482
+ const liveLibrary = ctx.state.get().libraries[libraryId];
483
+ if (!liveLibrary) throw stampError("not-found", `library '${libraryId}' no longer exists`);
484
+ const assetId = assetIdFor(liveLibrary.id, name);
485
+ if (ctx.state.get().assets[assetId]) throw stampError("invalid-input", `library '${liveLibrary.name}' already has a stamp named '${name}'`);
486
+ const canonicalBytes = libraryBinaries.get(liveLibrary.id);
487
+ if (!canonicalBytes) throw stampError("operation-failed", `canonical bytes are missing for library '${liveLibrary.id}'`);
488
+ const doc = await ctx.cancellable(signal, openAssetDocument(canonicalBytes));
489
+ let appended;
490
+ try {
491
+ let page;
492
+ if (isPdf) {
493
+ const result = await doc.pages.insert(new Uint8Array(resolved.bytes));
494
+ if (result.insertedPages.length !== 1) throw stampError("invalid-input", "a library asset must be a single-page PDF");
495
+ page = result.insertedPages[0];
496
+ } else {
497
+ if (!doc.pages.flatten) throw stampError("unsupported", "raster assets need an asset engine with pages.flatten");
498
+ page = (await doc.pages.insertBlank({ size: rasterSize })).insertedPages[0];
499
+ await doc.page(page).annotations.create({
500
+ subtype: "stamp",
501
+ box: {
502
+ x: 0,
503
+ y: 0,
504
+ width: rasterSize.width,
505
+ height: rasterSize.height
506
+ },
507
+ fit: "fill"
508
+ }, { resources: { appearance: new Uint8Array(resolved.bytes) } });
509
+ if ((await doc.pages.flatten([page], { usage: "display" })).results.some(({ status }) => status !== "applied")) throw stampError("operation-failed", "flattening the raster into its page failed");
510
+ }
511
+ const layout = (await doc.pages.list()).pages.find((candidate) => candidate.ref.objectNumber === page.objectNumber);
512
+ const handle = doc.page(page);
513
+ if (!layout) throw stampError("operation-failed", "the new page is missing from the library layout");
514
+ await doc.pages.setName({
515
+ name: stampKey(name, label),
516
+ page
517
+ });
518
+ const asset = {
519
+ id: assetId,
520
+ libraryId: liveLibrary.id,
521
+ kind: input.kind ?? "stamp",
522
+ name,
523
+ label,
524
+ size: {
525
+ width: layout.size.width,
526
+ height: layout.size.height
527
+ },
528
+ page,
529
+ ...input.subject !== void 0 ? { subject: input.subject } : {},
530
+ ...input.categories !== void 0 ? { categories: input.categories } : {}
531
+ };
532
+ await handle.pieceInfo.update(STAMP_PIECEINFO_APP, stampPieceInfo(asset.kind, {
533
+ subject: asset.subject,
534
+ categories: asset.categories
535
+ }));
536
+ appended = {
537
+ asset,
538
+ bytes: await doc.pages.extract([page]),
539
+ preview: suppliedPreview ?? await renderThumbnail(handle),
540
+ canonical: await doc.download()
541
+ };
542
+ } finally {
543
+ await doc.close();
544
+ }
545
+ throwIfCancelled(signal);
546
+ libraryBinaries.set(liveLibrary.id, appended.canonical);
547
+ assetBinaries.set(appended.asset.id, {
548
+ bytes: appended.bytes,
549
+ preview: appended.preview
550
+ });
551
+ ctx.state.update(addAsset, appended.asset);
552
+ libraryChanged.emit({
553
+ libraryId: liveLibrary.id,
554
+ reason: "asset-added"
555
+ });
556
+ assetCreated.emit({
557
+ assetId: appended.asset.id,
558
+ libraryId: liveLibrary.id,
559
+ asset: appended.asset
560
+ });
561
+ return { asset: appended.asset };
562
+ }, signal);
563
+ };
564
+ const createAssetFromAnnotations = async (page, refs, input, options) => {
565
+ const signal = options?.signal;
566
+ throwIfCancelled(signal);
567
+ const documentId = targetOf(options);
568
+ if (!canCreateFromAnnotations(documentId)) throw permissionDenied("doc.download", "stamp.createAssetFromAnnotations");
569
+ const doc = ctx.documentHandle(documentId);
570
+ if (!doc) throw stampError("not-found", `document '${documentId}' is not open`);
571
+ const handle = doc.page(pageOf(documentId, page).ref);
572
+ const source = await ctx.cancellable(signal, handle.annotations.exportAppearance([...refs]));
573
+ return createAsset({
574
+ ...input,
575
+ source
576
+ }, { signal });
577
+ };
578
+ const deleteAsset = async (id, options) => {
579
+ const signal = options?.signal;
580
+ throwIfCancelled(signal);
581
+ const initialAsset = ctx.state.get().assets[id];
582
+ if (!initialAsset) return;
583
+ return mutateLibrary(initialAsset.libraryId, async () => {
584
+ const asset = ctx.state.get().assets[id];
585
+ if (!asset) return;
586
+ const library = ctx.state.get().libraries[asset.libraryId];
587
+ if (!library) return;
588
+ const canonicalBytes = libraryBinaries.get(library.id);
589
+ if (!canonicalBytes) throw stampError("operation-failed", `canonical bytes are missing for library '${library.id}'`);
590
+ const doc = await ctx.cancellable(signal, openAssetDocument(canonicalBytes));
591
+ let rewritten;
592
+ try {
593
+ await doc.pages.delete([asset.page]);
594
+ rewritten = await doc.download();
595
+ } finally {
596
+ await doc.close();
597
+ }
598
+ throwIfCancelled(signal);
599
+ libraryBinaries.set(library.id, rewritten);
600
+ assetBinaries.delete(id);
601
+ ghostRenders.delete(id);
602
+ ctx.state.update(removeAsset, id);
603
+ libraryChanged.emit({
604
+ libraryId: library.id,
605
+ reason: "asset-removed"
606
+ });
607
+ assetDeleted.emit({
608
+ assetId: id,
609
+ libraryId: library.id,
610
+ asset: null
611
+ });
612
+ }, signal);
613
+ };
614
+ const updateAsset = async (id, patch, options) => {
615
+ const signal = options?.signal;
616
+ throwIfCancelled(signal);
617
+ const initial = ctx.state.get().assets[id];
618
+ if (!initial) throw notFound("asset", id);
619
+ return mutateLibrary(initial.libraryId, async () => {
620
+ const asset = ctx.state.get().assets[id];
621
+ const library = asset ? ctx.state.get().libraries[asset.libraryId] : void 0;
622
+ if (!asset || !library) throw notFound("asset", id);
623
+ const next = {
624
+ ...asset,
625
+ ...patch.label !== void 0 ? { label: patch.label } : {},
626
+ ...patch.categories !== void 0 ? { categories: patch.categories } : {}
627
+ };
628
+ if (patch.subject === null) delete next.subject;
629
+ else if (patch.subject !== void 0) next.subject = patch.subject;
630
+ const canonicalBytes = libraryBinaries.get(library.id);
631
+ if (!canonicalBytes) throw stampError("operation-failed", `canonical bytes are missing for library '${library.id}'`);
632
+ const doc = await ctx.cancellable(signal, openAssetDocument(canonicalBytes));
633
+ let rewritten;
634
+ try {
635
+ if (next.label !== asset.label) await doc.pages.setName({
636
+ name: stampKey(asset.name, next.label),
637
+ page: asset.page,
638
+ replace: stampKey(asset.name, asset.label)
639
+ });
640
+ await doc.page(asset.page).pieceInfo.update(STAMP_PIECEINFO_APP, stampPieceInfo(next.kind, {
641
+ subject: next.subject,
642
+ categories: next.categories
643
+ }));
644
+ rewritten = await doc.download();
645
+ } finally {
646
+ await doc.close();
647
+ }
648
+ throwIfCancelled(signal);
649
+ libraryBinaries.set(library.id, rewritten);
650
+ ctx.state.update(setAsset, next);
651
+ libraryChanged.emit({
652
+ libraryId: library.id,
653
+ reason: "asset-updated"
654
+ });
655
+ assetUpdated.emit({
656
+ assetId: next.id,
657
+ libraryId: library.id,
658
+ asset: next
659
+ });
660
+ return { asset: next };
661
+ }, signal);
662
+ };
663
+ const moveAsset = async (id, to, options) => {
664
+ const signal = options?.signal;
665
+ throwIfCancelled(signal);
666
+ const asset = ctx.state.get().assets[id];
667
+ const binary = assetBinaries.get(id);
668
+ if (!asset || !binary) throw notFound("asset", id);
669
+ if (to.libraryId === asset.libraryId) return { asset };
670
+ const copy = await createAsset({
671
+ libraryId: to.libraryId,
672
+ source: new Uint8Array(binary.bytes),
673
+ kind: asset.kind,
674
+ label: asset.label,
675
+ ...asset.subject !== void 0 ? { subject: asset.subject } : {},
676
+ ...asset.categories ? { categories: [...asset.categories] } : {},
677
+ ...binary.preview ? { preview: binary.preview.bytes } : {}
678
+ }, { signal });
679
+ await deleteAsset(id);
680
+ return copy;
681
+ };
682
+ const duplicateAsset = async (id, options) => {
683
+ throwIfCancelled(options?.signal);
684
+ const asset = ctx.state.get().assets[id];
685
+ const binary = assetBinaries.get(id);
686
+ if (!asset || !binary) throw notFound("asset", id);
687
+ return createAsset({
688
+ libraryId: asset.libraryId,
689
+ source: new Uint8Array(binary.bytes),
690
+ kind: asset.kind,
691
+ label: options?.label ?? `${asset.label} copy`,
692
+ ...asset.subject !== void 0 ? { subject: asset.subject } : {},
693
+ ...asset.categories ? { categories: [...asset.categories] } : {},
694
+ ...binary.preview ? { preview: binary.preview.bytes } : {}
695
+ }, { signal: options?.signal });
696
+ };
697
+ return { api: {
698
+ createAsset: verb(createAsset),
699
+ createAssetFromAnnotations: verb(createAssetFromAnnotations),
700
+ updateAsset: verb(updateAsset),
701
+ deleteAsset: verb(deleteAsset),
702
+ moveAsset: verb(moveAsset),
703
+ duplicateAsset: verb(duplicateAsset)
704
+ } };
705
+ }
706
+ //#endregion
707
+ //#region src/blank-library.ts
708
+ /**
709
+ * The seed of a new library: a one-page PDF whose page is unregistered, the
710
+ * shape Acrobat itself gives a fresh stamp library (its first page is a
711
+ * blank starter that no `/Names /Pages` key points at). A library must be a
712
+ * PDF from the moment it exists, and a PDF must have a page; the unregistered
713
+ * blank is that page. It is never an asset, never placed, never listed.
714
+ */
715
+ const BLANK_OBJECTS = [
716
+ "<< /Type /Catalog /Pages 2 0 R >>",
717
+ "<< /Type /Pages /Kids [3 0 R] /Count 1 >>",
718
+ "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>"
719
+ ];
720
+ let cached = null;
721
+ function blankLibraryPdf() {
722
+ if (cached) return new Uint8Array(cached);
723
+ let body = "%PDF-1.7\n";
724
+ const offsets = [];
725
+ BLANK_OBJECTS.forEach((object, index) => {
726
+ offsets.push(body.length);
727
+ body += `${index + 1} 0 obj\n${object}\nendobj\n`;
728
+ });
729
+ const xref = body.length;
730
+ body += `xref\n0 ${BLANK_OBJECTS.length + 1}\n0000000000 65535 f \n`;
731
+ for (const offset of offsets) body += `${String(offset).padStart(10, "0")} 00000 n \n`;
732
+ body += `trailer\n<< /Size ${BLANK_OBJECTS.length + 1} /Root 1 0 R >>\nstartxref\n${xref}\n%%EOF\n`;
733
+ cached = new TextEncoder().encode(body);
734
+ return new Uint8Array(cached);
735
+ }
736
+ //#endregion
737
+ //#region src/write/libraries.ts
738
+ /**
739
+ * Library writes. A library is a PDF: its `/Title` is the name, its
740
+ * `/Names /Pages` registry the assets, its pages the artwork, PieceInfo only
741
+ * what has no standard home. Every whole-PDF rewrite rides the per-library
742
+ * mutation queue.
743
+ */
14
744
  const entryString = (entries, key) => {
15
745
  const entry = entries[key];
16
746
  return entry?.type === "string" && entry.value.length > 0 ? entry.value : void 0;
@@ -23,7 +753,6 @@ const entryStringArray = (entries, key) => {
23
753
  const entry = entries[key];
24
754
  return entry?.type === "string-array" ? [...entry.value] : void 0;
25
755
  };
26
- const kindToPdfName = (kind) => kind === "signature" ? "Signature" : kind === "initials" ? "Initials" : "Stamp";
27
756
  const kindFromPdfName = (name) => {
28
757
  switch (name?.toLowerCase()) {
29
758
  case "stamp": return "stamp";
@@ -32,167 +761,159 @@ const kindFromPdfName = (name) => {
32
761
  default: return;
33
762
  }
34
763
  };
35
- const metadataPatch = (id, name, kind, subject, categories) => ({
36
- Version: STAMP_SCHEMA_VERSION,
37
- Id: id,
38
- Name: name,
39
- Kind: { name: kindToPdfName(kind) },
40
- Subject: subject ?? null,
41
- Categories: categories ?? null
42
- });
43
- const libraryMetadataPatch = (id, name, categories) => ({
44
- Version: STAMP_SCHEMA_VERSION,
45
- Id: id,
46
- Name: name,
47
- Kind: { name: "StampLibrary" },
48
- Categories: categories ?? null
49
- });
50
- function createStampCapability(ctx, config = {}) {
51
- /** Binary sidecar of the serializable store: asset bytes + cached preview,
52
- * keyed by asset id. The reducer never sees these (kernel rule 1). */
53
- const binaries = /* @__PURE__ */ new Map();
54
- /** The durable source of truth for a canonical library. Asset PDFs above
55
- * are derived page extractions; this map owns the rewritten whole PDF. */
56
- const libraryBinaries = /* @__PURE__ */ new Map();
57
- /** Whole-PDF rewrites must be serialized per library or two concurrent
58
- * appends could both start from the same bytes and lose one page. */
59
- const libraryMutationTails = /* @__PURE__ */ new Map();
60
- const mutateLibrary = (libraryId, mutation) => {
61
- const result = (libraryMutationTails.get(libraryId) ?? Promise.resolve()).then(mutation);
62
- const tail = result.then(() => void 0, () => void 0);
63
- libraryMutationTails.set(libraryId, tail);
64
- return result.finally(() => {
65
- if (libraryMutationTails.get(libraryId) === tail) libraryMutationTails.delete(libraryId);
66
- });
67
- };
68
- let assetEngineRef = null;
69
- const assetEngine = () => {
70
- if (!assetEngineRef) {
71
- const cfg = config.assetEngine;
72
- assetEngineRef = !cfg ? ctx.engine : typeof cfg === "function" ? cfg() : cfg;
73
- }
74
- return assetEngineRef;
75
- };
76
- const openAssetDocument = async (bytes, identity) => {
764
+ const allocateId = (preferred, prefix, taken) => {
765
+ let id = preferred;
766
+ if (!id || taken.has(id)) do
767
+ id = uid(prefix);
768
+ while (taken.has(id));
769
+ taken.add(id);
770
+ return id;
771
+ };
772
+ function createLibraryWrites(ctx, { events, binaries, assetEngine }) {
773
+ const { libraryChanged, libraryCreated, libraryUpdated, libraryDeleted, assetCreated } = events;
774
+ const { binaries: assetBinaries, libraryBinaries, ghostRenders, mutateLibrary } = binaries;
775
+ const { openAssetDocument, renderThumbnail } = assetEngine;
776
+ const createLibrary = async (name, options) => {
777
+ const signal = options?.signal;
778
+ throwIfCancelled(signal);
779
+ const kind = options?.kind ?? "stamps";
780
+ const taken = new Set(Object.keys(ctx.state.get().libraries));
781
+ const id = allocateId(options?.id, "stamp-lib", taken);
782
+ const doc = await ctx.cancellable(signal, openAssetDocument(blankLibraryPdf()));
783
+ let bytes;
77
784
  try {
78
- return await (await assetEngine()).open({
79
- kind: "bytes",
80
- id: uid("stamp-import"),
81
- bytes
82
- }, {
83
- scope: ["*"],
84
- ...identity ? { identity } : {}
85
- });
86
- } catch (err) {
87
- if (!config.assetEngine && EngineError.is(err, EngineErrorCode.InvalidArg)) throw new EngineError(EngineErrorCode.NotImplemented, "[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.");
88
- throw err;
785
+ await doc.metadata.update({ title: name });
786
+ await doc.pieceInfo.update(STAMP_LIBRARY_PIECEINFO_APP, stampLibraryPieceInfo(id, {
787
+ kind,
788
+ categories: options?.categories
789
+ }));
790
+ bytes = await doc.download();
791
+ } finally {
792
+ await doc.close();
89
793
  }
90
- };
91
- /** Import-time preview render → bytes. The asset engine is local by
92
- * definition, so the image source is always inline bytes. */
93
- const imageToPreview = (image) => {
94
- if (image.source.kind !== "bytes") throw new EngineError(EngineErrorCode.NotImplemented, "[stamp] asset engine returned a URL-sourced render; asset engines must be local");
95
- return {
96
- bytes: image.source.bytes,
97
- mimeType: image.contentType
794
+ throwIfCancelled(signal);
795
+ const library = {
796
+ id,
797
+ name,
798
+ kind,
799
+ assetIds: [],
800
+ ...options?.categories ? { categories: options.categories } : {}
98
801
  };
99
- };
100
- const allocateId = (preferred, prefix, taken) => {
101
- let id = preferred;
102
- if (!id || taken.has(id)) do
103
- id = uid(prefix);
104
- while (taken.has(id));
105
- taken.add(id);
106
- return id;
107
- };
108
- const createLooseLibrary = (name) => {
109
- const id = uid("stamp-lib");
110
- ctx.dispatch({
111
- type: "LIBRARY_ADDED",
112
- library: {
113
- id,
114
- name,
115
- storage: "loose",
116
- assetIds: []
117
- }
802
+ libraryBinaries.set(id, bytes);
803
+ ctx.state.update(addLibrary, library);
804
+ libraryChanged.emit({
805
+ libraryId: id,
806
+ reason: "created"
807
+ });
808
+ libraryCreated.emit({
809
+ libraryId: id,
810
+ library
118
811
  });
119
- return id;
812
+ return { library };
120
813
  };
121
- const importLibraryPdf = async (source, opts) => {
122
- const resolved = await resolveBinarySource(source);
123
- if (sniffBinaryMetadata(resolved.bytes)?.mimeType !== "application/pdf") throw new EngineError(EngineErrorCode.InvalidArg, "[stamp] importLibraryPdf needs PDF bytes (use addAsset for a raster image)");
124
- const doc = await openAssetDocument(new Uint8Array(resolved.bytes));
814
+ const importLibrary = async (source, options) => {
815
+ const signal = options?.signal;
816
+ throwIfCancelled(signal);
817
+ const resolved = await ctx.cancellable(signal, resolveBinarySource(source));
818
+ if (sniffBinaryMetadata(resolved.bytes)?.mimeType !== "application/pdf") throw stampError("invalid-input", "importLibrary needs PDF bytes (use createAsset for a raster image)");
819
+ const doc = await ctx.cancellable(signal, openAssetDocument(new Uint8Array(resolved.bytes)));
125
820
  let imported;
126
821
  try {
127
- if (!doc.pieceInfo || !doc.pages.extract) throw new EngineError(EngineErrorCode.NotImplemented, "[stamp] canonical PDF libraries need an asset engine with pieceInfo and pages.extract");
128
- const snapshot = await doc.pages.list();
129
- if (snapshot.pageCount === 0) throw new EngineError(EngineErrorCode.InvalidArg, "[stamp] a canonical stamp library PDF must contain at least one page");
130
- const pages = snapshot.pages.map((layout) => {
131
- const handle = doc.page(layout.pageObjectNumber);
132
- if (!handle.pieceInfo) throw new EngineError(EngineErrorCode.NotImplemented, "[stamp] canonical PDF libraries need page pieceInfo support");
133
- return {
134
- layout,
135
- handle,
136
- metadata: null
137
- };
138
- });
139
- const catalogMetadata = await doc.pieceInfo.read(LIBRARY_PIECEINFO_APP);
140
- for (const page of pages) page.metadata = await page.handle.pieceInfo.read(STAMP_PIECEINFO_APP);
141
- const state = ctx.getState();
142
- const takenLibraryIds = new Set(Object.keys(state.libraries));
143
- const takenAssetIds = new Set(Object.keys(state.assets));
144
- const catalogEntries = catalogMetadata?.entries ?? {};
822
+ const layout = await doc.pages.list();
823
+ if (layout.pageCount === 0) throw stampError("invalid-input", "a canonical stamp library PDF must contain at least one page");
824
+ const pagesByObjectNumber = new Map(layout.pages.map((page) => [page.ref.objectNumber, page]));
825
+ const catalogEntries = (await doc.pieceInfo.get("EMBD_StampLibrary"))?.entries ?? {};
826
+ const takenLibraryIds = new Set(Object.keys(ctx.state.get().libraries));
145
827
  const libraryId = allocateId(entryString(catalogEntries, "Id"), "stamp-lib", takenLibraryIds);
146
- const libraryName = opts?.name ?? entryString(catalogEntries, "Name") ?? "Stamps";
147
- const libraryCategories = opts?.categories ?? entryStringArray(catalogEntries, "Categories");
148
- const descriptors = pages.map(({ layout, handle, metadata: pageMetadata }) => {
149
- const entries = pageMetadata?.entries ?? {};
150
- const id = allocateId(entryString(entries, "Id"), "stamp", takenAssetIds);
151
- const kind = opts?.kind ?? kindFromPdfName(entryName(entries, "Kind")) ?? "stamp";
152
- return {
153
- handle,
154
- asset: {
155
- id,
156
- libraryId,
157
- kind,
158
- name: opts?.assetName?.(layout.index) ?? entryString(entries, "Name") ?? `Stamp ${layout.index + 1}`,
159
- size: {
160
- width: layout.size.width,
161
- height: layout.size.height
162
- },
163
- format: "pdf",
164
- pageObjectNumber: layout.pageObjectNumber,
165
- subject: entryString(entries, "Subject"),
166
- categories: entryStringArray(entries, "Categories")
167
- }
168
- };
169
- });
170
- await doc.pieceInfo.update(LIBRARY_PIECEINFO_APP, libraryMetadataPatch(libraryId, libraryName, libraryCategories));
828
+ const docMeta = await doc.metadata.get();
829
+ const libraryName = (docMeta.title && docMeta.title.length > 0 ? docMeta.title : void 0) ?? entryString(catalogEntries, "Name") ?? options?.name ?? "Stamps";
830
+ if (!docMeta.title) await doc.metadata.update({ title: libraryName });
831
+ const libraryCategories = options?.categories ?? entryStringArray(catalogEntries, "Categories");
832
+ const libraryLocale = entryString(catalogEntries, "Locale");
833
+ const libraryKind = options?.libraryKind ?? libraryKindFromPdfName(entryName(catalogEntries, "Kind"));
834
+ const registry = (layout.namedPages ?? []).filter((entry) => entry.target.kind === "page");
835
+ const hidden = (layout.namedPages ?? []).filter((entry) => entry.target.kind !== "page");
836
+ if (hidden.length > 0) globalThis.console?.warn(`[stamp] library '${libraryName}' carries ${hidden.length} hidden-template or dangling registration(s); they are not stamps and were ignored`);
837
+ let descriptors;
838
+ if (registry.length > 0) {
839
+ const seen = /* @__PURE__ */ new Set();
840
+ descriptors = registry.map((entry) => {
841
+ const { name, label } = parseStampKey(entry.name);
842
+ if (!name) throw stampError("invalid-input", `library '${libraryName}': empty stamp identifier in key '${entry.name}'`);
843
+ if (seen.has(name)) throw stampError("invalid-input", `library '${libraryName}': duplicate stamp identifier '${name}'`);
844
+ seen.add(name);
845
+ const page = pagesByObjectNumber.get(entry.target.page.objectNumber);
846
+ return {
847
+ page: page.ref,
848
+ index: page.index,
849
+ name,
850
+ label
851
+ };
852
+ });
853
+ descriptors.sort((left, right) => left.index - right.index);
854
+ } else if (layout.namedPages === void 0) throw stampError("unsupported", "the asset engine reports no named-page registry; an engine with named pages is needed to import libraries");
855
+ else {
856
+ descriptors = [];
857
+ for (const page of layout.pages) {
858
+ const version1Entries = (await doc.page(page.ref).pieceInfo.get(STAMP_PIECEINFO_APP))?.entries;
859
+ const name = (version1Entries && entryString(version1Entries, "Name")) ?? `Stamp${page.index + 1}`;
860
+ const label = (version1Entries && entryString(version1Entries, "Subject")) ?? options?.assetName?.(page.index) ?? name;
861
+ descriptors.push({
862
+ page: page.ref,
863
+ index: page.index,
864
+ name,
865
+ label
866
+ });
867
+ }
868
+ for (const descriptor of descriptors) await doc.pages.setName({
869
+ name: stampKey(descriptor.name, descriptor.label),
870
+ page: descriptor.page
871
+ });
872
+ }
873
+ await doc.pieceInfo.update(STAMP_LIBRARY_PIECEINFO_APP, stampLibraryPieceInfo(libraryId, {
874
+ kind: libraryKind,
875
+ categories: libraryCategories,
876
+ locale: libraryLocale
877
+ }));
171
878
  const assets = [];
172
879
  for (const descriptor of descriptors) {
173
- const { asset, handle } = descriptor;
174
- await handle.pieceInfo.update(STAMP_PIECEINFO_APP, metadataPatch(asset.id, asset.name, asset.kind, asset.subject, asset.categories));
175
- const bytes = await doc.pages.extract([asset.pageObjectNumber]);
176
- const image = await handle.render.image({
177
- viewport: {
178
- kind: "width",
179
- width: config.previewWidth ?? DEFAULT_PREVIEW_WIDTH
880
+ const handle = doc.page(descriptor.page);
881
+ const entries = (await handle.pieceInfo.get("EMBD_Stamp"))?.entries ?? {};
882
+ const kind = options?.kind ?? kindFromPdfName(entryName(entries, "Kind")) ?? "stamp";
883
+ const subject = entryString(entries, "SubjectOverride");
884
+ const categories = entryStringArray(entries, "Categories");
885
+ const page = pagesByObjectNumber.get(descriptor.page.objectNumber);
886
+ const asset = {
887
+ id: assetIdFor(libraryId, descriptor.name),
888
+ libraryId,
889
+ kind,
890
+ name: descriptor.name,
891
+ label: descriptor.label,
892
+ size: {
893
+ width: page.size.width,
894
+ height: page.size.height
180
895
  },
181
- background: "transparent",
182
- includeAnnotations: true,
183
- format: "png"
184
- });
896
+ page: descriptor.page,
897
+ ...subject !== void 0 ? { subject } : {},
898
+ ...categories !== void 0 ? { categories } : {}
899
+ };
900
+ await handle.pieceInfo.update(STAMP_PIECEINFO_APP, stampPieceInfo(kind, {
901
+ subject,
902
+ categories
903
+ }));
904
+ const bytes = await doc.pages.extract([descriptor.page]);
185
905
  assets.push({
186
906
  asset,
187
907
  bytes,
188
- preview: imageToPreview(image)
908
+ preview: await renderThumbnail(handle)
189
909
  });
190
910
  }
191
911
  imported = {
192
912
  library: {
193
913
  id: libraryId,
194
914
  name: libraryName,
195
- storage: "canonical-pdf",
915
+ kind: libraryKind,
916
+ ...libraryLocale ? { locale: libraryLocale } : {},
196
917
  categories: libraryCategories,
197
918
  assetIds: []
198
919
  },
@@ -202,231 +923,305 @@ function createStampCapability(ctx, config = {}) {
202
923
  } finally {
203
924
  await doc.close();
204
925
  }
926
+ throwIfCancelled(signal);
205
927
  libraryBinaries.set(imported.library.id, imported.canonicalBytes);
206
- ctx.dispatch({
207
- type: "LIBRARY_ADDED",
208
- library: imported.library
209
- });
928
+ ctx.state.update(addLibrary, imported.library);
210
929
  for (const { asset, bytes, preview } of imported.assets) {
211
- binaries.set(asset.id, {
930
+ assetBinaries.set(asset.id, {
212
931
  bytes,
213
932
  preview
214
933
  });
215
- ctx.dispatch({
216
- type: "ASSET_ADDED",
217
- asset
218
- });
934
+ ctx.state.update(addAsset, asset);
219
935
  }
220
- return imported.library.id;
936
+ libraryChanged.emit({
937
+ libraryId: imported.library.id,
938
+ reason: "imported"
939
+ });
940
+ libraryCreated.emit({
941
+ libraryId: imported.library.id,
942
+ library: imported.library
943
+ });
944
+ for (const { asset } of imported.assets) assetCreated.emit({
945
+ assetId: asset.id,
946
+ libraryId: imported.library.id,
947
+ asset
948
+ });
949
+ return { library: ctx.state.get().libraries[imported.library.id] ?? imported.library };
221
950
  };
222
- const addAsset = async (input) => {
223
- const targetLibrary = input.libraryId ? ctx.getState().libraries[input.libraryId] ?? null : null;
224
- if (input.libraryId && !targetLibrary) throw new EngineError(EngineErrorCode.NotFound, `[stamp] unknown library '${input.libraryId}'`);
225
- const resolved = await resolveBinarySource(input.source);
226
- const meta = sniffBinaryMetadata(resolved.bytes);
227
- if (!meta) throw new EngineError(EngineErrorCode.InvalidArg, "[stamp] asset source must be PNG, JPEG, or single-page PDF bytes");
228
- const isPdf = meta.mimeType === "application/pdf";
229
- let suppliedPreview = null;
230
- if (input.preview) {
231
- const preview = await resolveBinarySource(input.preview);
232
- suppliedPreview = {
233
- bytes: new Uint8Array(preview.bytes),
234
- mimeType: preview.mimeType ?? "image/png"
235
- };
951
+ const dropLibrary = (id) => {
952
+ const library = ctx.state.get().libraries[id];
953
+ if (library) for (const assetId of library.assetIds) {
954
+ assetBinaries.delete(assetId);
955
+ ghostRenders.delete(assetId);
236
956
  }
237
- if (targetLibrary?.storage === "canonical-pdf") {
238
- if (!isPdf) throw new EngineError(EngineErrorCode.InvalidArg, "[stamp] raster assets cannot be appended to a canonical PDF library");
239
- return mutateLibrary(targetLibrary.id, async () => {
240
- const liveLibrary = ctx.getState().libraries[targetLibrary.id];
241
- if (liveLibrary?.storage !== "canonical-pdf") throw new EngineError(EngineErrorCode.NotFound, `[stamp] canonical library '${targetLibrary.id}' no longer exists`);
242
- const canonicalBytes = libraryBinaries.get(liveLibrary.id);
243
- if (!canonicalBytes) throw new EngineError(EngineErrorCode.Unknown, `[stamp] canonical bytes are missing for library '${liveLibrary.id}'`);
244
- const assetId = uid("stamp");
245
- const doc = await openAssetDocument(canonicalBytes);
246
- let appended;
247
- try {
248
- if (!doc.pages.insert || !doc.pages.extract) throw new EngineError(EngineErrorCode.NotImplemented, "[stamp] appending to a canonical library needs pages.insert and pages.extract");
249
- const result = await doc.pages.insert(new Uint8Array(resolved.bytes));
250
- if (result.insertedPageObjectNumbers.length !== 1) throw new EngineError(EngineErrorCode.InvalidArg, "[stamp] a canonical library asset must be a single-page PDF");
251
- const pageObjectNumber = result.insertedPageObjectNumbers[0];
252
- const layout = result.layout.pages.find((candidate) => candidate.pageObjectNumber === pageObjectNumber);
253
- const page = doc.page(pageObjectNumber);
254
- if (!layout || !page.pieceInfo) throw new EngineError(EngineErrorCode.NotImplemented, "[stamp] canonical PDF libraries need page layout and pieceInfo support");
255
- const asset = {
256
- id: assetId,
257
- libraryId: liveLibrary.id,
258
- kind: input.kind ?? "stamp",
259
- name: input.name,
260
- size: {
261
- width: layout.size.width,
262
- height: layout.size.height
263
- },
264
- format: "pdf",
265
- pageObjectNumber,
266
- subject: input.subject,
267
- categories: input.categories
268
- };
269
- await page.pieceInfo.update(STAMP_PIECEINFO_APP, metadataPatch(asset.id, asset.name, asset.kind, asset.subject, asset.categories));
270
- const bytes = await doc.pages.extract([pageObjectNumber]);
271
- let preview = suppliedPreview;
272
- if (!preview) preview = imageToPreview(await page.render.image({
273
- viewport: {
274
- kind: "width",
275
- width: config.previewWidth ?? DEFAULT_PREVIEW_WIDTH
276
- },
277
- background: "transparent",
278
- includeAnnotations: true,
279
- format: "png"
280
- }));
281
- appended = {
282
- asset,
283
- bytes,
284
- preview,
285
- canonical: await doc.download()
286
- };
287
- } finally {
288
- await doc.close();
289
- }
290
- libraryBinaries.set(liveLibrary.id, appended.canonical);
291
- binaries.set(appended.asset.id, {
292
- bytes: appended.bytes,
293
- preview: appended.preview
294
- });
295
- ctx.dispatch({
296
- type: "ASSET_ADDED",
297
- asset: appended.asset
298
- });
299
- return appended.asset.id;
957
+ libraryBinaries.delete(id);
958
+ ctx.state.update(removeLibrary, id);
959
+ };
960
+ const deleteLibrary = (id, options) => mutateLibrary(id, async () => {
961
+ const existed = ctx.state.get().libraries[id] !== void 0;
962
+ dropLibrary(id);
963
+ if (existed) {
964
+ libraryChanged.emit({
965
+ libraryId: id,
966
+ reason: "removed"
967
+ });
968
+ libraryDeleted.emit({
969
+ libraryId: id,
970
+ library: null
300
971
  });
301
972
  }
302
- const size = input.size ?? ("width" in meta ? {
303
- width: meta.width,
304
- height: meta.height
305
- } : null);
306
- if (!size) throw new EngineError(EngineErrorCode.InvalidArg, "[stamp] a PDF asset needs `size` (its page size in points) — PDF bytes carry no sniffable dimensions");
307
- let preview = suppliedPreview;
308
- if (!preview && !isPdf) preview = {
309
- bytes: new Uint8Array(resolved.bytes),
310
- mimeType: meta.mimeType
311
- };
312
- const commitLooseAsset = (libraryId) => {
313
- const asset = {
314
- id: uid("stamp"),
315
- libraryId,
316
- kind: input.kind ?? "stamp",
317
- name: input.name,
318
- size,
319
- format: isPdf ? "pdf" : meta.mimeType === "image/png" ? "png" : "jpeg",
320
- subject: input.subject,
321
- categories: input.categories
973
+ }, options?.signal);
974
+ const updateLibrary = async (id, patch, options) => {
975
+ const signal = options?.signal;
976
+ throwIfCancelled(signal);
977
+ if (!ctx.state.get().libraries[id]) throw notFound("library", id);
978
+ return mutateLibrary(id, async () => {
979
+ const library = ctx.state.get().libraries[id];
980
+ if (!library) throw notFound("library", id);
981
+ const canonicalBytes = libraryBinaries.get(id);
982
+ if (!canonicalBytes) throw stampError("operation-failed", `canonical bytes are missing for library '${id}'`);
983
+ const next = {
984
+ ...library,
985
+ ...patch.name !== void 0 ? { name: patch.name } : {},
986
+ ...patch.categories !== void 0 ? { categories: patch.categories } : {}
322
987
  };
323
- binaries.set(asset.id, {
324
- bytes: new Uint8Array(resolved.bytes),
325
- preview
988
+ const doc = await ctx.cancellable(signal, openAssetDocument(canonicalBytes));
989
+ let rewritten;
990
+ try {
991
+ if (next.name !== library.name) await doc.metadata.update({ title: next.name });
992
+ await doc.pieceInfo.update(STAMP_LIBRARY_PIECEINFO_APP, stampLibraryPieceInfo(id, {
993
+ kind: next.kind,
994
+ categories: next.categories,
995
+ locale: next.locale
996
+ }));
997
+ rewritten = await doc.download();
998
+ } finally {
999
+ await doc.close();
1000
+ }
1001
+ throwIfCancelled(signal);
1002
+ libraryBinaries.set(id, rewritten);
1003
+ ctx.state.update(setLibrary, next);
1004
+ libraryChanged.emit({
1005
+ libraryId: id,
1006
+ reason: "updated"
326
1007
  });
327
- ctx.dispatch({
328
- type: "ASSET_ADDED",
329
- asset
1008
+ libraryUpdated.emit({
1009
+ libraryId: id,
1010
+ library: next
330
1011
  });
331
- return asset.id;
332
- };
333
- if (!targetLibrary) return commitLooseAsset(createLooseLibrary(input.name));
334
- return mutateLibrary(targetLibrary.id, async () => {
335
- const liveLibrary = ctx.getState().libraries[targetLibrary.id];
336
- if (liveLibrary?.storage !== "loose") throw new EngineError(EngineErrorCode.NotFound, `[stamp] loose library '${targetLibrary.id}' no longer exists`);
337
- return commitLooseAsset(liveLibrary.id);
338
- });
1012
+ return { library: next };
1013
+ }, signal);
339
1014
  };
340
- const dropLibrary = (id) => {
341
- const library = ctx.getState().libraries[id];
342
- if (library) for (const assetId of library.assetIds) binaries.delete(assetId);
343
- libraryBinaries.delete(id);
344
- ctx.dispatch({
345
- type: "LIBRARY_REMOVED",
346
- libraryId: id
347
- });
1015
+ return {
1016
+ createLibrary,
1017
+ api: {
1018
+ createLibrary: verb(createLibrary),
1019
+ updateLibrary: verb(updateLibrary),
1020
+ importLibrary: verb(importLibrary),
1021
+ deleteLibrary: verb(deleteLibrary)
1022
+ }
348
1023
  };
349
- const removeAsset = async (id) => {
350
- const initialAsset = ctx.getState().assets[id];
351
- if (!initialAsset) return;
352
- return mutateLibrary(initialAsset.libraryId, async () => {
353
- const asset = ctx.getState().assets[id];
354
- if (!asset) return;
355
- const library = ctx.getState().libraries[asset.libraryId];
356
- if (library?.storage === "canonical-pdf") {
357
- if (library.assetIds.length === 1) {
358
- dropLibrary(library.id);
359
- return;
360
- }
361
- if (asset.pageObjectNumber === void 0) throw new EngineError(EngineErrorCode.Unknown, `[stamp] canonical asset '${id}' has no page object number`);
362
- const canonicalBytes = libraryBinaries.get(library.id);
363
- if (!canonicalBytes) throw new EngineError(EngineErrorCode.Unknown, `[stamp] canonical bytes are missing for library '${library.id}'`);
364
- const doc = await openAssetDocument(canonicalBytes);
365
- let rewritten;
366
- try {
367
- await doc.pages.delete([asset.pageObjectNumber]);
368
- rewritten = await doc.download();
369
- } finally {
370
- await doc.close();
371
- }
372
- libraryBinaries.set(library.id, rewritten);
373
- }
374
- binaries.delete(id);
375
- ctx.dispatch({
376
- type: "ASSET_REMOVED",
377
- assetId: id
1024
+ }
1025
+ //#endregion
1026
+ //#region src/write/marks.ts
1027
+ /**
1028
+ * Authoring: a drawn or typed mark rendered to a one-page PDF (the
1029
+ * annotation is authored on a scratch page and exported the way "stamp from
1030
+ * selection" exports), a page of a PDF as a single-page PDF, and the bytes
1031
+ * an asset is made from.
1032
+ */
1033
+ /** A mark's `#rrggbb` color, checked before anything is drawn. */
1034
+ const hexColor = (hex) => {
1035
+ const color = hex.trim();
1036
+ if (!/^#[0-9a-f]{6}$/i.test(color)) throw stampError("invalid-input", `mark color must be #rrggbb, got '${hex}'`);
1037
+ return color;
1038
+ };
1039
+ /** An exact ArrayBuffer over a view (the engine's binary idiom). */
1040
+ const toArrayBuffer = (bytes) => {
1041
+ const buffer = new ArrayBuffer(bytes.byteLength);
1042
+ new Uint8Array(buffer).set(bytes);
1043
+ return buffer;
1044
+ };
1045
+ /** An ink mark's strokes, as the engine takes them; a mark needs at least one point. */
1046
+ const inkListOf = (strokes) => {
1047
+ if (!strokes.some((stroke) => stroke.length > 0)) throw stampError("invalid-input", "an ink mark needs at least one point");
1048
+ return strokes.map((stroke) => stroke.map(({ x, y }) => ({
1049
+ x,
1050
+ y
1051
+ })));
1052
+ };
1053
+ /**
1054
+ * A generous box for typed text. The export keeps the whole box, so the
1055
+ * text is centered in it: the mark then sits in the middle of a preview
1056
+ * or a signature field.
1057
+ */
1058
+ const textBounds = (text, fontSize) => ({
1059
+ x: 0,
1060
+ y: 0,
1061
+ width: Math.max(1, text.length) * fontSize * .75 + fontSize,
1062
+ height: fontSize * 1.6
1063
+ });
1064
+ function createMarks({ assetEngine }) {
1065
+ const { openAssetDocument, registerFont } = assetEngine;
1066
+ /**
1067
+ * A drawn or typed mark rendered to a one-page PDF: the annotation is
1068
+ * authored on a scratch page and exported the way "stamp from selection"
1069
+ * exports — a fresh page the size of the mark, paths kept as paths, the
1070
+ * font subset-embedded. Self-contained and Acrobat-readable.
1071
+ */
1072
+ const renderMark = async (mark) => {
1073
+ if (mark.kind === "text") await registerFont(mark.fontFamily);
1074
+ const doc = await openAssetDocument(blankLibraryPdf());
1075
+ try {
1076
+ const scratch = (await doc.pages.list()).pages[0];
1077
+ if (!scratch) throw stampError("operation-failed", "the scratch document has no page");
1078
+ const page = doc.page(scratch.ref);
1079
+ const color = hexColor(mark.color ?? "#1d2b53");
1080
+ const created = mark.kind === "ink" ? await page.annotations.create({
1081
+ subtype: "ink",
1082
+ inkList: inkListOf(mark.strokes),
1083
+ color,
1084
+ strokeWidth: mark.strokeWidth ?? 2
1085
+ }) : await page.annotations.create({
1086
+ subtype: "free-text",
1087
+ intent: "free-text",
1088
+ contents: mark.text,
1089
+ fontFamily: mark.fontFamily,
1090
+ fontSize: mark.fontSize ?? 36,
1091
+ textAlign: "center",
1092
+ verticalAlign: "middle",
1093
+ box: textBounds(mark.text, mark.fontSize ?? 36),
1094
+ fontColor: color,
1095
+ strokeWidth: 0
378
1096
  });
379
- });
1097
+ return new Uint8Array(await page.annotations.exportAppearance([created.annotation.ref]));
1098
+ } finally {
1099
+ await doc.close();
1100
+ }
380
1101
  };
381
- const removeLibrary = (id) => mutateLibrary(id, async () => dropLibrary(id));
382
- const surfaceScriptingResult = (result) => {
1102
+ /** One page of a PDF as a single-page PDF (a `pdf` mark with `pageIndex`). */
1103
+ const extractPage = async (bytes, pageIndex) => {
1104
+ const doc = await openAssetDocument(bytes);
383
1105
  try {
384
- for (const effect of result.uiEffects) config.scripting?.onUiEffect?.(effect);
385
- for (const diagnostic of result.diagnostics) config.scripting?.onDiagnostic?.(diagnostic);
386
- if (result.error) config.scripting?.onError?.(result.error);
387
- } catch (error) {
388
- globalThis.console?.error("[stamp] scripting observer failed:", error);
1106
+ const layout = await doc.pages.list();
1107
+ const page = layout.pages[pageIndex];
1108
+ if (!page) throw stampError("invalid-input", `the PDF has no page ${pageIndex} (${layout.pageCount} pages)`);
1109
+ return await doc.pages.extract([page.ref]);
1110
+ } finally {
1111
+ await doc.close();
1112
+ }
1113
+ };
1114
+ /** The bytes an asset is made from: the caller's `source`, or its `mark` authored into one. */
1115
+ const resolveAssetSource = async (input) => {
1116
+ if (input.source === void 0 === (input.mark === void 0)) throw stampError("invalid-input", "createAsset takes exactly one of `source` / `mark`");
1117
+ if (input.source !== void 0) return resolveBinarySource(input.source);
1118
+ const mark = input.mark;
1119
+ switch (mark.kind) {
1120
+ case "image": return resolveBinarySource(mark.source);
1121
+ case "pdf": {
1122
+ const resolved = await resolveBinarySource(mark.source);
1123
+ if (mark.pageIndex === void 0) return resolved;
1124
+ return { bytes: toArrayBuffer(await extractPage(new Uint8Array(resolved.bytes), mark.pageIndex)) };
1125
+ }
1126
+ case "ink":
1127
+ case "text": return { bytes: toArrayBuffer(await renderMark(mark)) };
389
1128
  }
390
1129
  };
1130
+ return { resolveAssetSource };
1131
+ }
1132
+ //#endregion
1133
+ //#region src/write/placement.ts
1134
+ /**
1135
+ * Placement: arm an asset on a document (the next click places) or place it
1136
+ * without the pointer. Form-backed stamps are executable templates only
1137
+ * until placement — they are evaluated on an isolated copy under the target
1138
+ * document's detached script realm, so neither the canonical library nor
1139
+ * its reusable per-page extraction becomes target/user/time specific.
1140
+ */
1141
+ function createPlacement(ctx, { binaries, assetEngine, ghosts, targets }, { canPlace }) {
1142
+ const { binaries: assetBinaries, libraryBinaries } = binaries;
1143
+ const { openAssetDocument, imageToPreview } = assetEngine;
1144
+ const { ghostProvider } = ghosts;
1145
+ const { documentIdOf, targetOf, pageOf } = targets;
1146
+ const settings = ctx.settings();
1147
+ const droppedArms = () => Object.keys(ctx.state.get().armed).filter((documentId) => !ctx.tryForDocument(AnnotationToken$1, documentId)?.stamps.isArmed()).join("\n");
1148
+ ctx.watch(droppedArms, (dropped) => {
1149
+ if (dropped) ctx.state.update(disarmDocuments, dropped.split("\n"));
1150
+ });
1151
+ /** The one payload both entry points hand the annotation plugin: artwork,
1152
+ * a resolution-aware ghost, true size, and the identity a placement
1153
+ * writes (`/Name` = identifier, `/Subj` = the subject override or label). */
1154
+ const stampPayload = (asset, placement, materialized) => ({
1155
+ source: placement.bytes,
1156
+ preview: ghostProvider(placement.bytes, placement.preview, materialized ? null : asset.id),
1157
+ intrinsicSize: asset.size,
1158
+ name: asset.name,
1159
+ subject: asset.subject ?? asset.label
1160
+ });
391
1161
  /**
392
1162
  * Form-backed stamps are executable templates only until placement. Work
393
1163
  * on an isolated copy so neither the canonical library nor its reusable
394
1164
  * per-page extraction becomes target/user/time specific.
1165
+ *
1166
+ * The realm comes from the target document's actions plugin: a detached
1167
+ * realm under that document's policy and environment, with its own
1168
+ * sandbox and none of the viewer realm's globals. No actions plugin,
1169
+ * scripting off, or `dynamic: false`: the template is armed as-is.
395
1170
  */
396
- const materializeForPlacement = async (documentId, asset, bin) => {
397
- if (asset.format !== "pdf" || !config.scripting?.enabled) return bin;
398
- const targetDoc = ctx.documentHandle(documentId);
399
- const targetMeta = ctx.core().documents[documentId] ?? null;
400
- if (!targetDoc || !targetMeta) throw new EngineError(EngineErrorCode.NotFound, `[stamp] target document '${documentId}' is not open`);
1171
+ const materializeForPlacement = async (documentId, asset, binary) => {
1172
+ if (!settings.get().dynamic) return binary;
1173
+ const actions = ctx.tryForDocument(ActionsToken$1, documentId);
1174
+ const mintRealm = actions?.createDetachedScriptRealm;
1175
+ if (!actions || !mintRealm) return binary;
1176
+ const documents = ctx.get(DocumentsToken);
1177
+ const target = documents.get(documentId);
1178
+ if (target?.status !== "ready") throw stampError("not-found", `document '${documentId}' is not open`);
1179
+ const targetDocument = {
1180
+ name: target.name,
1181
+ pageCount: target.pageCount,
1182
+ pages: documents.listPages(documentId)
1183
+ };
401
1184
  const canonicalBytes = libraryBinaries.get(asset.libraryId);
402
- const sourceBytes = canonicalBytes ?? bin.bytes;
403
- const doc = await openAssetDocument(new Uint8Array(sourceBytes), targetDoc.security.identity);
1185
+ const sourceBytes = canonicalBytes ?? binary.bytes;
1186
+ const doc = await openAssetDocument(new Uint8Array(sourceBytes));
1187
+ let realm = null;
404
1188
  let scripting = null;
405
1189
  try {
406
1190
  const layout = await doc.pages.list();
407
- const selectedPage = asset.pageObjectNumber === void 0 ? layout.pageCount === 1 ? layout.pages[0] : void 0 : layout.pages.find(({ pageObjectNumber }) => pageObjectNumber === asset.pageObjectNumber);
408
- if (!selectedPage) throw new EngineError(EngineErrorCode.InvalidArg, canonicalBytes ? `[stamp] canonical page ${asset.pageObjectNumber ?? "unknown"} no longer exists` : "[stamp] a loose dynamic stamp asset must contain exactly one page");
1191
+ const selectedPage = asset.page === void 0 ? layout.pageCount === 1 ? layout.pages[0] : void 0 : layout.pages.find(({ ref }) => ref.objectNumber === asset.page.objectNumber);
1192
+ if (!selectedPage) throw stampError("invalid-input", canonicalBytes ? `canonical page ${asset.page?.objectNumber ?? "unknown"} no longer exists` : "a loose dynamic stamp asset must contain exactly one page");
409
1193
  const snapshot = await doc.forms.list();
410
- if (!snapshot.fields.some((field) => field.widgets.some(({ pageObjectNumber }) => pageObjectNumber === selectedPage.pageObjectNumber))) return bin;
411
- if (!doc.pages.flatten || !doc.pages.extract) throw new EngineError(EngineErrorCode.NotImplemented, "[stamp] dynamic PDF stamps need an asset engine with pages.flatten and pages.extract");
412
- const scriptingConfig = config.scripting;
413
- scripting = createFormScriptingController({
1194
+ if (!snapshot.fields.some((field) => field.widgets.some(({ page }) => page?.objectNumber === selectedPage.ref.objectNumber))) return binary;
1195
+ if (!doc.pages.flatten || !doc.pages.extract) throw stampError("unsupported", "dynamic PDF stamps need an asset engine with pages.flatten and pages.extract");
1196
+ realm = mintRealm.call(actions, {
414
1197
  doc,
415
- document: () => targetMeta,
416
- config: scriptingConfig,
417
- sandboxFactory: scriptingConfig.sandboxFactory ?? (() => import("@embedpdf/core-js-sandbox").then(({ createQuickJsSandbox }) => createQuickJsSandbox()))
1198
+ document: () => targetDocument,
1199
+ bootSources: async () => {
1200
+ return (doc.actions ? await doc.actions.get() : null)?.nameTreeScripts.map(({ action }) => javaScriptProgramFromActionTree(action)) ?? [];
1201
+ }
1202
+ });
1203
+ scripting = createFormScriptingController({
1204
+ document: () => targetDocument,
1205
+ transaction: realm.transaction.bind(realm),
1206
+ budget: realm.budget
1207
+ });
1208
+ const result = await scripting.transaction(async (scripts) => {
1209
+ const calculated = await scripts.recalculate(snapshot);
1210
+ if (calculated.status === "accepted" && calculated.effects.length > 0) await doc.apply({ ops: formEffectOps(calculated.effects) });
1211
+ return calculated;
1212
+ });
1213
+ actions.surfaceScriptCommit(result, {
1214
+ origin: "user",
1215
+ realm: "detached"
418
1216
  });
419
- const result = await scripting.recalculate(snapshot);
420
- surfaceScriptingResult(result);
421
- if (result.status === "failed") throw new EngineError(EngineErrorCode.Unknown, `[stamp] dynamic stamp scripting failed: ${result.error?.message ?? "native form effect failed"}`);
422
- const pageObjectNumber = selectedPage.pageObjectNumber;
423
- const failed = (await doc.pages.flatten([pageObjectNumber], "display")).results.find(({ status }) => status === "failed" || status === "skipped");
424
- if (failed) throw new EngineError(EngineErrorCode.Unknown, `[stamp] dynamic stamp flatten failed for page ${failed.pageObjectNumber}`);
425
- const bytes = await doc.pages.extract([pageObjectNumber]);
426
- const image = await doc.page(pageObjectNumber).render.image({
1217
+ if (result.status === "failed") throw stampError("operation-failed", `dynamic stamp scripting failed: ${result.error?.message ?? "native form effect failed"}`);
1218
+ const page = selectedPage.ref;
1219
+ await doc.pages.flatten([page], { usage: "display" });
1220
+ const bytes = await doc.pages.extract([page]);
1221
+ const image = await doc.page(page).render.image({
427
1222
  viewport: {
428
1223
  kind: "width",
429
- width: config.previewWidth ?? DEFAULT_PREVIEW_WIDTH
1224
+ width: settings.get().previewWidth
430
1225
  },
431
1226
  background: "transparent",
432
1227
  includeAnnotations: false,
@@ -438,152 +1233,280 @@ function createStampCapability(ctx, config = {}) {
438
1233
  };
439
1234
  } finally {
440
1235
  scripting?.dispose();
1236
+ realm?.dispose();
441
1237
  await doc.close();
442
1238
  }
443
1239
  };
444
- const armAsset = async (documentId, assetId, opts) => {
445
- const asset = ctx.getState().assets[assetId];
446
- const bin = binaries.get(assetId);
447
- if (!asset || !bin) throw new EngineError(EngineErrorCode.NotFound, `[stamp] unknown asset '${assetId}'`);
448
- const placement = await materializeForPlacement(documentId, asset, bin);
449
- await ctx.forDocument(AnnotationToken, documentId).armStamp({
450
- source: placement.bytes,
451
- preview: placement.preview ? {
452
- data: placement.preview.bytes,
453
- mimeType: placement.preview.mimeType
454
- } : void 0,
455
- intrinsicSize: asset.size,
456
- targetWidth: opts?.targetWidth
457
- });
1240
+ /** An asset and its bytes, or `not-found`. */
1241
+ const assetOf = (assetId) => {
1242
+ const asset = ctx.state.get().assets[assetId];
1243
+ const binary = assetBinaries.get(assetId);
1244
+ if (!asset || !binary) throw notFound("asset", assetId);
1245
+ return {
1246
+ asset,
1247
+ binary
1248
+ };
458
1249
  };
459
- ctx.cleanup(() => {
460
- binaries.clear();
461
- libraryBinaries.clear();
462
- libraryMutationTails.clear();
463
- const ownedAssetEngine = typeof config.assetEngine === "function" ? assetEngineRef : null;
464
- assetEngineRef = null;
465
- if (ownedAssetEngine) Promise.resolve(ownedAssetEngine).then((engine) => engine.destroy()).catch(() => {});
466
- });
467
- return {
468
- libraries: () => {
469
- const s = ctx.getState();
470
- return s.libraryOrder.map((id) => s.libraries[id]).filter((l) => l != null);
471
- },
472
- library: (id) => ctx.getState().libraries[id] ?? null,
473
- assets: (libraryId) => {
474
- const s = ctx.getState();
475
- if (libraryId) {
476
- const library = s.libraries[libraryId];
477
- return library ? library.assetIds.map((id) => s.assets[id]).filter((a) => a != null) : [];
478
- }
479
- return s.libraryOrder.flatMap((lid) => (s.libraries[lid]?.assetIds ?? []).map((id) => s.assets[id]).filter((a) => a != null));
480
- },
481
- asset: (id) => ctx.getState().assets[id] ?? null,
482
- assetPreview: (id) => binaries.get(id)?.preview ?? null,
483
- assetBytes: (id) => binaries.get(id)?.bytes ?? null,
484
- libraryBytes: (id) => libraryBinaries.get(id) ?? null,
485
- importLibraryPdf,
486
- addAsset,
487
- removeAsset,
488
- removeLibrary,
489
- armAsset,
490
- disarm: (documentId) => ctx.forDocument(AnnotationToken, documentId).disarmStamp()
1250
+ /** Placing is annotation work: refused where the document's annotation plugin refuses a create. */
1251
+ const assertMayPlace = (documentId, operation) => {
1252
+ if (!canPlace(documentId)) throw permissionDenied("annotations:create", operation);
1253
+ };
1254
+ const armAsset$1 = async (assetId, options) => {
1255
+ const signal = options?.signal;
1256
+ throwIfCancelled(signal);
1257
+ const documentId = targetOf(options);
1258
+ const { asset, binary } = assetOf(assetId);
1259
+ assertMayPlace(documentId, "stamp.armAsset");
1260
+ const placement = await ctx.cancellable(signal, materializeForPlacement(documentId, asset, binary));
1261
+ throwIfCancelled(signal);
1262
+ await ctx.forDocument(AnnotationToken, documentId).stamps.arm({
1263
+ ...stampPayload(asset, placement, placement !== binary),
1264
+ targetWidth: options?.targetWidth
1265
+ }, { signal });
1266
+ ctx.state.update(armAsset, documentId, assetId);
1267
+ };
1268
+ const getArmedAsset = (documentId) => {
1269
+ const id = documentIdOf(documentId);
1270
+ const assetId = id === null ? void 0 : ctx.state.get().armed[id];
1271
+ if (id === null || assetId === void 0) return null;
1272
+ if (!ctx.tryForDocument(AnnotationToken$1, id)?.stamps.isArmed()) return null;
1273
+ return ctx.state.get().assets[assetId] ?? null;
1274
+ };
1275
+ const disarm = (documentId) => {
1276
+ const id = documentIdOf(documentId);
1277
+ if (id === null) return;
1278
+ ctx.tryForDocument(AnnotationToken, id)?.stamps.disarm();
1279
+ ctx.state.update(disarmDocuments, [id]);
1280
+ };
1281
+ /** Place on one document, its permission already checked. */
1282
+ const placeOn = async (documentId, assetId, placement, signal) => {
1283
+ const { asset, binary } = assetOf(assetId);
1284
+ const materialized = await ctx.cancellable(signal, materializeForPlacement(documentId, asset, binary));
1285
+ throwIfCancelled(signal);
1286
+ return ctx.forDocument(AnnotationToken, documentId).stamps.place(stampPayload(asset, materialized, materialized !== binary), placement, { signal });
491
1287
  };
1288
+ const placeAsset = async (assetId, placement, options) => {
1289
+ throwIfCancelled(options?.signal);
1290
+ const documentId = targetOf(options);
1291
+ assetOf(assetId);
1292
+ assertMayPlace(documentId, "stamp.placeAsset");
1293
+ return placeOn(documentId, assetId, placement, options?.signal);
1294
+ };
1295
+ const placeAssetOnPages = async (assetId, pages, placement, options) => {
1296
+ const signal = options?.signal;
1297
+ throwIfCancelled(signal);
1298
+ const documentId = targetOf(options);
1299
+ assetOf(assetId);
1300
+ assertMayPlace(documentId, "stamp.placeAssetOnPages");
1301
+ const targetPages = pages === "all" ? ctx.get(DocumentsToken).listPages(documentId).map((page) => page.ref) : pages.map((page) => pageOf(documentId, page).ref);
1302
+ const applied = [];
1303
+ const failed = [];
1304
+ for (const page of targetPages) try {
1305
+ const placed = await placeOn(documentId, assetId, {
1306
+ ...placement,
1307
+ page
1308
+ }, signal);
1309
+ applied.push(placed.annotation);
1310
+ } catch (error) {
1311
+ const refused = toPluginError("stamp", error);
1312
+ if (refused.code === "operation-cancelled") throw refused;
1313
+ failed.push({
1314
+ ref: page,
1315
+ error: toPluginErrorInfo(refused)
1316
+ });
1317
+ }
1318
+ return {
1319
+ applied,
1320
+ skipped: [],
1321
+ failed
1322
+ };
1323
+ };
1324
+ return { api: {
1325
+ armAsset: verb(armAsset$1),
1326
+ disarm,
1327
+ getArmedAsset,
1328
+ placeAsset: verb(placeAsset),
1329
+ placeAssetOnPages: verb(placeAssetOnPages)
1330
+ } };
492
1331
  }
493
1332
  //#endregion
494
- //#region src/reducer.ts
495
- const initialStampState = () => ({
496
- libraries: {},
497
- libraryOrder: [],
498
- assets: {}
499
- });
500
- /** Pure and serializable (kernel rule 1) — descriptors only; the bytes and
501
- * previews live in the capability and never enter the store. */
502
- const stampReducer = (state, action) => {
503
- switch (action.type) {
504
- case "LIBRARY_ADDED": return {
505
- ...state,
506
- libraries: {
507
- ...state.libraries,
508
- [action.library.id]: action.library
509
- },
510
- libraryOrder: [...state.libraryOrder, action.library.id]
511
- };
512
- case "LIBRARY_REMOVED": {
513
- const library = state.libraries[action.libraryId];
514
- if (!library) return state;
515
- const libraries = { ...state.libraries };
516
- delete libraries[action.libraryId];
517
- const assets = { ...state.assets };
518
- for (const id of library.assetIds) delete assets[id];
519
- return {
520
- ...state,
521
- libraries,
522
- libraryOrder: state.libraryOrder.filter((id) => id !== action.libraryId),
523
- assets
524
- };
525
- }
526
- case "ASSET_ADDED": {
527
- const library = state.libraries[action.asset.libraryId];
528
- if (!library) return state;
529
- return {
530
- ...state,
531
- assets: {
532
- ...state.assets,
533
- [action.asset.id]: action.asset
534
- },
535
- libraries: {
536
- ...state.libraries,
537
- [library.id]: {
538
- ...library,
539
- assetIds: [...library.assetIds, action.asset.id]
540
- }
541
- }
542
- };
1333
+ //#region src/controller.ts
1334
+ /**
1335
+ * The stamp controller: the composition root. It builds the plugin's
1336
+ * services once, wires each area with the services it declares, and
1337
+ * assembles the capability from the areas' API slices. Every verb and read
1338
+ * has a home in `read/` or `write/`; the one state-change event is derived
1339
+ * here.
1340
+ */
1341
+ function createStampController(ctx) {
1342
+ const services = createServices(ctx);
1343
+ const { events } = services;
1344
+ const settings = ctx.settings();
1345
+ ctx.state.onChange(({ previous, next }) => {
1346
+ if (previous.armed === next.armed) return;
1347
+ const documentIds = /* @__PURE__ */ new Set([...Object.keys(previous.armed), ...Object.keys(next.armed)]);
1348
+ for (const documentId of documentIds) {
1349
+ const assetId = next.armed[documentId];
1350
+ if (previous.armed[documentId] === assetId) continue;
1351
+ events.armChanged.emit({
1352
+ documentId,
1353
+ asset: assetId === void 0 ? null : next.assets[assetId] ?? null
1354
+ });
543
1355
  }
544
- case "ASSET_REMOVED": {
545
- const asset = state.assets[action.assetId];
546
- if (!asset) return state;
547
- const assets = { ...state.assets };
548
- delete assets[action.assetId];
549
- const library = state.libraries[asset.libraryId];
550
- return {
551
- ...state,
552
- assets,
553
- libraries: library ? {
554
- ...state.libraries,
555
- [library.id]: {
556
- ...library,
557
- assetIds: library.assetIds.filter((id) => id !== action.assetId)
558
- }
559
- } : state.libraries
560
- };
1356
+ });
1357
+ const catalog = createCatalog(ctx, services);
1358
+ const marks = createMarks(services);
1359
+ const libraries = createLibraryWrites(ctx, services);
1360
+ const assets = createAssetWrites(ctx, services, marks, libraries, catalog);
1361
+ const placement = createPlacement(ctx, services, catalog);
1362
+ return { api: composeApi("stamp", [
1363
+ settings.api,
1364
+ catalog.api,
1365
+ libraries.api,
1366
+ assets.api,
1367
+ placement.api,
1368
+ {
1369
+ onLibraryChanged: events.libraryChanged.on,
1370
+ onLibraryCreated: events.libraryCreated.on,
1371
+ onLibraryUpdated: events.libraryUpdated.on,
1372
+ onLibraryDeleted: events.libraryDeleted.on,
1373
+ onAssetCreated: events.assetCreated.on,
1374
+ onAssetUpdated: events.assetUpdated.on,
1375
+ onAssetDeleted: events.assetDeleted.on,
1376
+ onArmChanged: events.armChanged.on
561
1377
  }
562
- default: return state;
563
- }
564
- };
565
- //#endregion
566
- //#region src/types.ts
567
- const StampToken = createCapabilityToken("stamp");
1378
+ ]) };
1379
+ }
568
1380
  //#endregion
569
1381
  //#region src/stamp.plugin.ts
570
1382
  /**
571
- * The stamp plugin. WORKSPACE-scoped: libraries are shared across every open
572
- * document; placement names its document explicitly (`armAsset(documentId, …)`)
573
- * and delegates to that document's annotation plugin — no hard `requires`,
574
- * because the annotation token is document-scoped and resolved lazily per
575
- * placement (a viewer without the annotation plugin fails at the arm call,
576
- * with the kernel's own missing-capability error).
1383
+ * Stamp libraries and assets. Workspace-scoped: libraries outlive any one
1384
+ * document; placement targets a document through its annotation plugin.
1385
+ * `config` is the settings the app registers, over {@link STAMP_DEFAULTS}.
577
1386
  */
578
- const stampPlugin = (config = {}) => definePlugin({
1387
+ const stampPlugin = (config) => definePlugin({
579
1388
  id: "stamp",
580
1389
  token: StampToken,
581
1390
  scope: "workspace",
582
- initialState: initialStampState,
583
- reduce: stampReducer,
584
- capability: (ctx) => createStampCapability(ctx, config)
1391
+ optional: [AnnotationToken, ActionsToken],
1392
+ state: initialStampModel,
1393
+ settings: {
1394
+ defaults: STAMP_DEFAULTS,
1395
+ registered: config,
1396
+ whole: ["assetEngine", "fonts"]
1397
+ },
1398
+ create: createStampController,
1399
+ inScope: (stamp, documentId) => {
1400
+ const scoped = (options) => ({
1401
+ ...options,
1402
+ documentId: options?.documentId ?? documentId
1403
+ });
1404
+ return {
1405
+ ...stamp,
1406
+ createAssetFromAnnotations: (page, refs, input, options) => stamp.createAssetFromAnnotations(page, refs, input, scoped(options)),
1407
+ armAsset: (assetId, options) => stamp.armAsset(assetId, scoped(options)),
1408
+ disarm: (target = documentId) => stamp.disarm(target),
1409
+ getArmedAsset: (target = documentId) => stamp.getArmedAsset(target),
1410
+ placeAsset: (assetId, placement, options) => stamp.placeAsset(assetId, placement, scoped(options)),
1411
+ placeAssetOnPages: (assetId, pages, placement, options) => stamp.placeAssetOnPages(assetId, pages, placement, scoped(options)),
1412
+ canPlace: (target = documentId) => stamp.canPlace(target),
1413
+ canCreateFromAnnotations: (target = documentId) => stamp.canCreateFromAnnotations(target)
1414
+ };
1415
+ }
585
1416
  });
586
1417
  //#endregion
587
- export { StampToken, stampPlugin };
1418
+ //#region src/state.ts
1419
+ /**
1420
+ * The stamps page's State table as code: what `useStampState()` returns, and
1421
+ * the same fields in every other framework. It reads the document in scope,
1422
+ * else the active one. The libraries and their stamps are not here:
1423
+ * `useStampLibraries()` and `useStampAssets()` read them, so a component that
1424
+ * only shows the armed stamp doesn't re-render when a library changes.
1425
+ */
1426
+ const stampState = defineState(StampToken, {
1427
+ read: (stamp) => ({ armedAsset: stamp.getArmedAsset() }),
1428
+ empty: { armedAsset: null }
1429
+ });
1430
+ //#endregion
1431
+ //#region src/persistence.ts
1432
+ /** An in-memory store, for tests and SSR. */
1433
+ function memoryStampStore() {
1434
+ const rows = /* @__PURE__ */ new Map();
1435
+ return {
1436
+ list: async () => [...rows.entries()].map(([id, bytes]) => ({
1437
+ id,
1438
+ bytes
1439
+ })),
1440
+ put: async (id, bytes) => {
1441
+ rows.set(id, new Uint8Array(bytes));
1442
+ },
1443
+ delete: async (id) => {
1444
+ rows.delete(id);
1445
+ }
1446
+ };
1447
+ }
1448
+ /**
1449
+ * Bring every stored library back: each PDF is imported as-is (its title,
1450
+ * registry, and PieceInfo id come from the file; the store's key is only a
1451
+ * hint). Call once at boot, before seeding defaults, so "already has
1452
+ * libraries" means the user's own.
1453
+ */
1454
+ async function restoreStampLibraries(stamp, store) {
1455
+ const restored = [];
1456
+ for (const { id, bytes } of await store.list()) try {
1457
+ restored.push((await stamp.importLibrary(bytes)).library.id);
1458
+ } catch (error) {
1459
+ globalThis.console?.warn(`[stamp] stored library '${id}' could not be restored:`, error);
1460
+ }
1461
+ return restored;
1462
+ }
1463
+ /**
1464
+ * Keep the store in sync from now on: every canonical change saves the
1465
+ * library's PDF, a removal deletes it. `except` names libraries never to
1466
+ * persist (the bundled default set, typically). Returns the unsubscribe;
1467
+ * work already asked for still finishes.
1468
+ *
1469
+ * Each library has one line of store work, so saves never overlap and a
1470
+ * delete never lands under a late save. The changes of one burst (one call
1471
+ * into the plugin) are one save; the changes made while a save runs are one
1472
+ * more after it.
1473
+ */
1474
+ function persistStampLibraries(stamp, store, options = {}) {
1475
+ const except = new Set(options.except ?? []);
1476
+ /** Per library: the store step waiting or running, and the one to follow it. */
1477
+ const lines = /* @__PURE__ */ new Map();
1478
+ const run = (libraryId, step) => {
1479
+ const line = lines.get(libraryId);
1480
+ if (line) {
1481
+ if (line.started) line.next = step;
1482
+ else line.step = step;
1483
+ return;
1484
+ }
1485
+ const fresh = {
1486
+ step,
1487
+ started: false,
1488
+ next: null
1489
+ };
1490
+ lines.set(libraryId, fresh);
1491
+ Promise.resolve().then(async () => {
1492
+ fresh.started = true;
1493
+ try {
1494
+ if (fresh.step === "save") await store.put(libraryId, await stamp.exportLibrary(libraryId));
1495
+ else await store.delete(libraryId);
1496
+ } catch (error) {
1497
+ const doing = fresh.step === "save" ? "persisting" : "deleting stored";
1498
+ globalThis.console?.warn(`[stamp] ${doing} library '${libraryId}' failed:`, error);
1499
+ }
1500
+ lines.delete(libraryId);
1501
+ if (fresh.next) run(libraryId, fresh.next);
1502
+ });
1503
+ };
1504
+ return stamp.onLibraryChanged(({ libraryId, reason }) => {
1505
+ if (except.has(libraryId)) return;
1506
+ run(libraryId, reason === "removed" ? "delete" : "save");
1507
+ });
1508
+ }
1509
+ //#endregion
1510
+ export { DEFAULT_LIBRARY_KIND, STAMP_DEFAULTS, StampToken, memoryStampStore, persistStampLibraries, restoreStampLibraries, stampPlugin, stampState };
588
1511
 
589
1512
  //# sourceMappingURL=index.js.map