@docmana/sdk 0.3.5 → 0.8.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.
Files changed (53) hide show
  1. package/CHANGELOG.md +33 -4
  2. package/README.md +175 -232
  3. package/dist/api/execution-result.d.ts +3 -0
  4. package/dist/api/execution-status.d.ts +6 -0
  5. package/dist/api/flow-definition.d.ts +3 -0
  6. package/dist/api/flow-metadata.d.ts +3 -0
  7. package/dist/api/list-flows.d.ts +3 -0
  8. package/dist/api/list-organizations.d.ts +3 -0
  9. package/dist/api/organization-documents.d.ts +7 -0
  10. package/dist/api/run-flow.d.ts +6 -0
  11. package/dist/cli.mjs +1022 -695
  12. package/dist/cli.mjs.map +1 -1
  13. package/dist/client.d.ts +26 -0
  14. package/dist/config.d.ts +21 -0
  15. package/dist/errors.d.ts +55 -0
  16. package/dist/files/resolve-input.d.ts +9 -0
  17. package/dist/http/http-client.d.ts +31 -0
  18. package/dist/index.d.ts +4 -349
  19. package/dist/index.js +323 -339
  20. package/dist/index.js.map +1 -1
  21. package/dist/index.mjs +319 -335
  22. package/dist/index.mjs.map +1 -1
  23. package/dist/models/docmana-api-document-execution-result.model.d.ts +9 -0
  24. package/dist/models/docmana-api-document-request.model.d.ts +15 -0
  25. package/dist/models/docmana-api-execution-result.model.d.ts +24 -0
  26. package/dist/models/docmana-api-node-result.model.d.ts +28 -0
  27. package/dist/models/docmana-classification-result.model.d.ts +3 -0
  28. package/dist/models/docmana-conclusion-result.model.d.ts +3 -0
  29. package/dist/models/docmana-cross-validation-result.model.d.ts +3 -0
  30. package/dist/models/docmana-document-mapping.model.d.ts +4 -0
  31. package/dist/models/docmana-document-result.model.d.ts +11 -0
  32. package/dist/models/docmana-execution-result.model.d.ts +15 -0
  33. package/dist/models/docmana-extraction-result.model.d.ts +3 -0
  34. package/dist/models/docmana-metadata-extraction-result.model.d.ts +3 -0
  35. package/dist/models/docmana-node-result.model.d.ts +7 -0
  36. package/dist/models/docmana-score-node-result.model.d.ts +5 -0
  37. package/dist/models/docmana-validation-result.model.d.ts +3 -0
  38. package/dist/models/document-content.model.d.ts +4 -0
  39. package/dist/models/execution-progress.model.d.ts +4 -0
  40. package/dist/models/execution-status.enum.d.ts +1 -0
  41. package/dist/models/flow-configs.model.d.ts +16 -0
  42. package/dist/models/flow-edge.model.d.ts +4 -0
  43. package/dist/models/flow-node-type.enum.d.ts +1 -0
  44. package/dist/models/flow-node.model.d.ts +33 -0
  45. package/dist/models/flow.model.d.ts +11 -0
  46. package/dist/models/index.d.ts +26 -0
  47. package/dist/models/node-translation-result.model.d.ts +7 -0
  48. package/dist/models/physical-document.model.d.ts +9 -0
  49. package/dist/models/virtual-document.model.d.ts +10 -0
  50. package/dist/polling/poll.d.ts +15 -0
  51. package/dist/types.d.ts +145 -0
  52. package/package.json +17 -14
  53. package/dist/index.d.cts +0 -349
package/CHANGELOG.md CHANGED
@@ -1,11 +1,40 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.8.0
4
+ - Add organization document depot methods and CLI commands:
5
+ `listOrganizationDocuments()`, `downloadOrganizationDocument()`, and
6
+ `downloadOrganizationDocuments()`.
7
+ - Add `docmana organization document list/download`.
8
+ - Make `docmana organization document download --output` optional; default output
9
+ is `./{path}`.
10
+
11
+ ## 0.7.0
12
+ - Add `getFlowMetadata()` / `docmana flow metadata` for projected flow runtime
13
+ metadata from `docmana-consumer-edge-api`.
14
+ - Add `getFlowDefinition()` / `docmana flow definition` for normalized flow
15
+ graph definitions without exposing the Docmana ZIP export.
16
+
17
+ ## 0.6.0
18
+ - Add `listOrganizations()` and `docmana organization list` to list organizations
19
+ available through `docmana-consumer-edge-api`.
20
+
21
+ ## 0.5.0
22
+ - Add `listFlows()` to list flows available through `docmana-consumer-edge-api`,
23
+ returning `{ id, name, state }[]` with `state: "unknown"` when Docmana omits it.
24
+ - Add `docmana flow list` CLI command, with the same API URL and Bearer token resolution as `docmana flow run`.
25
+ - Rename `RunFlowInput` to `RunFlowParams` and move polling controls to
26
+ `RunFlowOptions`.
27
+ - Remove the single-file `file` shortcut from flow params; callers now pass
28
+ `files`.
29
+ - Remove `fileName` from flow params; byte and stream inputs now use
30
+ `{ data, filename, contentType? }`.
31
+ - Replace `runFlowWithCallback` with `runFlowAsync(..., { callbackUrl })`.
32
+
3
33
  ## 0.3.5
