@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/README.md ADDED
@@ -0,0 +1,367 @@
1
+ # Docling Client
2
+
3
+ `@docling/docling-client` is the official TypeScript client for
4
+ [Docling Serve](https://github.com/docling-project/docling-serve) and managed
5
+ Docling services implementing the same API, including IBM-hosted Docling.
6
+
7
+ It is a remote client. Document conversion, OCR, table extraction, enrichment,
8
+ and chunking run in the service; the package submits work, follows task state,
9
+ retrieves results, and safely materializes artifacts.
10
+
11
+ ## Install
12
+
13
+ ```sh
14
+ npm install @docling/docling-client
15
+ ```
16
+
17
+ Node.js 18 or newer is required. URL and base64 requests work in Node and
18
+ browsers. Node additionally supports local paths. Browser applications using
19
+ the default presigned-artifact path must provide a trusted DNS resolver through
20
+ `artifactDownload.resolver`, or explicitly opt into their own URL policy with
21
+ `allowPrivateUrls`; browsers do not expose DNS answers needed by the default
22
+ SSRF check.
23
+
24
+ ## Configure
25
+
26
+ ```ts
27
+ import { DoclingClient } from '@docling/docling-client';
28
+
29
+ const client = new DoclingClient({
30
+ baseUrl: process.env.DOCLING_URL!,
31
+ apiKey: process.env.DOCLING_API_KEY,
32
+ options: {
33
+ do_ocr: true,
34
+ table_mode: 'accurate',
35
+ },
36
+ statusWatcher: 'websocket',
37
+ webSocketFallbackToPoll: true,
38
+ jobTimeoutMs: 15 * 60_000,
39
+ maxConcurrency: 8,
40
+ httpRetries: 3,
41
+ httpTimeoutMs: 60_000,
42
+ });
43
+ ```
44
+
45
+ The base URL is the service root, without `/v1`, a query, or a fragment.
46
+ `X-Api-Key` is sent when `apiKey` is set. Per-call service headers override
47
+ constructor headers.
48
+
49
+ ## Convert
50
+
51
+ `convert()` is the high-level, Python-compatible path. It tries a presigned
52
+ artifact target first, narrowly falls back to an in-body result when artifact
53
+ storage is unavailable, requests Markdown plus Docling JSON by default, and
54
+ returns a `ConversionResult`.
55
+
56
+ ```ts
57
+ const result = await client.convert('https://example.org/manual.pdf', {
58
+ options: {
59
+ do_ocr: true,
60
+ table_mode: 'accurate',
61
+ include_images: true,
62
+ },
63
+ maxNumPages: 100,
64
+ maxFileSize: 100 * 1024 * 1024,
65
+ pageRange: [1, 20],
66
+ raisesOnError: true,
67
+ });
68
+
69
+ console.log(result.status);
70
+ console.log(result.document);
71
+ console.log(result.errors);
72
+ ```
73
+
74
+ Sources accepted by high-level calls are:
75
+
76
+ - HTTP(S) URL strings, `URL`, or `{kind: "http"}` sources, including
77
+ source-fetch headers;
78
+ - Node filesystem paths;
79
+ - `{data, filename, contentType}` using `Blob`, `ArrayBuffer`, or typed arrays;
80
+ - base64 `{kind: "file", filename, base64_string}` sources.
81
+
82
+ ZIP URLs are rejected on ordinary conversion routes. Local and binary inputs
83
+ use multipart upload for in-body, ZIP, and presigned targets. External targets
84
+ use the unified base64 request so their complete credentials and coordinates
85
+ are preserved.
86
+
87
+ `convertAll()` lazily runs one complete task per source with bounded
88
+ concurrency, preserves input order, and turns individual failures into failed
89
+ `ConversionResult` values without stopping unrelated work:
90
+
91
+ ```ts
92
+ for await (const result of client.convertAll(urls, {
93
+ maxConcurrency: 16,
94
+ })) {
95
+ console.log(result.input.filename, result.status);
96
+ }
97
+ ```
98
+
99
+ ## Submit jobs and choose a target
100
+
101
+ `submitSource()` mirrors Python's job-oriented `submit()`. Convenience methods
102
+ are available for URL, base64, and binary inputs.
103
+
104
+ ```ts
105
+ const job = await client.submitUrl(
106
+ 'https://example.org/manual.pdf',
107
+ { to_formats: ['md', 'json'] },
108
+ { target: { kind: 'inbody' } }
109
+ );
110
+
111
+ for await (const status of job.watch()) {
112
+ console.log(status.task_status, status.task_position);
113
+ }
114
+
115
+ const result = await job.result();
116
+ console.log(result.document);
117
+ ```
118
+
119
+ Target-specific results are statically typed:
120
+
121
+ | Target | Result |
122
+ | -------------------------------------------------------------------- | --------------------------------------------------------------------------- |
123
+ | omitted | presigned response, or `ConversionResult` after the narrow in-body fallback |
124
+ | `{kind: "inbody"}` | `ConversionResult` |
125
+ | `{kind: "zip"}` | `RawServiceResult` with lossless `Uint8Array` content |
126
+ | `{kind: "presigned_url"}` | per-document artifacts and outcome counts |
127
+ | S3, Azure Blob, Google Cloud Storage, Google Drive, or low-level Put | outcome counts |
128
+
129
+ S3, Azure, GCS, Drive, generic connector, callback, and Put payloads can carry
130
+ credentials. Treat request bodies and logs accordingly.
131
+
132
+ ## Batch connectors
133
+
134
+ The batch route enumerates documents from remote connectors and writes to a
135
+ presigned or storage target:
136
+
137
+ ```ts
138
+ const job = await client.submitBatch(
139
+ {
140
+ sources: [
141
+ {
142
+ kind: 's3',
143
+ endpoint: 's3.us-east-1.amazonaws.com',
144
+ access_key: process.env.S3_ACCESS_KEY!,
145
+ secret_key: process.env.S3_SECRET_KEY!,
146
+ bucket: 'incoming-documents',
147
+ key_prefix: 'manuals/',
148
+ },
149
+ ],
150
+ target: { kind: 'presigned_url' },
151
+ callbacks: [
152
+ {
153
+ url: 'https://workflow.example.com/docling-progress',
154
+ headers: { authorization: `Bearer ${process.env.CALLBACK_TOKEN}` },
155
+ },
156
+ ],
157
+ },
158
+ { outputFormats: ['json', 'md'] }
159
+ );
160
+
161
+ const result = await job.result();
162
+ ```
163
+
164
+ Batch sources support HTTP, S3, Azure Blob, GCS, Google Drive, and
165
+ forward-compatible generic connectors. Batch targets support presigned
166
+ artifacts, those storage systems, and generic connectors. File, in-body, ZIP,
167
+ and Put targets are rejected on the batch route, matching the Python client.
168
+
169
+ ## Convert and chunk
170
+
171
+ Chunk endpoints convert and chunk in one service task:
172
+
173
+ ```ts
174
+ const result = await client.chunk('https://example.org/manual.pdf', {
175
+ chunker: 'hybrid',
176
+ convert_options: {
177
+ do_ocr: true,
178
+ table_mode: 'accurate',
179
+ },
180
+ chunking_options: {
181
+ max_tokens: 384,
182
+ tokenizer: 'sentence-transformers/all-MiniLM-L6-v2',
183
+ merge_peers: true,
184
+ include_raw_text: true,
185
+ use_markdown_tables: true,
186
+ use_markdown_images: true,
187
+ },
188
+ include_converted_doc: true,
189
+ });
190
+
191
+ console.log(result.chunks[0]?.text);
192
+ console.log(result.documents[0]?.content.json_content);
193
+ ```
194
+
195
+ The Python-shaped overload is also supported:
196
+
197
+ ```ts
198
+ const result = await client.chunk(
199
+ 'https://example.org/manual.pdf',
200
+ 'hierarchical',
201
+ { do_ocr: true },
202
+ { includeConvertedDoc: true }
203
+ );
204
+ ```
205
+
206
+ Use `submitChunk()`, `submitChunkUrl()`, `submitChunkFile()`, or
207
+ `submitChunkBinary()` when a job handle is needed. JSON chunk requests support
208
+ multiple sources, callbacks, all chunker options, and
209
+ `include_converted_doc`. Multipart chunk routes accept one file and do not
210
+ support callbacks.
211
+
212
+ Although `chunks` is a member of Docling's general `OutputFormat` enum, Serve
213
+ chunking is selected through
214
+ `/v1/chunk/{hybrid|hierarchical}/{source|file}/async`, not by setting
215
+ `to_formats: ["chunks"]` on a normal conversion.
216
+
217
+ ## Fan-out
218
+
219
+ `submitAndRetrieveEach()` accepts `Iterable` and `AsyncIterable` inputs, keeps
220
+ at most `maxInFlight` full task lifecycles active, and yields completion order
221
+ by default:
222
+
223
+ ```ts
224
+ for await (const [item, outcome] of client.submitAndRetrieveEach(items, {
225
+ maxInFlight: 8,
226
+ ordered: false,
227
+ })) {
228
+ if (outcome instanceof Error) {
229
+ console.error(item.metadata, outcome);
230
+ } else {
231
+ console.log(item.metadata, outcome);
232
+ }
233
+ }
234
+ ```
235
+
236
+ Omitting `target` retains the correctly typed presigned-or-in-body result.
237
+ When more than 64 jobs are in flight, the client uses polling for those waits
238
+ instead of opening more WebSockets. `submitAndRetrieveMany()` remains as a
239
+ deprecated alias.
240
+
241
+ ## Task lifecycle
242
+
243
+ `DoclingJob` exposes:
244
+
245
+ - `taskId`, `submittedAt`, `queuePosition`, `done`, and the full cached
246
+ `TaskStatusResponse` through `status`;
247
+ - `poll()`, `watch()`, `wait()`, `getResult()`, and `result()`.
248
+
249
+ `client.job(taskId, status?, loader?)` attaches to existing work. WebSocket
250
+ watching is the default, authenticates with the query parameter and, in Node,
251
+ also `X-Api-Key`, implements Serve's `next` handshake, reconnects transport
252
+ failures up to three times, and can fall back to long polling. Polling uses
253
+ `GET /v1/status/poll/{task_id}?wait=...`.
254
+
255
+ All waits accept `AbortSignal`. Result lookup distinguishes an unknown task, a
256
+ not-yet-ready result, an expired terminal result, and authoritative task
257
+ failure.
258
+
259
+ ## Retries and errors
260
+
261
+ The default `FetchTransport` matches the Python retry policy:
262
+
263
+ - HTTP 500 and 502 retry for every method with exponential backoff;
264
+ - HTTP 429 and 503 retry only with a valid `Retry-After`;
265
+ - transport failures retry only for GET, HEAD, and OPTIONS;
266
+ - caller cancellation is never retried;
267
+ - health and version calls use zero retries.
268
+
269
+ All service-originated failures derive from `DoclingServiceError`.
270
+ Specialized errors cover HTTP responses, exhausted/unavailable service,
271
+ usage limits, response-schema mismatch, task execution, task timeout, task
272
+ not-found, result-not-ready, result-expired, artifact download, and
273
+ high-level conversion failure.
274
+
275
+ ## Presigned artifact safety
276
+
277
+ High-level conversion can materialize a JSON artifact or a resource bundle.
278
+ The downloader:
279
+
280
+ - never forwards Docling service headers to artifact hosts;
281
+ - allows only HTTP(S), resolves every DNS address, and rejects any non-global
282
+ address unless explicitly configured otherwise;
283
+ - revalidates every redirect, with a five-redirect default;
284
+ - enforces timeout, compressed-download, uncompressed-bundle, and entry-count
285
+ limits;
286
+ - validates ZIP paths, requires exactly one top-level Docling JSON file, and
287
+ validates referenced image MIME signatures before embedding data URIs.
288
+
289
+ Download or reconstruction failure becomes a failed `ConversionResult`, which
290
+ lets `convertAll()` continue. Caller cancellation still propagates.
291
+
292
+ ## Conversion options
293
+
294
+ `ConvertDocumentsOptions` explicitly types the current Python/Serve fields:
295
+ format selection, pipeline, page range, OCR, PDF backend, table extraction,
296
+ image export, code/formula/picture/chart enrichments, VLM presets and custom
297
+ configuration, layout/table/classification presets, deprecated legacy VLM and
298
+ picture-description options, timeout, and abort behavior.
299
+
300
+ Options merge shallowly: constructor defaults are copied, per-call values
301
+ replace top-level fields, `undefined` leaves a default unchanged, and `null`
302
+ clears an optional default. An index signature preserves forward compatibility
303
+ with managed-service options added ahead of this package; the selected
304
+ service's OpenAPI document remains authoritative.
305
+
306
+ ## Docling document types
307
+
308
+ The client deliberately does not pin `@docling/docling-core`. Its default
309
+ `DoclingDocument` is a version-neutral JSON boundary. Applications wanting the
310
+ exact schema from their installed core package can parameterize the client:
311
+
312
+ ```ts
313
+ import type { DoclingDocument } from '@docling/docling-core';
314
+ import { DoclingClient } from '@docling/docling-client';
315
+
316
+ const client = new DoclingClient<DoclingDocument>({ baseUrl, apiKey });
317
+ ```
318
+
319
+ This keeps service-client releases independent from document-schema releases
320
+ while preserving full static typing when desired.
321
+
322
+ ## Custom transports
323
+
324
+ Hosts such as n8n can inject HTTP:
325
+
326
+ ```ts
327
+ import { DoclingClient, type DoclingTransport } from '@docling/docling-client';
328
+
329
+ const transport: DoclingTransport = {
330
+ async request<T>(request) {
331
+ return platformHttpRequest(request) as Promise<T>;
332
+ },
333
+ async close() {
334
+ await platformHttpClose();
335
+ },
336
+ };
337
+
338
+ const client = new DoclingClient({
339
+ baseUrl: 'https://managed-docling.example.com',
340
+ transport,
341
+ });
342
+ ```
343
+
344
+ A custom transport is the complete HTTP policy boundary: it must preserve
345
+ binary responses, exact-200 behavior, retry/error mapping, headers, timeout,
346
+ and cancellation described by `DoclingTransportRequest`. It cannot be combined
347
+ with the built-in fetch/retry options. WebSocket watching and artifact
348
+ downloads remain separately injectable.
349
+
350
+ ## Development
351
+
352
+ ```sh
353
+ npm install
354
+ npm run check
355
+ ```
356
+
357
+ The unit suite requires no live service. To verify endpoint, response-content,
358
+ schema-property, required-field, target/connector, and enum compatibility
359
+ against a running service:
360
+
361
+ ```sh
362
+ DOCLING_API_KEY=... \
363
+ npm run contract:check -- https://managed-docling.example.com/openapi.json
364
+ ```
365
+
366
+ See [Python client parity](./PYTHON_CLIENT_PARITY.md) for the complete
367
+ feature-by-feature comparison.