@docling/docling-client 0.1.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/index.js ADDED
@@ -0,0 +1,4091 @@
1
+ // src/artifacts.ts
2
+ import { Unzip, UnzipInflate } from "fflate";
3
+ import ipaddr from "ipaddr.js";
4
+
5
+ // src/errors.ts
6
+ var DoclingError = class extends Error {
7
+ constructor(message, options) {
8
+ super(message, options);
9
+ this.name = new.target.name;
10
+ }
11
+ };
12
+ var DoclingServiceError = class extends DoclingError {
13
+ status;
14
+ detail;
15
+ constructor(message, options = {}) {
16
+ super(message, options.cause === void 0 ? void 0 : { cause: options.cause });
17
+ this.status = options.status ?? null;
18
+ this.detail = options.detail ?? null;
19
+ }
20
+ };
21
+ var DoclingHttpError = class extends DoclingServiceError {
22
+ method;
23
+ url;
24
+ status;
25
+ body;
26
+ headers;
27
+ constructor(options) {
28
+ const serialized = typeof options.body === "string" ? options.body : safeSerialize(options.body);
29
+ super(
30
+ `Docling request ${options.method} ${options.url} returned HTTP ${options.status}${serialized === "" ? "" : `: ${serialized.slice(0, 500)}`}`,
31
+ { status: options.status, detail: options.detail }
32
+ );
33
+ this.method = options.method;
34
+ this.url = options.url;
35
+ this.status = options.status;
36
+ this.body = options.body;
37
+ this.headers = options.headers ?? {};
38
+ }
39
+ };
40
+ function safeSerialize(value) {
41
+ if (value === void 0) {
42
+ return "";
43
+ }
44
+ try {
45
+ return JSON.stringify(value) ?? "";
46
+ } catch {
47
+ return String(value);
48
+ }
49
+ }
50
+ var DoclingProtocolError = class extends DoclingError {
51
+ };
52
+ var DoclingResponseSchemaMismatchError = class extends DoclingServiceError {
53
+ };
54
+ var DoclingServiceUnavailableError = class extends DoclingServiceError {
55
+ };
56
+ var DoclingUsageLimitExceededError = class extends DoclingHttpError {
57
+ currentUsage;
58
+ limit;
59
+ constructor(options) {
60
+ super(options);
61
+ this.currentUsage = options.currentUsage ?? null;
62
+ this.limit = options.limit ?? null;
63
+ }
64
+ };
65
+ var DoclingTaskError = class extends DoclingError {
66
+ task;
67
+ failure;
68
+ constructor(task) {
69
+ super(
70
+ task.failure?.message ?? task.error_message ?? `Docling task ${task.task_id} failed`
71
+ );
72
+ this.task = task;
73
+ if (task.failure !== void 0 && task.failure !== null) {
74
+ this.failure = task.failure;
75
+ }
76
+ }
77
+ };
78
+ var DoclingTimeoutError = class extends DoclingError {
79
+ taskId;
80
+ timeoutMs;
81
+ constructor(taskId, timeoutMs) {
82
+ super(`Docling task ${taskId} did not finish within ${timeoutMs} ms`);
83
+ this.taskId = taskId;
84
+ this.timeoutMs = timeoutMs;
85
+ }
86
+ };
87
+ var DoclingTaskNotFoundError = class extends DoclingError {
88
+ taskId;
89
+ constructor(taskId) {
90
+ super(`Docling task ${taskId} was not found`);
91
+ this.taskId = taskId;
92
+ }
93
+ };
94
+ var DoclingResultNotReadyError = class extends DoclingError {
95
+ taskId;
96
+ constructor(taskId) {
97
+ super(`Result for Docling task ${taskId} is not ready`);
98
+ this.taskId = taskId;
99
+ }
100
+ };
101
+ var DoclingResultExpiredError = class extends DoclingError {
102
+ taskId;
103
+ constructor(taskId) {
104
+ super(`Result for Docling task ${taskId} has expired`);
105
+ this.taskId = taskId;
106
+ }
107
+ };
108
+ var DoclingArtifactDownloadError = class extends DoclingError {
109
+ };
110
+ var DoclingConversionError = class extends DoclingError {
111
+ };
112
+ var DoclingBatchConversionError = class extends DoclingError {
113
+ failures;
114
+ constructor(message, failures) {
115
+ super(`${message} (${failures.length} failure(s))`);
116
+ this.failures = failures;
117
+ }
118
+ };
119
+
120
+ // src/artifacts.ts
121
+ var ArtifactDownloader = class {
122
+ #fetch;
123
+ #resolver;
124
+ #allowPrivateUrls;
125
+ #timeoutMs;
126
+ #maxBytes;
127
+ #maxRedirects;
128
+ constructor(options = {}) {
129
+ if (options.fetch === void 0 && globalThis.fetch === void 0) {
130
+ throw new DoclingArtifactDownloadError(
131
+ "No fetch implementation is available for artifact downloads"
132
+ );
133
+ }
134
+ this.#fetch = options.fetch ?? globalThis.fetch;
135
+ this.#resolver = options.resolver ?? resolveAllAddresses;
136
+ this.#allowPrivateUrls = options.allowPrivateUrls ?? false;
137
+ this.#timeoutMs = options.timeoutMs ?? 6e4;
138
+ this.#maxBytes = options.maxBytes ?? 512 * 1024 * 1024;
139
+ this.#maxRedirects = options.maxRedirects ?? 5;
140
+ validateArtifactLimits(this.#timeoutMs, this.#maxBytes, this.#maxRedirects);
141
+ }
142
+ async download(url, signal) {
143
+ let currentUrl = url;
144
+ for (let redirects = 0; redirects <= this.#maxRedirects; redirects += 1) {
145
+ await this.#validateUrl(currentUrl);
146
+ const controller = new AbortController();
147
+ const timeout = setTimeout(() => {
148
+ controller.abort(
149
+ new DoclingArtifactDownloadError(
150
+ `Artifact download exceeded ${this.#timeoutMs} ms`
151
+ )
152
+ );
153
+ }, this.#timeoutMs);
154
+ const combinedSignal = combineAbortSignals(signal, controller.signal);
155
+ try {
156
+ const response = await this.#fetch(currentUrl, {
157
+ redirect: "manual",
158
+ signal: combinedSignal
159
+ });
160
+ if (isRedirect(response.status)) {
161
+ if (redirects >= this.#maxRedirects) {
162
+ throw new DoclingArtifactDownloadError(
163
+ `Artifact download exceeded ${this.#maxRedirects} redirects`
164
+ );
165
+ }
166
+ const location = response.headers.get("location");
167
+ if (location === null || location === "") {
168
+ throw new DoclingArtifactDownloadError(
169
+ "Artifact redirect response is missing Location"
170
+ );
171
+ }
172
+ currentUrl = new URL(location, currentUrl).toString();
173
+ await response.body?.cancel();
174
+ continue;
175
+ }
176
+ if (response.status !== 200) {
177
+ throw new DoclingArtifactDownloadError(
178
+ `Artifact download returned HTTP ${response.status}`
179
+ );
180
+ }
181
+ return await readBoundedBody(response, this.#maxBytes, combinedSignal);
182
+ } catch (error) {
183
+ if (signal?.aborted === true) {
184
+ throw signal.reason;
185
+ }
186
+ if (error instanceof DoclingArtifactDownloadError) {
187
+ throw error;
188
+ }
189
+ throw new DoclingArtifactDownloadError(
190
+ `Artifact download failed for ${currentUrl}`,
191
+ { cause: error }
192
+ );
193
+ } finally {
194
+ clearTimeout(timeout);
195
+ }
196
+ }
197
+ throw new DoclingArtifactDownloadError("Artifact redirect loop did not terminate");
198
+ }
199
+ async #validateUrl(value) {
200
+ let url;
201
+ try {
202
+ url = new URL(value);
203
+ } catch (error) {
204
+ throw new DoclingArtifactDownloadError("Artifact URL is invalid", {
205
+ cause: error
206
+ });
207
+ }
208
+ if (!["http:", "https:"].includes(url.protocol) || url.hostname === "") {
209
+ throw new DoclingArtifactDownloadError(
210
+ "Artifact URL must be an absolute HTTP(S) URL"
211
+ );
212
+ }
213
+ if (this.#allowPrivateUrls) {
214
+ return;
215
+ }
216
+ const hostname = url.hostname.replace(/^\[|\]$/g, "");
217
+ let addresses;
218
+ try {
219
+ addresses = ipaddr.isValid(hostname) ? [hostname] : await this.#resolver(hostname);
220
+ } catch (error) {
221
+ throw new DoclingArtifactDownloadError(
222
+ `Could not resolve artifact host ${hostname}`,
223
+ { cause: error }
224
+ );
225
+ }
226
+ if (addresses.length === 0 || addresses.some((address) => !isGlobalAddress(address))) {
227
+ throw new DoclingArtifactDownloadError(
228
+ `Artifact URL does not resolve exclusively to globally routable addresses: ${url.hostname}`
229
+ );
230
+ }
231
+ }
232
+ };
233
+ async function materializePresignedResult(response, input, downloader, signal) {
234
+ const item = response.documents[0];
235
+ if (item === void 0) {
236
+ return failedConversion(
237
+ input,
238
+ response.processing_time,
239
+ "Presigned result contained no documents"
240
+ );
241
+ }
242
+ if (item.status === "failure") {
243
+ return conversionFromArtifactItem(
244
+ item,
245
+ input,
246
+ response.processing_time,
247
+ emptyDocument(item.filename || input.filename)
248
+ );
249
+ }
250
+ try {
251
+ const artifact = selectDocumentArtifact(item);
252
+ const bytes = await downloader.download(artifact.uri, signal);
253
+ const document = artifact.artifact_type === "resource_bundle" ? documentFromBundle(bytes) : documentFromJson(bytes);
254
+ return conversionFromArtifactItem(item, input, response.processing_time, document);
255
+ } catch (error) {
256
+ if (signal?.aborted === true || isAbortError(error)) {
257
+ throw signal?.reason ?? error;
258
+ }
259
+ const message = error instanceof DoclingArtifactDownloadError ? error.message : `Failed to reconstruct document from presigned artifacts: ${error instanceof Error ? error.message : String(error)}`;
260
+ return failedConversion(input, response.processing_time, message);
261
+ }
262
+ }
263
+ function isAbortError(value) {
264
+ return value instanceof Error && value.name === "AbortError";
265
+ }
266
+ function selectDocumentArtifact(item) {
267
+ const bundle = item.artifacts.find(
268
+ (artifact) => artifact.artifact_type === "resource_bundle"
269
+ );
270
+ if (bundle !== void 0) {
271
+ return bundle;
272
+ }
273
+ const json = item.artifacts.find((artifact) => artifact.artifact_type === "json");
274
+ if (json !== void 0) {
275
+ return json;
276
+ }
277
+ throw new DoclingArtifactDownloadError(
278
+ "Presigned result exposes neither a 'json' nor a 'resource_bundle' artifact"
279
+ );
280
+ }
281
+ function documentFromBundle(bytes) {
282
+ let entries;
283
+ try {
284
+ entries = unzipBundle(bytes);
285
+ } catch (error) {
286
+ if (error instanceof DoclingArtifactDownloadError) {
287
+ throw error;
288
+ }
289
+ throw new DoclingArtifactDownloadError(
290
+ "Downloaded resource bundle is not a valid ZIP",
291
+ { cause: error }
292
+ );
293
+ }
294
+ for (const name of Object.keys(entries)) {
295
+ validateBundlePath(name);
296
+ }
297
+ const jsonNames = Object.keys(entries).filter((name) => !name.includes("/") && name.toLowerCase().endsWith(".json")).sort();
298
+ if (jsonNames.length !== 1) {
299
+ throw new DoclingArtifactDownloadError(
300
+ `Resource bundle must contain exactly one top-level JSON document; found ${jsonNames.length}`
301
+ );
302
+ }
303
+ const jsonName = jsonNames[0];
304
+ const jsonBytes = entries[jsonName];
305
+ if (jsonBytes === void 0) {
306
+ throw new DoclingArtifactDownloadError("Resource bundle JSON is missing");
307
+ }
308
+ const document = documentFromJson(jsonBytes);
309
+ embedBundleImages(document, entries);
310
+ return document;
311
+ }
312
+ function documentFromJson(bytes) {
313
+ let value;
314
+ try {
315
+ value = JSON.parse(new TextDecoder().decode(bytes));
316
+ } catch (error) {
317
+ throw new DoclingArtifactDownloadError(
318
+ "Downloaded artifact is not valid Docling JSON",
319
+ { cause: error }
320
+ );
321
+ }
322
+ if (!isRecord(value) || value.schema_name !== "DoclingDocument" || typeof value.name !== "string") {
323
+ throw new DoclingArtifactDownloadError(
324
+ "Downloaded artifact is not a DoclingDocument"
325
+ );
326
+ }
327
+ return value;
328
+ }
329
+ function conversionFromArtifactItem(item, fallbackInput2, processingTime, document) {
330
+ return {
331
+ input: {
332
+ ...fallbackInput2,
333
+ filename: item.filename || fallbackInput2.filename,
334
+ source: item.source_uri || fallbackInput2.source
335
+ },
336
+ document,
337
+ status: item.status,
338
+ errors: item.errors,
339
+ processing_time: processingTime,
340
+ timings: item.timings,
341
+ ...item.confidence === void 0 ? {} : { confidence: item.confidence }
342
+ };
343
+ }
344
+ function failedConversion(input, processingTime, message) {
345
+ const error = {
346
+ component_type: "user_input",
347
+ module_name: "@docling/docling-client",
348
+ error_message: message,
349
+ category: "unknown"
350
+ };
351
+ return {
352
+ input,
353
+ document: emptyDocument(input.filename),
354
+ status: "failure",
355
+ errors: [error],
356
+ processing_time: processingTime,
357
+ timings: {}
358
+ };
359
+ }
360
+ function emptyDocument(filename) {
361
+ const leaf = filename.replaceAll("\\", "/").split("/").at(-1) ?? filename;
362
+ const extension = leaf.lastIndexOf(".");
363
+ const name = extension > 0 ? leaf.slice(0, extension) : leaf;
364
+ return {
365
+ schema_name: "DoclingDocument",
366
+ name: name || "document"
367
+ };
368
+ }
369
+ function embedBundleImages(document, entries) {
370
+ if (!isRecord(document)) {
371
+ return;
372
+ }
373
+ if (Array.isArray(document.pictures)) {
374
+ for (const picture of document.pictures) {
375
+ if (isRecord(picture) && isRecord(picture.image)) {
376
+ embedImageRef(picture.image, entries);
377
+ }
378
+ }
379
+ }
380
+ if (isRecord(document.pages)) {
381
+ for (const page of Object.values(document.pages)) {
382
+ if (isRecord(page) && isRecord(page.image)) {
383
+ embedImageRef(page.image, entries);
384
+ }
385
+ }
386
+ }
387
+ }
388
+ function embedImageRef(value, entries) {
389
+ if (!isImageRef(value)) {
390
+ throw new DoclingArtifactDownloadError(
391
+ "Resource bundle contains an invalid image reference"
392
+ );
393
+ }
394
+ const uri = value.uri;
395
+ if (uri.startsWith("data:") || uri.startsWith("http://") || uri.startsWith("https://")) {
396
+ return;
397
+ }
398
+ const path = normalizeBundleReference(uri);
399
+ const content = entries[path];
400
+ if (content === void 0) {
401
+ throw new DoclingArtifactDownloadError(`Resource bundle image is missing: ${uri}`);
402
+ }
403
+ if (!isSupportedImage(value.mimetype, content)) {
404
+ throw new DoclingArtifactDownloadError(
405
+ `Resource bundle image bytes do not match ${value.mimetype}`
406
+ );
407
+ }
408
+ value.uri = `data:${value.mimetype};base64,${bytesToBase64(content)}`;
409
+ }
410
+ function validateBundlePath(value) {
411
+ const normalized = value.replaceAll("\\", "/");
412
+ if (normalized.startsWith("/") || /^[a-z]:\//i.test(normalized) || normalized.split("/").some((part) => part === "..")) {
413
+ throw new DoclingArtifactDownloadError(
414
+ `Resource bundle contains an unsafe path: ${value}`
415
+ );
416
+ }
417
+ }
418
+ function normalizeBundleReference(value) {
419
+ validateBundlePath(value);
420
+ return value.replaceAll("\\", "/").replace(/^\.\//, "");
421
+ }
422
+ function isImageRef(value) {
423
+ return typeof value.mimetype === "string" && typeof value.dpi === "number" && typeof value.uri === "string";
424
+ }
425
+ function isSupportedImage(mimeType, bytes) {
426
+ const mime = mimeType.toLowerCase();
427
+ if (mime === "image/png") {
428
+ return startsWith(bytes, [137, 80, 78, 71, 13, 10, 26, 10]);
429
+ }
430
+ if (mime === "image/jpeg") {
431
+ return startsWith(bytes, [255, 216, 255]);
432
+ }
433
+ if (mime === "image/gif") {
434
+ return new TextDecoder().decode(bytes.subarray(0, 6)).startsWith("GIF8");
435
+ }
436
+ if (mime === "image/webp") {
437
+ return new TextDecoder().decode(bytes.subarray(0, 4)) === "RIFF" && new TextDecoder().decode(bytes.subarray(8, 12)) === "WEBP";
438
+ }
439
+ if (mime === "image/bmp") {
440
+ return startsWith(bytes, [66, 77]);
441
+ }
442
+ if (mime === "image/tiff") {
443
+ return startsWith(bytes, [73, 73, 42, 0]) || startsWith(bytes, [77, 77, 0, 42]);
444
+ }
445
+ return false;
446
+ }
447
+ function startsWith(bytes, prefix) {
448
+ return bytes.length >= prefix.length && prefix.every((value, index) => bytes[index] === value);
449
+ }
450
+ function unzipBundle(bytes) {
451
+ const entries = {};
452
+ const maxEntries = 1e4;
453
+ const maxUncompressedBytes = 512 * 1024 * 1024;
454
+ let entryCount = 0;
455
+ let total = 0;
456
+ const archive = new Unzip((file) => {
457
+ entryCount += 1;
458
+ if (entryCount > maxEntries) {
459
+ throw new DoclingArtifactDownloadError(
460
+ `Resource bundle exceeds ${maxEntries} entries`
461
+ );
462
+ }
463
+ validateBundlePath(file.name);
464
+ const chunks = [];
465
+ file.ondata = (error, chunk, final) => {
466
+ if (error !== null) {
467
+ throw error;
468
+ }
469
+ total += chunk.byteLength;
470
+ if (total > maxUncompressedBytes) {
471
+ throw new DoclingArtifactDownloadError(
472
+ `Resource bundle exceeds ${maxUncompressedBytes} uncompressed bytes`
473
+ );
474
+ }
475
+ chunks.push(chunk);
476
+ if (final) {
477
+ const content = new Uint8Array(
478
+ chunks.reduce((sum, value) => sum + value.byteLength, 0)
479
+ );
480
+ let offset = 0;
481
+ for (const value of chunks) {
482
+ content.set(value, offset);
483
+ offset += value.byteLength;
484
+ }
485
+ entries[file.name] = content;
486
+ }
487
+ };
488
+ file.start();
489
+ });
490
+ archive.register(UnzipInflate);
491
+ archive.push(bytes, true);
492
+ return entries;
493
+ }
494
+ function isRecord(value) {
495
+ return value !== null && typeof value === "object" && !Array.isArray(value);
496
+ }
497
+ function isRedirect(status) {
498
+ return [301, 302, 303, 307, 308].includes(status);
499
+ }
500
+ async function readBoundedBody(response, maxBytes, signal) {
501
+ if (response.body === null) {
502
+ return new Uint8Array();
503
+ }
504
+ const reader = response.body.getReader();
505
+ const chunks = [];
506
+ let total = 0;
507
+ try {
508
+ while (true) {
509
+ if (signal?.aborted === true) {
510
+ throw signal.reason;
511
+ }
512
+ const next = await reader.read();
513
+ if (next.done) {
514
+ break;
515
+ }
516
+ total += next.value.byteLength;
517
+ if (total > maxBytes) {
518
+ await reader.cancel();
519
+ throw new DoclingArtifactDownloadError(
520
+ `Artifact exceeds the ${maxBytes} byte download limit`
521
+ );
522
+ }
523
+ chunks.push(next.value);
524
+ }
525
+ } finally {
526
+ reader.releaseLock();
527
+ }
528
+ const result = new Uint8Array(total);
529
+ let offset = 0;
530
+ for (const chunk of chunks) {
531
+ result.set(chunk, offset);
532
+ offset += chunk.byteLength;
533
+ }
534
+ return result;
535
+ }
536
+ async function resolveAllAddresses(hostname) {
537
+ const { lookup } = await import("dns/promises");
538
+ const addresses = await lookup(hostname, { all: true, verbatim: true });
539
+ return addresses.map((item) => item.address);
540
+ }
541
+ function isGlobalAddress(value) {
542
+ if (!ipaddr.isValid(value)) {
543
+ return false;
544
+ }
545
+ const address = ipaddr.parse(value);
546
+ if (address.kind() === "ipv6") {
547
+ const ipv6 = address;
548
+ if (ipv6.isIPv4MappedAddress()) {
549
+ return ipv6.toIPv4Address().range() === "unicast";
550
+ }
551
+ }
552
+ return address.range() === "unicast";
553
+ }
554
+ function validateArtifactLimits(timeoutMs, maxBytes, maxRedirects) {
555
+ if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {
556
+ throw new DoclingArtifactDownloadError("Artifact timeout must be positive");
557
+ }
558
+ if (!Number.isSafeInteger(maxBytes) || maxBytes < 0) {
559
+ throw new DoclingArtifactDownloadError(
560
+ "Artifact size limit must be a non-negative safe integer"
561
+ );
562
+ }
563
+ if (!Number.isSafeInteger(maxRedirects) || maxRedirects < 0) {
564
+ throw new DoclingArtifactDownloadError(
565
+ "Artifact redirect limit must be a non-negative safe integer"
566
+ );
567
+ }
568
+ }
569
+ function combineAbortSignals(callerSignal, timeoutSignal) {
570
+ if (callerSignal === void 0) {
571
+ return timeoutSignal;
572
+ }
573
+ if (typeof AbortSignal.any === "function") {
574
+ return AbortSignal.any([callerSignal, timeoutSignal]);
575
+ }
576
+ const controller = new AbortController();
577
+ const abort = (signal) => controller.abort(signal.reason);
578
+ if (callerSignal.aborted) {
579
+ abort(callerSignal);
580
+ } else {
581
+ callerSignal.addEventListener("abort", () => abort(callerSignal), {
582
+ once: true
583
+ });
584
+ }
585
+ timeoutSignal.addEventListener("abort", () => abort(timeoutSignal), {
586
+ once: true
587
+ });
588
+ return controller.signal;
589
+ }
590
+ function bytesToBase64(bytes) {
591
+ if (typeof Buffer !== "undefined") {
592
+ return Buffer.from(bytes).toString("base64");
593
+ }
594
+ let binary = "";
595
+ for (let offset = 0; offset < bytes.length; offset += 32768) {
596
+ binary += String.fromCharCode(...bytes.subarray(offset, offset + 32768));
597
+ }
598
+ return btoa(binary);
599
+ }
600
+
601
+ // src/scheduler.ts
602
+ async function* boundedOutcomes(items, process, options) {
603
+ validateConcurrency(options.maxInFlight);
604
+ const iterator = toAsyncIterator(items);
605
+ const controller = new AbortController();
606
+ const signal = combineAbortSignals2(options.signal, controller.signal);
607
+ if (signal.aborted) {
608
+ throw abortReason(signal);
609
+ }
610
+ const active = /* @__PURE__ */ new Map();
611
+ const buffered = /* @__PURE__ */ new Map();
612
+ let nextInputIndex = 0;
613
+ let nextOutputIndex = 0;
614
+ let exhausted = false;
615
+ const startNext = async () => {
616
+ if (exhausted || signal.aborted) {
617
+ return;
618
+ }
619
+ const next = await iterator.next();
620
+ if (next.done === true) {
621
+ exhausted = true;
622
+ return;
623
+ }
624
+ const index = nextInputIndex;
625
+ nextInputIndex += 1;
626
+ const item = next.value;
627
+ const operation = process(item, index, signal).then((outcome) => ({ index, item, outcome })).catch((error) => {
628
+ if (signal.aborted) {
629
+ throw abortReason(signal);
630
+ }
631
+ return {
632
+ index,
633
+ item,
634
+ outcome: normalizeError(error)
635
+ };
636
+ });
637
+ active.set(index, operation);
638
+ };
639
+ try {
640
+ while (active.size < options.maxInFlight && !exhausted) {
641
+ await startNext();
642
+ }
643
+ while (active.size > 0) {
644
+ const completed = await Promise.race(active.values());
645
+ active.delete(completed.index);
646
+ await startNext();
647
+ if (!options.ordered) {
648
+ yield completed;
649
+ continue;
650
+ }
651
+ buffered.set(completed.index, completed);
652
+ while (buffered.has(nextOutputIndex)) {
653
+ const ready = buffered.get(nextOutputIndex);
654
+ buffered.delete(nextOutputIndex);
655
+ nextOutputIndex += 1;
656
+ if (ready !== void 0) {
657
+ yield ready;
658
+ }
659
+ }
660
+ }
661
+ } finally {
662
+ controller.abort(new Error("Docling bounded operation stopped"));
663
+ await Promise.allSettled(active.values());
664
+ await iterator.return?.();
665
+ }
666
+ }
667
+ function abortReason(signal) {
668
+ return signal.reason instanceof Error ? signal.reason : new DOMException("The operation was aborted", "AbortError");
669
+ }
670
+ function validateConcurrency(value) {
671
+ if (!Number.isSafeInteger(value) || value < 1 || value > 512) {
672
+ throw new DoclingProtocolError(
673
+ "Concurrency must be a safe integer between 1 and 512"
674
+ );
675
+ }
676
+ return value;
677
+ }
678
+ function toAsyncIterator(items) {
679
+ if (Symbol.asyncIterator in Object(items)) {
680
+ return items[Symbol.asyncIterator]();
681
+ }
682
+ const iterator = items[Symbol.iterator]();
683
+ return {
684
+ next: async () => iterator.next(),
685
+ return: iterator.return === void 0 ? void 0 : async () => {
686
+ const returned = iterator.return?.();
687
+ return returned ?? { done: true, value: void 0 };
688
+ }
689
+ };
690
+ }
691
+ function normalizeError(value) {
692
+ return value instanceof Error ? value : new Error(String(value));
693
+ }
694
+ function combineAbortSignals2(callerSignal, internalSignal) {
695
+ if (callerSignal === void 0) {
696
+ return internalSignal;
697
+ }
698
+ if (typeof AbortSignal.any === "function") {
699
+ return AbortSignal.any([callerSignal, internalSignal]);
700
+ }
701
+ const controller = new AbortController();
702
+ const abort = (signal) => controller.abort(signal.reason);
703
+ if (callerSignal.aborted) {
704
+ abort(callerSignal);
705
+ } else {
706
+ callerSignal.addEventListener("abort", () => abort(callerSignal), {
707
+ once: true
708
+ });
709
+ }
710
+ internalSignal.addEventListener("abort", () => abort(internalSignal), {
711
+ once: true
712
+ });
713
+ return controller.signal;
714
+ }
715
+
716
+ // src/sources.ts
717
+ var EXTENSION_FORMATS = {
718
+ pdf: "pdf",
719
+ docx: "docx",
720
+ dotx: "docx",
721
+ docm: "docx",
722
+ dotm: "docx",
723
+ doc: "doc",
724
+ dot: "doc",
725
+ pptx: "pptx",
726
+ potx: "pptx",
727
+ ppsx: "pptx",
728
+ pptm: "pptx",
729
+ potm: "pptx",
730
+ ppsm: "pptx",
731
+ ppt: "ppt",
732
+ pot: "ppt",
733
+ pps: "ppt",
734
+ html: "html",
735
+ htm: "html",
736
+ xhtml: "html",
737
+ md: "md",
738
+ markdown: "md",
739
+ txt: "md",
740
+ text: "md",
741
+ qmd: "md",
742
+ rmd: "md",
743
+ csv: "csv",
744
+ xlsx: "xlsx",
745
+ xlsm: "xlsx",
746
+ xls: "xls",
747
+ xlt: "xls",
748
+ asciidoc: "asciidoc",
749
+ adoc: "asciidoc",
750
+ asc: "asciidoc",
751
+ json: "json_docling",
752
+ dclx: "dclx",
753
+ "dclg.xml": "xml_doclang",
754
+ dclg: "xml_doclang",
755
+ xml: "xml_jats",
756
+ nxml: "xml_jats",
757
+ xbrl: "xml_xbrl",
758
+ "tar.gz": "mets_gbs",
759
+ jpg: "image",
760
+ jpeg: "image",
761
+ png: "image",
762
+ tif: "image",
763
+ tiff: "image",
764
+ bmp: "image",
765
+ webp: "image",
766
+ wav: "audio",
767
+ mp3: "audio",
768
+ m4a: "audio",
769
+ aac: "audio",
770
+ ogg: "audio",
771
+ flac: "audio",
772
+ mp4: "video",
773
+ avi: "video",
774
+ mov: "video",
775
+ mkv: "video",
776
+ webm: "video",
777
+ vtt: "vtt",
778
+ odt: "odt",
779
+ ott: "odt",
780
+ ods: "ods",
781
+ ots: "ods",
782
+ odp: "odp",
783
+ otp: "odp",
784
+ tex: "latex",
785
+ latex: "latex",
786
+ eml: "email",
787
+ epub: "epub",
788
+ boxnote: "boxnote"
789
+ };
790
+ async function normalizeSourceInput(input, signal) {
791
+ throwIfAborted(signal);
792
+ if (typeof input === "string") {
793
+ return normalizeStringSource(input, signal);
794
+ }
795
+ if (input instanceof URL) {
796
+ return normalizeHttpUrl(input.toString());
797
+ }
798
+ if (isHttpSource(input)) {
799
+ validateHttpUrl(input.url, true);
800
+ const normalized = {
801
+ kind: "json",
802
+ source: clone(input),
803
+ descriptor: describeHttpSource(input.url)
804
+ };
805
+ throwIfAborted(signal);
806
+ return normalized;
807
+ }
808
+ if (isFileSource(input)) {
809
+ const normalized = {
810
+ kind: "json",
811
+ source: clone(input),
812
+ descriptor: {
813
+ filename: input.filename,
814
+ source: input.filename,
815
+ format: guessInputFormat(input.filename),
816
+ file_size: base64ByteLength(input.base64_string)
817
+ }
818
+ };
819
+ throwIfAborted(signal);
820
+ return normalized;
821
+ }
822
+ if (isBinaryFileSource(input)) {
823
+ const blob = await toBlob(input.data, input.contentType);
824
+ throwIfAborted(signal);
825
+ return {
826
+ kind: "multipart",
827
+ blob,
828
+ descriptor: {
829
+ filename: input.filename,
830
+ source: input.filename,
831
+ format: guessInputFormat(input.filename),
832
+ file_size: blob.size
833
+ }
834
+ };
835
+ }
836
+ throw new DoclingProtocolError("Unsupported Docling conversion source");
837
+ }
838
+ function resolveConvertOptions(defaults, overrides) {
839
+ const resolved = clone(defaults);
840
+ for (const [key, value] of Object.entries(overrides ?? {})) {
841
+ if (value === void 0) {
842
+ continue;
843
+ }
844
+ if (value === null) {
845
+ delete resolved[key];
846
+ continue;
847
+ }
848
+ resolved[key] = clone(value);
849
+ }
850
+ decodeNestedConfigStrings(resolved);
851
+ validateConvertOptions(resolved);
852
+ return resolved;
853
+ }
854
+ function decodeNestedConfigStrings(options) {
855
+ for (const key of JSON_STRING_CONFIG_OPTIONS) {
856
+ const value = options[key];
857
+ if (typeof value !== "string") {
858
+ continue;
859
+ }
860
+ let decoded;
861
+ try {
862
+ decoded = JSON.parse(value);
863
+ } catch (error) {
864
+ throw new DoclingProtocolError(`${key} contains invalid JSON`, {
865
+ cause: error
866
+ });
867
+ }
868
+ if (decoded === null || typeof decoded !== "object" || Array.isArray(decoded)) {
869
+ throw new DoclingProtocolError(`${key} JSON must decode to an object`);
870
+ }
871
+ options[key] = decoded;
872
+ }
873
+ }
874
+ function withJsonOutput(options) {
875
+ const formats = options.to_formats ?? ["md"];
876
+ if (formats.includes("json")) {
877
+ return clone(options);
878
+ }
879
+ return {
880
+ ...clone(options),
881
+ to_formats: [...formats, "json"]
882
+ };
883
+ }
884
+ function validateConvertOptions(options) {
885
+ validateStringEnumArray(options.from_formats, INPUT_FORMATS, "from_formats");
886
+ validateStringEnumArray(options.to_formats, OUTPUT_FORMATS, "to_formats");
887
+ validateStringEnum(options.pipeline, PIPELINES, "pipeline");
888
+ validateStringEnum(
889
+ options.image_export_mode,
890
+ IMAGE_EXPORT_MODES,
891
+ "image_export_mode"
892
+ );
893
+ validateStringEnum(options.table_mode, TABLE_MODES, "table_mode");
894
+ validateStringEnum(options.pdf_backend, PDF_BACKENDS, "pdf_backend");
895
+ if (options.vlm_pipeline_model !== void 0 && options.vlm_pipeline_model !== null) {
896
+ validateStringEnum(
897
+ options.vlm_pipeline_model,
898
+ LEGACY_VLM_MODELS,
899
+ "vlm_pipeline_model"
900
+ );
901
+ }
902
+ if (options.page_range !== void 0) {
903
+ validatePageRange(options.page_range);
904
+ }
905
+ for (const key of BOOLEAN_OPTIONS) {
906
+ const value = options[key];
907
+ if (value !== void 0 && typeof value !== "boolean") {
908
+ throw new DoclingProtocolError(`${key} must be a boolean`);
909
+ }
910
+ }
911
+ for (const key of NUMBER_OPTIONS) {
912
+ const value = options[key];
913
+ if (value !== void 0 && value !== null && (typeof value !== "number" || !Number.isFinite(value))) {
914
+ throw new DoclingProtocolError(`${key} must be a finite number or null`);
915
+ }
916
+ }
917
+ for (const key of STRING_OPTIONS) {
918
+ const value = options[key];
919
+ if (value !== void 0 && value !== null && typeof value !== "string") {
920
+ throw new DoclingProtocolError(`${key} must be a string or null`);
921
+ }
922
+ }
923
+ if (options.ocr_lang !== void 0 && options.ocr_lang !== null && (!Array.isArray(options.ocr_lang) || options.ocr_lang.some((value) => typeof value !== "string"))) {
924
+ throw new DoclingProtocolError("ocr_lang must be an array of strings or null");
925
+ }
926
+ for (const key of RECORD_OPTIONS) {
927
+ const value = options[key];
928
+ if (value !== void 0 && value !== null && (typeof value !== "object" || Array.isArray(value))) {
929
+ throw new DoclingProtocolError(`${key} must be an object or null`);
930
+ }
931
+ }
932
+ validateLegacyPictureDescription(options.picture_description_local);
933
+ validateLegacyPictureDescription(options.picture_description_api, true);
934
+ validateLegacyVlmModel(options.vlm_pipeline_model_local);
935
+ validateLegacyVlmModel(options.vlm_pipeline_model_api, true);
936
+ validateOptionExclusivity(options);
937
+ }
938
+ function validateLegacyPictureDescription(value, api = false) {
939
+ if (value === void 0 || value === null) {
940
+ return;
941
+ }
942
+ if (!isRecord2(value)) {
943
+ throw new DoclingProtocolError(
944
+ `${api ? "picture_description_api" : "picture_description_local"} must be an object`
945
+ );
946
+ }
947
+ const path = api ? "picture_description_api" : "picture_description_local";
948
+ if (api) {
949
+ validateAbsoluteUrl(value.url, `${path}.url`);
950
+ validateOptionalStringRecord(value.headers, `${path}.headers`);
951
+ validateOptionalRecord(value.params, `${path}.params`);
952
+ validateOptionalPositiveInteger(value.concurrency, `${path}.concurrency`);
953
+ validateOptionalFiniteNumber(value.timeout, `${path}.timeout`);
954
+ } else {
955
+ validateRequiredString(value.repo_id, `${path}.repo_id`);
956
+ validateOptionalRecord(value.generation_config, `${path}.generation_config`);
957
+ }
958
+ validateOptionalString(value.prompt, `${path}.prompt`);
959
+ validateOptionalEnumArray(
960
+ value.classification_allow,
961
+ PICTURE_CLASSIFICATION_LABELS,
962
+ `${path}.classification_allow`
963
+ );
964
+ validateOptionalEnumArray(
965
+ value.classification_deny,
966
+ PICTURE_CLASSIFICATION_LABELS,
967
+ `${path}.classification_deny`
968
+ );
969
+ const minimum = value.classification_min_confidence;
970
+ if (minimum !== void 0 && (typeof minimum !== "number" || !Number.isFinite(minimum) || minimum < 0 || minimum > 1)) {
971
+ throw new DoclingProtocolError(
972
+ `${path}.classification_min_confidence must be between 0 and 1`
973
+ );
974
+ }
975
+ }
976
+ function validateLegacyVlmModel(value, api = false) {
977
+ if (value === void 0 || value === null) {
978
+ return;
979
+ }
980
+ if (!isRecord2(value)) {
981
+ throw new DoclingProtocolError(
982
+ `${api ? "vlm_pipeline_model_api" : "vlm_pipeline_model_local"} must be an object`
983
+ );
984
+ }
985
+ const path = api ? "vlm_pipeline_model_api" : "vlm_pipeline_model_local";
986
+ if (api) {
987
+ validateAbsoluteUrl(value.url, `${path}.url`);
988
+ validateOptionalStringRecord(value.headers, `${path}.headers`);
989
+ validateOptionalRecord(value.params, `${path}.params`);
990
+ validateOptionalPositiveInteger(value.concurrency, `${path}.concurrency`);
991
+ validateOptionalFiniteNumber(value.timeout, `${path}.timeout`);
992
+ } else {
993
+ validateRequiredString(value.repo_id, `${path}.repo_id`);
994
+ validateRequiredEnum(
995
+ value.inference_framework,
996
+ VLM_INFERENCE_FRAMEWORKS,
997
+ `${path}.inference_framework`
998
+ );
999
+ validateStringEnum(
1000
+ value.transformers_model_type,
1001
+ TRANSFORMERS_MODEL_TYPES,
1002
+ `${path}.transformers_model_type`
1003
+ );
1004
+ validateOptionalRecord(
1005
+ value.extra_generation_config,
1006
+ `${path}.extra_generation_config`
1007
+ );
1008
+ }
1009
+ validateRequiredEnum(
1010
+ value.response_format,
1011
+ VLM_RESPONSE_FORMATS,
1012
+ `${path}.response_format`
1013
+ );
1014
+ validateOptionalString(value.prompt, `${path}.prompt`);
1015
+ validateOptionalFiniteNumber(value.scale, `${path}.scale`);
1016
+ validateOptionalFiniteNumber(value.temperature, `${path}.temperature`);
1017
+ }
1018
+ function validateOptionExclusivity(options) {
1019
+ const present = (...values) => values.filter((value) => value !== void 0 && value !== null).length;
1020
+ const conflicting = (preset, custom) => typeof preset === "string" && preset !== "" && isRecord2(custom) && Object.keys(custom).length > 0;
1021
+ if (present(options.picture_description_local, options.picture_description_api) > 1) {
1022
+ throw new DoclingProtocolError(
1023
+ "picture_description_local and picture_description_api are mutually exclusive"
1024
+ );
1025
+ }
1026
+ const legacyVlmCount = present(
1027
+ options.vlm_pipeline_model,
1028
+ options.vlm_pipeline_model_local,
1029
+ options.vlm_pipeline_model_api
1030
+ );
1031
+ if (legacyVlmCount > 1) {
1032
+ throw new DoclingProtocolError(
1033
+ "vlm_pipeline_model, vlm_pipeline_model_local, and vlm_pipeline_model_api are mutually exclusive"
1034
+ );
1035
+ }
1036
+ if (conflicting(options.vlm_pipeline_preset, options.vlm_pipeline_custom_config)) {
1037
+ throw new DoclingProtocolError(
1038
+ "vlm_pipeline_preset and vlm_pipeline_custom_config are mutually exclusive"
1039
+ );
1040
+ }
1041
+ if (legacyVlmCount > 0 && present(options.vlm_pipeline_preset, options.vlm_pipeline_custom_config) > 0) {
1042
+ throw new DoclingProtocolError(
1043
+ "Legacy VLM model options cannot be mixed with VLM preset/custom options"
1044
+ );
1045
+ }
1046
+ const legacyPictureCount = present(
1047
+ options.picture_description_local,
1048
+ options.picture_description_api
1049
+ );
1050
+ if (conflicting(
1051
+ options.picture_description_preset,
1052
+ options.picture_description_custom_config
1053
+ )) {
1054
+ throw new DoclingProtocolError(
1055
+ "picture_description_preset and picture_description_custom_config are mutually exclusive"
1056
+ );
1057
+ }
1058
+ if (legacyPictureCount > 0 && present(
1059
+ options.picture_description_preset,
1060
+ options.picture_description_custom_config
1061
+ ) > 0) {
1062
+ throw new DoclingProtocolError(
1063
+ "Legacy picture-description options cannot be mixed with picture-description preset/custom options"
1064
+ );
1065
+ }
1066
+ for (const [name, preset, custom] of [
1067
+ ["code_formula", options.code_formula_preset, options.code_formula_custom_config],
1068
+ ["layout", options.layout_preset, options.layout_custom_config],
1069
+ [
1070
+ "picture_classification",
1071
+ options.picture_classification_preset,
1072
+ options.picture_classification_custom_config
1073
+ ]
1074
+ ]) {
1075
+ if (conflicting(preset, custom)) {
1076
+ throw new DoclingProtocolError(
1077
+ `${name}_preset and ${name}_custom_config are mutually exclusive`
1078
+ );
1079
+ }
1080
+ }
1081
+ if (options.ocr_preset !== void 0 && options.ocr_preset !== "auto" && isRecord2(options.ocr_custom_config) && Object.keys(options.ocr_custom_config).length > 0) {
1082
+ throw new DoclingProtocolError(
1083
+ "ocr_preset and ocr_custom_config are mutually exclusive"
1084
+ );
1085
+ }
1086
+ }
1087
+ function applyPageLimits(options, pageRange, maxNumPages) {
1088
+ let effectiveRange = pageRange ?? options.page_range;
1089
+ if (maxNumPages !== void 0) {
1090
+ validateNonNegativeSafeInteger(maxNumPages, "maxNumPages");
1091
+ effectiveRange = [
1092
+ effectiveRange?.[0] ?? 1,
1093
+ Math.min(effectiveRange?.[1] ?? Number.MAX_SAFE_INTEGER, maxNumPages)
1094
+ ];
1095
+ }
1096
+ if (effectiveRange !== void 0) {
1097
+ validatePageRange(effectiveRange);
1098
+ return { ...clone(options), page_range: [...effectiveRange] };
1099
+ }
1100
+ return clone(options);
1101
+ }
1102
+ function validateMaxFileSize(value) {
1103
+ if (value === void 0) {
1104
+ return;
1105
+ }
1106
+ validateNonNegativeSafeInteger(value, "maxFileSize");
1107
+ }
1108
+ function preflightFileSize(source, maxFileSize) {
1109
+ if (maxFileSize === void 0 || source.descriptor.file_size === void 0 || source.descriptor.file_size === null || source.descriptor.file_size <= maxFileSize) {
1110
+ return null;
1111
+ }
1112
+ return `File size ${source.descriptor.file_size} exceeds the configured limit of ${maxFileSize} bytes`;
1113
+ }
1114
+ function formValue(value) {
1115
+ if (typeof value === "string") {
1116
+ return value;
1117
+ }
1118
+ if (typeof value === "number" || typeof value === "boolean") {
1119
+ return String(value);
1120
+ }
1121
+ return JSON.stringify(value);
1122
+ }
1123
+ async function fileSourceFromBinary(source, signal) {
1124
+ throwIfAborted(signal);
1125
+ const bytes = new Uint8Array(await (await toBlob(source.data)).arrayBuffer());
1126
+ throwIfAborted(signal);
1127
+ return {
1128
+ kind: "file",
1129
+ filename: source.filename,
1130
+ base64_string: bytesToBase642(bytes)
1131
+ };
1132
+ }
1133
+ async function normalizeStringSource(value, signal) {
1134
+ const scheme = /^([a-z][a-z\d+.-]*):\/\//i.exec(value)?.[1]?.toLowerCase();
1135
+ if (scheme !== void 0) {
1136
+ if (!["http", "https"].includes(scheme)) {
1137
+ throw new DoclingProtocolError(
1138
+ `Unsupported document source URL scheme: ${scheme}`
1139
+ );
1140
+ }
1141
+ return normalizeHttpUrl(value);
1142
+ }
1143
+ let bytes;
1144
+ try {
1145
+ const { readFile } = await import("fs/promises");
1146
+ bytes = await readFile(value, { signal });
1147
+ } catch (error) {
1148
+ if (signal?.aborted === true) {
1149
+ throw abortReason2(signal);
1150
+ }
1151
+ throw new DoclingProtocolError(`Could not read local document: ${value}`, {
1152
+ cause: error
1153
+ });
1154
+ }
1155
+ throwIfAborted(signal);
1156
+ const filename = fileNameFromPath(value);
1157
+ const blob = new Blob([Uint8Array.from(bytes).buffer], {
1158
+ type: guessMimeType(filename)
1159
+ });
1160
+ return {
1161
+ kind: "multipart",
1162
+ blob,
1163
+ descriptor: {
1164
+ filename,
1165
+ source: value,
1166
+ format: guessInputFormat(filename),
1167
+ file_size: bytes.byteLength
1168
+ }
1169
+ };
1170
+ }
1171
+ function normalizeHttpUrl(value) {
1172
+ validateHttpUrl(value, true);
1173
+ const source = { kind: "http", url: value, headers: {} };
1174
+ return {
1175
+ kind: "json",
1176
+ source,
1177
+ descriptor: describeHttpSource(value)
1178
+ };
1179
+ }
1180
+ function validateHttpUrl(value, rejectZip) {
1181
+ let url;
1182
+ try {
1183
+ url = new URL(value);
1184
+ } catch (error) {
1185
+ throw new DoclingProtocolError("Document source must be a valid URL", {
1186
+ cause: error
1187
+ });
1188
+ }
1189
+ if (!["http:", "https:"].includes(url.protocol)) {
1190
+ throw new DoclingProtocolError(
1191
+ `Unsupported document source URL scheme: ${url.protocol.replace(":", "")}`
1192
+ );
1193
+ }
1194
+ if (rejectZip && url.pathname.toLowerCase().endsWith(".zip")) {
1195
+ throw new DoclingProtocolError(
1196
+ "ZIP URLs are not accepted on the Docling convert endpoint"
1197
+ );
1198
+ }
1199
+ return url;
1200
+ }
1201
+ function describeHttpSource(value) {
1202
+ const url = validateHttpUrl(value, true);
1203
+ const pathParts = url.pathname.split("/").filter((part) => part !== "");
1204
+ const filename = pathParts.at(-1) ?? "document";
1205
+ return {
1206
+ filename,
1207
+ source: value,
1208
+ format: guessInputFormat(filename),
1209
+ file_size: null
1210
+ };
1211
+ }
1212
+ function guessInputFormat(filename) {
1213
+ const normalized = filename.toLowerCase();
1214
+ const extension = ["dclg.xml", "tar.gz"].find((suffix) => normalized.endsWith(`.${suffix}`)) ?? normalized.split(".").at(-1) ?? "";
1215
+ return EXTENSION_FORMATS[extension] ?? "pdf";
1216
+ }
1217
+ function guessMimeType(filename) {
1218
+ const extension = filename.toLowerCase().split(".").at(-1) ?? "";
1219
+ return {
1220
+ pdf: "application/pdf",
1221
+ doc: "application/msword",
1222
+ docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
1223
+ ppt: "application/vnd.ms-powerpoint",
1224
+ pptx: "application/vnd.openxmlformats-officedocument.presentationml.presentation",
1225
+ xls: "application/vnd.ms-excel",
1226
+ xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
1227
+ html: "text/html",
1228
+ htm: "text/html",
1229
+ md: "text/markdown",
1230
+ txt: "text/plain",
1231
+ csv: "text/csv",
1232
+ json: "application/json",
1233
+ png: "image/png",
1234
+ jpg: "image/jpeg",
1235
+ jpeg: "image/jpeg",
1236
+ tif: "image/tiff",
1237
+ tiff: "image/tiff",
1238
+ wav: "audio/wav",
1239
+ mp3: "audio/mpeg",
1240
+ mp4: "video/mp4",
1241
+ vtt: "text/vtt",
1242
+ eml: "message/rfc822",
1243
+ epub: "application/epub+zip"
1244
+ }[extension] ?? "application/octet-stream";
1245
+ }
1246
+ var INPUT_FORMATS = /* @__PURE__ */ new Set([
1247
+ "docx",
1248
+ "doc",
1249
+ "pptx",
1250
+ "html",
1251
+ "image",
1252
+ "pdf",
1253
+ "asciidoc",
1254
+ "md",
1255
+ "csv",
1256
+ "xlsx",
1257
+ "xml_uspto",
1258
+ "xml_jats",
1259
+ "json_docling",
1260
+ "dclx",
1261
+ "audio",
1262
+ "vtt",
1263
+ "xml_xbrl",
1264
+ "mets_gbs",
1265
+ "latex",
1266
+ "ppt",
1267
+ "xls",
1268
+ "odt",
1269
+ "ods",
1270
+ "odp",
1271
+ "xml_doclang",
1272
+ "video",
1273
+ "email",
1274
+ "epub",
1275
+ "boxnote"
1276
+ ]);
1277
+ var OUTPUT_FORMATS = /* @__PURE__ */ new Set([
1278
+ "md",
1279
+ "json",
1280
+ "yaml",
1281
+ "html",
1282
+ "html_split_page",
1283
+ "text",
1284
+ "doctags",
1285
+ "vtt",
1286
+ "doclang",
1287
+ "dclx",
1288
+ "chunks"
1289
+ ]);
1290
+ var PIPELINES = /* @__PURE__ */ new Set(["legacy", "standard", "vlm", "asr"]);
1291
+ var IMAGE_EXPORT_MODES = /* @__PURE__ */ new Set(["placeholder", "embedded", "referenced"]);
1292
+ var TABLE_MODES = /* @__PURE__ */ new Set(["fast", "accurate"]);
1293
+ var PDF_BACKENDS = /* @__PURE__ */ new Set([
1294
+ "pypdfium2",
1295
+ "docling_parse",
1296
+ "threaded_docling_parse",
1297
+ "dlparse_v1",
1298
+ "dlparse_v2",
1299
+ "dlparse_v4"
1300
+ ]);
1301
+ var LEGACY_VLM_MODELS = /* @__PURE__ */ new Set([
1302
+ "smoldocling",
1303
+ "smoldocling_vllm",
1304
+ "granite_vision",
1305
+ "granite_vision_vllm",
1306
+ "granite_vision_ollama",
1307
+ "got_ocr_2",
1308
+ "granite_docling",
1309
+ "granite_docling_vllm",
1310
+ "nanonets_ocr2",
1311
+ "nanonets_ocr2_vllm",
1312
+ "nanonets_ocr2_lmstudio",
1313
+ "glm_ocr",
1314
+ "glm_ocr_vllm",
1315
+ "lightonocr",
1316
+ "lightonocr_vllm",
1317
+ "deepseekocr_ollama"
1318
+ ]);
1319
+ var VLM_RESPONSE_FORMATS = /* @__PURE__ */ new Set([
1320
+ "doctags",
1321
+ "doclang",
1322
+ "markdown",
1323
+ "deepseekocr_markdown",
1324
+ "html",
1325
+ "otsl",
1326
+ "plaintext",
1327
+ "chandra_html",
1328
+ "dots_json"
1329
+ ]);
1330
+ var VLM_INFERENCE_FRAMEWORKS = /* @__PURE__ */ new Set(["mlx", "transformers", "vllm"]);
1331
+ var TRANSFORMERS_MODEL_TYPES = /* @__PURE__ */ new Set([
1332
+ "automodel",
1333
+ "automodel-causallm",
1334
+ "automodel-imagetexttotext"
1335
+ ]);
1336
+ var PICTURE_CLASSIFICATION_LABELS = /* @__PURE__ */ new Set([
1337
+ "bar_chart",
1338
+ "box_plot",
1339
+ "flow_chart",
1340
+ "line_chart",
1341
+ "pie_chart",
1342
+ "scatter_plot",
1343
+ "table",
1344
+ "other_chart",
1345
+ "full_page_image",
1346
+ "page_thumbnail",
1347
+ "photograph",
1348
+ "chemistry_structure",
1349
+ "bar_code",
1350
+ "icon",
1351
+ "logo",
1352
+ "qr_code",
1353
+ "signature",
1354
+ "stamp",
1355
+ "engineering_drawing",
1356
+ "screenshot_from_computer",
1357
+ "screenshot_from_manual",
1358
+ "geographical_map",
1359
+ "topographical_map",
1360
+ "calendar",
1361
+ "crossword_puzzle",
1362
+ "music",
1363
+ "other",
1364
+ "cad_drawing",
1365
+ "electrical_diagram",
1366
+ "map",
1367
+ "heatmap",
1368
+ "chemistry_markush_structure",
1369
+ "chemistry_molecular_structure",
1370
+ "natural_image",
1371
+ "picture_group",
1372
+ "remote_sensing",
1373
+ "scatter_chart",
1374
+ "screenshot",
1375
+ "stacked_bar_chart",
1376
+ "stratigraphic_chart"
1377
+ ]);
1378
+ var BOOLEAN_OPTIONS = [
1379
+ "do_ocr",
1380
+ "force_ocr",
1381
+ "table_cell_matching",
1382
+ "do_table_structure",
1383
+ "include_images",
1384
+ "include_page_images",
1385
+ "do_code_enrichment",
1386
+ "do_formula_enrichment",
1387
+ "do_picture_classification",
1388
+ "do_chart_extraction",
1389
+ "do_picture_description",
1390
+ "abort_on_error"
1391
+ ];
1392
+ var NUMBER_OPTIONS = [
1393
+ "document_timeout",
1394
+ "images_scale",
1395
+ "picture_description_area_threshold"
1396
+ ];
1397
+ var STRING_OPTIONS = [
1398
+ "ocr_engine",
1399
+ "ocr_preset",
1400
+ "md_page_break_placeholder",
1401
+ "vlm_pipeline_preset",
1402
+ "picture_description_preset",
1403
+ "code_formula_preset",
1404
+ "table_structure_preset",
1405
+ "layout_preset",
1406
+ "picture_classification_preset"
1407
+ ];
1408
+ var RECORD_OPTIONS = [
1409
+ "ocr_custom_config",
1410
+ "vlm_pipeline_custom_config",
1411
+ "picture_description_custom_config",
1412
+ "code_formula_custom_config",
1413
+ "table_structure_custom_config",
1414
+ "layout_custom_config",
1415
+ "picture_classification_custom_config",
1416
+ "picture_description_local",
1417
+ "picture_description_api",
1418
+ "vlm_pipeline_model_local",
1419
+ "vlm_pipeline_model_api"
1420
+ ];
1421
+ var JSON_STRING_CONFIG_OPTIONS = [
1422
+ "ocr_custom_config",
1423
+ "table_structure_custom_config",
1424
+ "layout_custom_config",
1425
+ "picture_classification_custom_config"
1426
+ ];
1427
+ function validateStringEnum(value, allowed, name) {
1428
+ if (value !== void 0 && !allowed.has(value)) {
1429
+ throw new DoclingProtocolError(`${name} contains an unsupported value`);
1430
+ }
1431
+ }
1432
+ function validateRequiredEnum(value, allowed, name) {
1433
+ if (typeof value !== "string" || !allowed.has(value)) {
1434
+ throw new DoclingProtocolError(`${name} contains an unsupported value`);
1435
+ }
1436
+ }
1437
+ function validateRequiredString(value, name) {
1438
+ if (typeof value !== "string") {
1439
+ throw new DoclingProtocolError(`${name} must be a string`);
1440
+ }
1441
+ }
1442
+ function validateOptionalString(value, name) {
1443
+ if (value !== void 0 && value !== null && typeof value !== "string") {
1444
+ throw new DoclingProtocolError(`${name} must be a string or null`);
1445
+ }
1446
+ }
1447
+ function validateOptionalEnumArray(value, allowed, name) {
1448
+ if (value !== void 0 && value !== null && (!Array.isArray(value) || value.some((item) => typeof item !== "string" || !allowed.has(item)))) {
1449
+ throw new DoclingProtocolError(`${name} contains an unsupported value`);
1450
+ }
1451
+ }
1452
+ function validateOptionalRecord(value, name) {
1453
+ if (value !== void 0 && value !== null && !isRecord2(value)) {
1454
+ throw new DoclingProtocolError(`${name} must be an object or null`);
1455
+ }
1456
+ }
1457
+ function validateOptionalStringRecord(value, name) {
1458
+ if (value !== void 0 && value !== null && (!isRecord2(value) || Object.values(value).some((item) => typeof item !== "string"))) {
1459
+ throw new DoclingProtocolError(`${name} must contain string values`);
1460
+ }
1461
+ }
1462
+ function validateOptionalFiniteNumber(value, name) {
1463
+ if (value !== void 0 && value !== null && (typeof value !== "number" || !Number.isFinite(value))) {
1464
+ throw new DoclingProtocolError(`${name} must be a finite number or null`);
1465
+ }
1466
+ }
1467
+ function validateOptionalPositiveInteger(value, name) {
1468
+ if (value !== void 0 && value !== null && (!Number.isSafeInteger(value) || value < 1)) {
1469
+ throw new DoclingProtocolError(`${name} must be a positive integer or null`);
1470
+ }
1471
+ }
1472
+ function validateAbsoluteUrl(value, name) {
1473
+ if (typeof value !== "string") {
1474
+ throw new DoclingProtocolError(`${name} must be an absolute URL`);
1475
+ }
1476
+ try {
1477
+ const url = new URL(value);
1478
+ if (url.protocol === "") {
1479
+ throw new Error("missing scheme");
1480
+ }
1481
+ } catch (error) {
1482
+ throw new DoclingProtocolError(`${name} must be an absolute URL`, {
1483
+ cause: error
1484
+ });
1485
+ }
1486
+ }
1487
+ function validateStringEnumArray(value, allowed, name) {
1488
+ if (value !== void 0 && (!Array.isArray(value) || value.some((item) => typeof item !== "string" || !allowed.has(item)))) {
1489
+ throw new DoclingProtocolError(`${name} contains an unsupported value`);
1490
+ }
1491
+ }
1492
+ function base64ByteLength(value) {
1493
+ const normalized = value.replace(/\s/g, "");
1494
+ if (normalized === "") {
1495
+ return 0;
1496
+ }
1497
+ const padding = normalized.endsWith("==") ? 2 : normalized.endsWith("=") ? 1 : 0;
1498
+ return Math.max(0, Math.floor(normalized.length * 3 / 4) - padding);
1499
+ }
1500
+ async function toBlob(data, contentType = "application/octet-stream") {
1501
+ if (data instanceof Blob) {
1502
+ return data;
1503
+ }
1504
+ if (data instanceof ArrayBuffer) {
1505
+ return new Blob([data], { type: contentType });
1506
+ }
1507
+ const bytes = new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
1508
+ return new Blob([Uint8Array.from(bytes).buffer], { type: contentType });
1509
+ }
1510
+ function isHttpSource(value) {
1511
+ return isRecord2(value) && value.kind === "http" && typeof value.url === "string";
1512
+ }
1513
+ function isFileSource(value) {
1514
+ return isRecord2(value) && value.kind === "file" && typeof value.base64_string === "string" && typeof value.filename === "string";
1515
+ }
1516
+ function isBinaryFileSource(value) {
1517
+ return isRecord2(value) && typeof value.filename === "string" && "data" in value && (value.data instanceof Blob || value.data instanceof ArrayBuffer || ArrayBuffer.isView(value.data));
1518
+ }
1519
+ function isRecord2(value) {
1520
+ return value !== null && typeof value === "object" && !Array.isArray(value);
1521
+ }
1522
+ function throwIfAborted(signal) {
1523
+ if (signal?.aborted === true) {
1524
+ throw abortReason2(signal);
1525
+ }
1526
+ }
1527
+ function abortReason2(signal) {
1528
+ return signal.reason instanceof Error ? signal.reason : new DOMException("The operation was aborted", "AbortError");
1529
+ }
1530
+ function fileNameFromPath(value) {
1531
+ const normalized = value.replaceAll("\\", "/");
1532
+ return normalized.split("/").at(-1) || "document";
1533
+ }
1534
+ function validatePageRange(value) {
1535
+ if (!Array.isArray(value) || value.length !== 2 || !Number.isSafeInteger(value[0]) || !Number.isSafeInteger(value[1]) || value[0] < 1 || value[1] < value[0]) {
1536
+ throw new DoclingProtocolError(
1537
+ "pageRange must contain positive integers with end >= start"
1538
+ );
1539
+ }
1540
+ }
1541
+ function validateNonNegativeSafeInteger(value, name) {
1542
+ if (!Number.isSafeInteger(value) || value < 0) {
1543
+ throw new DoclingProtocolError(`${name} must be a non-negative safe integer`);
1544
+ }
1545
+ }
1546
+ function bytesToBase642(bytes) {
1547
+ if (typeof Buffer !== "undefined") {
1548
+ return Buffer.from(bytes).toString("base64");
1549
+ }
1550
+ let binary = "";
1551
+ const chunkSize = 32768;
1552
+ for (let offset = 0; offset < bytes.length; offset += chunkSize) {
1553
+ binary += String.fromCharCode(...bytes.subarray(offset, offset + chunkSize));
1554
+ }
1555
+ return btoa(binary);
1556
+ }
1557
+ function clone(value) {
1558
+ return structuredClone(value);
1559
+ }
1560
+
1561
+ // src/transport.ts
1562
+ var FetchTransport = class {
1563
+ #fetch;
1564
+ #retries;
1565
+ #timeoutMs;
1566
+ #backoffBaseMs;
1567
+ #sleep;
1568
+ constructor(optionsOrFetch = globalThis.fetch) {
1569
+ const options = typeof optionsOrFetch === "function" ? { fetch: optionsOrFetch } : optionsOrFetch;
1570
+ const fetchImplementation = options?.fetch ?? globalThis.fetch;
1571
+ if (fetchImplementation === void 0) {
1572
+ throw new DoclingProtocolError(
1573
+ "No fetch implementation is available; provide a DoclingTransport"
1574
+ );
1575
+ }
1576
+ this.#fetch = fetchImplementation;
1577
+ this.#retries = validateNonNegativeInteger(options?.retries ?? 3, "retries");
1578
+ this.#timeoutMs = validatePositiveNumber(options?.timeoutMs ?? 6e4, "timeoutMs");
1579
+ this.#backoffBaseMs = validatePositiveNumber(
1580
+ options?.backoffBaseMs ?? 1e3,
1581
+ "backoffBaseMs"
1582
+ );
1583
+ this.#sleep = options?.sleep ?? abortableDelay;
1584
+ }
1585
+ async request(request) {
1586
+ const maxRetries = request.retries === void 0 ? this.#retries : validateNonNegativeInteger(request.retries, "request.retries");
1587
+ for (let attempt = 0; attempt <= maxRetries; attempt += 1) {
1588
+ try {
1589
+ const response = await this.#requestOnce(request);
1590
+ const retryDelay = retryDelayMs(
1591
+ response,
1592
+ attempt,
1593
+ maxRetries,
1594
+ this.#backoffBaseMs
1595
+ );
1596
+ if (retryDelay === "exhausted") {
1597
+ const body = await decodeErrorResponse(response);
1598
+ throw new DoclingServiceUnavailableError(
1599
+ `Docling returned HTTP ${response.status} after retries`,
1600
+ {
1601
+ status: response.status,
1602
+ detail: httpDetail(body)
1603
+ }
1604
+ );
1605
+ }
1606
+ if (retryDelay !== null) {
1607
+ await discardResponse(response);
1608
+ if (retryDelay > 0) {
1609
+ await this.#sleep(retryDelay, request.signal);
1610
+ }
1611
+ continue;
1612
+ }
1613
+ const responseHeaders = headersToRecord(response.headers);
1614
+ if (response.status !== 200) {
1615
+ const body = await decodeErrorResponse(response);
1616
+ if (response.status === 402) {
1617
+ const usage = isUsageLimitBody(body) ? body : void 0;
1618
+ throw new DoclingUsageLimitExceededError({
1619
+ method: request.method,
1620
+ url: request.url,
1621
+ status: response.status,
1622
+ body,
1623
+ headers: responseHeaders,
1624
+ ...usage === void 0 ? {} : {
1625
+ currentUsage: usage.details.currentUsage,
1626
+ limit: usage.details.limit,
1627
+ detail: usage.message
1628
+ }
1629
+ });
1630
+ }
1631
+ if (response.status >= 500) {
1632
+ throw new DoclingServiceUnavailableError(
1633
+ `Docling returned HTTP ${response.status}`,
1634
+ {
1635
+ status: response.status,
1636
+ detail: httpDetail(body)
1637
+ }
1638
+ );
1639
+ }
1640
+ throw new DoclingHttpError({
1641
+ method: request.method,
1642
+ url: request.url,
1643
+ status: response.status,
1644
+ body,
1645
+ headers: responseHeaders,
1646
+ detail: httpDetail(body)
1647
+ });
1648
+ }
1649
+ return await decodeResponse(response, request.responseType ?? "json");
1650
+ } catch (error) {
1651
+ if (error instanceof DoclingHttpError || error instanceof DoclingProtocolError || error instanceof DoclingServiceUnavailableError || error instanceof DoclingUsageLimitExceededError || isAbort(error, request.signal)) {
1652
+ throw error;
1653
+ }
1654
+ const retryableMethod = ["GET", "HEAD", "OPTIONS"].includes(request.method);
1655
+ if (retryableMethod && attempt < maxRetries) {
1656
+ await this.#sleep(this.#backoffBaseMs * 2 ** attempt, request.signal);
1657
+ continue;
1658
+ }
1659
+ throw new DoclingServiceUnavailableError(
1660
+ attempt >= maxRetries && retryableMethod ? "Docling transport request failed after retries" : "Docling transport request failed",
1661
+ {
1662
+ detail: error instanceof Error ? error.message : String(error),
1663
+ cause: error
1664
+ }
1665
+ );
1666
+ }
1667
+ }
1668
+ throw new DoclingServiceUnavailableError(
1669
+ "Docling request failed after the retry loop"
1670
+ );
1671
+ }
1672
+ async #requestOnce(request) {
1673
+ const timeoutMs = request.timeoutMs ?? this.#timeoutMs;
1674
+ validatePositiveNumber(timeoutMs, "request.timeoutMs");
1675
+ const timeoutController = new AbortController();
1676
+ const timeout = setTimeout(() => {
1677
+ timeoutController.abort(
1678
+ new DoclingServiceUnavailableError(
1679
+ `Docling request exceeded its ${timeoutMs} ms transport timeout`
1680
+ )
1681
+ );
1682
+ }, timeoutMs);
1683
+ const combined = combineAbortSignals3(request.signal, timeoutController.signal);
1684
+ try {
1685
+ try {
1686
+ return await this.#fetch(request.url, {
1687
+ method: request.method,
1688
+ headers: request.headers,
1689
+ ...request.body === void 0 ? {} : { body: encodeBody(request.body, request.bodyType ?? "json") },
1690
+ signal: combined.signal
1691
+ });
1692
+ } catch (error) {
1693
+ if (timeoutController.signal.aborted && request.signal?.aborted !== true) {
1694
+ throw new TransportTimeoutError(
1695
+ `Docling request exceeded its ${timeoutMs} ms transport timeout`,
1696
+ { cause: error }
1697
+ );
1698
+ }
1699
+ throw error;
1700
+ }
1701
+ } finally {
1702
+ clearTimeout(timeout);
1703
+ combined.dispose();
1704
+ }
1705
+ }
1706
+ };
1707
+ function encodeBody(body, bodyType) {
1708
+ if (bodyType === "json") {
1709
+ return JSON.stringify(body);
1710
+ }
1711
+ if (bodyType === "form") {
1712
+ if (!(body instanceof FormData)) {
1713
+ throw new DoclingProtocolError("A form request body must be FormData");
1714
+ }
1715
+ return body;
1716
+ }
1717
+ if (typeof body === "string" || body instanceof Blob || body instanceof ArrayBuffer || ArrayBuffer.isView(body) || body instanceof URLSearchParams) {
1718
+ return body;
1719
+ }
1720
+ throw new DoclingProtocolError("Unsupported raw transport request body");
1721
+ }
1722
+ async function decodeResponse(response, responseType) {
1723
+ if (responseType === "bytes") {
1724
+ return {
1725
+ content: new Uint8Array(await response.arrayBuffer()),
1726
+ headers: headersToRecord(response.headers),
1727
+ contentType: response.headers.get("content-type") ?? "application/octet-stream"
1728
+ };
1729
+ }
1730
+ if (response.status === 204) {
1731
+ return void 0;
1732
+ }
1733
+ const text = await response.text();
1734
+ if (text === "") {
1735
+ return void 0;
1736
+ }
1737
+ if (responseType === "text") {
1738
+ return text;
1739
+ }
1740
+ const contentType = response.headers.get("content-type") ?? "";
1741
+ const shouldDecodeJson = responseType === "json" || contentType.toLowerCase().includes("json");
1742
+ if (!shouldDecodeJson) {
1743
+ return text;
1744
+ }
1745
+ try {
1746
+ return JSON.parse(text);
1747
+ } catch (error) {
1748
+ throw new DoclingProtocolError("Docling returned invalid JSON", {
1749
+ cause: error
1750
+ });
1751
+ }
1752
+ }
1753
+ async function decodeErrorResponse(response) {
1754
+ const text = await response.text();
1755
+ if (text === "") {
1756
+ return void 0;
1757
+ }
1758
+ try {
1759
+ return JSON.parse(text);
1760
+ } catch {
1761
+ return text;
1762
+ }
1763
+ }
1764
+ function retryDelayMs(response, attempt, maxRetries, backoffBaseMs) {
1765
+ if ([500, 502].includes(response.status)) {
1766
+ return attempt < maxRetries ? backoffBaseMs * 2 ** attempt : "exhausted";
1767
+ }
1768
+ if ([429, 503].includes(response.status)) {
1769
+ const retryAfter = parseRetryAfter(response.headers.get("retry-after"));
1770
+ if (retryAfter === null) {
1771
+ return null;
1772
+ }
1773
+ return attempt < maxRetries ? retryAfter : "exhausted";
1774
+ }
1775
+ return null;
1776
+ }
1777
+ function parseRetryAfter(value) {
1778
+ if (value === null) {
1779
+ return null;
1780
+ }
1781
+ const normalized = value.trim();
1782
+ if (normalized === "") {
1783
+ return null;
1784
+ }
1785
+ const seconds = /^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i.test(normalized) ? Number(normalized) : Number.NaN;
1786
+ if (Number.isFinite(seconds)) {
1787
+ return Math.max(0, seconds * 1e3);
1788
+ }
1789
+ const retryAt = Date.parse(value);
1790
+ if (Number.isNaN(retryAt)) {
1791
+ return null;
1792
+ }
1793
+ return Math.max(0, retryAt - Date.now());
1794
+ }
1795
+ function isUsageLimitBody(value) {
1796
+ if (value === null || typeof value !== "object" || Array.isArray(value)) {
1797
+ return false;
1798
+ }
1799
+ const body = value;
1800
+ if (body.error !== "usage_limit_exceeded" || typeof body.message !== "string" || body.details === null || typeof body.details !== "object" || Array.isArray(body.details)) {
1801
+ return false;
1802
+ }
1803
+ const details = body.details;
1804
+ return typeof details.currentUsage === "number" && typeof details.limit === "number";
1805
+ }
1806
+ function httpDetail(value) {
1807
+ return value !== null && typeof value === "object" && !Array.isArray(value) && typeof value.detail === "string" ? value.detail : void 0;
1808
+ }
1809
+ function headersToRecord(headers) {
1810
+ return Object.fromEntries(headers.entries());
1811
+ }
1812
+ function validateNonNegativeInteger(value, name) {
1813
+ if (!Number.isInteger(value) || value < 0) {
1814
+ throw new DoclingProtocolError(`${name} must be a non-negative integer`);
1815
+ }
1816
+ return value;
1817
+ }
1818
+ function validatePositiveNumber(value, name) {
1819
+ if (!Number.isFinite(value) || value <= 0) {
1820
+ throw new DoclingProtocolError(`${name} must be a positive number`);
1821
+ }
1822
+ return value;
1823
+ }
1824
+ function combineAbortSignals3(callerSignal, timeoutSignal) {
1825
+ if (callerSignal === void 0) {
1826
+ return { signal: timeoutSignal, dispose: () => void 0 };
1827
+ }
1828
+ if (typeof AbortSignal.any === "function") {
1829
+ return {
1830
+ signal: AbortSignal.any([callerSignal, timeoutSignal]),
1831
+ dispose: () => void 0
1832
+ };
1833
+ }
1834
+ const controller = new AbortController();
1835
+ const abort = (signal) => {
1836
+ controller.abort(signal.reason);
1837
+ };
1838
+ if (callerSignal.aborted) {
1839
+ abort(callerSignal);
1840
+ } else if (timeoutSignal.aborted) {
1841
+ abort(timeoutSignal);
1842
+ } else {
1843
+ const abortCaller = () => abort(callerSignal);
1844
+ const abortTimeout = () => abort(timeoutSignal);
1845
+ callerSignal.addEventListener("abort", abortCaller, { once: true });
1846
+ timeoutSignal.addEventListener("abort", abortTimeout, { once: true });
1847
+ return {
1848
+ signal: controller.signal,
1849
+ dispose: () => {
1850
+ callerSignal.removeEventListener("abort", abortCaller);
1851
+ timeoutSignal.removeEventListener("abort", abortTimeout);
1852
+ }
1853
+ };
1854
+ }
1855
+ return { signal: controller.signal, dispose: () => void 0 };
1856
+ }
1857
+ async function discardResponse(response) {
1858
+ try {
1859
+ if (response.body !== null) {
1860
+ await response.body.cancel();
1861
+ }
1862
+ } catch {
1863
+ }
1864
+ }
1865
+ function isAbort(error, signal) {
1866
+ return signal?.aborted === true || error instanceof DOMException && error.name === "AbortError";
1867
+ }
1868
+ function abortableDelay(milliseconds, signal) {
1869
+ if (milliseconds <= 0) {
1870
+ return Promise.resolve();
1871
+ }
1872
+ if (signal?.aborted === true) {
1873
+ return Promise.reject(signal.reason);
1874
+ }
1875
+ return new Promise((resolve, reject) => {
1876
+ const timeout = setTimeout(() => {
1877
+ signal?.removeEventListener("abort", abort);
1878
+ resolve();
1879
+ }, milliseconds);
1880
+ const abort = () => {
1881
+ clearTimeout(timeout);
1882
+ reject(signal?.reason);
1883
+ };
1884
+ signal?.addEventListener("abort", abort, { once: true });
1885
+ });
1886
+ }
1887
+ var TransportTimeoutError = class extends Error {
1888
+ };
1889
+
1890
+ // src/watchers.ts
1891
+ import WebSocket from "isomorphic-ws";
1892
+ async function* watchTask(options) {
1893
+ if (options.watcher === "polling") {
1894
+ yield* pollUpdates(options);
1895
+ return;
1896
+ }
1897
+ try {
1898
+ yield* webSocketUpdates(options);
1899
+ } catch (error) {
1900
+ if (error instanceof DoclingServiceUnavailableError && options.fallbackToPoll) {
1901
+ yield* pollUpdates(options);
1902
+ return;
1903
+ }
1904
+ throw error;
1905
+ }
1906
+ }
1907
+ async function* pollUpdates(options) {
1908
+ const timeoutMs = options.timeoutMs ?? 3e5;
1909
+ const serverWaitSeconds = options.serverWaitSeconds ?? 5;
1910
+ const pollIntervalMs = options.pollIntervalMs ?? serverWaitSeconds * 1e3;
1911
+ validateWatchTimes(timeoutMs, serverWaitSeconds, pollIntervalMs);
1912
+ const deadline = Date.now() + timeoutMs;
1913
+ while (true) {
1914
+ const remaining = deadline - Date.now();
1915
+ if (remaining <= 0) {
1916
+ throw new DoclingTimeoutError(options.taskId, timeoutMs);
1917
+ }
1918
+ const waitSeconds = Math.min(serverWaitSeconds, remaining / 1e3);
1919
+ const pollStarted = Date.now();
1920
+ const status = await options.poll(options.taskId, {
1921
+ waitSeconds,
1922
+ ...options.signal === void 0 ? {} : { signal: options.signal }
1923
+ });
1924
+ await options.onStatus?.(status);
1925
+ yield status;
1926
+ if (isTerminal(status)) {
1927
+ return;
1928
+ }
1929
+ const elapsed = Date.now() - pollStarted;
1930
+ const sleepMs = Math.max(
1931
+ 0,
1932
+ Math.min(pollIntervalMs, deadline - Date.now()) - elapsed
1933
+ );
1934
+ await (options.sleep ?? abortableDelay2)(sleepMs, options.signal);
1935
+ }
1936
+ }
1937
+ async function* webSocketUpdates(options) {
1938
+ const timeoutMs = options.timeoutMs ?? 3e5;
1939
+ const deadline = Date.now() + timeoutMs;
1940
+ const factory = options.webSocketFactory ?? ((socketUrl, factoryOptions) => new WebSocket(socketUrl, [], {
1941
+ headers: factoryOptions.headers
1942
+ }));
1943
+ const url = webSocketUrl(options.baseUrl, options.taskId, options.apiKey);
1944
+ for (let attempt = 0; attempt <= 3; attempt += 1) {
1945
+ let socket;
1946
+ try {
1947
+ try {
1948
+ socket = factory(url, {
1949
+ headers: options.apiKey === void 0 || options.apiKey === "" ? {} : { "X-Api-Key": options.apiKey }
1950
+ });
1951
+ } catch (error) {
1952
+ throw new WebSocketConnectionError("WebSocket connection failed", {
1953
+ cause: error
1954
+ });
1955
+ }
1956
+ const events = socketEvents(socket);
1957
+ await waitForOpen(events, options.connectTimeoutMs, options.signal);
1958
+ let awaitingNextUpdate = false;
1959
+ while (true) {
1960
+ const remaining = deadline - Date.now();
1961
+ if (remaining <= 0) {
1962
+ throw new DoclingTimeoutError(options.taskId, timeoutMs);
1963
+ }
1964
+ const event = await withTimeout(
1965
+ events.next(),
1966
+ remaining,
1967
+ options.signal,
1968
+ () => new DoclingTimeoutError(options.taskId, timeoutMs)
1969
+ );
1970
+ if (event.done) {
1971
+ throw new WebSocketConnectionError(
1972
+ "WebSocket status stream ended unexpectedly"
1973
+ );
1974
+ }
1975
+ if (event.value.kind === "error") {
1976
+ throw new WebSocketConnectionError(
1977
+ `WebSocket status stream failed: ${event.value.error instanceof Error ? event.value.error.message : String(event.value.error ?? "unknown error")}`
1978
+ );
1979
+ }
1980
+ if (event.value.kind === "close") {
1981
+ if (awaitingNextUpdate && isCleanWebSocketClose(event.value)) {
1982
+ return;
1983
+ }
1984
+ throw new WebSocketConnectionError(
1985
+ `WebSocket status stream closed before a terminal status: ${`${event.value.code ?? 0} ${event.value.reason ?? ""}`.trim()}`
1986
+ );
1987
+ }
1988
+ if (event.value.kind !== "message") {
1989
+ continue;
1990
+ }
1991
+ awaitingNextUpdate = false;
1992
+ const envelope = parseEnvelope(event.value.data, options.parseStatus);
1993
+ if (envelope.error !== void 0 && envelope.error !== null) {
1994
+ if (envelope.error === "Task not found.") {
1995
+ throw new DoclingTaskNotFoundError(options.taskId);
1996
+ }
1997
+ throw new DoclingServiceUnavailableError("WebSocket status stream failed", {
1998
+ detail: envelope.error
1999
+ });
2000
+ }
2001
+ if (envelope.task === void 0) {
2002
+ continue;
2003
+ }
2004
+ await options.onStatus?.(envelope.task);
2005
+ yield envelope.task;
2006
+ if (isTerminal(envelope.task)) {
2007
+ return;
2008
+ }
2009
+ if (envelope.message === "update") {
2010
+ try {
2011
+ socket.send("next");
2012
+ } catch (error) {
2013
+ if (isCleanWebSocketClose(error)) {
2014
+ return;
2015
+ }
2016
+ throw new WebSocketConnectionError(
2017
+ "WebSocket status stream could not request the next update",
2018
+ { cause: error }
2019
+ );
2020
+ }
2021
+ awaitingNextUpdate = true;
2022
+ }
2023
+ }
2024
+ } catch (error) {
2025
+ if (error instanceof DoclingTimeoutError || error instanceof DoclingTaskNotFoundError || options.signal?.aborted === true) {
2026
+ throw error;
2027
+ }
2028
+ if (!(error instanceof WebSocketConnectionError)) {
2029
+ throw error;
2030
+ }
2031
+ const remaining = deadline - Date.now();
2032
+ if (attempt >= 3 || remaining <= 0) {
2033
+ throw new DoclingServiceUnavailableError(
2034
+ "WebSocket status stream is unavailable",
2035
+ {
2036
+ detail: error instanceof Error ? error.message : String(error),
2037
+ cause: error
2038
+ }
2039
+ );
2040
+ }
2041
+ await (options.sleep ?? abortableDelay2)(
2042
+ Math.min(1e3 * 2 ** attempt, remaining),
2043
+ options.signal
2044
+ );
2045
+ } finally {
2046
+ try {
2047
+ socket?.close();
2048
+ } catch {
2049
+ }
2050
+ }
2051
+ }
2052
+ }
2053
+ function webSocketUrl(baseUrl, taskId, apiKey) {
2054
+ const url = new URL(baseUrl);
2055
+ url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
2056
+ url.pathname = `${url.pathname.replace(/\/+$/, "")}/v1/status/ws/${encodeURIComponent(
2057
+ taskId
2058
+ )}`;
2059
+ if (apiKey !== void 0 && apiKey !== "") {
2060
+ url.searchParams.set("api_key", apiKey);
2061
+ }
2062
+ return url.toString();
2063
+ }
2064
+ function socketEvents(socket) {
2065
+ const queue = [];
2066
+ const waiters = [];
2067
+ const push = (event) => {
2068
+ const waiter = waiters.shift();
2069
+ if (waiter === void 0) {
2070
+ queue.push(event);
2071
+ } else {
2072
+ waiter(event);
2073
+ }
2074
+ };
2075
+ socket.addEventListener("open", () => push({ kind: "open" }));
2076
+ socket.addEventListener(
2077
+ "message",
2078
+ (event) => push({ kind: "message", data: event.data })
2079
+ );
2080
+ socket.addEventListener(
2081
+ "error",
2082
+ (event) => push({ kind: "error", error: event.error ?? event.message })
2083
+ );
2084
+ socket.addEventListener(
2085
+ "close",
2086
+ (event) => push({
2087
+ kind: "close",
2088
+ code: event.code ?? 0,
2089
+ reason: event.reason ?? "",
2090
+ wasClean: event.wasClean ?? false
2091
+ })
2092
+ );
2093
+ return (async function* () {
2094
+ while (true) {
2095
+ if (queue.length > 0) {
2096
+ const event = queue.shift();
2097
+ if (event !== void 0) {
2098
+ yield event;
2099
+ }
2100
+ continue;
2101
+ }
2102
+ yield await new Promise((resolve) => waiters.push(resolve));
2103
+ }
2104
+ })();
2105
+ }
2106
+ async function waitForOpen(events, timeoutMs, signal) {
2107
+ const event = await withTimeout(
2108
+ events.next(),
2109
+ timeoutMs,
2110
+ signal,
2111
+ () => new WebSocketConnectionError(`WebSocket connection exceeded ${timeoutMs} ms`)
2112
+ );
2113
+ if (event.done || event.value.kind !== "open") {
2114
+ throw new WebSocketConnectionError("WebSocket connection failed before opening");
2115
+ }
2116
+ }
2117
+ var WebSocketConnectionError = class extends Error {
2118
+ };
2119
+ function isCleanWebSocketClose(value) {
2120
+ if (value instanceof Error && value.name === "ConnectionClosedOK") {
2121
+ return true;
2122
+ }
2123
+ return isRecord3(value) && (value.wasClean === true || value.code === 1e3 || value.closeCode === 1e3);
2124
+ }
2125
+ function parseEnvelope(data, parseStatus) {
2126
+ let value;
2127
+ try {
2128
+ const text = typeof data === "string" ? data : data instanceof ArrayBuffer ? new TextDecoder().decode(data) : ArrayBuffer.isView(data) ? new TextDecoder().decode(data) : String(data);
2129
+ value = JSON.parse(text);
2130
+ } catch (error) {
2131
+ throw new DoclingServiceUnavailableError(
2132
+ "WebSocket returned an invalid JSON envelope",
2133
+ { cause: error }
2134
+ );
2135
+ }
2136
+ if (!isRecord3(value) || !["connection", "update", "error"].includes(String(value.message))) {
2137
+ throw new DoclingServiceUnavailableError(
2138
+ "WebSocket returned an invalid status envelope"
2139
+ );
2140
+ }
2141
+ return {
2142
+ message: value.message,
2143
+ ...value.task === void 0 ? {} : { task: parseStatus(value.task) },
2144
+ ...typeof value.error === "string" || value.error === null ? { error: value.error } : {}
2145
+ };
2146
+ }
2147
+ function isTerminal(status) {
2148
+ return ["success", "failure"].includes(status.task_status);
2149
+ }
2150
+ function validateWatchTimes(timeoutMs, serverWaitSeconds, pollIntervalMs) {
2151
+ if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {
2152
+ throw new DoclingProtocolError("timeoutMs must be a positive number");
2153
+ }
2154
+ if (!Number.isFinite(serverWaitSeconds) || serverWaitSeconds < 0) {
2155
+ throw new DoclingProtocolError("serverWaitSeconds must be non-negative");
2156
+ }
2157
+ if (!Number.isFinite(pollIntervalMs) || pollIntervalMs < 0) {
2158
+ throw new DoclingProtocolError("pollIntervalMs must be non-negative");
2159
+ }
2160
+ }
2161
+ async function withTimeout(promise, milliseconds, signal, error) {
2162
+ if (signal?.aborted === true) {
2163
+ throw signal.reason;
2164
+ }
2165
+ return new Promise((resolve, reject) => {
2166
+ const timeout = setTimeout(() => reject(error()), milliseconds);
2167
+ const abort = () => reject(signal?.reason);
2168
+ signal?.addEventListener("abort", abort, { once: true });
2169
+ promise.then(
2170
+ (value) => {
2171
+ clearTimeout(timeout);
2172
+ signal?.removeEventListener("abort", abort);
2173
+ resolve(value);
2174
+ },
2175
+ (reason) => {
2176
+ clearTimeout(timeout);
2177
+ signal?.removeEventListener("abort", abort);
2178
+ reject(reason);
2179
+ }
2180
+ );
2181
+ });
2182
+ }
2183
+ function abortableDelay2(milliseconds, signal) {
2184
+ if (milliseconds <= 0) {
2185
+ return Promise.resolve();
2186
+ }
2187
+ if (signal?.aborted === true) {
2188
+ return Promise.reject(signal.reason);
2189
+ }
2190
+ return new Promise((resolve, reject) => {
2191
+ const timeout = setTimeout(() => {
2192
+ signal?.removeEventListener("abort", abort);
2193
+ resolve();
2194
+ }, milliseconds);
2195
+ const abort = () => {
2196
+ clearTimeout(timeout);
2197
+ reject(signal?.reason);
2198
+ };
2199
+ signal?.addEventListener("abort", abort, { once: true });
2200
+ });
2201
+ }
2202
+ function isRecord3(value) {
2203
+ return value !== null && typeof value === "object" && !Array.isArray(value);
2204
+ }
2205
+
2206
+ // src/client.ts
2207
+ var DEFAULT_JOB_TIMEOUT_MS = 3e5;
2208
+ var DEFAULT_MAX_CONCURRENCY = 8;
2209
+ var MAX_CONCURRENCY_LIMIT = 512;
2210
+ var DoclingClient = class {
2211
+ #baseUrl;
2212
+ #apiKey;
2213
+ #headers;
2214
+ #transport;
2215
+ #defaultOptions;
2216
+ #statusWatcher;
2217
+ #webSocketFallbackToPoll;
2218
+ #webSocketFactory;
2219
+ #connectTimeoutMs;
2220
+ #pollServerWaitSeconds;
2221
+ #pollClientIntervalMs;
2222
+ #jobTimeoutMs;
2223
+ #maxConcurrency;
2224
+ #artifactDownloader;
2225
+ #closed = false;
2226
+ constructor(options) {
2227
+ this.#baseUrl = normalizeBaseUrl(options.baseUrl);
2228
+ this.#apiKey = options.apiKey ?? "";
2229
+ this.#headers = {
2230
+ accept: "application/json",
2231
+ ...normalizeHeaders(options.headers),
2232
+ ...this.#apiKey === "" ? {} : { "x-api-key": this.#apiKey }
2233
+ };
2234
+ if (options.transport !== void 0 && (options.fetch !== void 0 || options.httpRetries !== void 0 || options.httpTimeoutMs !== void 0 || options.httpBackoffBaseMs !== void 0)) {
2235
+ throw new DoclingProtocolError(
2236
+ "fetch/http retry options cannot be combined with a custom transport"
2237
+ );
2238
+ }
2239
+ this.#transport = options.transport ?? new FetchTransport({
2240
+ ...options.fetch === void 0 ? {} : { fetch: options.fetch },
2241
+ ...options.httpRetries === void 0 ? {} : { retries: options.httpRetries },
2242
+ ...options.httpTimeoutMs === void 0 ? {} : { timeoutMs: options.httpTimeoutMs },
2243
+ ...options.httpBackoffBaseMs === void 0 ? {} : { backoffBaseMs: options.httpBackoffBaseMs }
2244
+ });
2245
+ this.#defaultOptions = resolveConvertOptions({}, options.options);
2246
+ this.#statusWatcher = options.statusWatcher ?? "websocket";
2247
+ this.#webSocketFallbackToPoll = options.webSocketFallbackToPoll ?? true;
2248
+ this.#webSocketFactory = options.webSocketFactory;
2249
+ this.#connectTimeoutMs = positiveNumber(
2250
+ options.connectTimeoutMs ?? 1e4,
2251
+ "connectTimeoutMs"
2252
+ );
2253
+ this.#pollServerWaitSeconds = nonNegativeNumber(
2254
+ options.pollServerWaitSeconds ?? 5,
2255
+ "pollServerWaitSeconds"
2256
+ );
2257
+ this.#pollClientIntervalMs = nonNegativeNumber(
2258
+ options.pollClientIntervalMs ?? this.#pollServerWaitSeconds * 1e3,
2259
+ "pollClientIntervalMs"
2260
+ );
2261
+ this.#jobTimeoutMs = positiveNumber(
2262
+ options.jobTimeoutMs ?? DEFAULT_JOB_TIMEOUT_MS,
2263
+ "jobTimeoutMs"
2264
+ );
2265
+ this.#maxConcurrency = validateConcurrency(
2266
+ options.maxConcurrency ?? DEFAULT_MAX_CONCURRENCY
2267
+ );
2268
+ this.#artifactDownloader = options.artifactDownloader ?? new ArtifactDownloader(options.artifactDownload);
2269
+ }
2270
+ async health(options = {}) {
2271
+ const value = await this.#request("GET", "/health", {
2272
+ signal: options.signal,
2273
+ retries: 0
2274
+ });
2275
+ if (!isRecord4(value)) {
2276
+ throw new DoclingResponseSchemaMismatchError(
2277
+ "Docling health response must be an object",
2278
+ { status: 200 }
2279
+ );
2280
+ }
2281
+ if (value.status !== void 0 && typeof value.status !== "string") {
2282
+ throw new DoclingResponseSchemaMismatchError(
2283
+ "Docling health response status must be a string",
2284
+ { status: 200 }
2285
+ );
2286
+ }
2287
+ return { status: value.status ?? "ok" };
2288
+ }
2289
+ async version(options = {}) {
2290
+ const value = await this.#request("GET", "/version", {
2291
+ signal: options.signal,
2292
+ retries: 0
2293
+ });
2294
+ if (!isRecord4(value)) {
2295
+ throw new DoclingResponseSchemaMismatchError(
2296
+ "Docling version response must be an object",
2297
+ { status: 200 }
2298
+ );
2299
+ }
2300
+ return value;
2301
+ }
2302
+ async close() {
2303
+ if (this.#closed) {
2304
+ return;
2305
+ }
2306
+ this.#closed = true;
2307
+ await this.#transport.close?.();
2308
+ }
2309
+ async submit(request, options = {}) {
2310
+ if (!Array.isArray(request.sources) || request.sources.length !== 1) {
2311
+ throw new DoclingProtocolError(
2312
+ "A single Docling submission requires exactly one source"
2313
+ );
2314
+ }
2315
+ const resolvedOptions = resolveConvertOptions(
2316
+ this.#defaultOptions,
2317
+ request.options
2318
+ );
2319
+ if (request.target === void 0) {
2320
+ return this.#submitWithAutoTarget(
2321
+ {
2322
+ ...request,
2323
+ options: resolvedOptions
2324
+ },
2325
+ options
2326
+ );
2327
+ }
2328
+ return this.#submitRequestForTarget(
2329
+ {
2330
+ ...request,
2331
+ options: targetNeedsJson(request.target) ? withJsonOutput(resolvedOptions) : resolvedOptions,
2332
+ target: request.target
2333
+ },
2334
+ options
2335
+ );
2336
+ }
2337
+ async submitSource(source, options = {}) {
2338
+ const normalized = await normalizeSourceInput(source, options.signal);
2339
+ let convertOptions = resolveConvertOptions(this.#defaultOptions, options.options);
2340
+ if (options.outputFormats !== void 0) {
2341
+ convertOptions = {
2342
+ ...convertOptions,
2343
+ to_formats: [...options.outputFormats]
2344
+ };
2345
+ validateConvertOptions(convertOptions);
2346
+ }
2347
+ if (options.target === void 0) {
2348
+ return this.#submitNormalizedWithAutoTarget(normalized, convertOptions, options);
2349
+ }
2350
+ return this.#submitNormalizedForTarget(
2351
+ normalized,
2352
+ targetNeedsJson(options.target) ? withJsonOutput(convertOptions) : convertOptions,
2353
+ options.target,
2354
+ options
2355
+ );
2356
+ }
2357
+ submitUrl(url, options = {}, requestOptions = {}) {
2358
+ const source = {
2359
+ kind: "http",
2360
+ url,
2361
+ headers: requestOptions.sourceHeaders ?? {}
2362
+ };
2363
+ return this.submitSource(source, {
2364
+ options,
2365
+ ...requestOptions.target === void 0 ? {} : { target: requestOptions.target },
2366
+ ...requestOptions.headers === void 0 ? {} : { headers: requestOptions.headers },
2367
+ ...requestOptions.signal === void 0 ? {} : { signal: requestOptions.signal }
2368
+ });
2369
+ }
2370
+ submitFile(base64, filename, options = {}, requestOptions = {}) {
2371
+ const source = {
2372
+ kind: "file",
2373
+ base64_string: base64,
2374
+ filename
2375
+ };
2376
+ return this.submitSource(source, {
2377
+ options,
2378
+ ...requestOptions
2379
+ });
2380
+ }
2381
+ submitBinary(source, options = {}) {
2382
+ return this.submitSource(source, options);
2383
+ }
2384
+ async submitBatch(request, options = {}) {
2385
+ throwIfAborted2(options.signal);
2386
+ validateBatchRequest(request);
2387
+ let convertOptions = resolveConvertOptions(this.#defaultOptions, request.options);
2388
+ if (options.outputFormats !== void 0) {
2389
+ convertOptions = {
2390
+ ...convertOptions,
2391
+ to_formats: [...options.outputFormats]
2392
+ };
2393
+ validateConvertOptions(convertOptions);
2394
+ }
2395
+ const payload = {
2396
+ options: convertOptions,
2397
+ sources: structuredClone(request.sources),
2398
+ target: structuredClone(request.target),
2399
+ callbacks: structuredClone(request.callbacks ?? [])
2400
+ };
2401
+ throwIfAborted2(options.signal);
2402
+ const status = parseTaskStatus(
2403
+ await this.#request("POST", "/v1/convert/source/batch", {
2404
+ body: payload,
2405
+ headers: options.headers,
2406
+ signal: options.signal
2407
+ })
2408
+ );
2409
+ const loader = isPresignedTarget(request.target) ? (taskId, lastStatus, signal) => this.#fetchPresignedResult(taskId, lastStatus, signal) : (taskId, lastStatus, signal) => this.#fetchCountsResult(taskId, lastStatus, signal);
2410
+ return new DoclingJob(
2411
+ this,
2412
+ status,
2413
+ loader
2414
+ );
2415
+ }
2416
+ async submitChunk(request, options = {}) {
2417
+ throwIfAborted2(options.signal);
2418
+ if (!Array.isArray(request.sources) || request.sources.length === 0) {
2419
+ throw new DoclingProtocolError("At least one Docling source is required");
2420
+ }
2421
+ if (!["hybrid", "hierarchical"].includes(request.chunker)) {
2422
+ throw new DoclingProtocolError(
2423
+ `Unsupported Docling chunker: ${String(request.chunker)}`
2424
+ );
2425
+ }
2426
+ validateChunkRequestOptions(request);
2427
+ for (const source of request.sources) {
2428
+ validateConversionSource(source);
2429
+ }
2430
+ validateCallbacks(request.callbacks);
2431
+ if (request.target !== void 0 && request.target.kind !== "inbody") {
2432
+ throw new DoclingProtocolError("Chunk conversion only supports inbody targets");
2433
+ }
2434
+ const payload = {
2435
+ convert_options: resolveConvertOptions(
2436
+ this.#defaultOptions,
2437
+ request.convert_options
2438
+ ),
2439
+ chunking_options: {
2440
+ ...request.chunking_options,
2441
+ chunker: request.chunker
2442
+ },
2443
+ sources: structuredClone(request.sources),
2444
+ include_converted_doc: request.include_converted_doc ?? false,
2445
+ target: request.target ?? { kind: "inbody" },
2446
+ callbacks: structuredClone(request.callbacks ?? [])
2447
+ };
2448
+ throwIfAborted2(options.signal);
2449
+ const status = parseTaskStatus(
2450
+ await this.#request(
2451
+ "POST",
2452
+ `/v1/chunk/${request.chunker}/source/async`,
2453
+ {
2454
+ body: payload,
2455
+ headers: options.headers,
2456
+ signal: options.signal
2457
+ }
2458
+ )
2459
+ );
2460
+ return new DoclingJob(
2461
+ this,
2462
+ status,
2463
+ (taskId, lastStatus, signal) => this.#fetchChunkResult(taskId, lastStatus, signal)
2464
+ );
2465
+ }
2466
+ submitChunkUrl(url, request, requestOptions = {}) {
2467
+ return this.submitChunk(
2468
+ {
2469
+ ...request,
2470
+ sources: [
2471
+ {
2472
+ kind: "http",
2473
+ url,
2474
+ headers: requestOptions.sourceHeaders ?? {}
2475
+ }
2476
+ ]
2477
+ },
2478
+ requestOptions
2479
+ );
2480
+ }
2481
+ submitChunkFile(base64, filename, request, requestOptions = {}) {
2482
+ return this.submitChunk(
2483
+ {
2484
+ ...request,
2485
+ sources: [
2486
+ {
2487
+ kind: "file",
2488
+ base64_string: base64,
2489
+ filename
2490
+ }
2491
+ ]
2492
+ },
2493
+ requestOptions
2494
+ );
2495
+ }
2496
+ async submitChunkBinary(source, request, requestOptions = {}) {
2497
+ if (!["hybrid", "hierarchical"].includes(request.chunker)) {
2498
+ throw new DoclingProtocolError(
2499
+ `Unsupported Docling chunker: ${String(request.chunker)}`
2500
+ );
2501
+ }
2502
+ validateChunkRequestOptions(request);
2503
+ if ((request.callbacks?.length ?? 0) > 0) {
2504
+ throw new DoclingProtocolError(
2505
+ "The multipart chunk endpoint does not support callbacks"
2506
+ );
2507
+ }
2508
+ const normalized = await normalizeSourceInput(source, requestOptions.signal);
2509
+ if (normalized.kind !== "multipart") {
2510
+ throw new DoclingProtocolError("Binary chunk source normalization failed");
2511
+ }
2512
+ const form = new FormData();
2513
+ const convertOptions = resolveConvertOptions(
2514
+ this.#defaultOptions,
2515
+ request.convert_options
2516
+ );
2517
+ for (const [key, value] of Object.entries(convertOptions)) {
2518
+ if (value !== void 0 && value !== null) {
2519
+ form.append(`convert_${key}`, formValue(value));
2520
+ }
2521
+ }
2522
+ for (const [key, value] of Object.entries(request.chunking_options ?? {})) {
2523
+ if (key !== "chunker" && value !== void 0 && value !== null) {
2524
+ form.append(`chunking_${key}`, formValue(value));
2525
+ }
2526
+ }
2527
+ form.append(
2528
+ "include_converted_doc",
2529
+ String(request.include_converted_doc ?? false)
2530
+ );
2531
+ form.append("target_type", "inbody");
2532
+ form.append("files", normalized.blob, normalized.descriptor.filename);
2533
+ const status = parseTaskStatus(
2534
+ await this.#request("POST", `/v1/chunk/${request.chunker}/file/async`, {
2535
+ body: form,
2536
+ bodyType: "form",
2537
+ headers: requestOptions.headers,
2538
+ signal: requestOptions.signal
2539
+ })
2540
+ );
2541
+ return new DoclingJob(
2542
+ this,
2543
+ status,
2544
+ (taskId, lastStatus, signal) => this.#fetchChunkResult(taskId, lastStatus, signal)
2545
+ );
2546
+ }
2547
+ job(taskId, status, resultLoader) {
2548
+ if (taskId === "") {
2549
+ throw new DoclingProtocolError("taskId must not be empty");
2550
+ }
2551
+ return new DoclingJob(
2552
+ this,
2553
+ status ?? {
2554
+ task_id: taskId,
2555
+ task_type: "convert",
2556
+ task_status: "pending"
2557
+ },
2558
+ resultLoader ?? ((id, lastStatus, signal) => this.#fetchInBodyResult(id, lastStatus, signal))
2559
+ );
2560
+ }
2561
+ async poll(taskId, options = {}) {
2562
+ requireTaskId(taskId);
2563
+ const waitSeconds = nonNegativeNumber(options.waitSeconds ?? 0, "waitSeconds");
2564
+ try {
2565
+ return parseTaskStatus(
2566
+ await this.#request(
2567
+ "GET",
2568
+ `/v1/status/poll/${encodeURIComponent(taskId)}?wait=${encodeURIComponent(
2569
+ waitSeconds
2570
+ )}`,
2571
+ { signal: options.signal }
2572
+ )
2573
+ );
2574
+ } catch (error) {
2575
+ if (error instanceof DoclingHttpError && error.status === 404) {
2576
+ throw new DoclingTaskNotFoundError(taskId);
2577
+ }
2578
+ throw error;
2579
+ }
2580
+ }
2581
+ watch(taskId, options = {}) {
2582
+ if (this.#closed) {
2583
+ throw new DoclingProtocolError("Docling client is closed");
2584
+ }
2585
+ requireTaskId(taskId);
2586
+ return watchTask({
2587
+ taskId,
2588
+ baseUrl: this.#baseUrl,
2589
+ apiKey: this.#apiKey,
2590
+ watcher: options.statusWatcher ?? this.#statusWatcher,
2591
+ fallbackToPoll: this.#webSocketFallbackToPoll,
2592
+ connectTimeoutMs: this.#connectTimeoutMs,
2593
+ ...this.#webSocketFactory === void 0 ? {} : { webSocketFactory: this.#webSocketFactory },
2594
+ poll: (id, pollOptions) => this.poll(id, pollOptions),
2595
+ parseStatus: parseTaskStatus,
2596
+ timeoutMs: options.timeoutMs ?? this.#jobTimeoutMs,
2597
+ pollIntervalMs: options.pollIntervalMs ?? this.#pollClientIntervalMs,
2598
+ serverWaitSeconds: options.serverWaitSeconds ?? this.#pollServerWaitSeconds,
2599
+ ...options.signal === void 0 ? {} : { signal: options.signal },
2600
+ ...options.onStatus === void 0 ? {} : { onStatus: options.onStatus }
2601
+ });
2602
+ }
2603
+ async waitForCompletion(taskId, options = {}) {
2604
+ let lastStatus;
2605
+ for await (const status of this.watch(taskId, options)) {
2606
+ lastStatus = status;
2607
+ }
2608
+ if (lastStatus === void 0) {
2609
+ throw new DoclingTimeoutError(taskId, options.timeoutMs ?? this.#jobTimeoutMs);
2610
+ }
2611
+ return lastStatus;
2612
+ }
2613
+ getResult(taskId, options = {}) {
2614
+ return this.#fetchInBodyResult(taskId, options.lastStatus, options.signal);
2615
+ }
2616
+ getBinaryResult(taskId, options = {}) {
2617
+ return this.#fetchBinaryResult(taskId, options.lastStatus, options.signal);
2618
+ }
2619
+ getRawResult(taskId, options = {}) {
2620
+ return this.#fetchJsonResult(
2621
+ taskId,
2622
+ options.lastStatus,
2623
+ options.signal
2624
+ );
2625
+ }
2626
+ async convert(source, options = {}) {
2627
+ const normalized = await normalizeSourceInput(source, options.signal);
2628
+ validateMaxFileSize(options.maxFileSize);
2629
+ let convertOptions = resolveConvertOptions(this.#defaultOptions, options.options);
2630
+ convertOptions = applyPageLimits(
2631
+ convertOptions,
2632
+ options.pageRange,
2633
+ options.maxNumPages
2634
+ );
2635
+ convertOptions = withJsonOutput(convertOptions);
2636
+ const preflight = preflightFileSize(normalized, options.maxFileSize);
2637
+ let result;
2638
+ if (preflight !== null) {
2639
+ result = syntheticConversion(
2640
+ normalized.descriptor,
2641
+ "skipped",
2642
+ preflight,
2643
+ "policy"
2644
+ );
2645
+ } else {
2646
+ const job = await this.#submitNormalizedWithAutoTarget(
2647
+ normalized,
2648
+ convertOptions,
2649
+ options
2650
+ );
2651
+ const response = await job.result(options);
2652
+ result = isPresignedResponse(response) ? await materializePresignedResult(
2653
+ response,
2654
+ normalized.descriptor,
2655
+ this.#artifactDownloader,
2656
+ options.signal
2657
+ ) : response;
2658
+ }
2659
+ if ((options.raisesOnError ?? true) && !["success", "partial_success"].includes(result.status)) {
2660
+ throw new DoclingConversionError(conversionFailureMessage(result));
2661
+ }
2662
+ return result;
2663
+ }
2664
+ async *convertAll(sources, options = {}) {
2665
+ const items = mapSourcesToItems(sources, options.options, options.headers);
2666
+ for await (const completed of boundedOutcomes(
2667
+ items,
2668
+ async (item, _index, signal) => {
2669
+ try {
2670
+ return await this.convert(item.source, {
2671
+ ...options,
2672
+ options: item.options,
2673
+ headers: item.headers,
2674
+ raisesOnError: false,
2675
+ signal
2676
+ });
2677
+ } catch (error) {
2678
+ if (signal.aborted || isAbortError2(error)) {
2679
+ throw signal.reason ?? error;
2680
+ }
2681
+ return syntheticConversion(
2682
+ fallbackInput(item.source),
2683
+ "failure",
2684
+ error instanceof Error ? error.message : String(error)
2685
+ );
2686
+ }
2687
+ },
2688
+ {
2689
+ maxInFlight: validateConcurrency(
2690
+ options.maxConcurrency ?? this.#maxConcurrency
2691
+ ),
2692
+ ordered: true,
2693
+ ...options.signal === void 0 ? {} : { signal: options.signal }
2694
+ }
2695
+ )) {
2696
+ if (completed.outcome instanceof Error) {
2697
+ yield syntheticConversion(
2698
+ fallbackInput(completed.item.source),
2699
+ "failure",
2700
+ completed.outcome.message
2701
+ );
2702
+ } else {
2703
+ yield completed.outcome;
2704
+ }
2705
+ }
2706
+ }
2707
+ async *submitAndRetrieveEach(items, options = {}) {
2708
+ const maxInFlight = validateConcurrency(
2709
+ options.maxInFlight ?? DEFAULT_MAX_CONCURRENCY
2710
+ );
2711
+ for await (const completed of boundedOutcomes(
2712
+ items,
2713
+ async (item, _index, signal) => {
2714
+ const job = await this.submitSource(item.source, {
2715
+ options: item.options,
2716
+ ...item.headers === void 0 ? {} : { headers: item.headers },
2717
+ ...options.target === void 0 ? {} : { target: options.target },
2718
+ signal
2719
+ });
2720
+ return job.result({
2721
+ timeoutMs: this.#jobTimeoutMs,
2722
+ ...maxInFlight > 64 && this.#statusWatcher === "websocket" ? { statusWatcher: "polling" } : {},
2723
+ signal
2724
+ });
2725
+ },
2726
+ {
2727
+ maxInFlight,
2728
+ ordered: options.ordered ?? false,
2729
+ ...options.signal === void 0 ? {} : { signal: options.signal }
2730
+ }
2731
+ )) {
2732
+ yield [completed.item, completed.outcome];
2733
+ }
2734
+ }
2735
+ submitAndRetrieveMany(items, options = {}) {
2736
+ return this.submitAndRetrieveEach(
2737
+ items,
2738
+ options
2739
+ );
2740
+ }
2741
+ async chunk(sourceOrRequest, chunkerOrOptions = {}, convertOrWaitOptions = {}, explicitWaitOptions = {}) {
2742
+ if (isChunkSourcesRequest(sourceOrRequest)) {
2743
+ const job2 = await this.submitChunk(sourceOrRequest, {
2744
+ signal: chunkerOrOptions.signal
2745
+ });
2746
+ return job2.result(chunkerOrOptions);
2747
+ }
2748
+ const pythonShaped = typeof chunkerOrOptions === "string";
2749
+ const request = pythonShaped ? {
2750
+ chunker: chunkerOrOptions,
2751
+ convert_options: convertOrWaitOptions,
2752
+ include_converted_doc: explicitWaitOptions.includeConvertedDoc ?? false
2753
+ } : chunkerOrOptions;
2754
+ const waitOptions = pythonShaped ? explicitWaitOptions : convertOrWaitOptions;
2755
+ const normalized = await normalizeSourceInput(sourceOrRequest, waitOptions.signal);
2756
+ const job = normalized.kind === "multipart" ? await this.submitChunkBinary(
2757
+ {
2758
+ data: normalized.blob,
2759
+ filename: normalized.descriptor.filename,
2760
+ contentType: normalized.blob.type
2761
+ },
2762
+ request,
2763
+ { signal: waitOptions.signal }
2764
+ ) : await this.submitChunk(
2765
+ {
2766
+ ...request,
2767
+ sources: [normalized.source]
2768
+ },
2769
+ { signal: waitOptions.signal }
2770
+ );
2771
+ return job.result(waitOptions);
2772
+ }
2773
+ #submitWithAutoTarget(request, options) {
2774
+ return this.#submitRequestForTarget(
2775
+ {
2776
+ ...request,
2777
+ options: request.options ?? {},
2778
+ target: { kind: "presigned_url" }
2779
+ },
2780
+ options
2781
+ ).catch((error) => {
2782
+ if (!shouldFallbackFromPresigned(error)) {
2783
+ throw error;
2784
+ }
2785
+ return this.#submitRequestForTarget(
2786
+ {
2787
+ ...request,
2788
+ options: withJsonOutput(request.options ?? {}),
2789
+ target: { kind: "inbody" }
2790
+ },
2791
+ options
2792
+ );
2793
+ });
2794
+ }
2795
+ #submitNormalizedWithAutoTarget(source, options, requestOptions) {
2796
+ return this.#submitNormalizedForTarget(
2797
+ source,
2798
+ options,
2799
+ { kind: "presigned_url" },
2800
+ requestOptions
2801
+ ).catch((error) => {
2802
+ if (!shouldFallbackFromPresigned(error)) {
2803
+ throw error;
2804
+ }
2805
+ return this.#submitNormalizedForTarget(
2806
+ source,
2807
+ withJsonOutput(options),
2808
+ { kind: "inbody" },
2809
+ requestOptions
2810
+ );
2811
+ });
2812
+ }
2813
+ async #submitRequestForTarget(request, options) {
2814
+ validateConversionSource(request.sources[0]);
2815
+ validateSubmitTarget(request.target);
2816
+ validateCallbacks(request.callbacks);
2817
+ const descriptor = (await normalizeSourceInput(request.sources[0], options.signal)).descriptor;
2818
+ const payload = {
2819
+ options: request.options ?? {},
2820
+ sources: structuredClone(request.sources),
2821
+ target: structuredClone(request.target),
2822
+ callbacks: structuredClone(request.callbacks ?? [])
2823
+ };
2824
+ throwIfAborted2(options.signal);
2825
+ const status = parseTaskStatus(
2826
+ await this.#request("POST", "/v1/convert/source/async", {
2827
+ body: payload,
2828
+ headers: options.headers,
2829
+ signal: options.signal
2830
+ })
2831
+ );
2832
+ return new DoclingJob(
2833
+ this,
2834
+ status,
2835
+ this.#resultLoaderForTarget(request.target, descriptor)
2836
+ );
2837
+ }
2838
+ async #submitNormalizedForTarget(source, options, target, requestOptions) {
2839
+ if (source.kind === "json") {
2840
+ return this.#submitRequestForTarget(
2841
+ {
2842
+ options,
2843
+ sources: [source.source],
2844
+ target,
2845
+ callbacks: []
2846
+ },
2847
+ requestOptions
2848
+ );
2849
+ }
2850
+ if (!["inbody", "zip", "presigned_url"].includes(target.kind)) {
2851
+ const fileSource = await fileSourceFromBlob(source, requestOptions.signal);
2852
+ return this.#submitRequestForTarget(
2853
+ {
2854
+ options,
2855
+ sources: [fileSource],
2856
+ target,
2857
+ callbacks: []
2858
+ },
2859
+ requestOptions
2860
+ );
2861
+ }
2862
+ const form = new FormData();
2863
+ for (const [key, value] of Object.entries(options)) {
2864
+ if (value !== void 0 && value !== null) {
2865
+ form.append(key, formValue(value));
2866
+ }
2867
+ }
2868
+ form.append("target_type", target.kind);
2869
+ form.append("files", source.blob, source.descriptor.filename);
2870
+ const status = parseTaskStatus(
2871
+ await this.#request("POST", "/v1/convert/file/async", {
2872
+ body: form,
2873
+ bodyType: "form",
2874
+ headers: requestOptions.headers,
2875
+ signal: requestOptions.signal
2876
+ })
2877
+ );
2878
+ return new DoclingJob(
2879
+ this,
2880
+ status,
2881
+ this.#resultLoaderForTarget(target, source.descriptor)
2882
+ );
2883
+ }
2884
+ #resultLoaderForTarget(target, descriptor) {
2885
+ if (target.kind === "zip") {
2886
+ return ((taskId, lastStatus, signal) => this.#fetchBinaryResult(taskId, lastStatus, signal));
2887
+ }
2888
+ if (target.kind === "presigned_url") {
2889
+ return ((taskId, lastStatus, signal) => this.#fetchPresignedResult(taskId, lastStatus, signal));
2890
+ }
2891
+ if (target.kind !== "inbody") {
2892
+ return ((taskId, lastStatus, signal) => this.#fetchCountsResult(taskId, lastStatus, signal));
2893
+ }
2894
+ return (async (taskId, lastStatus, signal) => conversionFromResponse(
2895
+ await this.#fetchConvertResult(taskId, lastStatus, signal),
2896
+ descriptor
2897
+ ));
2898
+ }
2899
+ async #fetchJsonResult(taskId, lastStatus, signal) {
2900
+ requireTaskId(taskId);
2901
+ try {
2902
+ const result = await this.#request(
2903
+ "GET",
2904
+ `/v1/result/${encodeURIComponent(taskId)}`,
2905
+ { signal }
2906
+ );
2907
+ if (isTaskFailureResult(result)) {
2908
+ throw new DoclingTaskError({
2909
+ task_id: taskId,
2910
+ task_type: lastStatus?.task_type ?? "convert",
2911
+ task_status: "failure",
2912
+ failure: result.failure
2913
+ });
2914
+ }
2915
+ return result;
2916
+ } catch (error) {
2917
+ if (error instanceof DoclingHttpError && error.status === 404) {
2918
+ throw mapResultNotFound(taskId, error, lastStatus);
2919
+ }
2920
+ if (error instanceof DoclingProtocolError) {
2921
+ throw new DoclingResponseSchemaMismatchError(
2922
+ "Docling result response is not valid JSON",
2923
+ { status: 200, cause: error }
2924
+ );
2925
+ }
2926
+ throw error;
2927
+ }
2928
+ }
2929
+ async #fetchConvertResult(taskId, lastStatus, signal) {
2930
+ const result = await this.#fetchJsonResult(taskId, lastStatus, signal);
2931
+ return parseConvertDocumentResponse(result);
2932
+ }
2933
+ async #fetchChunkResult(taskId, lastStatus, signal) {
2934
+ const result = await this.#fetchJsonResult(taskId, lastStatus, signal);
2935
+ return parseChunkDocumentResponse(result);
2936
+ }
2937
+ async #fetchInBodyResult(taskId, lastStatus, signal) {
2938
+ const result = await this.#fetchJsonResult(taskId, lastStatus, signal);
2939
+ if (isConvertDocumentResponse(result) || isChunkDocumentResponse(result)) {
2940
+ return isConvertDocumentResponse(result) ? parseConvertDocumentResponse(result) : parseChunkDocumentResponse(result);
2941
+ }
2942
+ throw new DoclingResponseSchemaMismatchError(
2943
+ "Docling returned an unknown in-body result response",
2944
+ { status: 200 }
2945
+ );
2946
+ }
2947
+ async #fetchPresignedResult(taskId, lastStatus, signal) {
2948
+ const result = await this.#fetchJsonResult(taskId, lastStatus, signal);
2949
+ return parsePresignedResponse(result);
2950
+ }
2951
+ async #fetchCountsResult(taskId, lastStatus, signal) {
2952
+ const result = await this.#fetchJsonResult(taskId, lastStatus, signal);
2953
+ return parseCountsResponse(result);
2954
+ }
2955
+ async #fetchBinaryResult(taskId, lastStatus, signal) {
2956
+ requireTaskId(taskId);
2957
+ try {
2958
+ const response = await this.#request(
2959
+ "GET",
2960
+ `/v1/result/${encodeURIComponent(taskId)}`,
2961
+ { responseType: "bytes", signal }
2962
+ );
2963
+ if (response.contentType.toLowerCase().includes("json")) {
2964
+ let json;
2965
+ try {
2966
+ json = JSON.parse(new TextDecoder().decode(response.content));
2967
+ } catch {
2968
+ }
2969
+ if (json !== void 0 && isTaskFailureResult(json)) {
2970
+ throw new DoclingTaskError({
2971
+ task_id: taskId,
2972
+ task_type: lastStatus?.task_type ?? "convert",
2973
+ task_status: "failure",
2974
+ failure: json.failure
2975
+ });
2976
+ }
2977
+ }
2978
+ return {
2979
+ content: response.content,
2980
+ content_type: response.contentType || "application/octet-stream",
2981
+ filename: filenameFromContentDisposition(
2982
+ response.headers["content-disposition"]
2983
+ )
2984
+ };
2985
+ } catch (error) {
2986
+ if (error instanceof DoclingHttpError && error.status === 404) {
2987
+ throw mapResultNotFound(taskId, error, lastStatus);
2988
+ }
2989
+ throw error;
2990
+ }
2991
+ }
2992
+ #request(method, path, options = {}) {
2993
+ if (this.#closed) {
2994
+ throw new DoclingProtocolError("Docling client is closed");
2995
+ }
2996
+ const headers = {
2997
+ ...this.#headers,
2998
+ ...options.bodyType === "form" ? {} : { "content-type": "application/json" },
2999
+ ...normalizeHeaders(options.headers)
3000
+ };
3001
+ if (options.bodyType === "form") {
3002
+ delete headers["content-type"];
3003
+ }
3004
+ return this.#transport.request({
3005
+ method,
3006
+ url: `${this.#baseUrl}${path}`,
3007
+ headers,
3008
+ ...options.body === void 0 ? {} : { body: options.body },
3009
+ ...options.bodyType === void 0 ? {} : { bodyType: options.bodyType },
3010
+ ...options.responseType === void 0 ? {} : { responseType: options.responseType },
3011
+ ...options.retries === void 0 ? {} : { retries: options.retries },
3012
+ ...options.timeoutMs === void 0 ? {} : { timeoutMs: options.timeoutMs },
3013
+ ...options.signal === void 0 ? {} : { signal: options.signal }
3014
+ });
3015
+ }
3016
+ };
3017
+ var DoclingJob = class {
3018
+ #client;
3019
+ #submittedAt;
3020
+ #loadResult;
3021
+ #status;
3022
+ constructor(client, status, loadResult) {
3023
+ this.#client = client;
3024
+ this.#status = status;
3025
+ this.#loadResult = loadResult;
3026
+ this.#submittedAt = /* @__PURE__ */ new Date();
3027
+ }
3028
+ get taskId() {
3029
+ return this.#status.task_id;
3030
+ }
3031
+ get status() {
3032
+ return this.#status;
3033
+ }
3034
+ get submittedAt() {
3035
+ return new Date(this.#submittedAt);
3036
+ }
3037
+ get queuePosition() {
3038
+ return this.#status.task_position ?? null;
3039
+ }
3040
+ get done() {
3041
+ return ["success", "failure"].includes(this.#status.task_status);
3042
+ }
3043
+ async poll(options = {}) {
3044
+ this.#status = await this.#client.poll(this.taskId, options);
3045
+ return this.#status;
3046
+ }
3047
+ async *watch(options = {}) {
3048
+ for await (const status of this.#client.watch(this.taskId, options)) {
3049
+ this.#status = status;
3050
+ yield status;
3051
+ }
3052
+ }
3053
+ async wait(options = {}) {
3054
+ if (!this.done) {
3055
+ this.#status = await this.#client.waitForCompletion(this.taskId, options);
3056
+ }
3057
+ return this.#status;
3058
+ }
3059
+ getResult(options = {}) {
3060
+ return this.#loadResult(this.taskId, this.#status, options.signal);
3061
+ }
3062
+ async result(options = {}) {
3063
+ if (!this.done) {
3064
+ await this.wait(options);
3065
+ }
3066
+ return this.getResult({ signal: options.signal });
3067
+ }
3068
+ };
3069
+ function parseTaskStatus(value) {
3070
+ if (!isRecord4(value)) {
3071
+ throw schemaMismatch("Docling returned a non-object task status");
3072
+ }
3073
+ if (typeof value.task_id !== "string" || value.task_id === "") {
3074
+ throw schemaMismatch("Docling task status is missing task_id");
3075
+ }
3076
+ if (!["convert", "chunk"].includes(String(value.task_type))) {
3077
+ throw schemaMismatch("Docling task status is missing task_type");
3078
+ }
3079
+ if (![
3080
+ "pending",
3081
+ "started",
3082
+ "success",
3083
+ "failure",
3084
+ "partial_success",
3085
+ "skipped"
3086
+ ].includes(String(value.task_status))) {
3087
+ throw schemaMismatch(
3088
+ `Docling returned unknown task_status: ${String(value.task_status)}`
3089
+ );
3090
+ }
3091
+ validateOptionalNullableInteger(value.task_position, "task_position");
3092
+ validateOptionalNullableString(value.error_message, "error_message");
3093
+ let taskMeta = value.task_meta;
3094
+ if (value.task_meta !== void 0 && value.task_meta !== null) {
3095
+ if (!isRecord4(value.task_meta)) {
3096
+ throw schemaMismatch("Docling task_meta must be an object or null");
3097
+ }
3098
+ requireInteger(value.task_meta.num_docs, "task_meta.num_docs");
3099
+ for (const field of [
3100
+ "num_processed",
3101
+ "num_succeeded",
3102
+ "num_partially_succeeded",
3103
+ "num_failed"
3104
+ ]) {
3105
+ if (value.task_meta[field] !== void 0) {
3106
+ requireInteger(value.task_meta[field], `task_meta.${field}`);
3107
+ }
3108
+ }
3109
+ taskMeta = {
3110
+ num_docs: value.task_meta.num_docs,
3111
+ num_processed: value.task_meta.num_processed ?? 0,
3112
+ num_succeeded: value.task_meta.num_succeeded ?? 0,
3113
+ num_partially_succeeded: value.task_meta.num_partially_succeeded ?? 0,
3114
+ num_failed: value.task_meta.num_failed ?? 0
3115
+ };
3116
+ }
3117
+ let failure = value.failure;
3118
+ if (value.failure !== void 0 && value.failure !== null) {
3119
+ failure = parseFailureInfo(value.failure);
3120
+ }
3121
+ return {
3122
+ ...value,
3123
+ ...value.task_meta === void 0 ? {} : { task_meta: taskMeta },
3124
+ ...value.failure === void 0 ? {} : { failure }
3125
+ };
3126
+ }
3127
+ function isConvertDocumentResponse(value) {
3128
+ if (!isRecord4(value) || !("document" in value)) {
3129
+ return false;
3130
+ }
3131
+ try {
3132
+ parseConvertDocumentResponse(value);
3133
+ return true;
3134
+ } catch {
3135
+ return false;
3136
+ }
3137
+ }
3138
+ function isChunkDocumentResponse(value) {
3139
+ if (!isRecord4(value) || !("chunks" in value)) {
3140
+ return false;
3141
+ }
3142
+ try {
3143
+ parseChunkDocumentResponse(value);
3144
+ return true;
3145
+ } catch {
3146
+ return false;
3147
+ }
3148
+ }
3149
+ function isCountsResponse(value) {
3150
+ if (!isRecord4(value)) {
3151
+ return false;
3152
+ }
3153
+ try {
3154
+ parseCountsResponse(value);
3155
+ return true;
3156
+ } catch {
3157
+ return false;
3158
+ }
3159
+ }
3160
+ function isPresignedResponse(value) {
3161
+ return isCountsResponse(value) && isRecord4(value) && Array.isArray(value.documents);
3162
+ }
3163
+ function isTaskFailureResult(value) {
3164
+ if (!isRecord4(value) || value.kind !== "TaskFailureResult") {
3165
+ return false;
3166
+ }
3167
+ try {
3168
+ parseFailureInfo(value.failure);
3169
+ return true;
3170
+ } catch {
3171
+ return false;
3172
+ }
3173
+ }
3174
+ function isConversionStatus(value) {
3175
+ return [
3176
+ "pending",
3177
+ "started",
3178
+ "success",
3179
+ "partial_success",
3180
+ "skipped",
3181
+ "failure"
3182
+ ].includes(String(value));
3183
+ }
3184
+ function parseConvertDocumentResponse(value) {
3185
+ if (!isRecord4(value) || !isRecord4(value.document)) {
3186
+ throw schemaMismatch("Docling conversion response is missing its document object");
3187
+ }
3188
+ const document = value.document;
3189
+ if (typeof document.filename !== "string") {
3190
+ throw schemaMismatch("Docling conversion document filename must be a string");
3191
+ }
3192
+ for (const field of [
3193
+ "md_content",
3194
+ "html_content",
3195
+ "text_content",
3196
+ "doctags_content",
3197
+ "doclang_content"
3198
+ ]) {
3199
+ validateOptionalNullableString(document[field], `document.${field}`);
3200
+ }
3201
+ if (document.json_content !== void 0 && document.json_content !== null && !isDoclingDocument(document.json_content)) {
3202
+ throw schemaMismatch("document.json_content is not a DoclingDocument");
3203
+ }
3204
+ requireConversionStatus(value.status, "status");
3205
+ requireFiniteNumber(value.processing_time, "processing_time");
3206
+ const errors = parseErrors(value.errors);
3207
+ const timings = parseTimings(value.timings);
3208
+ const confidence = parseConfidence(value.confidence, "confidence");
3209
+ return {
3210
+ document,
3211
+ status: value.status,
3212
+ errors,
3213
+ processing_time: value.processing_time,
3214
+ timings,
3215
+ ...value.confidence === void 0 ? {} : { confidence }
3216
+ };
3217
+ }
3218
+ function parseChunkDocumentResponse(value) {
3219
+ if (!isRecord4(value) || !Array.isArray(value.chunks) || !Array.isArray(value.documents)) {
3220
+ throw schemaMismatch("Docling chunk response must contain arrays");
3221
+ }
3222
+ requireFiniteNumber(value.processing_time, "processing_time");
3223
+ const chunks = value.chunks.map((chunk, index) => {
3224
+ if (!isRecord4(chunk)) {
3225
+ throw schemaMismatch(`chunks[${index}] must be an object`);
3226
+ }
3227
+ requireString(chunk.filename, `chunks[${index}].filename`);
3228
+ requireInteger(chunk.chunk_index, `chunks[${index}].chunk_index`);
3229
+ requireString(chunk.text, `chunks[${index}].text`);
3230
+ if (!Array.isArray(chunk.doc_items) || chunk.doc_items.some((item) => typeof item !== "string")) {
3231
+ throw schemaMismatch(`chunks[${index}].doc_items must be strings`);
3232
+ }
3233
+ validateOptionalNullableString(chunk.raw_text, `chunks[${index}].raw_text`);
3234
+ validateOptionalNullableInteger(chunk.num_tokens, `chunks[${index}].num_tokens`);
3235
+ validateOptionalNullableStringArray(chunk.headings, `chunks[${index}].headings`);
3236
+ validateOptionalNullableStringArray(chunk.captions, `chunks[${index}].captions`);
3237
+ if (chunk.page_numbers !== void 0 && chunk.page_numbers !== null && (!Array.isArray(chunk.page_numbers) || chunk.page_numbers.some((page) => !Number.isSafeInteger(page)))) {
3238
+ throw schemaMismatch(`chunks[${index}].page_numbers must be integers`);
3239
+ }
3240
+ validateOptionalRecordOrNull(chunk.metadata, `chunks[${index}].metadata`);
3241
+ return chunk;
3242
+ });
3243
+ const documents = value.documents.map(
3244
+ (document, index) => parseExportResult(document, `documents[${index}]`)
3245
+ );
3246
+ return {
3247
+ chunks,
3248
+ documents,
3249
+ processing_time: value.processing_time
3250
+ };
3251
+ }
3252
+ function parseExportResult(value, path) {
3253
+ if (!isRecord4(value)) {
3254
+ throw schemaMismatch(`${path} must be an object`);
3255
+ }
3256
+ if (value.kind !== void 0 && value.kind !== "ExportResult") {
3257
+ throw schemaMismatch(`${path}.kind must be ExportResult`);
3258
+ }
3259
+ const document = value.content ?? value.document;
3260
+ const parsed = parseConvertDocumentResponse({
3261
+ document,
3262
+ status: value.status,
3263
+ errors: value.errors,
3264
+ timings: value.timings,
3265
+ confidence: value.confidence,
3266
+ processing_time: 0
3267
+ });
3268
+ return {
3269
+ kind: "ExportResult",
3270
+ content: parsed.document,
3271
+ status: parsed.status,
3272
+ errors: parsed.errors,
3273
+ timings: parsed.timings,
3274
+ ...parsed.confidence === void 0 ? {} : { confidence: parsed.confidence }
3275
+ };
3276
+ }
3277
+ function parseCountsResponse(value) {
3278
+ if (!isRecord4(value)) {
3279
+ throw schemaMismatch("Docling remote-target result must be an object");
3280
+ }
3281
+ for (const field of ["num_converted", "num_succeeded", "num_failed"]) {
3282
+ requireInteger(value[field], field);
3283
+ }
3284
+ if (value.num_partially_succeeded !== void 0) {
3285
+ requireInteger(value.num_partially_succeeded, "num_partially_succeeded");
3286
+ }
3287
+ requireFiniteNumber(value.processing_time, "processing_time");
3288
+ return {
3289
+ num_converted: value.num_converted,
3290
+ num_succeeded: value.num_succeeded,
3291
+ num_partially_succeeded: value.num_partially_succeeded ?? 0,
3292
+ num_failed: value.num_failed,
3293
+ processing_time: value.processing_time
3294
+ };
3295
+ }
3296
+ function parsePresignedResponse(value) {
3297
+ const counts = parseCountsResponse(value);
3298
+ if (!isRecord4(value) || !Array.isArray(value.documents)) {
3299
+ throw schemaMismatch("Docling presigned result must contain documents");
3300
+ }
3301
+ const documents = value.documents.map((item, index) => {
3302
+ const path = `documents[${index}]`;
3303
+ if (!isRecord4(item)) {
3304
+ throw schemaMismatch(`${path} must be an object`);
3305
+ }
3306
+ requireInteger(item.source_index, `${path}.source_index`);
3307
+ requireString(item.source_uri, `${path}.source_uri`);
3308
+ requireString(item.filename, `${path}.filename`);
3309
+ requireConversionStatus(item.status, `${path}.status`);
3310
+ const errors = parseErrors(item.errors);
3311
+ const timings = parseTimings(item.timings);
3312
+ const confidence = parseConfidence(item.confidence, `${path}.confidence`);
3313
+ const artifactsValue = item.artifacts ?? [];
3314
+ if (!Array.isArray(artifactsValue)) {
3315
+ throw schemaMismatch(`${path}.artifacts must be an array`);
3316
+ }
3317
+ const artifacts = artifactsValue.map((artifact, artifactIndex) => {
3318
+ const artifactPath = `${path}.artifacts[${artifactIndex}]`;
3319
+ if (!isRecord4(artifact)) {
3320
+ throw schemaMismatch(`${artifactPath} must be an object`);
3321
+ }
3322
+ if (![
3323
+ "json",
3324
+ "html",
3325
+ "markdown",
3326
+ "text",
3327
+ "doctags",
3328
+ "doclang",
3329
+ "resource_bundle"
3330
+ ].includes(String(artifact.artifact_type))) {
3331
+ throw schemaMismatch(`${artifactPath}.artifact_type is unsupported`);
3332
+ }
3333
+ requireString(artifact.mime_type, `${artifactPath}.mime_type`);
3334
+ requireString(artifact.uri, `${artifactPath}.uri`);
3335
+ parseAbsoluteUrl(artifact.uri, `${artifactPath}.uri`);
3336
+ validateOptionalNullableString(
3337
+ artifact.url_expires_at,
3338
+ `${artifactPath}.url_expires_at`
3339
+ );
3340
+ if (typeof artifact.url_expires_at === "string" && Number.isNaN(Date.parse(artifact.url_expires_at))) {
3341
+ throw schemaMismatch(`${artifactPath}.url_expires_at must be a datetime`);
3342
+ }
3343
+ return artifact;
3344
+ });
3345
+ return {
3346
+ source_index: item.source_index,
3347
+ source_uri: item.source_uri,
3348
+ filename: item.filename,
3349
+ status: item.status,
3350
+ errors,
3351
+ timings,
3352
+ artifacts,
3353
+ ...item.confidence === void 0 ? {} : { confidence }
3354
+ };
3355
+ });
3356
+ return { ...counts, documents };
3357
+ }
3358
+ function parseErrors(value) {
3359
+ const errors = value ?? [];
3360
+ if (!Array.isArray(errors)) {
3361
+ throw schemaMismatch("errors must be an array");
3362
+ }
3363
+ return errors.map((error, index) => {
3364
+ if (!isRecord4(error)) {
3365
+ throw schemaMismatch(`errors[${index}] must be an object`);
3366
+ }
3367
+ if (![
3368
+ "document_backend",
3369
+ "model",
3370
+ "doc_assembler",
3371
+ "user_input",
3372
+ "pipeline"
3373
+ ].includes(String(error.component_type))) {
3374
+ throw schemaMismatch(`errors[${index}].component_type is unsupported`);
3375
+ }
3376
+ requireString(error.module_name, `errors[${index}].module_name`);
3377
+ requireString(error.error_message, `errors[${index}].error_message`);
3378
+ if (error.category !== void 0 && !FAILURE_CATEGORIES.has(String(error.category))) {
3379
+ throw schemaMismatch(`errors[${index}].category is unsupported`);
3380
+ }
3381
+ validateOptionalNullableInteger(error.page_no, `errors[${index}].page_no`);
3382
+ return {
3383
+ component_type: error.component_type,
3384
+ module_name: error.module_name,
3385
+ error_message: error.error_message,
3386
+ category: error.category ?? "unknown",
3387
+ page_no: error.page_no ?? null
3388
+ };
3389
+ });
3390
+ }
3391
+ function parseTimings(value) {
3392
+ const timings = value ?? {};
3393
+ if (!isRecord4(timings)) {
3394
+ throw schemaMismatch("timings must be an object");
3395
+ }
3396
+ const parsed = {};
3397
+ for (const [name, timing] of Object.entries(timings)) {
3398
+ if (!isRecord4(timing) || !["page", "document"].includes(String(timing.scope))) {
3399
+ throw schemaMismatch(`timings.${name}.scope is unsupported`);
3400
+ }
3401
+ if (timing.count !== void 0) {
3402
+ requireInteger(timing.count, `timings.${name}.count`);
3403
+ }
3404
+ const times = timing.times ?? [];
3405
+ if (!Array.isArray(times) || times.some((time) => typeof time !== "number" || !Number.isFinite(time))) {
3406
+ throw schemaMismatch(`timings.${name}.times must contain numbers`);
3407
+ }
3408
+ const timestamps = timing.start_timestamps ?? [];
3409
+ if (!Array.isArray(timestamps) || timestamps.some((timestamp) => typeof timestamp !== "string")) {
3410
+ throw schemaMismatch(`timings.${name}.start_timestamps must contain strings`);
3411
+ }
3412
+ if (timestamps.some((timestamp) => Number.isNaN(Date.parse(timestamp)))) {
3413
+ throw schemaMismatch(`timings.${name}.start_timestamps must contain datetimes`);
3414
+ }
3415
+ parsed[name] = {
3416
+ scope: timing.scope,
3417
+ count: timing.count ?? 0,
3418
+ times,
3419
+ start_timestamps: timestamps
3420
+ };
3421
+ }
3422
+ return parsed;
3423
+ }
3424
+ function parseFailureInfo(value) {
3425
+ if (!isRecord4(value)) {
3426
+ throw schemaMismatch("failure must be an object");
3427
+ }
3428
+ if (!FAILURE_CATEGORIES.has(String(value.category))) {
3429
+ throw schemaMismatch("failure.category is unsupported");
3430
+ }
3431
+ requireString(value.message, "failure.message");
3432
+ if (typeof value.retryable !== "boolean") {
3433
+ throw schemaMismatch("failure.retryable must be a boolean");
3434
+ }
3435
+ if (!["admission", "source_enumeration", "execution", "orchestration"].includes(
3436
+ String(value.phase)
3437
+ )) {
3438
+ throw schemaMismatch("failure.phase is unsupported");
3439
+ }
3440
+ const details = value.details ?? {};
3441
+ if (!isRecord4(details) || Object.values(details).some((detail) => typeof detail !== "string")) {
3442
+ throw schemaMismatch("failure.details must contain string values");
3443
+ }
3444
+ return {
3445
+ category: value.category,
3446
+ message: value.message,
3447
+ retryable: value.retryable,
3448
+ phase: value.phase,
3449
+ details
3450
+ };
3451
+ }
3452
+ var FAILURE_CATEGORIES = /* @__PURE__ */ new Set([
3453
+ "policy",
3454
+ "capacity",
3455
+ "source_unavailable",
3456
+ "target_unavailable",
3457
+ "timeout",
3458
+ "internal",
3459
+ "backend_failure",
3460
+ "inference_failure",
3461
+ "unknown"
3462
+ ]);
3463
+ function isDoclingDocument(value) {
3464
+ return isRecord4(value) && value.schema_name === "DoclingDocument" && typeof value.name === "string";
3465
+ }
3466
+ function requireConversionStatus(value, path) {
3467
+ if (!isConversionStatus(value)) {
3468
+ throw schemaMismatch(`${path} is not a conversion status`);
3469
+ }
3470
+ }
3471
+ function requireString(value, path) {
3472
+ if (typeof value !== "string") {
3473
+ throw schemaMismatch(`${path} must be a string`);
3474
+ }
3475
+ }
3476
+ function requireInteger(value, path) {
3477
+ if (!Number.isSafeInteger(value)) {
3478
+ throw schemaMismatch(`${path} must be an integer`);
3479
+ }
3480
+ }
3481
+ function requireFiniteNumber(value, path) {
3482
+ if (typeof value !== "number" || !Number.isFinite(value)) {
3483
+ throw schemaMismatch(`${path} must be a finite number`);
3484
+ }
3485
+ }
3486
+ function validateOptionalNullableString(value, path) {
3487
+ if (value !== void 0 && value !== null && typeof value !== "string") {
3488
+ throw schemaMismatch(`${path} must be a string or null`);
3489
+ }
3490
+ }
3491
+ function validateOptionalNullableInteger(value, path) {
3492
+ if (value !== void 0 && value !== null && !Number.isSafeInteger(value)) {
3493
+ throw schemaMismatch(`${path} must be an integer or null`);
3494
+ }
3495
+ }
3496
+ function validateOptionalNullableStringArray(value, path) {
3497
+ if (value !== void 0 && value !== null && (!Array.isArray(value) || value.some((item) => typeof item !== "string"))) {
3498
+ throw schemaMismatch(`${path} must contain strings or be null`);
3499
+ }
3500
+ }
3501
+ function validateOptionalRecordOrNull(value, path) {
3502
+ if (value !== void 0 && value !== null && !isRecord4(value)) {
3503
+ throw schemaMismatch(`${path} must be an object or null`);
3504
+ }
3505
+ }
3506
+ function parseConfidence(value, path) {
3507
+ if (value === void 0 || value === null) {
3508
+ return value;
3509
+ }
3510
+ if (!isRecord4(value)) {
3511
+ throw schemaMismatch(`${path} must be an object or null`);
3512
+ }
3513
+ for (const field of [
3514
+ "parse_score",
3515
+ "layout_score",
3516
+ "table_score",
3517
+ "ocr_score",
3518
+ "mean_score",
3519
+ "low_score"
3520
+ ]) {
3521
+ const score = value[field];
3522
+ if (score !== void 0 && score !== null && (typeof score !== "number" || !Number.isFinite(score))) {
3523
+ throw schemaMismatch(`${path}.${field} must be a number or null`);
3524
+ }
3525
+ }
3526
+ for (const field of ["mean_grade", "low_grade"]) {
3527
+ const grade = value[field];
3528
+ if (grade !== void 0 && !["poor", "fair", "good", "excellent", "unspecified"].includes(String(grade))) {
3529
+ throw schemaMismatch(`${path}.${field} is unsupported`);
3530
+ }
3531
+ }
3532
+ return value;
3533
+ }
3534
+ function schemaMismatch(message) {
3535
+ return new DoclingResponseSchemaMismatchError(message, { status: 200 });
3536
+ }
3537
+ function conversionFromResponse(response, input) {
3538
+ return {
3539
+ input: {
3540
+ ...input,
3541
+ filename: response.document.filename || input.filename
3542
+ },
3543
+ document: response.document.json_content ?? emptyDocument2(response.document.filename || input.filename),
3544
+ status: response.status,
3545
+ errors: response.errors,
3546
+ processing_time: response.processing_time,
3547
+ timings: response.timings,
3548
+ ...response.confidence === void 0 ? {} : { confidence: response.confidence }
3549
+ };
3550
+ }
3551
+ function syntheticConversion(input, status, message, category = "unknown") {
3552
+ const error = {
3553
+ component_type: "user_input",
3554
+ module_name: "@docling/docling-client",
3555
+ error_message: message,
3556
+ category
3557
+ };
3558
+ return {
3559
+ input,
3560
+ document: emptyDocument2(input.filename),
3561
+ status,
3562
+ errors: [error],
3563
+ processing_time: 0,
3564
+ timings: {}
3565
+ };
3566
+ }
3567
+ function emptyDocument2(filename) {
3568
+ const leaf = filename.replaceAll("\\", "/").split("/").at(-1) ?? filename;
3569
+ const extension = leaf.lastIndexOf(".");
3570
+ const name = extension > 0 ? leaf.slice(0, extension) : leaf;
3571
+ return {
3572
+ schema_name: "DoclingDocument",
3573
+ name: name || "document"
3574
+ };
3575
+ }
3576
+ function conversionFailureMessage(result) {
3577
+ const errors = result.errors.map((error) => error.error_message).join("; ");
3578
+ return `Conversion failed for ${result.input.filename} with status ${result.status}${errors === "" ? "" : `. Errors: ${errors}`}`;
3579
+ }
3580
+ function mapResultNotFound(taskId, error, lastStatus) {
3581
+ const detail = httpDetail2(error.body);
3582
+ if (detail === "Task not found.") {
3583
+ return new DoclingTaskNotFoundError(taskId);
3584
+ }
3585
+ if (detail?.startsWith("Task result not found") === true) {
3586
+ if (lastStatus?.task_status === "failure") {
3587
+ return new DoclingTaskError(lastStatus);
3588
+ }
3589
+ if (lastStatus?.task_status === "success") {
3590
+ return new DoclingResultExpiredError(taskId);
3591
+ }
3592
+ return new DoclingResultNotReadyError(taskId);
3593
+ }
3594
+ return new DoclingServiceError("Unexpected result lookup error", {
3595
+ status: 404,
3596
+ detail,
3597
+ cause: error
3598
+ });
3599
+ }
3600
+ function shouldFallbackFromPresigned(error) {
3601
+ if (!(error instanceof DoclingHttpError) || ![400, 422].includes(error.status)) {
3602
+ return false;
3603
+ }
3604
+ const detail = httpDetail2(error.body)?.toLowerCase();
3605
+ if (detail === void 0) {
3606
+ return false;
3607
+ }
3608
+ if (detail.includes("artifact storage to be configured")) {
3609
+ return true;
3610
+ }
3611
+ if (!detail.includes("presigned_url") && !detail.includes("presigned url")) {
3612
+ return false;
3613
+ }
3614
+ return [
3615
+ "input should be",
3616
+ "unexpected value",
3617
+ "validation error",
3618
+ "literal_error",
3619
+ "enum"
3620
+ ].some((phrase) => detail.includes(phrase));
3621
+ }
3622
+ function targetNeedsJson(target) {
3623
+ return target.kind === "inbody";
3624
+ }
3625
+ function isPresignedTarget(target) {
3626
+ return target.kind === "presigned_url";
3627
+ }
3628
+ function validateBatchRequest(request) {
3629
+ if (!Array.isArray(request.sources) || request.sources.length === 0) {
3630
+ throw new DoclingProtocolError("Batch conversion requires at least one source");
3631
+ }
3632
+ for (const source of request.sources) {
3633
+ if (source.kind === "file") {
3634
+ throw new DoclingProtocolError("Batch conversion does not accept file sources");
3635
+ }
3636
+ if (typeof source.kind !== "string" || source.kind === "") {
3637
+ throw new DoclingProtocolError("Batch source kind must not be empty");
3638
+ }
3639
+ validateKnownConnector(source, "source");
3640
+ }
3641
+ if (!isRecord4(request.target) || typeof request.target.kind !== "string" || request.target.kind === "") {
3642
+ throw new DoclingProtocolError("Batch target kind must not be empty");
3643
+ }
3644
+ if (["inbody", "zip", "put"].includes(request.target.kind)) {
3645
+ throw new DoclingProtocolError(
3646
+ `Batch conversion does not accept ${request.target.kind} targets`
3647
+ );
3648
+ }
3649
+ validateKnownConnector(request.target, "target");
3650
+ validateCallbacks(request.callbacks);
3651
+ }
3652
+ function validateChunkRequestOptions(request) {
3653
+ if (request.include_converted_doc !== void 0 && typeof request.include_converted_doc !== "boolean") {
3654
+ throw new DoclingProtocolError("include_converted_doc must be a boolean");
3655
+ }
3656
+ if (request.target !== void 0 && (!isRecord4(request.target) || request.target.kind !== "inbody")) {
3657
+ throw new DoclingProtocolError("Chunk conversion only supports inbody targets");
3658
+ }
3659
+ const options = request.chunking_options;
3660
+ if (options === void 0) {
3661
+ return;
3662
+ }
3663
+ if (!isRecord4(options)) {
3664
+ throw new DoclingProtocolError("chunking_options must be an object");
3665
+ }
3666
+ for (const key of [
3667
+ "use_markdown_tables",
3668
+ "use_markdown_images",
3669
+ "include_raw_text",
3670
+ "merge_peers"
3671
+ ]) {
3672
+ const value = options[key];
3673
+ if (value !== void 0 && typeof value !== "boolean") {
3674
+ throw new DoclingProtocolError(`chunking_options.${key} must be a boolean`);
3675
+ }
3676
+ }
3677
+ if (options.image_placeholder !== void 0 && typeof options.image_placeholder !== "string") {
3678
+ throw new DoclingProtocolError(
3679
+ "chunking_options.image_placeholder must be a string"
3680
+ );
3681
+ }
3682
+ if (options.max_tokens !== void 0 && options.max_tokens !== null && !Number.isInteger(options.max_tokens)) {
3683
+ throw new DoclingProtocolError(
3684
+ "chunking_options.max_tokens must be an integer or null"
3685
+ );
3686
+ }
3687
+ if (options.tokenizer !== void 0 && typeof options.tokenizer !== "string") {
3688
+ throw new DoclingProtocolError("chunking_options.tokenizer must be a string");
3689
+ }
3690
+ }
3691
+ function validateConversionSource(source) {
3692
+ if (source === void 0) {
3693
+ throw new DoclingProtocolError("A conversion source is required");
3694
+ }
3695
+ if (source.kind === "http") {
3696
+ if (typeof source.url !== "string" || source.url === "") {
3697
+ throw new DoclingProtocolError("HTTP source url is required");
3698
+ }
3699
+ const url = parseHttpUrl(source.url, "HTTP source");
3700
+ if (!["http:", "https:"].includes(url.protocol)) {
3701
+ throw new DoclingProtocolError("HTTP source must use HTTP or HTTPS");
3702
+ }
3703
+ if (url.pathname.toLowerCase().endsWith(".zip")) {
3704
+ throw new DoclingProtocolError(
3705
+ "ZIP URLs are not accepted on the Docling convert endpoint"
3706
+ );
3707
+ }
3708
+ if (source.headers !== void 0 && !isRecord4(source.headers)) {
3709
+ throw new DoclingProtocolError("HTTP source headers must be an object");
3710
+ }
3711
+ return;
3712
+ }
3713
+ if (typeof source.filename !== "string" || source.filename === "" || typeof source.base64_string !== "string" || source.base64_string === "") {
3714
+ throw new DoclingProtocolError(
3715
+ "File source filename and base64_string are required"
3716
+ );
3717
+ }
3718
+ }
3719
+ function validateSubmitTarget(target) {
3720
+ if (target.kind === "put") {
3721
+ parseHttpUrl(target.url, "Put target");
3722
+ return;
3723
+ }
3724
+ if (![
3725
+ "inbody",
3726
+ "zip",
3727
+ "presigned_url",
3728
+ "s3",
3729
+ "azure_blob",
3730
+ "google_cloud_storage",
3731
+ "google_drive"
3732
+ ].includes(target.kind)) {
3733
+ throw new DoclingProtocolError(
3734
+ `Unsupported Docling conversion target: ${String(target.kind)}`
3735
+ );
3736
+ }
3737
+ validateKnownConnector(target, "target");
3738
+ }
3739
+ function validateKnownConnector(value, role) {
3740
+ const fields = value;
3741
+ if (value.kind === "http") {
3742
+ requireStringFields(fields, ["url"], role, false);
3743
+ parseHttpUrl(fields.url, `HTTP ${role}`);
3744
+ return;
3745
+ }
3746
+ if (value.kind === "s3") {
3747
+ requireStringFields(
3748
+ fields,
3749
+ ["endpoint", "access_key", "secret_key", "bucket", "key_prefix"],
3750
+ role,
3751
+ true
3752
+ );
3753
+ validateOptionalBoolean(fields.verify_ssl, `${role} verify_ssl`);
3754
+ validatePositiveMaxElements(fields.max_num_elements, role);
3755
+ return;
3756
+ }
3757
+ if (value.kind === "azure_blob") {
3758
+ requireStringFields(
3759
+ fields,
3760
+ ["account_name", "container", "connection_string", "blob_prefix"],
3761
+ role,
3762
+ true
3763
+ );
3764
+ validateOptionalInteger(fields.max_num_elements, `${role} max_num_elements`);
3765
+ return;
3766
+ }
3767
+ if (value.kind === "google_cloud_storage") {
3768
+ requireStringFields(fields, ["bucket", "key_prefix"], role, true);
3769
+ validatePositiveMaxElements(fields.max_num_elements, role);
3770
+ validateOptionalString2(fields.project, `${role} project`);
3771
+ if (fields.service_account_key !== void 0 && fields.service_account_key !== null) {
3772
+ if (!isRecord4(fields.service_account_key)) {
3773
+ throw new DoclingProtocolError(
3774
+ `Google Cloud Storage ${role} service_account_key must be an object`
3775
+ );
3776
+ }
3777
+ requireStringFields(
3778
+ fields.service_account_key,
3779
+ [
3780
+ "project_id",
3781
+ "private_key_id",
3782
+ "private_key",
3783
+ "client_email",
3784
+ "client_id",
3785
+ "auth_uri",
3786
+ "token_uri",
3787
+ "auth_provider_x509_cert_url",
3788
+ "client_x509_cert_url",
3789
+ "universe_domain"
3790
+ ],
3791
+ `${role} service_account_key`,
3792
+ true
3793
+ );
3794
+ }
3795
+ return;
3796
+ }
3797
+ if (value.kind === "google_drive") {
3798
+ requireStringFields(fields, ["path_id"], role);
3799
+ if (!hasNonEmptyString(fields.token_path) && !hasNonEmptyString(fields.refresh_token)) {
3800
+ throw new DoclingProtocolError(
3801
+ `Google Drive ${role} requires token_path or refresh_token`
3802
+ );
3803
+ }
3804
+ if (!hasNonEmptyString(fields.credentials_path) && !isRecord4(fields.credentials)) {
3805
+ throw new DoclingProtocolError(
3806
+ `Google Drive ${role} requires credentials_path or credentials`
3807
+ );
3808
+ }
3809
+ validateOptionalString2(fields.token_path, `${role} token_path`);
3810
+ validateOptionalString2(fields.refresh_token, `${role} refresh_token`);
3811
+ validateOptionalString2(fields.credentials_path, `${role} credentials_path`);
3812
+ if (isRecord4(fields.credentials)) {
3813
+ requireStringFields(
3814
+ fields.credentials,
3815
+ [
3816
+ "client_id",
3817
+ "project_id",
3818
+ "auth_uri",
3819
+ "token_uri",
3820
+ "auth_provider_x509_cert_url",
3821
+ "client_secret"
3822
+ ],
3823
+ `${role} credentials`,
3824
+ true
3825
+ );
3826
+ for (const key of ["auth_uri", "token_uri", "auth_provider_x509_cert_url"]) {
3827
+ parseHttpUrl(
3828
+ fields.credentials[key],
3829
+ `Google Drive ${role} credentials.${key}`
3830
+ );
3831
+ }
3832
+ const redirectUris = fields.credentials.redirect_uris;
3833
+ if (!Array.isArray(redirectUris) || redirectUris.some((uri) => typeof uri !== "string")) {
3834
+ throw new DoclingProtocolError(
3835
+ `Google Drive ${role} credentials redirect_uris must be an array of URLs`
3836
+ );
3837
+ }
3838
+ for (const uri of redirectUris) {
3839
+ parseHttpUrl(uri, `Google Drive ${role} redirect URI`);
3840
+ }
3841
+ }
3842
+ }
3843
+ }
3844
+ function requireStringFields(value, fields, role, allowMissingDefault = false) {
3845
+ for (const field of fields) {
3846
+ if (allowMissingDefault && ["key_prefix", "blob_prefix"].includes(field) && value[field] === void 0) {
3847
+ continue;
3848
+ }
3849
+ if (typeof value[field] !== "string") {
3850
+ throw new DoclingProtocolError(
3851
+ `${value.kind} ${role} requires ${field}`
3852
+ );
3853
+ }
3854
+ }
3855
+ }
3856
+ function validatePositiveMaxElements(value, role) {
3857
+ if (value !== void 0 && value !== null && (!Number.isSafeInteger(value) || value < 1)) {
3858
+ throw new DoclingProtocolError(
3859
+ `${role} max_num_elements must be a positive integer`
3860
+ );
3861
+ }
3862
+ }
3863
+ function validateOptionalInteger(value, name) {
3864
+ if (value !== void 0 && value !== null && !Number.isSafeInteger(value)) {
3865
+ throw new DoclingProtocolError(`${name} must be an integer or null`);
3866
+ }
3867
+ }
3868
+ function validateOptionalBoolean(value, name) {
3869
+ if (value !== void 0 && typeof value !== "boolean") {
3870
+ throw new DoclingProtocolError(`${name} must be a boolean`);
3871
+ }
3872
+ }
3873
+ function validateOptionalString2(value, name) {
3874
+ if (value !== void 0 && value !== null && typeof value !== "string") {
3875
+ throw new DoclingProtocolError(`${name} must be a string or null`);
3876
+ }
3877
+ }
3878
+ function validateCallbacks(callbacks) {
3879
+ if (callbacks !== void 0 && !Array.isArray(callbacks)) {
3880
+ throw new DoclingProtocolError("callbacks must be an array");
3881
+ }
3882
+ for (const callback of callbacks ?? []) {
3883
+ if (!isRecord4(callback) || typeof callback.url !== "string") {
3884
+ throw new DoclingProtocolError("Callback url is required");
3885
+ }
3886
+ parseAbsoluteUrl(callback.url, "Callback url");
3887
+ if (callback.headers !== void 0 && (!isRecord4(callback.headers) || Object.values(callback.headers).some((value) => typeof value !== "string"))) {
3888
+ throw new DoclingProtocolError("Callback headers must contain string values");
3889
+ }
3890
+ if (callback.ca_cert !== void 0 && typeof callback.ca_cert !== "string") {
3891
+ throw new DoclingProtocolError("Callback ca_cert must be a string");
3892
+ }
3893
+ }
3894
+ }
3895
+ function parseHttpUrl(value, name) {
3896
+ const url = parseAbsoluteUrl(value, name);
3897
+ if (!["http:", "https:"].includes(url.protocol)) {
3898
+ throw new DoclingProtocolError(`${name} must use HTTP or HTTPS`);
3899
+ }
3900
+ return url;
3901
+ }
3902
+ function parseAbsoluteUrl(value, name) {
3903
+ if (typeof value !== "string" || value === "") {
3904
+ throw new DoclingProtocolError(`${name} must be a URL`);
3905
+ }
3906
+ try {
3907
+ return new URL(value);
3908
+ } catch (error) {
3909
+ throw new DoclingProtocolError(`${name} must be a valid URL`, {
3910
+ cause: error
3911
+ });
3912
+ }
3913
+ }
3914
+ async function fileSourceFromBlob(source, signal) {
3915
+ throwIfAborted2(signal);
3916
+ const bytes = new Uint8Array(await source.blob.arrayBuffer());
3917
+ throwIfAborted2(signal);
3918
+ let binary = "";
3919
+ const chunkSize = 32768;
3920
+ for (let offset = 0; offset < bytes.length; offset += chunkSize) {
3921
+ binary += String.fromCharCode(...bytes.subarray(offset, offset + chunkSize));
3922
+ }
3923
+ const base64 = typeof globalThis.btoa === "function" ? globalThis.btoa(binary) : Buffer.from(bytes).toString("base64");
3924
+ return {
3925
+ kind: "file",
3926
+ filename: source.descriptor.filename,
3927
+ base64_string: base64
3928
+ };
3929
+ }
3930
+ function throwIfAborted2(signal) {
3931
+ if (signal?.aborted === true) {
3932
+ throw signal.reason instanceof Error ? signal.reason : new DOMException("The operation was aborted", "AbortError");
3933
+ }
3934
+ }
3935
+ function hasNonEmptyString(value) {
3936
+ return typeof value === "string" && value !== "";
3937
+ }
3938
+ function filenameFromContentDisposition(value) {
3939
+ if (value === void 0) {
3940
+ return null;
3941
+ }
3942
+ const encoded = /filename\*=UTF-8''([^;]+)/i.exec(value)?.[1];
3943
+ if (encoded !== void 0) {
3944
+ try {
3945
+ return decodeURIComponent(encoded.replace(/^"|"$/g, ""));
3946
+ } catch {
3947
+ return encoded;
3948
+ }
3949
+ }
3950
+ return /filename="?([^";]+)"?/i.exec(value)?.[1] ?? null;
3951
+ }
3952
+ function httpDetail2(value) {
3953
+ return isRecord4(value) && typeof value.detail === "string" ? value.detail : void 0;
3954
+ }
3955
+ function normalizeBaseUrl(value) {
3956
+ const normalized = value.trim().replace(/\/+$/, "");
3957
+ if (normalized === "") {
3958
+ throw new DoclingProtocolError("Docling baseUrl must not be empty");
3959
+ }
3960
+ let url;
3961
+ try {
3962
+ url = new URL(normalized);
3963
+ } catch (error) {
3964
+ throw new DoclingProtocolError("Docling baseUrl must be a valid URL", {
3965
+ cause: error
3966
+ });
3967
+ }
3968
+ if (!["http:", "https:"].includes(url.protocol)) {
3969
+ throw new DoclingProtocolError("Docling baseUrl must use HTTP or HTTPS");
3970
+ }
3971
+ if (url.search !== "" || url.hash !== "") {
3972
+ throw new DoclingProtocolError(
3973
+ "Docling baseUrl must not include query or fragment components"
3974
+ );
3975
+ }
3976
+ const path = url.pathname.replace(/\/+$/, "");
3977
+ if (path.endsWith("/v1")) {
3978
+ throw new DoclingProtocolError(
3979
+ "Docling baseUrl must be the service base URL and not include /v1"
3980
+ );
3981
+ }
3982
+ url.pathname = path;
3983
+ return url.toString().replace(/\/+$/, "");
3984
+ }
3985
+ function normalizeHeaders(headers) {
3986
+ return Object.fromEntries(
3987
+ Object.entries(headers ?? {}).map(([name, value]) => [name.toLowerCase(), value])
3988
+ );
3989
+ }
3990
+ function positiveNumber(value, name) {
3991
+ if (!Number.isFinite(value) || value <= 0) {
3992
+ throw new DoclingProtocolError(`${name} must be a positive number`);
3993
+ }
3994
+ return value;
3995
+ }
3996
+ function nonNegativeNumber(value, name) {
3997
+ if (!Number.isFinite(value) || value < 0) {
3998
+ throw new DoclingProtocolError(`${name} must be non-negative`);
3999
+ }
4000
+ return value;
4001
+ }
4002
+ function requireTaskId(taskId) {
4003
+ if (taskId === "") {
4004
+ throw new DoclingProtocolError("taskId must not be empty");
4005
+ }
4006
+ }
4007
+ function isChunkSourcesRequest(value) {
4008
+ return isRecord4(value) && Array.isArray(value.sources) && ["hybrid", "hierarchical"].includes(String(value.chunker));
4009
+ }
4010
+ function fallbackInput(source) {
4011
+ if (typeof source === "string") {
4012
+ return {
4013
+ filename: source.replaceAll("\\", "/").split("/").at(-1) || "document",
4014
+ source
4015
+ };
4016
+ }
4017
+ if (source instanceof URL) {
4018
+ return {
4019
+ filename: source.pathname.split("/").filter(Boolean).at(-1) ?? "document",
4020
+ source: source.toString()
4021
+ };
4022
+ }
4023
+ if (isRecord4(source)) {
4024
+ let urlFilename;
4025
+ if (typeof source.url === "string") {
4026
+ try {
4027
+ urlFilename = new URL(source.url).pathname.split("/").filter(Boolean).at(-1) ?? "document";
4028
+ } catch {
4029
+ urlFilename = source.url.replaceAll("\\", "/").split("/").at(-1);
4030
+ }
4031
+ }
4032
+ const filename = typeof source.filename === "string" ? source.filename : typeof source.url === "string" ? urlFilename || "document" : "document";
4033
+ return { filename, source: filename };
4034
+ }
4035
+ return { filename: "document", source: "document" };
4036
+ }
4037
+ function isAbortError2(value) {
4038
+ return value instanceof Error && value.name === "AbortError";
4039
+ }
4040
+ async function* mapSourcesToItems(sources, options, headers) {
4041
+ if (Symbol.asyncIterator in Object(sources)) {
4042
+ for await (const source of sources) {
4043
+ yield { source, options, headers };
4044
+ }
4045
+ return;
4046
+ }
4047
+ for (const source of sources) {
4048
+ yield { source, options, headers };
4049
+ }
4050
+ }
4051
+ function isRecord4(value) {
4052
+ return value !== null && typeof value === "object" && !Array.isArray(value);
4053
+ }
4054
+ export {
4055
+ ArtifactDownloader,
4056
+ DEFAULT_MAX_CONCURRENCY,
4057
+ DoclingArtifactDownloadError,
4058
+ DoclingBatchConversionError,
4059
+ DoclingClient,
4060
+ DoclingConversionError,
4061
+ DoclingError,
4062
+ DoclingHttpError,
4063
+ DoclingJob,
4064
+ DoclingProtocolError,
4065
+ DoclingResponseSchemaMismatchError,
4066
+ DoclingResultExpiredError,
4067
+ DoclingResultNotReadyError,
4068
+ DoclingServiceError,
4069
+ DoclingServiceUnavailableError,
4070
+ DoclingTaskError,
4071
+ DoclingTaskNotFoundError,
4072
+ DoclingTimeoutError,
4073
+ DoclingUsageLimitExceededError,
4074
+ FetchTransport,
4075
+ MAX_CONCURRENCY_LIMIT,
4076
+ applyPageLimits,
4077
+ documentFromBundle,
4078
+ documentFromJson,
4079
+ fileSourceFromBinary,
4080
+ formValue,
4081
+ materializePresignedResult,
4082
+ normalizeSourceInput,
4083
+ preflightFileSize,
4084
+ resolveConvertOptions,
4085
+ selectDocumentArtifact,
4086
+ validateConvertOptions,
4087
+ validateMaxFileSize,
4088
+ watchTask,
4089
+ withJsonOutput
4090
+ };
4091
+ //# sourceMappingURL=index.js.map