4
- - Add `runFlowWithCallback(flowId, input)`: starts a flow and returns `{ executionResultId, fileIds }` **without polling**, registering a `callback_url` so docmana-api POSTs a completion notification when the run finishes. Call `getResult(executionResultId)` on receipt to fetch the mapped result. Works with both `run_flow` and `run_once_flow` (via `input.once`).
5
- - New `RunFlowWithCallbackInput` type carries the required `callbackUrl` (wire: `callback_url`). It is intentionally separate from `RunFlowInput`: the polling `runFlow`/`runFlowAsync` remain callback-free, so a callback run never polls or fetches the result inline.
34
+ - Add callback execution support: starts a flow and returns `{ executionResultId, fileIds }` **without polling**, registering a `callback_url` so docmana-api POSTs a completion notification when the run finishes. Call `getResult(executionResultId)` on receipt to fetch the mapped result.
6
35
 
7
36
  ## 0.3.3
8
- - Add `RunFlowInput.context` (business `json_context`): when provided, `runFlow`/`runFlowAsync` include `json_context` in the request body for both `run_flow` and `run_once_flow`. The context is passed through as-is — filtering against the flow's *Start* node properties is performed server-side by docmana-api.
37
+ - Add `RunFlowParams.context` (business `json_context`): when provided, `runFlow`/`runFlowAsync` include `json_context` in the request body for both `run_flow` and `run_once_flow`. The context is passed through as-is — filtering against the flow's *Start* node properties is performed server-side by docmana-api.
9
38
 
10
39
  ## 0.3.2
11
40
  - Add `scoreDescription` to score-node results (Validation, Classification, CrossValidation, Conclusion).
@@ -29,7 +58,7 @@
29
58
  - 400 responses now throw `DocmanaRequestError` (was `DocmanaAuthError`); add `Incompleted` to `ExecutionStatus`.
30
59
 
31
60
  ## 0.2.0
32
- - `RunFlowInput.once` selects the ad-hoc `run_once_flow` endpoint (current/draft flow) instead of the published `run_flow`.
61
+ - `RunFlowParams.once` selects the ad-hoc `run_once_flow` endpoint (current/draft flow) instead of the published `run_flow`.
33
62
  - `DocmanaConfig.headers` are sent on every API request (e.g. `X-Selected-Organization`), without overriding the bearer token or per-request headers.
34
63
  - `FileInput` now accepts a plain `Uint8Array` (e.g. pdf-lib output) in addition to path, `Buffer`, and `Stream`.
35
64
  - Uploads send a `Content-Type` inferred from the filename extension instead of always `application/octet-stream`.
package/README.md CHANGED
@@ -1,12 +1,9 @@
1
1
  # @docmana/sdk
2
2
 
3
- Official Docmana SDK run document-analysis flows with a single call.
3
+ Official Docmana SDK for calling `docmana-consumer-edge-api`.
4
4
 
5
- Docmana's HTTP API requires four steps to analyze a document: upload the file, start a flow run, poll for status, then fetch the result. This SDK collapses all four into one call. Authentication, token caching, and polling are handled for you.
6
-
7
- ```ts
8
- const result = await docmana.runFlow("<flow-id>", { file: "./contract.pdf" });
9
- ```
5
+ The SDK sends documents to Consumer, starts an async flow, polls Consumer for
6
+ status, and returns the mapped Consumer execution DTO.
10
7
 
11
8
  ## Installation
12
9
 
@@ -22,107 +19,144 @@ Requires Node.js 20+.
22
19
  import { Docmana } from "@docmana/sdk";
23
20
 
24
21
  const docmana = new Docmana({
25
- clientId: process.env.DOCMANA_CLIENT_ID!,
26
- clientSecret: process.env.DOCMANA_CLIENT_SECRET!,
22
+ apiBaseUrl: process.env.DOCMANA_API_URL!,
23
+ accessToken: process.env.DOCMANA_ACCESS_TOKEN!,
27
24
  });
28
25
 
29
- const result = await docmana.runFlow("<flow-id>", { file: "./contract.pdf" });
26
+ const result = await docmana.runFlow("<flow-id>", {
27
+ files: ["./contract.pdf"],
28
+ context: { contract: { destination: "Canada" } },
29
+ useDraftVersion: true,
30
+ });
30
31
 
