@3sln/emon 0.0.0-stage → 0.3.0-preview.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.
package/src/index.js ADDED
@@ -0,0 +1,590 @@
1
+ // emon's JavaScript SDK (DEVLOG P9.3, SPEC 13, 13.1, 7.3; D058, D089, D117; D356-D361): PDFs and images to semantic HTML and
2
+ // emon JSON in the browser, over the WASM binding (`host/wasm`, the Rust host built for wasm32).
3
+ //
4
+ // import { Emon } from '@3sln/emon';
5
+ // const emon = await Emon.load('/emon.wasm');
6
+ // const model = await emon.convert(file /* a File, Blob, URL, ArrayBuffer, ReadableStream or { size, read } */, { assets: 'images' });
7
+ // const html = model.html({ assets: 'external' }); // assets are files, not data: URIs
8
+ // for (const a of model.assets) img.src = URL.createObjectURL(a.blob());
9
+ // const tree = model.object(); // the JSON, parsed
10
+ // model.dispose();
11
+ //
12
+ // THE LOOP IS THIS FILE'S (D058 revised, SPEC 13.1, 7.3). JavaScript cannot block on a promise, so the engine never calls out: it
13
+ // runs until it needs something, says what, and this loop awaits it and runs it again. What the engine needs is (1) BYTES of the
14
+ // document its `Src` missed (the engine re-runs the unit that missed from scratch, so the bytes it ends up with are the bytes it
15
+ // touched), read from the byte source a chunk at a time with doubling read-ahead; (2) answers to `ocr` requests, from
16
+ // `ports.ocr` (tesseract.js: `@3sln/emon/tesseract`); (3) answers to `render` and `crop` requests, from `ports.render` (pdfium's
17
+ // WebAssembly build: `@3sln/emon/pdfium`, the form in `render.js`). `decode` and `decode-img` are the engine's own (PNG, JPEG, TIFF,
18
+ // CCITT, DCT in Rust/WASM). A request no port is given for is answered `unsupported`, which is an answer: a page that needed a
19
+ // render then has no text from it, and nothing is guessed (D038, D199).
20
+ //
21
+ // There is no whole-file read: a Blob or a URL is read by range. (An ArrayBuffer is already in memory, so its source says so and
22
+ // the engine is handed it at once; `{ lazy: true }` reads it by range like the others.) THE ONE EXCEPTION is the renderer
23
+ // (SPEC 13.1, P11.4c): pdfium wants the file, so the first `render` or `crop` request reads the whole of it, once, for `ports.render`
24
+ // (a born-digital document that asks for no raster never does).
25
+
26
+ import { Wasm } from './wasm.js';
27
+ import { toSource, bytesSource, blobSource, urlSource, streamSource, SourceChangedError, EmonError } from './sources.js';
28
+ import { ocrRequest, encodeOcr, canonicalOcr } from './ocr.js';
29
+
30
+ export { bytesSource, blobSource, urlSource, streamSource, toSource, SourceChangedError, EmonError };
31
+
32
+ // The WASM instance (`w`), a Model's handle (`h`) and an Asset's Model (`model`) are NOT public API (P11.4, D542): they are defined
33
+ // non-enumerable, so they are not in `Object.keys`, a spread, `JSON.stringify` or a `for...in`, and `index.d.ts` does not declare them.
34
+ // (The SDK's own classes reach each other's through them; a test may read `emon.w`.) The constructors of `Emon`, `Model` and `Asset` are the
35
+ // SDK's own: an embedder gets an `Emon` from `Emon.load`, a `Model` from `convert` and an `Asset` from `model.assets`.
36
+ const hide = (o, k, value) => Object.defineProperty(o, k, { value, writable: true, enumerable: false, configurable: true });
37
+
38
+ const STAGE = 4 * 1024 * 1024; // bytes handed to the module per call: a read of a big range is staged, never doubled in memory
39
+ const READS = 8; // reads of the source in flight at once
40
+
41
+ const optionLines = (o, chunk, record) => {
42
+ const L = [];
43
+ const put = (k, v) => v !== undefined && v !== null && L.push(`${k}=${v}`);
44
+ put('locale', o.locale);
45
+ put('ocr', o.ocr);
46
+ put('ocr-engine', o.ocrEngine);
47
+ put('furniture', o.furniture);
48
+ put('assets', o.assets);
49
+ put('asset-dpi', o.assetDpi);
50
+ put('asset-pixels', o.assetPixels);
51
+ put('asset-bytes', o.assetBytes);
52
+ put('assets-bytes', o.assetsBytes);
53
+ if (o.assetSignatures !== undefined) put('asset-signatures', o.assetSignatures === true || o.assetSignatures === 'on' ? 'on' : 'off');
54
+ if (o.keepEvidence) put('keep-evidence', 1);
55
+ put('ocr-scope', o.ocrScope);
56
+ put('max-rounds', o.maxRounds);
57
+ put('fetch-rounds', o.fetchRounds);
58
+ for (const [k, v] of Object.entries(o.limits || {})) put(`limit.${k}`, v);
59
+ if (record) put('record', 1);
60
+ for (const [k, v] of Object.entries(o.producer || {})) put(`producer.${k}`, v);
61
+ // what the renderer says produced its pixels (`pdfium.js`'s `producer`), after the embedder's own
62
+ for (const [k, v] of Object.entries((o.ports && o.ports.render && o.ports.render.producer) || {})) put(`producer.${k}`, v);
63
+ for (const [k, v] of Object.entries(o.ports?.ocr?.producer || {})) put(`producer.${k}`, v);
64
+ if (o.ports && o.ports.ocr) put('js-ocr', 1);
65
+ if (o.ports && o.ports.render) put('js-render', 1);
66
+ return L.join('\n');
67
+ };
68
+
69
+ const pairs = (i32) => {
70
+ const out = [];
71
+ for (let i = 0; i + 1 < i32.length; i += 2) out.push({ offset: i32[i], length: i32[i + 1] });
72
+ return out;
73
+ };
74
+
75
+ const entriesOf = (t) => (t instanceof Map ? [...t.entries()] : Array.isArray(t) ? t : Object.entries(t));
76
+
77
+ export class Asset {
78
+ constructor(model, i, name, type, size) {
79
+ hide(this, 'model', model);
80
+ this.index = i;
81
+ /** the file name, `a<id>.jpg` or `a<id>.png` (what `external` HTML refers to) */
82
+ this.name = name;
83
+ /** `image/jpeg` or `image/png` */
84
+ this.type = type;
85
+ /** the encoded size in bytes */
86
+ this.size = size;
87
+ }
88
+
89
+ /** The encoded bytes: a copy in a `Uint8Array` (an embedded JPEG's own bytes, or the canonical PNG of its pixels). */
90
+ bytes() {
91
+ const w = this.model.w;
92
+ const n = w.x.emon_model_asset_bytes(this.model.h, this.index);
93
+ if (n < 0) throw new EmonError('internal', 'no such asset');
94
+ const b = w.outBytes();
95
+ w.outFree();
96
+ return b;
97
+ }
98
+
99
+ /** The same as a `Blob` of the asset's media type (made from the module's memory: the page's heap holds no copy). */
100
+ blob() {
101
+ const w = this.model.w;
102
+ const n = w.x.emon_model_asset_bytes(this.model.h, this.index);
103
+ if (n < 0) throw new EmonError('internal', 'no such asset');
104
+ const blob = new Blob([w.outView()], { type: this.type });
105
+ w.outFree();
106
+ return blob;
107
+ }
108
+ }
109
+
110
+ const registry = typeof FinalizationRegistry !== 'undefined' ? new FinalizationRegistry(({ w, h }) => w.x.emon_model_free(h)) : null;
111
+
112
+ export class Model {
113
+ constructor(w, h, stats, evidenceKept, transcript) {
114
+ hide(this, 'w', w);
115
+ hide(this, 'h', h);
116
+ this.stats = stats;
117
+ this._evidence = evidenceKept;
118
+ this._transcript = transcript;
119
+ this._assets = null;
120
+ registry?.register(this, { w, h }, this);
121
+ }
122
+
123
+ _text(rc) {
124
+ if (rc < 0) throw new EmonError('internal', this.w.outText());
125
+ const s = this.w.outText();
126
+ this.w.outFree();
127
+ return s;
128
+ }
129
+
130
+ /** SPEC 4: emon JSON, as text. */
131
+ json({ pretty = false } = {}) {
132
+ return this._text(this.w.x.emon_model_json(this.h, pretty ? 1 : 0));
133
+ }
134
+
135
+ /** The JSON, parsed. */
136
+ object() {
137
+ return JSON.parse(this.json());
138
+ }
139
+
140
+ /**
141
+ * SPEC 5: HTML. Options: `ids`, `geometry`, `confidenceBelow` (0..1000), `ledger`, `pretty`, `furnitureDrop`, `milestones`
142
+ * (default true), `initialsPlain`, `alignStyle`, `assets`: `inline` (data: URIs, the default), `external` (the HTML names each
143
+ * asset file by `assetPrefix + name`, and the caller serves them: `model.assets[i].blob()`) or `omit`; `assetPrefix`.
144
+ */
145
+ html(o = {}) {
146
+ const L = [];
147
+ if (o.ids) L.push('ids');
148
+ if (o.geometry) L.push('geometry');
149
+ if (o.confidenceBelow !== undefined) L.push(`confidence=${o.confidenceBelow}`);
150
+ if (o.ledger) L.push('ledger');
151
+ if (o.pretty) L.push('pretty');
152
+ if (o.furnitureDrop) L.push('drop-furniture');
153
+ if (o.milestones === false) L.push('no-milestones');
154
+ if (o.initialsPlain) L.push('initials-plain');
155
+ if (o.alignStyle) L.push('align-style');
156
+ if (o.assets) L.push(`assets=${o.assets}`);
157
+ if (o.assetPrefix) L.push(`prefix=${o.assetPrefix}`);
158
+ const w = this.w;
159
+ return this._text(w.withText(L.join(','), (p, n) => w.x.emon_model_html(this.h, p, n)));
160
+ }
161
+
162
+ /**
163
+ * `external` mode in the browser's form: the HTML refers to each asset by an object URL of its Blob. `revoke()` frees them.
164
+ * @returns {{ html: string, urls: Map<string, string>, revoke(): void }}
165
+ */
166
+ htmlWithBlobURLs(o = {}) {
167
+ const prefix = 'emon-asset:';
168
+ let html = this.html({ ...o, assets: 'external', assetPrefix: prefix });
169
+ const urls = new Map();
170
+ for (const a of this.assets) {
171
+ const u = URL.createObjectURL(a.blob());
172
+ urls.set(a.name, u);
173
+ html = html.split(prefix + a.name).join(u);
174
+ }
175
+ return { html, urls, revoke: () => urls.forEach((u) => URL.revokeObjectURL(u)) };
176
+ }
177
+
178
+ /** The text layer's evidence dump, when the conversion was asked to `keepEvidence`. */
179
+ evidence() {
180
+ return this._text(this.w.x.emon_model_evidence(this.h));
181
+ }
182
+
183
+ /** The Model's assets (SPEC 10.11, D117; empty unless `assets` was on), in admission order. */
184
+ get assets() {
185
+ if (!this._assets) {
186
+ const w = this.w;
187
+ const n = w.x.emon_model_asset_count(this.h);
188
+ this._assets = [];
189
+ for (let i = 0; i < n; i++) {
190
+ w.x.emon_model_asset_info(this.h, i);
191
+ const [name, type, size] = w.outText().split('\n');
192
+ this._assets.push(new Asset(this, i, name, type, Number(size)));
193
+ }
194
+ }
195
+ return this._assets;
196
+ }
197
+
198
+ /** The plan/fulfil transcript this conversion recorded (`record: true`): a Map of file name to bytes. */
199
+ transcript() {
200
+ if (!this._transcript) throw new EmonError('usage', 'this conversion did not record (record: true)');
201
+ return this._transcript;
202
+ }
203
+
204
+ /** Free the Model's memory (the WASM heap's: it is not the garbage collector's until a finalizer runs). */
205
+ dispose() {
206
+ if (this.h) {
207
+ registry?.unregister(this);
208
+ this.w.x.emon_model_free(this.h);
209
+ this.h = 0;
210
+ }
211
+ }
212
+
213
+ [Symbol.dispose]() {
214
+ this.dispose();
215
+ }
216
+ }
217
+
218
+ export class Emon {
219
+ /**
220
+ * @param {ArrayBuffer|Uint8Array|WebAssembly.Module|Response|Promise<Response>|string|URL} wasm the module (`emon.wasm`)
221
+ * @param {{ chunk?: number }} [defaults] chunk: the byte source's chunk size (default 64 KiB)
222
+ */
223
+ static async load(wasm, defaults = {}) {
224
+ return new Emon(await Wasm.instantiate(wasm), defaults);
225
+ }
226
+
227
+ constructor(w, defaults = {}) {
228
+ hide(this, 'w', w);
229
+ this.defaults = defaults;
230
+ }
231
+
232
+ _open(source, password, mode, options) {
233
+ const w = this.w;
234
+ const chunk = options.chunk ?? this.defaults.chunk ?? 65536;
235
+ const pw = typeof password === 'string' ? new TextEncoder().encode(password) : password || new Uint8Array(0);
236
+ const text = new TextEncoder().encode(optionLines(options, chunk, !!options.record));
237
+ w.x.emon_clock(performance.now()); // the first unit's clock starts here
238
+ const h = w.withBytes(pw, (pp, pl) => w.withBytes(text, (op, ol) => w.x.emon_open(source.size, chunk, mode, pp, pl, op, ol)));
239
+ if (h < 0) throw this._error(h);
240
+ return { h, chunk };
241
+ }
242
+
243
+ _error(rc) {
244
+ const [code, ...rest] = this.w.outText().split('\n');
245
+ this.w.outFree();
246
+ return new EmonError(code, rest.join('\n') || code);
247
+ }
248
+
249
+ _provide(h, offset, u8, chunk) {
250
+ const w = this.w;
251
+ const step = Math.max(chunk, Math.floor(STAGE / chunk) * chunk);
252
+ for (let o = 0; o < u8.length; o += step) {
253
+ const part = u8.subarray(o, Math.min(o + step, u8.length));
254
+ w.withBytes(part, (p, l) => w.x.emon_provide(h, offset + o, p, l));
255
+ }
256
+ }
257
+
258
+ async _fetch(h, source, ranges, chunk, ctx) {
259
+ const w = this.w;
260
+ let next = 0;
261
+ let failed = false;
262
+ const one = async () => {
263
+ while (next < ranges.length && !failed) {
264
+ const { offset, length } = ranges[next++];
265
+ let data;
266
+ try {
267
+ data = await source.read(offset, length);
268
+ ctx.reads++;
269
+ if (!(data instanceof Uint8Array)) data = ArrayBuffer.isView(data) ? new Uint8Array(data.buffer, data.byteOffset, data.byteLength) : new Uint8Array(data);
270
+ ctx.bytesRead += data.length;
271
+ } catch (e) {
272
+ failed = true;
273
+ const short = !!(e && (e.code === 'source-changed' || e.name === 'SourceChangedError'));
274
+ w.withText(String((e && e.message) || e), (p, n) => w.x.emon_fail(h, short ? 1 : 0, p, n));
275
+ return;
276
+ }
277
+ if (data.length !== length) {
278
+ failed = true;
279
+ w.withText(`the source gave ${data.length} bytes at offset ${offset} and its length said ${length}`, (p, n) => w.x.emon_fail(h, 1, p, n));
280
+ return;
281
+ }
282
+ this._provide(h, offset, data, chunk);
283
+ }
284
+ };
285
+ await Promise.all(Array.from({ length: Math.min(READS, ranges.length) }, one));
286
+ }
287
+
288
+ async _fulfil(h, reqs, ports, ctx) {
289
+ const w = this.w;
290
+ const k = w.kind;
291
+ await Promise.all(
292
+ reqs.map(async (rec) => {
293
+ const kind = rec[1];
294
+ const failed = (status) => w.withBytes(new Uint8Array(Int32Array.of(4, kind, rec[2], status).buffer), (p) => w.x.emon_answer(h, p, 4));
295
+ if (kind === k.ocr && ports && ports.ocr) {
296
+ const bitmapId = rec[3];
297
+ const req = ocrRequest(
298
+ rec,
299
+ () => {
300
+ const n = w.x.emon_bitmap_png(h, bitmapId);
301
+ if (n < 0) throw new EmonError('internal', 'the ocr request names no bitmap');
302
+ const b = w.outBytes();
303
+ w.outFree();
304
+ return b;
305
+ },
306
+ w,
307
+ );
308
+ let result;
309
+ try {
310
+ result = await ports.ocr(req);
311
+ } catch (e) {
312
+ ctx.notes.push(`ocr ${rec[2]} failed: ${(e && e.message) || e}`);
313
+ failed(w.status.failed);
314
+ return;
315
+ }
316
+ if (result === null || result === undefined) {
317
+ failed(w.status.unsupported);
318
+ return;
319
+ }
320
+ if (result[canonicalOcr]) {
321
+ const answer = result[canonicalOcr];
322
+ if (!(answer instanceof Int32Array) || answer.length < 4 || answer[0] !== answer.length || answer[1] !== kind || answer[2] !== rec[2]) {
323
+ throw new EmonError('internal', 'invalid canonical OCR answer');
324
+ }
325
+ const rc = w.withBytes(new Uint8Array(answer.buffer, answer.byteOffset, answer.byteLength), p => w.x.emon_answer(h, p, answer.length));
326
+ if (rc < 0) throw this._error(rc);
327
+ return;
328
+ }
329
+ const cells = encodeOcr(result, w.ocrWord);
330
+ const observed = w.ocrObserved(result.observed ?? ports.ocr.producer?.observed ?? ports.ocr.producer?.engine ?? 'external');
331
+ cells[2] = observed[0]; cells[3] = observed[1];
332
+ const rc = w.withBytes(new Uint8Array(cells.buffer), (p) => w.x.emon_answer_ocr(h, rec[2], p, cells.length));
333
+ if (rc < 0) throw this._error(rc);
334
+ return;
335
+ }
336
+ if ((kind === k.render || kind === k.crop) && ports && ports.render) {
337
+ await this._render(h, rec, ports.render, ctx);
338
+ return;
339
+ }
340
+ // nothing in this host fulfils it (the engine does not route a request here it has no port for)
341
+ failed(w.status.unsupported);
342
+ }),
343
+ );
344
+ }
345
+
346
+ // `render` and `crop` from `ports.render` (a Renderer, `render.js`). The renderer is asked for WHOLE PAGES only and its calls are serialised on
347
+ // `ctx.render.chain` (pdfium is single-threaded): the page is kept in the module's memory between requests (`last`), so a page and its crops are
348
+ // rendered once, and `emon_answer_render` cuts a crop out of it. The renderer is opened by the first request, with the whole file (SPEC 13.1).
349
+ _render(h, rec, port, ctx) {
350
+ const rc = (ctx.render ||= { chain: Promise.resolve(), doc: null, dead: false, readError: null, last: null });
351
+ const run = rc.chain.then(() => this._renderOne(h, rec, port, ctx, rc));
352
+ rc.chain = run.catch(() => {});
353
+ return run;
354
+ }
355
+
356
+ async _renderOne(h, rec, port, ctx, rc) {
357
+ const w = this.w;
358
+ const [kind, id] = [rec[1], rec[2]];
359
+ const answer = (status) => w.withBytes(new Uint8Array(Int32Array.of(4, kind, id, status).buffer), (p) => w.x.emon_answer(h, p, 4));
360
+ const req = { page: rec[3 + w.rd.page], dpi: rec[3 + w.rd.dpi], layer: rec[3 + w.rd.layer] };
361
+ // a layer the renderer says it cannot separate is `unsupported` without asking it (`layers` is a bit set over kin's `lay-*`)
362
+ if (req.layer < 0 || req.layer > 30 || !(((port.layers ?? 1) >> req.layer) & 1)) return answer(w.status.unsupported);
363
+ if (!rc.doc && !rc.dead) {
364
+ const src = ctx.source;
365
+ // the whole file, once: what the renderer reads through is the conversion's own byte source, and its faults are the conversion's (`io`, `source-changed`)
366
+ const read = async (offset, length) => {
367
+ let data;
368
+ try {
369
+ data = await src.read(offset, length);
370
+ if (!(data instanceof Uint8Array)) data = ArrayBuffer.isView(data) ? new Uint8Array(data.buffer, data.byteOffset, data.byteLength) : new Uint8Array(data);
371
+ } catch (e) {
372
+ rc.readError = { short: !!(e && (e.code === 'source-changed' || e.name === 'SourceChangedError')), message: String((e && e.message) || e) };
373
+ throw e;
374
+ }
375
+ ctx.reads++;
376
+ ctx.bytesRead += data.length;
377
+ if (data.length !== length) {
378
+ rc.readError = { short: true, message: `the source gave ${data.length} bytes at offset ${offset} and its length said ${length}` };
379
+ throw new SourceChangedError(rc.readError.message);
380
+ }
381
+ return data;
382
+ };
383
+ try {
384
+ rc.doc = await port.open({ size: src.size, bytes: src.bytes, read, password: ctx.password }, { pixels: w.x.emon_limit(h, w.pixelsKind) });
385
+ } catch (e) {
386
+ rc.dead = true;
387
+ if (rc.readError) {
388
+ // the source failed under the renderer's read: the conversion ends with the source's error, as it does for any read
389
+ const re = rc.readError;
390
+ w.withText(re.message, (p, n) => w.x.emon_fail(h, re.short ? 1 : 0, p, n));
391
+ } else {
392
+ ctx.notes.push(`render: the renderer did not open: ${(e && e.message) || e}`);
393
+ }
394
+ }
395
+ }
396
+ if (!rc.doc) return answer(w.status.failed);
397
+ const key = `${req.page}/${req.dpi}/${req.layer}`;
398
+ if (!rc.last || rc.last.key !== key) {
399
+ this._renderFree(rc);
400
+ let alloc = null;
401
+ const sink = (n) => {
402
+ alloc = { ptr: w.x.emon_alloc(n), len: n };
403
+ return new Uint8Array(w.x.memory.buffer, alloc.ptr, n);
404
+ };
405
+ const drop = () => alloc && w.x.emon_free(alloc.ptr, alloc.len);
406
+ // a page that could not be made is remembered as it is (a figure document asks for several crops of it): the renderer is asked once
407
+ const refused = (status, why) => {
408
+ drop();
409
+ rc.last = { key, status, why };
410
+ };
411
+ let r;
412
+ try {
413
+ r = await rc.doc.render(req, sink);
414
+ } catch (e) {
415
+ refused(w.status.failed, (e && e.message) || String(e));
416
+ }
417
+ if (!rc.last || rc.last.key !== key) {
418
+ if (r && r.status) refused(r.status === 'unsupported' ? w.status.unsupported : w.status.failed, r.reason || r.status);
419
+ else if (!(r && Number.isInteger(r.width) && Number.isInteger(r.height) && r.width > 0 && r.height > 0 && r.rgb && r.rgb.length === r.width * r.height * 3)) {
420
+ refused(w.status.failed, "the renderer's bitmap is not width x height x 3 bytes");
421
+ } else {
422
+ const n = r.width * r.height * 3;
423
+ if (!alloc || alloc.len !== n) {
424
+ drop();
425
+ alloc = { ptr: w.x.emon_alloc(n), len: n };
426
+ }
427
+ const at = new Uint8Array(w.x.memory.buffer, alloc.ptr, n);
428
+ if (r.rgb.buffer !== at.buffer || r.rgb.byteOffset !== at.byteOffset) at.set(r.rgb);
429
+ rc.last = { key, width: r.width, height: r.height, ptr: alloc.ptr, len: n };
430
+ }
431
+ }
432
+ }
433
+ const l = rc.last;
434
+ if (l.status !== undefined) {
435
+ if (l.status === w.status.failed) ctx.notes.push(`render ${id} failed: ${l.why}`);
436
+ return answer(l.status);
437
+ }
438
+ const rcode = w.x.emon_answer_render(h, id, l.width, l.height, l.ptr, l.len);
439
+ if (rcode < 0) throw this._error(rcode);
440
+ }
441
+
442
+ _renderFree(rc) {
443
+ if (rc.last) {
444
+ if (rc.last.ptr) this.w.x.emon_free(rc.last.ptr, rc.last.len);
445
+ rc.last = null;
446
+ }
447
+ }
448
+
449
+ // the conversion is over: the renderer's document is closed and the page it kept is freed
450
+ async _renderEnd(ctx) {
451
+ const rc = ctx.render;
452
+ if (!rc) return;
453
+ await rc.chain;
454
+ try {
455
+ if (rc.doc) rc.doc.close();
456
+ } catch (_) {
457
+ /* a renderer that fails to close has nothing more to say */
458
+ }
459
+ rc.doc = null;
460
+ this._renderFree(rc);
461
+ }
462
+
463
+ async _run(h, source, chunk, options, mode, password) {
464
+ const w = this.w;
465
+ const ctx = { reads: 0, bytesRead: 0, notes: [], source, password: typeof password === 'string' ? new TextEncoder().encode(password) : password || undefined, render: null };
466
+ try {
467
+ if (options.transcript) {
468
+ for (const [name, data] of entriesOf(options.transcript)) {
469
+ const u8 = data instanceof Uint8Array ? data : new Uint8Array(data);
470
+ const rc = w.withText(name, (np, nl) => w.withBytes(u8, (dp, dl) => w.x.emon_replay_file(h, np, nl, dp, dl)));
471
+ if (rc < 0) throw this._error(rc);
472
+ }
473
+ const rc = w.x.emon_replay_end(h);
474
+ if (rc < 0) throw this._error(rc);
475
+ }
476
+ if (source.bytes && !options.lazy) {
477
+ this._provide(h, 0, source.bytes, chunk);
478
+ ctx.reads++;
479
+ ctx.bytesRead += source.bytes.length;
480
+ } else {
481
+ w.x.emon_prefetch(h);
482
+ await this._fetch(h, source, pairs(w.outI32()), chunk, ctx);
483
+ }
484
+ for (;;) {
485
+ // the browser's clock is the page's (D396): the module has none, so the loop's `stage-ms` is judged against what is set here
486
+ w.x.emon_clock(performance.now());
487
+ const st = w.x.emon_step(h);
488
+ if (st === 0) return ctx;
489
+ if (st === 1) {
490
+ await this._fetch(h, source, pairs(w.outI32()), chunk, ctx);
491
+ continue;
492
+ }
493
+ if (st === 2) {
494
+ const v = w.outBytes();
495
+ const dv = new DataView(v.buffer, v.byteOffset, v.byteLength);
496
+ const n = dv.getInt32(0, true);
497
+ const reqs = [];
498
+ let at = 4;
499
+ for (let i = 0; i < n; i++) {
500
+ const len = dv.getInt32(at, true);
501
+ at += 4;
502
+ const rec = [];
503
+ for (let j = 0; j < len; j++, at += 4) rec.push(dv.getInt32(at, true));
504
+ reqs.push(rec);
505
+ }
506
+ await this._fulfil(h, reqs, options.ports, ctx);
507
+ continue;
508
+ }
509
+ throw this._error(st);
510
+ }
511
+ } catch (e) {
512
+ w.x.emon_close(h);
513
+ throw e;
514
+ } finally {
515
+ await this._renderEnd(ctx);
516
+ }
517
+ }
518
+
519
+ _input(input) {
520
+ if (input && typeof input === 'object' && 'source' in input && !('read' in input) && !(input instanceof Blob)) return { src: input.source, password: input.password };
521
+ return { src: input, password: undefined };
522
+ }
523
+
524
+ /**
525
+ * Convert one input (SPEC 13: stages 0-3) to a Model. An input is anything `toSource` takes, or `{ source, password }`.
526
+ * Options are SPEC 13's settings by their names (`locale`, `ocr`, `furniture`, `assets`, `assetDpi`, `assetPixels`,
527
+ * `assetBytes`, `assetsBytes`, `assetSignatures`), `limits` (`{ 'input-bytes': n, ... }`), `maxRounds`, `fetchRounds`, `chunk`,
528
+ * `keepEvidence`, `lazy` (read even an in-memory input by range), `ports: { ocr, render }` (`ocr`: `ocr.js`'s form, `@3sln/emon/tesseract`;
529
+ * `render`: `render.js`'s form, `@3sln/emon/pdfium`), `transcript` (replay: a Map of file name to bytes: no port is called) and
530
+ * `record` (the Model then has `transcript()`).
531
+ */
532
+ async convert(input, options = {}) {
533
+ const { src, password } = this._input(input);
534
+ const source = await toSource(src, { lazy: options.lazy, max: options.limits?.['input-bytes'] ?? this.w.inputBytes });
535
+ const { h, chunk } = this._open(source, password, 0, options);
536
+ const ctx = await this._run(h, source, chunk, options, 0, password);
537
+ const w = this.w;
538
+ let transcript = null;
539
+ if (options.record) {
540
+ if (w.x.emon_transcript(h) < 0) throw new EmonError('internal', 'no transcript');
541
+ const v = w.outBytes();
542
+ const dv = new DataView(v.buffer, v.byteOffset, v.byteLength);
543
+ const dec = new TextDecoder();
544
+ transcript = new Map();
545
+ let at = 4;
546
+ for (let i = 0, n = dv.getUint32(0, true); i < n; i++) {
547
+ const nl = dv.getUint32(at, true);
548
+ const name = dec.decode(v.subarray(at + 4, at + 4 + nl));
549
+ at += 4 + nl;
550
+ const dl = dv.getUint32(at, true);
551
+ transcript.set(name, v.slice(at + 4, at + 4 + dl));
552
+ at += 4 + dl;
553
+ }
554
+ }
555
+ const mh = w.x.emon_finish(h);
556
+ if (mh < 0) {
557
+ const e = this._error(mh);
558
+ w.x.emon_close(h);
559
+ throw e;
560
+ }
561
+ const s = w.outI32();
562
+ w.x.emon_close(h);
563
+ const stats = { attempts: s[0], fetchRounds: s[1], bytesRequests: s[2], requests: s[3], sourceReads: s[4], bytesFetched: s[5], inputBytes: s[6], reads: ctx.reads, bytesRead: ctx.bytesRead, notes: ctx.notes };
564
+ return new Model(w, mh, stats, !!options.keepEvidence, transcript);
565
+ }
566
+
567
+ /** Stage 0 of each input, cheap: `{ format, version, pages, encrypted, bytes, line }` (the line is the drivers'). */
568
+ async intake(inputs, options = {}) {
569
+ const list = Array.isArray(inputs) ? inputs : [inputs];
570
+ const out = [];
571
+ for (const input of list) {
572
+ const { src, password } = this._input(input);
573
+ const source = await toSource(src, { lazy: options.lazy, max: options.limits?.['input-bytes'] ?? this.w.inputBytes });
574
+ const { h, chunk } = this._open(source, password, 1, { ...options, ports: undefined, record: false, transcript: undefined });
575
+ await this._run(h, source, chunk, { ...options, ports: undefined, transcript: undefined }, 1);
576
+ const rc = this.w.x.emon_finish_intake(h);
577
+ if (rc < 0) {
578
+ const e = this._error(rc);
579
+ this.w.x.emon_close(h);
580
+ throw e;
581
+ }
582
+ const line = this.w.outText();
583
+ this.w.x.emon_close(h);
584
+ // (a damaged header can have a version that is not a number: `pdf -38.-16`, as the engine says it)
585
+ const m = /^(\S+) (-?\d+)\.(-?\d+) pages=(\d+) encrypted=(true|false) bytes=(\d+)$/.exec(line);
586
+ out.push({ format: m[1], version: [Number(m[2]), Number(m[3])], pages: Number(m[4]), encrypted: m[5] === 'true', bytes: Number(m[6]), line });
587
+ }
588
+ return out;
589
+ }
590
+ }