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