@copio/sdk 0.0.0-stage → 0.1.1

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.
Files changed (149) hide show
  1. package/README.md +204 -2
  2. package/css/container.css +177 -0
  3. package/css/cropper.css +306 -0
  4. package/css/main.css +139 -0
  5. package/css/reset.css +204 -0
  6. package/css/shoelace.css +485 -0
  7. package/css/utils.css +689 -0
  8. package/dist/adapters/image/canvas2d-adapter.js +2 -0
  9. package/dist/adapters/image/canvas2d-adapter.js.map +7 -0
  10. package/dist/adapters/image/index.js +2 -0
  11. package/dist/adapters/image/index.js.map +7 -0
  12. package/dist/adapters/image/null-image-processor-adapter.js +2 -0
  13. package/dist/adapters/image/null-image-processor-adapter.js.map +7 -0
  14. package/dist/adapters/index.js +2 -0
  15. package/dist/adapters/index.js.map +7 -0
  16. package/dist/adapters/indexeddb-adapter.js +2 -0
  17. package/dist/adapters/indexeddb-adapter.js.map +7 -0
  18. package/dist/adapters/memory-adapter.js +2 -0
  19. package/dist/adapters/memory-adapter.js.map +7 -0
  20. package/dist/adapters/ocr/index.js +2 -0
  21. package/dist/adapters/ocr/index.js.map +7 -0
  22. package/dist/adapters/ocr/null-ocr-adapter.js +2 -0
  23. package/dist/adapters/ocr/null-ocr-adapter.js.map +7 -0
  24. package/dist/adapters/ocr/tesseract-wasm-adapter.js +2 -0
  25. package/dist/adapters/ocr/tesseract-wasm-adapter.js.map +7 -0
  26. package/dist/adapters/pdf/index.js +2 -0
  27. package/dist/adapters/pdf/index.js.map +7 -0
  28. package/dist/adapters/pdf/null-pdf-adapter.js +2 -0
  29. package/dist/adapters/pdf/null-pdf-adapter.js.map +7 -0
  30. package/dist/adapters/pdf/pdfkit-adapter.js +2 -0
  31. package/dist/adapters/pdf/pdfkit-adapter.js.map +7 -0
  32. package/dist/adapters/storage/index.js +2 -0
  33. package/dist/adapters/storage/index.js.map +7 -0
  34. package/dist/adapters/storage/indexeddb-adapter.js +2 -0
  35. package/dist/adapters/storage/indexeddb-adapter.js.map +7 -0
  36. package/dist/adapters/storage/memory-adapter.js +2 -0
  37. package/dist/adapters/storage/memory-adapter.js.map +7 -0
  38. package/dist/adapters/sync/index.js +2 -0
  39. package/dist/adapters/sync/index.js.map +7 -0
  40. package/dist/adapters/sync/null-sync-adapter.js +2 -0
  41. package/dist/adapters/sync/null-sync-adapter.js.map +7 -0
  42. package/dist/adapters/sync/peerjs-adapter.js +2 -0
  43. package/dist/adapters/sync/peerjs-adapter.js.map +7 -0
  44. package/dist/canvas-FAXPLPXN.js +2 -0
  45. package/dist/cdn.js +2770 -0
  46. package/dist/chunk-36F637QU.js +2 -0
  47. package/dist/chunk-4C666HHU.js +2 -0
  48. package/dist/chunk-4GEMGDRU.js +1 -0
  49. package/dist/chunk-4JPEWIT4.js +2 -0
  50. package/dist/chunk-A5G52Q2W.js +2 -0
  51. package/dist/chunk-B2EK6INF.js +2 -0
  52. package/dist/chunk-B5BEYYR2.js +8 -0
  53. package/dist/chunk-B7HT2X67.js +2 -0
  54. package/dist/chunk-BKZEOOH4.js +2 -0
  55. package/dist/chunk-CWCS22CQ.js +1 -0
  56. package/dist/chunk-DGGK5KEX.js +2 -0
  57. package/dist/chunk-E7JYVRJA.js +2 -0
  58. package/dist/chunk-G65H4ZTJ.js +2 -0
  59. package/dist/chunk-HN3336JN.js +2 -0
  60. package/dist/chunk-IUBYFIV6.js +12 -0
  61. package/dist/chunk-K6YP7EET.js +8 -0
  62. package/dist/chunk-K7RTGT3Q.js +2601 -0
  63. package/dist/chunk-KIMVF5UG.js +2 -0
  64. package/dist/chunk-LI54F6PA.js +2 -0
  65. package/dist/chunk-N4R55VRR.js +2 -0
  66. package/dist/chunk-N7Q34F2P.js +4 -0
  67. package/dist/chunk-OI4WCW7E.js +2 -0
  68. package/dist/chunk-PUJYN435.js +1 -0
  69. package/dist/chunk-PVNRK4OH.js +2 -0
  70. package/dist/chunk-QPUCXOOR.js +2 -0
  71. package/dist/chunk-SH4P4XSZ.js +2 -0
  72. package/dist/chunk-UCV3MQ6I.js +33 -0
  73. package/dist/chunk-V2FP4EEH.js +2 -0
  74. package/dist/chunk-V6E2SSSW.js +1 -0
  75. package/dist/chunk-XEN5VKAV.js +19 -0
  76. package/dist/chunk-YHLOPPXM.js +2 -0
  77. package/dist/core.js +2 -0
  78. package/dist/custom-elements.json +4779 -0
  79. package/dist/export.js +2 -0
  80. package/dist/fs-HJ6WWW73.js +2 -0
  81. package/dist/http-FKJJMT2N.js +2 -0
  82. package/dist/https-MUBFLDZM.js +2 -0
  83. package/dist/index.js +99 -0
  84. package/dist/ocr.js +2 -0
  85. package/dist/path2d-QWN6DFCC.js +2 -0
  86. package/dist/scanner.js +2631 -0
  87. package/dist/sync.js +2 -0
  88. package/dist/types/js/adapters/image/canvas2d-adapter.d.ts +42 -0
  89. package/dist/types/js/adapters/image/image-processor-port.d.ts +41 -0
  90. package/dist/types/js/adapters/image/index.d.ts +3 -0
  91. package/dist/types/js/adapters/image/null-image-processor-adapter.d.ts +13 -0
  92. package/dist/types/js/adapters/ocr/index.d.ts +3 -0
  93. package/dist/types/js/adapters/ocr/null-ocr-adapter.d.ts +39 -0
  94. package/dist/types/js/adapters/ocr/ocr-port.d.ts +139 -0
  95. package/dist/types/js/adapters/ocr/tesseract-wasm-adapter.d.ts +40 -0
  96. package/dist/types/js/adapters/pdf/index.d.ts +3 -0
  97. package/dist/types/js/adapters/pdf/null-pdf-adapter.d.ts +23 -0
  98. package/dist/types/js/adapters/pdf/pdf-port.d.ts +21 -0
  99. package/dist/types/js/adapters/pdf/pdfkit-adapter.d.ts +16 -0
  100. package/dist/types/js/adapters/storage/index.d.ts +22 -0
  101. package/dist/types/js/adapters/storage/indexeddb-adapter.d.ts +109 -0
  102. package/dist/types/js/adapters/storage/memory-adapter.d.ts +101 -0
  103. package/dist/types/js/adapters/storage/storage-port.d.ts +113 -0
  104. package/dist/types/js/adapters/sync/index.d.ts +3 -0
  105. package/dist/types/js/adapters/sync/null-sync-adapter.d.ts +14 -0
  106. package/dist/types/js/adapters/sync/peerjs-adapter.d.ts +16 -0
  107. package/dist/types/js/adapters/sync/sync-port.d.ts +18 -0
  108. package/dist/types/js/components/copio-header.d.ts +19 -0
  109. package/dist/types/js/components/copio-loader.d.ts +6 -0
  110. package/dist/types/js/core/store.d.ts +2 -0
  111. package/dist/types/js/routes/add-edit/copio-add-edit-dialog.d.ts +9 -0
  112. package/dist/types/js/routes/doc/copio-carousel.d.ts +43 -0
  113. package/dist/types/js/routes/doc/copio-images.d.ts +37 -0
  114. package/dist/types/js/routes/home/copio-row.d.ts +49 -0
  115. package/dist/types/js/routes/ocr/copio-doc-ocr-dialog.d.ts +97 -0
  116. package/dist/types/js/routes/sync/copio-sync-dialog.d.ts +13 -0
  117. package/dist/types/js/services/doc-repository.d.ts +233 -0
  118. package/dist/types/js/services/export-utils.d.ts +42 -0
  119. package/dist/types/js/services/ice-servers.d.ts +1 -0
  120. package/dist/types/js/services/notify.d.ts +82 -0
  121. package/dist/types/js/services/ocr-service.d.ts +64 -0
  122. package/dist/types/js/services/sync-service.d.ts +11 -0
  123. package/dist/types/js/styles/cropper-styles.d.ts +5 -0
  124. package/dist/types/js/utils/module-loader.d.ts +76 -0
  125. package/dist/types/js/utils/pdf-utils.d.ts +7 -0
  126. package/dist/types/js/utils/utils.d.ts +54 -0
  127. package/dist/types/sdk/cdn.d.ts +7 -0
  128. package/dist/types/sdk/core.d.ts +310 -0
  129. package/dist/types/sdk/elements.d.ts +25 -0
  130. package/dist/types/sdk/events.d.ts +227 -0
  131. package/dist/types/sdk/index.d.ts +37 -0
  132. package/dist/types/sdk/license.d.ts +12 -0
  133. package/dist/types/sdk/models.d.ts +174 -0
  134. package/dist/types/sdk/scanner.d.ts +68 -0
  135. package/dist/types/sdk/styles.d.ts +21 -0
  136. package/dist/types/sdk/sync.d.ts +7 -0
  137. package/dist/types/sdk/version.d.ts +2 -0
  138. package/dist/url-ABJ6S2Y6.js +2 -0
  139. package/package.json +73 -4
  140. package/sdk/cdn.js +13 -0
  141. package/sdk/core.js +961 -0
  142. package/sdk/events.js +99 -0
  143. package/sdk/index.js +137 -0
  144. package/sdk/license.js +28 -0
  145. package/sdk/models.js +177 -0
  146. package/sdk/scanner.js +1597 -0
  147. package/sdk/styles.js +1236 -0
  148. package/sdk/sync.js +12 -0
  149. package/sdk/version.js +7 -0