31
- console.log(result.status, result.results);
32
+ console.log(result.status, result.executionId);
32
33
  ```
33
34
 
34
- The package ships both ESM and CommonJS builds. In a CommonJS project:
35
+ ## Authentication
35
36
 
36
- ```js
37
- const { Docmana } = require("@docmana/sdk");
37
+ The public SDK is Bearer-only. It does not acquire OAuth tokens and it never
38
+ calls `docmana-api` directly. Provide either a static `accessToken` or a
39
+ `getAccessToken` provider:
38
40
 
41
+ ```ts
39
42
  const docmana = new Docmana({
40
- clientId: process.env.DOCMANA_CLIENT_ID,
41
- clientSecret: process.env.DOCMANA_CLIENT_SECRET,
43
+ apiBaseUrl: "https://consumer.example.com/v1",
44
+ getAccessToken: async ({ forceRefresh } = {}) => {
45
+ return forceRefresh ? refreshTokenSomehow() : currentToken();
46
+ },
42
47
  });
43
-
44
- const result = await docmana.runFlow("<flow-id>", { file: "./contract.pdf" });
45
48
  ```
46
49
 
47
- ## Authentication
48
-
49
- The SDK authenticates with OAuth2 `client_credentials` against the Docmana CIAM tenant. Docmana provisions a `client_id` and `client_secret` for you during onboarding pass them to the constructor. The SDK acquires the bearer token on the first request, then caches and refreshes it automatically in memory. You never handle tokens directly.
50
+ If Consumer returns `401` and `getAccessToken` is configured, the SDK calls
51
+ `getAccessToken({ forceRefresh: true })` once and retries the request. With a
52
+ static `accessToken`, `401` is returned as an auth error without retry.
50
53
 
51
54
  ## Configuration
52
55
 
