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