package/sdk/core.js ADDED
@@ -0,0 +1,961 @@
1
+ /**
2
+ * Copio Headless Core Domain & Storage (CPO-035, CPO-037, CPO-045, CPO-061)
3
+ *
4
+ * Hexagonal Core: Pure JS domain use cases, models, and driven ports.
5
+ * Zero DOM, zero Lit, zero browser UI globals.
6
+ *
7
+ * Outbound driven ports (StoragePort, PdfPort, OcrPort, SyncPort) are decoupled
8
+ * via pluggable service adapters, keeping core strictly under 80KB.
9
+ */
10
+ import { DocRepository, docRepository } from '../js/services/doc-repository.js';
11
+ import {
12
+ StoragePort,
13
+ MemoryStorageAdapter,
14
+ IndexedDbStorageAdapter,
15
+ createDefaultAdapter,
16
+ } from '../js/adapters/storage/index.js';
17
+ import {
18
+ randomId,
19
+ fileToBase64,
20
+ thresholdSrc,
21
+ rotateSrc,
22
+ getCroppedSrc,
23
+ extractExif,
24
+ applyEdits,
25
+ normalizeEdits,
26
+ renderEditsToCanvas,
27
+ applySauvolaToImageData,
28
+ } from '../js/utils/utils.js';
29
+ import { setAssetBase, getAssetBase } from '../js/utils/module-loader.js';
30
+ import { BUILD_DATE, VERSION } from './version.js';
31
+ import { NullOcrAdapter } from '../js/adapters/ocr/null-ocr-adapter.js';
32
+ import { NullPdfAdapter } from '../js/adapters/pdf/null-pdf-adapter.js';
33
+ import {
34
+ ImageProcessorPort,
35
+ Canvas2DAdapter,
36
+ NullImageProcessorAdapter,
37
+ } from '../js/adapters/image/index.js';
38
+ import {
39
+ Document,
40
+ Page,
41
+ ScanSession,
42
+ normalizeEditStack,
43
+ hasActiveEdits,
44
+ } from './models.js';
45
+
46
+ export const DEFAULT_FEATURES = ['crop', 'rotate', 'filter', 'ocr', 'export', 'sync'];
47
+ export const DEFAULT_EXPORT_FORMATS = ['pdf', 'zip', 'png', 'jpg'];
48
+ export const DEFAULT_OCR_LANGUAGES = ['eng'];
49
+
50
+ const registeredServices = {};
51
+
52
+ /**
53
+ * Register a pluggable service adapter for headless ports (export, ocr, sync, pdf).
54
+ * @param {string} name
55
+ * @param {any} service
56
+ */
57
+ export function registerService(name, service) {
58
+ if (!name || !service) return;
59
+ registeredServices[name] = service;
60
+ if (typeof globalThis !== 'undefined') {
61
+ globalThis.__copio_services__ = globalThis.__copio_services__ || {};
62
+ globalThis.__copio_services__[name] = service;
63
+ }
64
+ }
65
+
66
+ /**
67
+ * Retrieve a registered service adapter.
68
+ * @param {string} name
69
+ * @returns {any}
70
+ */
71
+ export function getRegisteredService(name) {
72
+ if (registeredServices[name]) return registeredServices[name];
73
+ if (typeof globalThis !== 'undefined' && globalThis.__copio_services__?.[name]) {
74
+ return globalThis.__copio_services__[name];
75
+ }
76
+ return null;
77
+ }
78
+
79
+ /**
80
+ * Normalizes features input (space/comma separated string or array) into a Set.
81
+ * @param {string|string[]|Set<string>} features
82
+ * @returns {Set<string>}
83
+ */
84
+ function normalizeFeatures(features) {
85
+ if (!features) return new Set(DEFAULT_FEATURES);
86
+ if (features instanceof Set) return new Set(features);
87
+ if (Array.isArray(features)) {
88
+ return new Set(features.map((f) => String(f).trim().toLowerCase()).filter(Boolean));
89
+ }
90
+ if (typeof features === 'string') {
91
+ return new Set(
92
+ features
93
+ .split(/[\s,]+/)
94
+ .map((f) => f.trim().toLowerCase())
95
+ .filter(Boolean),
96
+ );
97
+ }
98
+ return new Set(DEFAULT_FEATURES);
99
+ }
100
+
101
+ /**
102
+ * Normalizes array or comma-separated string list.
103
+ * @param {string|string[]} val
104
+ * @param {string[]} defaultVal
105
+ * @returns {string[]}
106
+ */
107
+ function normalizeList(val, defaultVal) {
108
+ if (!val) return [...defaultVal];
109
+ if (Array.isArray(val)) return val.map((v) => String(v).trim().toLowerCase()).filter(Boolean);
110
+ if (typeof val === 'string') {
111
+ return val
112
+ .split(/[\s,]+/)
113
+ .map((v) => v.trim().toLowerCase())
114
+ .filter(Boolean);
115
+ }
116
+ return [...defaultVal];
117
+ }
118
+
119
+ /**
120
+ * Headless Copio Engine driving port.
121
+ */
122
+ export class CopioEngine {
123
+ #features = new Set(DEFAULT_FEATURES);
124
+ #exportFormats = [...DEFAULT_EXPORT_FORMATS];
125
+ #ocrLanguages = [...DEFAULT_OCR_LANGUAGES];
126
+ #maxPages = 0;
127
+ #licenseKey = '';
128
+ #storage = null;
129
+ #repository = null;
130
+ #services = {};
131
+ #ocr = true;
132
+ #pdf = true;
133
+ #imageProcessor = null;
134
+ #undoStack = new Map();
135
+ #redoStack = new Map();
136
+
137
+ /**
138
+ * @param {Object} [options]
139
+ * @param {StoragePort} [options.storage] - Persistence adapter implementing StoragePort
140
+ * @param {DocRepository} [options.repository] - Headless document repository instance
141
+ * @param {Object} [options.services] - Custom driven adapters ({ export, ocr, sync, pdf, imageProcessor })
142
+ * @param {ImageProcessorPort} [options.imageProcessor] - Image transform adapter
143
+ * @param {string|string[]} [options.features] - Enabled feature set ('crop rotate filter ocr export sync')
144
+ * @param {string|string[]} [options.exportFormats] - Supported export formats ('pdf', 'zip', 'png', 'jpg')
145
+ * @param {string|string[]} [options.ocrLanguages] - Configured OCR languages ('eng', 'deu', etc.)
146
+ * @param {number} [options.maxPages=0] - Maximum allowed pages (0 = unlimited)
147
+ * @param {string} [options.assetBase] - Base URL for lazy-loaded assets and workers
148
+ * @param {string} [options.licenseKey] - SDK commercial license key
149
+ * @param {boolean} [options.ocr=true] - Whether OCR module is enabled (developer opt-in CPO-042)
150
+ * @param {boolean} [options.pdf=true] - Whether PDF module is enabled (developer opt-in CPO-042)
151
+ */
152
+ constructor(options = {}) {
153
+ this.#storage = options.storage || createDefaultAdapter(/** @type {any} */ (options));
154
+ this.#repository = options.repository || new DocRepository(this.#storage);
155
+
156
+ if (options.services) {
157
+ this.#services = { ...options.services };
158
+ }
159
+ if (options.imageProcessor) {
160
+ this.#imageProcessor = options.imageProcessor;
161
+ this.#services.imageProcessor = options.imageProcessor;
162
+ } else if (this.getService('imageProcessor')) {
163
+ this.#imageProcessor = this.getService('imageProcessor');
164
+ } else if (typeof document !== 'undefined') {
165
+ this.#imageProcessor = new Canvas2DAdapter();
166
+ } else {
167
+ this.#imageProcessor = new NullImageProcessorAdapter();
168
+ }
169
+ if (options.features !== undefined) {
170
+ this.setFeatures(options.features);
171
+ }
172
+ if (options.exportFormats !== undefined) {
173
+ this.#exportFormats = normalizeList(options.exportFormats, DEFAULT_EXPORT_FORMATS);
174
+ }
175
+ if (options.ocrLanguages !== undefined) {
176
+ this.#ocrLanguages = normalizeList(options.ocrLanguages, DEFAULT_OCR_LANGUAGES);
177
+ }
178
+ if (options.maxPages !== undefined) {
179
+ this.#maxPages = Math.max(0, Number(options.maxPages) || 0);
180
+ }
181
+ if (options.assetBase !== undefined) {
182
+ setAssetBase(options.assetBase);
183
+ }
184
+ if (options.licenseKey !== undefined) {
185
+ this.#licenseKey = String(options.licenseKey || '');
186
+ }
187
+ if (options.ocr !== undefined) {
188
+ this.ocr = Boolean(options.ocr);
189
+ } else if (options.features !== undefined && !this.hasFeature('ocr')) {
190
+ this.ocr = false;
191
+ }
192
+ if (options.pdf !== undefined) {
193
+ this.pdf = Boolean(options.pdf);
194
+ } else if (options.exportFormats !== undefined && !this.#exportFormats.includes('pdf')) {
195
+ this.pdf = false;
196
+ }
197
+ }
198
+
199
+ /**
200
+ * Initializes the underlying storage adapter.
201
+ * @returns {Promise<{ kind: string, persistent: boolean }>}
202
+ */
203
+ async init() {
204
+ return this.#storage.init();
205
+ }
206
+
207
+ // --- Configuration & Feature Gating API (CPO-035) ---
208
+
209
+ /**
210
+ * Register or override an adapter service for this engine instance.
211
+ * @param {string} name
212
+ * @param {any} service
213
+ */
214
+ setService(name, service) {
215
+ this.#services[name] = service;
216
+ }
217
+
218
+ /**
219
+ * Retrieve an adapter service instance.
220
+ * @param {string} name
221
+ * @returns {any}
222
+ */
223
+ getService(name) {
224
+ return this.#services[name] || getRegisteredService(name);
225
+ }
226
+
227
+ /**
228
+ * Check if a specific feature is enabled.
229
+ * @param {string} featureName
230
+ * @returns {boolean}
231
+ */
232
+ hasFeature(featureName) {
233
+ if (!featureName) return false;
234
+ return this.#features.has(String(featureName).trim().toLowerCase());
235
+ }
236
+
237
+ /**
238
+ * Returns list of currently enabled features.
239
+ * @returns {string[]}
240
+ */
241
+ get features() {
242
+ return Array.from(this.#features);
243
+ }
244
+
245
+ /**
246
+ * Set enabled features.
247
+ * @param {string|string[]|Set<string>} features
248
+ */
249
+ setFeatures(features) {
250
+ this.#features = normalizeFeatures(features);
251
+ if (!this.hasFeature('ocr')) {
252
+ this.#ocr = false;
253
+ this.setService('ocr', new NullOcrAdapter());
254
+ } else {
255
+ this.#ocr = true;
256
+ if (this.getService('ocr') instanceof NullOcrAdapter) {
257
+ this.setService('ocr', getRegisteredService('ocr'));
258
+ }
259
+ }
260
+ }
261
+
262
+ /**
263
+ * Enable a specific feature.
264
+ * @param {string} featureName
265
+ */
266
+ enableFeature(featureName) {
267
+ if (featureName) {
268
+ const name = String(featureName).trim().toLowerCase();
269
+ this.#features.add(name);
270
+ if (name === 'ocr') {
271
+ this.#ocr = true;
272
+ if (this.getService('ocr') instanceof NullOcrAdapter) {
273
+ this.setService('ocr', getRegisteredService('ocr'));
274
+ }
275
+ }
276
+ }
277
+ }
278
+
279
+ /**
280
+ * Disable a specific feature.
281
+ * @param {string} featureName
282
+ */
283
+ disableFeature(featureName) {
284
+ if (featureName) {
285
+ const name = String(featureName).trim().toLowerCase();
286
+ this.#features.delete(name);
287
+ if (name === 'ocr') {
288
+ this.#ocr = false;
289
+ this.setService('ocr', new NullOcrAdapter());
290
+ }
291
+ }
292
+ }
293
+
294
+ /**
295
+ * Developer opt-in status for OCR heavy module (CPO-042).
296
+ * @type {boolean}
297
+ */
298
+ get ocr() {
299
+ return this.#ocr && this.hasFeature('ocr');
300
+ }
301
+
302
+ set ocr(enabled) {
303
+ this.#ocr = Boolean(enabled);
304
+ if (this.#ocr) {
305
+ this.enableFeature('ocr');
306
+ if (this.getService('ocr') instanceof NullOcrAdapter) {
307
+ this.setService('ocr', getRegisteredService('ocr'));
308
+ }
309
+ } else {
310
+ this.disableFeature('ocr');
311
+ this.setService('ocr', new NullOcrAdapter());
312
+ }
313
+ }
314
+
315
+ /**
316
+ * Developer opt-in status for PDF heavy module (CPO-042).
317
+ * @type {boolean}
318
+ */
319
+ get pdf() {
320
+ return this.#pdf && this.#exportFormats.includes('pdf');
321
+ }
322
+
323
+ set pdf(enabled) {
324
+ this.#pdf = Boolean(enabled);
325
+ if (this.#pdf) {
326
+ if (!this.#exportFormats.includes('pdf')) {
327
+ this.#exportFormats.push('pdf');
328
+ }
329
+ if (this.getService('pdf') instanceof NullPdfAdapter) {
330
+ this.setService('pdf', getRegisteredService('pdf'));
331
+ }
332
+ } else {
333
+ this.#exportFormats = this.#exportFormats.filter((f) => f !== 'pdf');
334
+ this.setService('pdf', new NullPdfAdapter());
335
+ }
336
+ }
337
+
338
+ /**
339
+ * Get supported export formats.
340
+ * @returns {string[]}
341
+ */
342
+ get exportFormats() {
343
+ return [...this.#exportFormats];
344
+ }
345
+
346
+ /**
347
+ * Set supported export formats.
348
+ * @param {string|string[]} formats
349
+ */
350
+ set exportFormats(formats) {
351
+ this.#exportFormats = normalizeList(formats, DEFAULT_EXPORT_FORMATS);
352
+ if (!this.#exportFormats.includes('pdf')) {
353
+ this.#pdf = false;
354
+ this.setService('pdf', new NullPdfAdapter());
355
+ } else {
356
+ this.#pdf = true;
357
+ if (this.getService('pdf') instanceof NullPdfAdapter) {
358
+ this.setService('pdf', getRegisteredService('pdf'));
359
+ }
360
+ }
361
+ }
362
+
363
+ /**
364
+ * Get configured OCR languages.
365
+ * @returns {string[]}
366
+ */
367
+ get ocrLanguages() {
368
+ return [...this.#ocrLanguages];
369
+ }
370
+
371
+ /**
372
+ * Set configured OCR languages.
373
+ * @param {string|string[]} langs
374
+ */
375
+ set ocrLanguages(langs) {
376
+ this.#ocrLanguages = normalizeList(langs, DEFAULT_OCR_LANGUAGES);
377
+ }
378
+
379
+ /**
380
+ * Maximum page limit (0 = unlimited).
381
+ * @returns {number}
382
+ */
383
+ get maxPages() {
384
+ return this.#maxPages;
385
+ }
386
+
387
+ /**
388
+ * Set maximum page limit.
389
+ * @param {number} limit
390
+ */
391
+ set maxPages(limit) {
392
+ this.#maxPages = Math.max(0, Number(limit) || 0);
393
+ }
394
+
395
+ /**
396
+ * Get asset base path.
397
+ * @returns {string}
398
+ */
399
+ get assetBase() {
400
+ return getAssetBase();
401
+ }
402
+
403
+ /**
404
+ * Set asset base path for lazy worker/WASM loading.
405
+ * @param {string} base
406
+ */
407
+ set assetBase(base) {
408
+ setAssetBase(base);
409
+ }
410
+
411
+ /**
412
+ * License key.
413
+ * @returns {string}
414
+ */
415
+ get licenseKey() {
416
+ return this.#licenseKey;
417
+ }
418
+
419
+ /**
420
+ * Set license key.
421
+ * @param {string} key
422
+ */
423
+ set licenseKey(key) {
424
+ this.#licenseKey = String(key || '');
425
+ }
426
+
427
+ /**
428
+ * Underlying StoragePort adapter.
429
+ * @returns {StoragePort}
430
+ */
431
+ get storage() {
432
+ return this.#storage;
433
+ }
434
+
435
+ /**
436
+ * Switch the underlying storage adapter.
437
+ * @param {StoragePort} newStorage
438
+ */
439
+ setStorage(newStorage) {
440
+ if (!newStorage) return;
441
+ this.#storage = newStorage;
442
+ this.#repository = new DocRepository(this.#storage);
443
+ }
444
+
445
+ #pushUndo(docId, action) {
446
+ if (!this.#undoStack.has(docId)) {
447
+ this.#undoStack.set(docId, []);
448
+ }
449
+ const stack = this.#undoStack.get(docId);
450
+ stack.push(action);
451
+ if (stack.length > 50) stack.shift();
452
+ if (this.#redoStack.has(docId)) {
453
+ this.#redoStack.get(docId).length = 0;
454
+ }
455
+ }
456
+
457
+ /**
458
+ * Current ImageProcessorPort adapter.
459
+ * @type {ImageProcessorPort}
460
+ */
461
+ get imageProcessor() {
462
+ return this.#imageProcessor;
463
+ }
464
+
465
+ setImageProcessor(processor) {
466
+ if (!processor) return;
467
+ this.#imageProcessor = processor;
468
+ this.setService('imageProcessor', processor);
469
+ }
470
+
471
+ /**
472
+ * Underlying document repository.
473
+ * @returns {DocRepository}
474
+ */
475
+ get docs() {
476
+ return this.#repository;
477
+ }
478
+
479
+ // --- Document Repository Delegation ---
480
+
481
+ async listDocuments() {
482
+ return this.#repository.listDocs();
483
+ }
484
+
485
+ async getDocument(id) {
486
+ return this.#repository.getDoc(id);
487
+ }
488
+
489
+ async createDocument(name, pages) {
490
+ return this.#repository.createDoc(name, pages);
491
+ }
492
+
493
+ async deleteDocument(id, options = {}) {
494
+ return this.#repository.deleteDoc(id, options);
495
+ }
496
+
497
+ async undoDeleteDocument(id) {
498
+ return this.#repository.undoDeleteDoc(id);
499
+ }
500
+
501
+ async renameDocument(id, name) {
502
+ return this.#repository.renameDoc(id, name);
503
+ }
504
+
505
+ async addPages(id, pages) {
506
+ return this.#repository.addPages(id, pages);
507
+ }
508
+
509
+ async deletePage(id, pageId, options = {}) {
510
+ this.#pushUndo(id, { type: 'delete', pageId });
511
+ return this.#repository.deletePage(id, pageId, options);
512
+ }
513
+
514
+ async undoDeletePage(id, pageId) {
515
+ return this.#repository.undoDeletePage(id, pageId);
516
+ }
517
+
518
+ async updatePage(id, pageId, updates) {
519
+ return this.#repository.updatePage(id, pageId, updates);
520
+ }
521
+
522
+ async reorderPages(id, pageIds) {
523
+ const doc = await this.getDocument(id);
524
+ const priorOrder = doc?.pages ? doc.pages.map((p) => p.id) : [];
525
+ this.#pushUndo(id, { type: 'reorder', priorOrder, newOrder: [...pageIds] });
526
+ return this.#repository.reorderPages(id, pageIds);
527
+ }
528
+
529
+ async #resolveDocId(docId) {
530
+ if (docId) return docId;
531
+ const docs = await this.listDocuments();
532
+ return docs.length > 0 ? docs[0].id : null;
533
+ }
534
+
535
+ /**
536
+ * Applies non-destructive edits to a document page (CPO-011, CPO-045).
537
+ * Generates derived src via ImageProcessorPort while keeping originalSrc intact.
538
+ *
539
+ * @param {string} docId
540
+ * @param {string} pageId
541
+ * @param {Object} edits
542
+ * @returns {Promise<Object>}
543
+ */
544
+ async applyEdit(docId, pageId, edits) {
545
+ const targetDocId = await this.#resolveDocId(docId);
546
+ const doc = targetDocId ? await this.getDocument(targetDocId) : null;
547
+ if (!doc || !doc.pages) {
548
+ throw new Error(`Document with ID "${targetDocId || docId}" not found`);
549
+ }
550
+ const page = doc.pages.find((p) => p.id === pageId);
551
+ if (!page) {
552
+ throw new Error(`Page with ID "${pageId}" not found in document "${targetDocId}"`);
553
+ }
554
+
555
+ const priorEdits = { ...(page.edits || { crop: null, rotate: 0, filter: 'none' }) };
556
+ const priorSrc = page.src;
557
+ const mergedEdits = normalizeEditStack({ ...priorEdits, ...edits });
558
+ const originalSrc = page.originalSrc || page.src;
559
+
560
+ let derivedSrc = originalSrc;
561
+ if (this.#imageProcessor) {
562
+ derivedSrc = await this.#imageProcessor.renderEdits(originalSrc, mergedEdits);
563
+ }
564
+
565
+ await this.updatePage(targetDocId, pageId, {
566
+ originalSrc,
567
+ src: derivedSrc,
568
+ edits: mergedEdits,
569
+ });
570
+
571
+ this.#pushUndo(targetDocId, {
572
+ type: 'edit',
573
+ pageId,
574
+ priorEdits,
575
+ priorSrc,
576
+ newEdits: mergedEdits,
577
+ newSrc: derivedSrc,
578
+ });
579
+
580
+ return {
581
+ ...page,
582
+ originalSrc,
583
+ src: derivedSrc,
584
+ edits: mergedEdits,
585
+ };
586
+ }
587
+
588
+ /**
589
+ * Reverts the most recent operation on a document (CPO-016, CPO-045).
590
+ * @param {string} docId
591
+ * @returns {Promise<Object|null>}
592
+ */
593
+ async undo(docId) {
594
+ const targetDocId = await this.#resolveDocId(docId);
595
+ const stack = targetDocId ? this.#undoStack.get(targetDocId) : null;
596
+ if (!stack || stack.length === 0) return null;
597
+ const action = stack.pop();
598
+
599
+ if (!this.#redoStack.has(targetDocId)) {
600
+ this.#redoStack.set(targetDocId, []);
601
+ }
602
+ this.#redoStack.get(targetDocId).push(action);
603
+
604
+ if (action.type === 'edit') {
605
+ await this.updatePage(targetDocId, action.pageId, {
606
+ edits: action.priorEdits,
607
+ src: action.priorSrc,
608
+ });
609
+ return { type: 'edit', pageId: action.pageId, restoredEdits: action.priorEdits };
610
+ } else if (action.type === 'delete') {
611
+ await this.undoDeletePage(targetDocId, action.pageId);
612
+ return { type: 'delete', pageId: action.pageId };
613
+ } else if (action.type === 'reorder') {
614
+ await this.#repository.reorderPages(targetDocId, action.priorOrder);
615
+ return { type: 'reorder', priorOrder: action.priorOrder };
616
+ }
617
+ return action;
618
+ }
619
+
620
+ /**
621
+ * Re-applies the most recently reverted operation on a document (CPO-045).
622
+ * @param {string} docId
623
+ * @returns {Promise<Object|null>}
624
+ */
625
+ async redo(docId) {
626
+ const targetDocId = await this.#resolveDocId(docId);
627
+ const stack = targetDocId ? this.#redoStack.get(targetDocId) : null;
628
+ if (!stack || stack.length === 0) return null;
629
+ const action = stack.pop();
630
+
631
+ if (!this.#undoStack.has(targetDocId)) {
632
+ this.#undoStack.set(targetDocId, []);
633
+ }
634
+ this.#undoStack.get(targetDocId).push(action);
635
+
636
+ if (action.type === 'edit') {
637
+ await this.updatePage(targetDocId, action.pageId, {
638
+ edits: action.newEdits,
639
+ src: action.newSrc,
640
+ });
641
+ return { type: 'edit', pageId: action.pageId, appliedEdits: action.newEdits };
642
+ } else if (action.type === 'delete') {
643
+ await this.deletePage(targetDocId, action.pageId);
644
+ return { type: 'delete', pageId: action.pageId };
645
+ } else if (action.type === 'reorder') {
646
+ await this.reorderPages(targetDocId, action.newOrder);
647
+ return { type: 'reorder', newOrder: action.newOrder };
648
+ }
649
+ return action;
650
+ }
651
+
652
+ subscribe(callback) {
653
+ return this.#repository.subscribe(callback);
654
+ }
655
+
656
+ // --- Public Domain Methods & Use Cases (CPO-037) ---
657
+
658
+ /**
659
+ * Ingest and process an array of File or Blob objects, converting them to document pages.
660
+ * Handles images (with EXIF extraction) and PDF files (rendering pages to data URLs).
661
+ *
662
+ * @param {FileList|File[]|Blob[]} files
663
+ * @param {string} [docId] - Target document ID (if omitted, attaches to latest or creates new doc)
664
+ * @returns {Promise<Array<Object>>} Added page entities
665
+ */
666
+ async addFiles(files, docId = null) {
667
+ if (!files || files.length === 0) return [];
668
+ const fileList = Array.from(files);
669
+
670
+ const newPages = [];
671
+
672
+ for (const file of fileList) {
673
+ if (file.type === 'application/pdf') {
674
+ const pdfService = this.getService('pdf');
675
+ if (pdfService && typeof pdfService.renderPdfPagesToDataUrls === 'function') {
676
+ const rendered = await pdfService.renderPdfPagesToDataUrls(file);
677
+ for (const dataUrl of rendered) {
678
+ newPages.push({
679
+ id: randomId(),
680
+ src: dataUrl,
681
+ originalSrc: dataUrl,
682
+ edits: { crop: null, rotation: 0, filter: 'none' },
683
+ type: 'image',
684
+ name: /** @type {any} */ (file).name || 'PDF Page',
685
+ });
686
+ }
687
+ } else {
688
+ console.warn('PDF import service (PdfPort) not registered. Skipping PDF file.');
689
+ }
690
+ } else if (file.type && file.type.startsWith('image/')) {
691
+ const base64 = await fileToBase64(file);
692
+ let orientation = null;
693
+ try {
694
+ orientation = await extractExif(file);
695
+ } catch {}
696
+
697
+ newPages.push({
698
+ id: randomId(),
699
+ src: base64,
700
+ originalSrc: base64,
701
+ edits: { crop: null, rotation: 0, filter: 'none' },
702
+ type: 'image',
703
+ name: /** @type {any} */ (file).name || 'Captured Image',
704
+ orientation,
705
+ });
706
+ }
707
+ }
708
+
709
+ if (newPages.length === 0) return [];
710
+
711
+ let targetDocId = docId;
712
+ if (!targetDocId) {
713
+ const docs = await this.listDocuments();
714
+ if (docs.length > 0) {
715
+ targetDocId = docs[0].id;
716
+ } else {
717
+ const created = await this.createDocument('Scanned Document', []);
718
+ targetDocId = created.id;
719
+ }
720
+ } else {
721
+ const existing = await this.getDocument(targetDocId);
722
+ if (!existing) {
723
+ await this.#repository.saveDoc(targetDocId, { name: 'Scanned Document', pages: [] });
724
+ }
725
+ }
726
+
727
+ // Check maxPages if configured
728
+ if (this.#maxPages > 0) {
729
+ const existing = (await this.getDocument(targetDocId))?.pages || [];
730
+ const remainingSlots = Math.max(0, this.#maxPages - existing.length);
731
+ if (remainingSlots <= 0) {
732
+ throw new Error(`Maximum page limit (${this.#maxPages}) reached`);
733
+ }
734
+ newPages.splice(remainingSlots);
735
+ }
736
+
737
+ await this.addPages(targetDocId, newPages);
738
+ return newPages;
739
+ }
740
+
741
+ /**
742
+ * Get all pages for a document.
743
+ * @param {string} [docId]
744
+ * @returns {Promise<Array<Object>>}
745
+ */
746
+ async getPages(docId = null) {
747
+ let targetDocId = docId;
748
+ if (!targetDocId) {
749
+ const docs = await this.listDocuments();
750
+ if (docs.length === 0) return [];
751
+ targetDocId = docs[0].id;
752
+ }
753
+ const doc = await this.getDocument(targetDocId);
754
+ return doc?.pages || [];
755
+ }
756
+
757
+ /**
758
+ * Clear all pages from a document.
759
+ * @param {string} [docId]
760
+ * @returns {Promise<void>}
761
+ */
762
+ async clear(docId = null) {
763
+ let targetDocId = docId;
764
+ if (!targetDocId) {
765
+ const docs = await this.listDocuments();
766
+ if (docs.length === 0) return;
767
+ targetDocId = docs[0].id;
768
+ }
769
+ const doc = await this.getDocument(targetDocId);
770
+ if (!doc || !doc.pages) return;
771
+ for (const p of doc.pages) {
772
+ await this.deletePage(targetDocId, p.id);
773
+ }
774
+ }
775
+
776
+ /**
777
+ * Resolve pages and document name from either doc ID, array of pages, or latest doc.
778
+ */
779
+ async #resolveDocAndPages(docIdOrPages) {
780
+ if (Array.isArray(docIdOrPages)) {
781
+ return { docName: 'document', pages: docIdOrPages, docId: null };
782
+ }
783
+ if (typeof docIdOrPages === 'string') {
784
+ const doc = await this.getDocument(docIdOrPages);
785
+ return {
786
+ docName: doc?.name || 'document',
787
+ pages: doc?.pages || [],
788
+ docId: docIdOrPages,
789
+ };
790
+ }
791
+ const docs = await this.listDocuments();
792
+ if (docs.length > 0) {
793
+ const doc = await this.getDocument(docs[0].id);
794
+ return {
795
+ docName: doc?.name || 'document',
796
+ pages: doc?.pages || [],
797
+ docId: docs[0].id,
798
+ };
799
+ }
800
+ return { docName: 'document', pages: [], docId: null };
801
+ }
802
+
803
+ /**
804
+ * Export document pages as a PDF Blob.
805
+ * Does NOT trigger automatic browser download unless options.download === true.
806
+ *
807
+ * @param {string|Array<Object>} [docIdOrPages]
808
+ * @param {Object} [options]
809
+ * @param {boolean} [options.download=false] - Whether to trigger browser download
810
+ * @param {Function} [options.onProgress] - Progress callback (done, total)
811
+ * @returns {Promise<Blob>}
812
+ */
813
+ async exportPdf(docIdOrPages, options = {}) {
814
+ if (!this.hasFeature('export')) {
815
+ const err = new Error('Feature "export" is disabled');
816
+ Object.assign(err, { code: 'FEATURE_DISABLED' });
817
+ throw err;
818
+ }
819
+ if (!this.#pdf || !this.#exportFormats.includes('pdf')) {
820
+ const err = new Error('Feature "pdf" is disabled');
821
+ Object.assign(err, { code: 'FEATURE_DISABLED' });
822
+ throw err;
823
+ }
824
+
825
+ const { docName, pages } = await this.#resolveDocAndPages(docIdOrPages);
826
+ const exportService = this.getService('pdf') || this.getService('export');
827
+ if (!exportService || typeof exportService.exportDocumentAsPdf !== 'function') {
828
+ throw new Error('Export service (PdfPort) is not registered. Import @copio/sdk or register an exportService.');
829
+ }
830
+
831
+ return exportService.exportDocumentAsPdf(docName, pages, {
832
+ download: false,
833
+ showProgress: false,
834
+ ...options,
835
+ });
836
+ }
837
+
838
+ /**
839
+ * Export document pages as a ZIP (or single image) Blob.
840
+ * Does NOT trigger automatic browser download unless options.download === true.
841
+ *
842
+ * @param {string|Array<Object>} [docIdOrPages]
843
+ * @param {Object} [options]
844
+ * @param {boolean} [options.download=false] - Whether to trigger browser download
845
+ * @param {Function} [options.onProgress] - Progress callback (done, total)
846
+ * @returns {Promise<Blob>}
847
+ */
848
+ async exportZip(docIdOrPages, options = {}) {
849
+ if (!this.hasFeature('export')) {
850
+ const err = new Error('Feature "export" is disabled');
851
+ Object.assign(err, { code: 'FEATURE_DISABLED' });
852
+ throw err;
853
+ }
854
+
855
+ const { docName, pages } = await this.#resolveDocAndPages(docIdOrPages);
856
+ const exportService = this.getService('export');
857
+ if (!exportService || typeof exportService.exportDocumentAsImages !== 'function') {
858
+ throw new Error('Export service is not registered. Import @copio/sdk or register an exportService.');
859
+ }
860
+
861
+ return exportService.exportDocumentAsImages(docName, pages, {
862
+ download: false,
863
+ showProgress: false,
864
+ ...options,
865
+ });
866
+ }
867
+
868
+ /**
869
+ * Run optical character recognition on document pages.
870
+ *
871
+ * @param {string|Array<Object>} [docIdOrPages]
872
+ * @param {string} [pageId] - Optional specific page ID to recognize
873
+ * @param {Object} [options]
874
+ * @param {string} [options.lang] - OCR language (defaults to first configured language or 'eng')
875
+ * @param {Function} [options.onPageProgress]
876
+ * @returns {Promise<{ combinedText: string, text: string, pagesResults: Array<Object>, averageConfidence: number }>}
877
+ */
878
+ async runOcr(docIdOrPages, pageId = null, options = {}) {
879
+ if (!this.#ocr || !this.hasFeature('ocr')) {
880
+ const err = new Error('Feature "ocr" is disabled');
881
+ Object.assign(err, { code: 'FEATURE_DISABLED' });
882
+ throw err;
883
+ }
884
+
885
+ const { pages } = await this.#resolveDocAndPages(docIdOrPages);
886
+ let targetPages = pages;
887
+ if (pageId) {
888
+ targetPages = pages.filter((p) => p.id === pageId);
889
+ }
890
+
891
+ const ocrService = this.getService('ocr');
892
+ if (!ocrService || typeof ocrService.recognizeDocumentPages !== 'function') {
893
+ throw new Error('OCR service (OcrPort) is not registered. Import @copio/sdk or register an ocrService.');
894
+ }
895
+
896
+ const lang = options.lang || this.#ocrLanguages[0] || 'eng';
897
+ const result = await ocrService.recognizeDocumentPages(targetPages, {
898
+ lang,
899
+ ...options,
900
+ });
901
+
902
+ return {
903
+ text: result.combinedText,
904
+ ...result,
905
+ };
906
+ }
907
+
908
+ /**
909
+ * Initialize P2P synchronization session.
910
+ *
911
+ * @param {Object} [options]
912
+ * @param {Function} [options.onStateChange]
913
+ * @returns {Promise<any>}
914
+ */
915
+ async sync(options = {}) {
916
+ if (!this.hasFeature('sync')) {
917
+ const err = new Error('Feature "sync" is disabled');
918
+ Object.assign(err, { code: 'FEATURE_DISABLED' });
919
+ throw err;
920
+ }
921
+
922
+ const SyncManagerClass = this.getService('sync');
923
+ if (!SyncManagerClass) {
924
+ throw new Error('Sync service (SyncPort) is not registered. Import @copio/sdk or register a syncService.');
925
+ }
926
+
927
+ return new SyncManagerClass(this.#repository, options.onStateChange);
928
+ }
929
+ }
930
+
931
+ export {
932
+ DocRepository,
933
+ docRepository,
934
+ StoragePort,
935
+ MemoryStorageAdapter,
936
+ IndexedDbStorageAdapter,
937
+ createDefaultAdapter,
938
+ ImageProcessorPort,
939
+ Canvas2DAdapter,
940
+ NullImageProcessorAdapter,
941
+ NullOcrAdapter,
942
+ NullPdfAdapter,
943
+ Document,
944
+ Page,
945
+ ScanSession,
946
+ normalizeEditStack,
947
+ hasActiveEdits,
948
+ randomId,
949
+ fileToBase64,
950
+ thresholdSrc,
951
+ rotateSrc,
952
+ getCroppedSrc,
953
+ extractExif,
954
+ applyEdits,
955
+ normalizeEdits,
956
+ renderEditsToCanvas,
957
+ applySauvolaToImageData,
958
+ BUILD_DATE,
959
+ VERSION,
960
+ };
961
+ export { COPIO_EVENTS, dispatchCopioEvent } from './events.js';