53
- The constructor takes a single `DocmanaConfig` object.
54
-
55
- | Field | Type | Required | Default | Description |
56
- | ---------------- | -------------- | -------- | ----------------------------------------- | ------------------------------------------------------------ |
57
- | `clientId` | `string` | Yes | | OAuth2 client ID provisioned by Docmana at onboarding. |
58
- | `clientSecret` | `string` | Yes | — | OAuth2 client secret provisioned by Docmana at onboarding. |
59
- | `apiBaseUrl` | `string` | No | `https://api.docmana.ai` | Base URL of the Docmana API. |
60
- | `tokenEndpoint` | `string` | No | Docmana CIAM `oauth2/v2.0/token` endpoint | OAuth2 token endpoint used to acquire the bearer token. |
61
- | `scope` | `string` | No | `api://d781e6ba-…/.default` | OAuth2 scope requested for the token. |
62
- | `timeoutMs` | `number` | No | `300000` (5 min) | Maximum time `runFlow` will poll before throwing a timeout. |
63
- | `pollIntervalMs` | `number` | No | `2000` (2 s) | Delay between status polls in `runFlow`. |
64
- | `fetch` | `typeof fetch` | No | global `fetch` | Custom `fetch` implementation (e.g. for proxies or testing). |
65
-
66
- Most integrations only set `clientId` and `clientSecret`. The other fields exist for non-production environments or advanced networking needs.
67
-
68
- ## Inputs
69
-
70
- `runFlow(flowId, input)` (and the lower-level `runFlowAsync`) accept a `RunFlowInput`:
71
-
72
- | Field | Type | Description |
73
- | ---------------- | ------------------------------------------------------------------- | -------------------------------------------------------------------- |
74
- | `file` | `string \| { path: string } \| Buffer \| NodeJS.ReadableStream` | A single document. A string or `{ path }` is treated as a file path. |
75
- | `files` | `(string \| { path: string } \| Buffer \| NodeJS.ReadableStream)[]` | Multiple documents for a multi-document flow. |
76
- | `fileName` | `string` | Required when passing a `Buffer` or stream with no derivable name. |
77
- | `signal` | `AbortSignal` | Cancels the in-flight run. |
78
- | `timeoutMs` | `number` | Overrides the configured polling timeout for this call. |
79
- | `pollIntervalMs` | `number` | Overrides the configured poll interval for this call. |
80
-
81
- Provide either `file` or `files`.
82
-
83
- A file path:
56
+ | Field | Type | Required | Description |
57
+ | ------------------- | --------------------------------------------------------------------- | -------- | ------------------------------------------------------------ |
58
+ | `apiBaseUrl` | `string` | Yes | Base URL of Consumer API, including version when applicable. |
59
+ | `accessToken` | `string` | One of | Static Bearer token sent to Consumer. |
60
+ | `getAccessToken` | `(options?: { forceRefresh?: boolean }) => string \| Promise<string>` | One of | Token provider for renewable Bearer tokens. |
61
+ | `timeoutMs` | `number` | No | Maximum polling time for `runFlow`. Default: 5 minutes. |
62
+ | `pollIntervalMs` | `number` | No | Fallback minimum delay between status polls. Default: 2s. |
63
+ | `pollMaxIntervalMs` | `number` | No | Fallback maximum polling delay. Default: 10s. |
64
+ | `fetch` | `typeof fetch` | No | Custom fetch implementation. |
65
+ | `headers` | `Record<string, string>` | No | Extra headers sent on every Consumer request. |
66
+
67
+ `apiBaseUrl` is required so a migrated SDK cannot accidentally call
68
+ `https://api.docmana.ai`.
69
+
70
+ ## Run flow params
71
+
72
+ `runFlow(flowId, params, options)` and `runFlowAsync(flowId, params, options)`
73
+ use `RunFlowParams` for request data:
74
+
75
+ | Field | Type | Description |
76
+ | ----------------- | -------------------------------------------------------------------- | ---------------------------------------------------------------------- |
77
+ | `files` | `(string \| { path: string } \| { data, filename, contentType? })[]` | Documents to upload. A string or `{ path }` is treated as a file path. |
78
+ | `context` | `Record<string, unknown>` | Business context serialized as multipart `json_context`. |
79
+ | `language` | `string` | Optional result language passed to Consumer. |
80
+ | `useDraftVersion` | `boolean` | Runs the current draft flow version. |
81
+ | `callbackUrl` | `string` | Async-only callback URL, serialized as `callback_url`. |
82
+
83
+ `runFlow` uses `RunFlowOptions` for local execution controls:
84
+
85
+ | Field | Type | Description |
86
+ | ------------------- | ----------------- | ------------------------------------------------------------ |
87
+ | `signal` | `AbortSignal` | Cancels the in-flight request/polling. |
88
+ | `timeoutMs` | `number` | Overrides configured polling timeout for this call. |
89
+ | `pollIntervalMs` | `number` | Overrides configured fallback minimum polling interval. |
90
+ | `pollMaxIntervalMs` | `number` | Overrides configured fallback maximum polling interval. |
91
+ | `onPoll` | `(event) => void` | Called after each status poll. |
92
+ | `onRateLimit` | `(event) => void` | Called when polling receives `429`; includes `retryAfterMs`. |
93
+
94
+ `runFlowAsync` accepts `RunFlowAsyncOptions` with `signal`.
95
+
96
+ `once` was removed. Use `useDraftVersion`.
97
+
98
+ ## Methods
99
+
100
+ - `listFlows()` calls `GET /v1/flows` and returns `{ id, name, state }[]` for
101
+ the flows available to the Bearer token. Missing flow states are returned as
102
+ `"unknown"`.
103
+ - `listOrganizations()` calls `GET /v1/organizations` and returns
104
+ `{ id, name }[]` for the organizations available to the Bearer token.
105
+ - `getFlowMetadata(flowId)` calls `GET /v1/flows/:flowId/metadata` and returns
106
+ `{ flowId, name?, contextSchema, languages, minScore?, documents }`.
107
+ - `getFlowDefinition(flowId)` calls `GET /v1/flows/:flowId/definition` and
108
+ returns the normalized flow definition `{ flowId, name?, languages, minScore?, nodes }`.
109
+ - `listOrganizationDocuments({ prefix? })` calls
110
+ `GET /v1/organization-documents` and returns `{ configured, documents }`.
111
+ - `downloadOrganizationDocument(path)` calls
112
+ `GET /v1/organization-documents/download?path=...` and returns
113
+ `{ bytes, filename, contentType? }`.
114
+ - `downloadOrganizationDocuments(paths)` downloads each requested path.
115
+ - `runFlowAsync(flowId, params, options?)` posts multipart files to
116
+ `POST /v1/flows/:flowId/execute-async` and returns
117
+ `{ executionResultId, fileIds }`.
118
+ - `getStatus(executionResultId)` calls
119
+ `GET /v1/executions/:executionResultId/status`.
120
+ - `getResult(executionResultId, signal?, language?)` calls
121
+ `GET /v1/executions/:executionResultId/result`.
122
+ - `runFlow(flowId, params, options?)` starts async execution, polls status, fetches the
123
+ result, respects `X-Poll-After` and `429 Retry-After` while polling, and throws
124
+ `DocmanaExecutionError` if the result status is `Failed`.
125
+
126
+ Consumer is the polling authority. When `GET /status` returns `X-Poll-After`,
127
+ the SDK waits that many milliseconds before the next status call. If the header
128
+ is absent, the SDK falls back to capped exponential full jitter between
129
+ `pollIntervalMs` and `pollMaxIntervalMs`. `Retry-After` on `429` always wins.
84
130
 
85
131
  ```ts
86
- await docmana.runFlow("<flow-id>", { file: "./contract.pdf" });
132
+ const flows = await docmana.listFlows();
133
+ console.log(flows.map((flow) => `${flow.id}: ${flow.name} (${flow.state})`).join("\n"));
87
134
  ```
88
135
 
89
- A `Buffer` (or stream) — supply `fileName` so Docmana can infer the document type:
90
-
91
136
  ```ts
92
- import { readFile } from "node:fs/promises";
93
-
94
- const buffer = await readFile("./contract.pdf");
95
- await docmana.runFlow("<flow-id>", { file: buffer, fileName: "contract.pdf" });
137
+ const organizations = await docmana.listOrganizations();
138
+ console.log(organizations.map((org) => `${org.id}: ${org.name}`).join("\n"));
96
139
  ```
97
140
 
98
- Multiple documents:
99
-
100
141
  ```ts
101
- await docmana.runFlow("<flow-id>", {
102
- files: ["./statement.pdf", "./id-card.png"],
103
- });
104
- ```
142
+ const metadata = await docmana.getFlowMetadata("<flow-id>");
143
+ console.log(metadata.contextSchema);
105
144
 
106
- Path objects are also supported, which is useful when your caller already models uploads as
107
- objects:
145
+ const definition = await docmana.getFlowDefinition("<flow-id>");
146
+ console.log(definition.nodes.map((node) => node.label).join("\n"));
147
+ ```
108
148
 
109
149
  ```ts
110
- await docmana.runFlow("<flow-id>", {
111
- files: [{ path: "./contract.pdf" }],
112
- });
150
+ const depot = await docmana.listOrganizationDocuments({ prefix: "dossier/" });
151
+ if (depot.configured) {
152
+ const file = await docmana.downloadOrganizationDocument(depot.documents[0].path);
153
+ console.log(file.filename, file.bytes.byteLength);
154
+ }
113
155
  ```
114
156
 
115
- ## Lower-level methods
116
-
117
- `runFlow` is the recommended entry point. If you need to manage polling yourself — for example to surface progress in your own job queue — the underlying steps are exposed:
118
-
119
- - `runFlowAsync(flowId, input)` → `{ executionResultId, fileIds }` — uploads the file(s) and starts the flow without waiting; `fileIds` are the uploaded document UUIDs.
120
- - `getStatus(executionResultId)` → `{ status }` — current execution status (`"Pending" | "Running" | "Completed" | "Failed"`).
121
- - `getResult(executionResultId)` → `ExecutionResult` — the result payload once the flow has finished.
122
-
123
157
  ```ts
124
158
  const { executionResultId } = await docmana.runFlowAsync("<flow-id>", {
125
- file: "./contract.pdf",
159
+ files: ["./contract.pdf"],
126
160
  });
127
161
 
128
162
  let status = "Pending";
@@ -131,221 +165,130 @@ while (status !== "Completed" && status !== "Failed") {
131
165
  ({ status } = await docmana.getStatus(executionResultId));
132
166
  }
133
167
 
134
- const result = await docmana.getResult(executionResultId);
135
- console.log(result.status, result.results);
168
+ const result = await docmana.getResult(executionResultId, undefined, "fr");
136
169
  ```
137
170
 
138
- Unlike `runFlow`, `getResult` does not throw on a failed execution — inspect `result.status` and `result.errors` yourself.
139
-
140
171
  ## Webhook callbacks
141
172
 
142
- When you don't want to poll, use `runFlowWithCallback`. It starts the flow with a `callbackUrl` and returns immediately — docmana-api POSTs a completion notification to that URL when the run finishes, so your server never polls.
143
-
144
- - `runFlowWithCallback(flowId, input)` → `{ executionResultId, fileIds }` — uploads the file(s) and starts the flow with the callback registered. It does **not** poll and does **not** fetch the result.
145
-
146
- `input` is a `RunFlowWithCallbackInput`:
147
-
148
- | Field | Type | Required | Description |
149
- | ------------- | ------------------------------------------------------------------- | -------- | ---------------------------------------------------------------------------- |
150
- | `callbackUrl` | `string` | Yes | URL docmana-api POSTs the completion notification to (wire: `callback_url`). |
151
- | `file` | `string \| { path: string } \| Buffer \| NodeJS.ReadableStream` | — | A single document. |
152
- | `files` | `(string \| { path: string } \| Buffer \| NodeJS.ReadableStream)[]` | — | Multiple documents for a multi-document flow. |
153
- | `fileName` | `string` | — | Required when passing a `Buffer`/stream with no derivable name. |
154
- | `once` | `boolean` | — | Use the ad-hoc `run_once_flow` endpoint instead of `run_flow`. |
155
- | `context` | `Record<string, unknown>` | — | Business `json_context` passed through to the flow. |
156
- | `signal` | `AbortSignal` | — | Cancels the upload/start. |
157
-
158
- `callbackUrl` lives only on this input — `RunFlowInput` (used by `runFlow`/`runFlowAsync`) has no callback field, so a polling run never registers one.
159
-
160
- The notification payload docmana-api sends is a small JSON object, e.g.:
161
-
162
- ```json
163
- {
164
- "execution_id": "faad872c-…",
165
- "status": "Success",
166
- "timestamp": "2026-06-08T21:45:28.415402+00:00",
167
- "flow_id": "f87bb991-…"
168
- }
169
- ```
170
-
171
- It is a notification only — it does not carry the result. On receipt, fetch and map the full result with `getResult`:
173
+ `runFlowAsync(flowId, params, options?)` accepts `callbackUrl` and sends it as
174
+ `callback_url`. It returns immediately and does not poll.
172
175
 
173
176
  ```ts
174
- const { executionResultId } = await docmana.runFlowWithCallback("<flow-id>", {
175
- file: "./contract.pdf",
177
+ const { executionResultId } = await docmana.runFlowAsync("<flow-id>", {
178
+ files: ["./contract.pdf"],
176
179
  callbackUrl: "https://your-service.example.com/webhooks/docmana/executions",
180
+ language: "fr",
177
181
  });
178
-
179
- // …later, in your webhook handler, keyed by the notification's execution_id:
180
- const result = await docmana.getResult(execution_id);
181
- console.log(result.status, result.results);
182
182
  ```
183
183
 
184
- ## CLI
185
-
186
- The package also installs a `docmana` command for simple terminal usage:
184
+ Consumer posts the mapped result DTO to your callback URL when the execution is
185
+ finished. Keep `executionResultId` if you also want to poll as a fallback.
187
186
 
188
- ```bash
189
- docmana flow run "<flow-id>" --files "./contract.pdf" --organisation "<organisation-id>"
190
- ```
187
+ ## CLI
191
188
 
192
- You can create a local config file interactively:
189
+ The CLI can still acquire and cache a token through OAuth:
193
190
 
194
191
  ```bash
195
192
  docmana config init
193
+ docmana login
196
194
  ```
197
195
 
198
- This writes `docmana.config.json` in the current directory. The file can include Docmana URLs,
199
- scope, organisation, client id, and client secret, so it is ignored by Git.
196
+ `docmana login` reads `clientId`, `clientSecret`, `tokenEndpoint`, and `scope`
197
+ from flags, environment variables, or `docmana.config.json`, then stores the
198
+ access token in `docmana.token.json`.
200
199
 
201
- Use a custom config path when needed:
200
+ `docmana flow run` always passes a Bearer token to the SDK. It resolves the token
201
+ in this order:
202
202
 
203
- ```bash
204
- docmana config init --config ./docmana.dev.config.json
205
- docmana flow run "<flow-id>" --files "./contract.pdf" --config ./docmana.dev.config.json
206
- ```
207
-
208
- `flow run` automatically loads `./docmana.config.json` when present. Credentials and connection
209
- settings can also be read from the environment:
203
+ 1. `--access-token`
204
+ 2. `DOCMANA_ACCESS_TOKEN`
205
+ 3. valid `docmana.token.json`
206
+ 4. OAuth refresh using CLI/config credentials
210
207
 
211
208
  ```bash
212
- DOCMANA_CLIENT_ID="<client-id>"
213
- DOCMANA_CLIENT_SECRET="<client-secret>"
214
- DOCMANA_ORGANISATION="<organisation-id>"
215
- DOCMANA_API_URL="https://api.docmana.ai"
216
- DOCMANA_TOKEN_URL="<token-endpoint>"
217
- DOCMANA_SCOPE="<oauth-scope>"
218
-
219
- docmana flow run "<flow-id>" --files "./contract.pdf,./annexe.pdf"
209
+ DOCMANA_API_URL="https://consumer.example.com/v1"
210
+ docmana flow list
220
211
  ```
221
212
 
222
- You can override config or environment values with flags:
223
-
224
213
  ```bash
225
- docmana flow run "<flow-id>" \
226
- --files "./contract.pdf" \
227
- --client-id "<client-id>" \
228
- --client-secret "<client-secret>" \
229
- --organisation "<organisation-id>" \
230
- --api-url "https://api.docmana.ai" \
231
- --token-url "<token-endpoint>" \
232
- --scope "<oauth-scope>"
214
+ DOCMANA_API_URL="https://consumer.example.com/v1"
215
+ docmana organization list
233
216
  ```
234
217
 
235
- The CLI caches OAuth2 access tokens in `docmana.token.json` by default, so repeated commands do
236
- not request a new token until the cached token expires. The cache file is ignored by Git. Use a
237
- custom token cache path when needed:
238
-
239
218
  ```bash
240
- docmana login
241
- docmana flow run "<flow-id>" --files "./contract.pdf" --token-cache ./docmana.dev.token.json
219
+ DOCMANA_API_URL="https://consumer.example.com/v1"
220
+ docmana organization document list --prefix "dossier/"
221
+ docmana organization document download "dossier/facture.pdf"
222
+ docmana organization document download "dossier/facture.pdf" --output "./facture.pdf"
242
223
  ```
243
224
 
244
- `docmana login` loads the same config, environment variables, and auth flags as `flow run`, then
245
- ensures a valid token is cached. It does not print the token.
246
-
247
- By default, the CLI prints a human-readable summary with a preview of the results. Use `--json`
248
- to print the complete result payload to stdout:
249
-
250
225
  ```bash
251
- docmana flow run "<flow-id>" --files "./contract.pdf" --organisation "<organisation-id>" --json
226
+ DOCMANA_API_URL="https://consumer.example.com/v1"
227
+ docmana flow metadata "<flow-id>"
228
+ docmana flow definition "<flow-id>"
252
229
  ```
253
230
 
254
- `--files` is a simple comma-separated list. Paths containing commas are not supported.
255
-
256
- To build the local checkout and expose the `docmana` command on your machine:
257
-
258
231
  ```bash
259
- npm run cli:link
232
+ DOCMANA_API_URL="https://consumer.example.com/v1"
233
+ docmana flow run "<flow-id>" --files "./contract.pdf"
260
234
  ```
261
235
 
262
- Then run:
236
+ You can also run without the cache:
263
237
 
264
238
  ```bash
265
- docmana flow run "<flow-id>" --files "./contract.pdf" --organisation "<organisation-id>"
266
- ```
267
-
268
- ## Error handling
269
-
270
- Every error thrown by the SDK extends `DocmanaError`, which carries `.status` (HTTP status, when applicable), `.code`, and an optional `.requestId`.
271
-
272
- | Error | Thrown when |
273
- | ------------------------ | ------------------------------------------------------------------------------- |
274
- | `DocmanaRequestError` | `400` — bad request (e.g. calling for a result before the flow has finished). |
275
- | `DocmanaAuthError` | `401` — bad credentials, wrong scope, or an expired/rejected token. |
276
- | `DocmanaPermissionError` | `403` — the client is missing the `access_m2m_apps` role. |
277
- | `DocmanaNotFoundError` | `404` — the flow or endpoint was not found. |
278
- | `DocmanaExecutionError` | The flow finished with status `"Failed"`. Carries the flow errors in `.errors`. |
279
- | `DocmanaTimeoutError` | Polling exceeded `timeoutMs` before the flow reached a terminal state. |
280
- | `DocmanaAbortError` | The provided `AbortSignal` fired. |
281
-
282
- ```ts
283
- import {
284
- Docmana,
285
- DocmanaAuthError,
286
- DocmanaExecutionError,
287
- DocmanaTimeoutError,
288
- } from "@docmana/sdk";
289
-
290
- try {
291
- const result = await docmana.runFlow("<flow-id>", { file: "./contract.pdf" });
292
- console.log(result.results);
293
- } catch (err) {
294
- if (err instanceof DocmanaAuthError) {
295
- // Check client_id / client_secret / scope.
296
- } else if (err instanceof DocmanaExecutionError) {
297
- console.error("Flow failed:", err.errors);
298
- } else if (err instanceof DocmanaTimeoutError) {
299
- // Retry, or raise timeoutMs.
300
- } else {
301
- throw err;
302
- }
303
- }
239
+ docmana flow run "<flow-id>" \
240
+ --api-url "https://consumer.example.com/v1" \
241
+ --access-token "$DOCMANA_ACCESS_TOKEN" \
242
+ --files "./contract.pdf,./annexe.pdf" \
243
+ --draft \
244
+ --json
304
245
  ```
305
246
 
306
- ## Security
247
+ Use `--draft` to run the current draft flow version.
248
+ Use `docmana flow list --json` to print the raw flow list returned by Consumer.
249
+ Use `docmana organization list --json` to print the organization list as JSON.
250
+ Use `docmana organization document list --json` for raw organization document JSON.
251
+ `docmana flow metadata` and `docmana flow definition` print JSON by default.
307
252
 
308
- Treat `clientSecret` as a credential with full access to your Docmana account.
253
+ The CLI no longer sends `X-Selected-Organization`; Consumer derives identity
254
+ from the Bearer token.
309
255
 
310
- - Store `clientId` and `clientSecret` in a secrets manager (Azure Key Vault, AWS Secrets Manager, etc.).
311
- - Never commit them to source control, and never expose them in a browser or frontend bundle — this SDK is server-side only.
312
- - Never log them.
313
-
314
- The SDK keeps the bearer token in memory only. It is never written to disk.
256
+ ## Error handling
315
257
 
316
- ## Requirements
258
+ Every SDK error extends `DocmanaError`, which carries `.status`, `.code`, and an
259
+ optional `.requestId` when available.
317
260
 
318
- - Node.js 20 or later.
319
- - ESM and CommonJS are both supported.
261
+ | Error | Thrown when |
262
+ | ------------------------ | -------------------------------------------------------------------------- |
263
+ | `DocmanaRequestError` | `400` bad request. |
264
+ | `DocmanaAuthError` | `401` rejected or expired Bearer token. |
265
+ | `DocmanaPermissionError` | `403` missing permission. |
266
+ | `DocmanaNotFoundError` | `404` flow or execution not found. |
267
+ | `DocmanaExecutionError` | The flow finished with status `"Failed"`. Carries `.errors` and `.result`. |
268
+ | `DocmanaTimeoutError` | Polling exceeded `timeoutMs`. |
269
+ | `DocmanaAbortError` | The provided `AbortSignal` fired. |
320
270
 
321
271
  ## Local development with yalc
322
272
 
323
- To test changes to this SDK inside a consuming project without publishing to npm, use [yalc](https://github.com/wclr/yalc).
324
-
325
- In **this library**:
273
+ In this library:
326
274
 
327
275
  ```bash
328
276
  npm run dev
329
277
  ```
330
278
 
331
- This runs `tsup` in watch mode. After every rebuild it runs `yalc push`, propagating the freshly built package to every project that has linked it.
332
-
333
- In the **consuming project** (once):
279
+ In the consuming project:
334
280
 
335
281
  ```bash
336
282
  yalc add @docmana/sdk
337
283
  npm install
338
284
  ```
339
285
 
340
- From then on, each change you save here is rebuilt and pushed automatically — the consumer picks it up without reinstalling. To stop using the local copy and restore the registry version:
286
+ For a one-shot publish to the local yalc store:
341
287
 
342
288
  ```bash
343
- yalc remove @docmana/sdk
344
- npm install
289
+ npm run yalc:publish
345
290
  ```
346
291
 
347
- For a single one-shot publish to the local yalc store (no watch), use `npm run yalc:publish`.
348
-
349
292
  ## License
350
293
 
351
294
  MIT
@@ -0,0 +1,3 @@
1
+ import type { HttpClient } from "../http/http-client.js";
2
+ import type { DocmanaExecutionResult } from "../types.js";
3
+ export declare function getResult(http: HttpClient, executionResultId: string, signal?: AbortSignal, language?: string): Promise<DocmanaExecutionResult>;
@@ -0,0 +1,6 @@
1
+ import type { HttpClient } from "../http/http-client.js";
2
+ import type { ExecutionStatus } from "../types.js";
3
+ export declare function getStatus(http: HttpClient, executionResultId: string, signal?: AbortSignal): Promise<{
4
+ status: ExecutionStatus | string;
5
+ pollAfterMs?: number;
6
+ }>;
@@ -0,0 +1,3 @@
1
+ import type { HttpClient } from "../http/http-client.js";
2
+ import type { FlowDefinition } from "../types.js";
3
+ export declare function getFlowDefinition(http: HttpClient, flowId: string): Promise<FlowDefinition>;
@@ -0,0 +1,3 @@
1
+ import type { HttpClient } from "../http/http-client.js";
2
+ import type { FlowMetadata } from "../types.js";
3
+ export declare function getFlowMetadata(http: HttpClient, flowId: string): Promise<FlowMetadata>;
@@ -0,0 +1,3 @@
1
+ import type { HttpClient } from "../http/http-client.js";
2
+ import type { FlowListItem } from "../types.js";
3
+ export declare function listFlows(http: HttpClient): Promise<FlowListItem[]>;
@@ -0,0 +1,3 @@
1
+ import type { HttpClient } from "../http/http-client.js";
2
+ import type { AccessibleOrganization } from "../types.js";
3
+ export declare function listOrganizations(http: HttpClient): Promise<AccessibleOrganization[]>;
@@ -0,0 +1,7 @@
1
+ import type { HttpClient } from "../http/http-client.js";
2
+ import type { DownloadedOrganizationDocument, OrganizationDocumentsPayload } from "../types.js";
3
+ export declare function listOrganizationDocuments(http: HttpClient, options?: {
4
+ prefix?: string;
5
+ }): Promise<OrganizationDocumentsPayload>;
6
+ export declare function downloadOrganizationDocument(http: HttpClient, path: string): Promise<DownloadedOrganizationDocument>;
7
+ export declare function downloadOrganizationDocuments(http: HttpClient, paths: string[]): Promise<DownloadedOrganizationDocument[]>;
@@ -0,0 +1,6 @@
1
+ import type { ResolvedPart } from "../files/resolve-input.js";
2
+ import type { HttpClient } from "../http/http-client.js";
3
+ export declare function runFlow(http: HttpClient, flowId: string, parts: ResolvedPart[], signal?: AbortSignal, useDraftVersion?: boolean, context?: Record<string, unknown>, callbackUrl?: string, language?: string): Promise<{
4
+ executionResultId: string;
5
+ fileIds: string[];
6
+ }>;