@insureco/docman 1.0.0 → 1.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunk-DBVEE4WX.js +457 -0
- package/dist/chunk-DBVEE4WX.js.map +1 -0
- package/dist/client-CdjgCtrw.d.cts +100 -0
- package/dist/client-nlarq_ao.d.ts +100 -0
- package/dist/index.cjs +19 -5
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +3 -95
- package/dist/index.d.ts +3 -95
- package/dist/index.js +3 -435
- package/dist/index.js.map +1 -1
- package/dist/mock.cjs +8 -0
- package/dist/mock.cjs.map +1 -1
- package/dist/mock.d.cts +2 -1
- package/dist/mock.d.ts +2 -1
- package/dist/mock.js +8 -0
- package/dist/mock.js.map +1 -1
- package/dist/{types-xbeSIrNB.d.cts → types-DvQ8gX3k.d.cts} +1 -1
- package/dist/{types-xbeSIrNB.d.ts → types-DvQ8gX3k.d.ts} +1 -1
- package/dist/ui/index.cjs +1938 -0
- package/dist/ui/index.cjs.map +1 -0
- package/dist/ui/index.d.cts +122 -0
- package/dist/ui/index.d.ts +122 -0
- package/dist/ui/index.js +1441 -0
- package/dist/ui/index.js.map +1 -0
- package/package.json +24 -8
|
@@ -0,0 +1,457 @@
|
|
|
1
|
+
import {
|
|
2
|
+
DocmanError
|
|
3
|
+
} from "./chunk-7DJVMOS3.js";
|
|
4
|
+
|
|
5
|
+
// src/client.ts
|
|
6
|
+
function toUint8(b) {
|
|
7
|
+
return b;
|
|
8
|
+
}
|
|
9
|
+
var DEFAULT_RETRIES = 2;
|
|
10
|
+
var DEFAULT_TIMEOUT_MS = 15e3;
|
|
11
|
+
var TOKEN_BUFFER_SECONDS = 30;
|
|
12
|
+
function sleep(ms) {
|
|
13
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
14
|
+
}
|
|
15
|
+
function backoff(attempt) {
|
|
16
|
+
const base = Math.min(1e3 * 2 ** attempt, 5e3);
|
|
17
|
+
return base * (0.5 + Math.random() * 0.5);
|
|
18
|
+
}
|
|
19
|
+
function isTokenExpired(token, bufferSeconds = TOKEN_BUFFER_SECONDS) {
|
|
20
|
+
try {
|
|
21
|
+
const parts = token.split(".");
|
|
22
|
+
if (parts.length !== 3) return true;
|
|
23
|
+
const payload = JSON.parse(Buffer.from(parts[1], "base64url").toString());
|
|
24
|
+
const now = Math.floor(Date.now() / 1e3);
|
|
25
|
+
return (payload.exp ?? 0) <= now + bufferSeconds;
|
|
26
|
+
} catch {
|
|
27
|
+
return true;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
function extractError(envelope) {
|
|
31
|
+
const err = envelope.error;
|
|
32
|
+
if (typeof err === "object" && err !== null) return err;
|
|
33
|
+
return { code: "REQUEST_ERROR", message: err ?? "Request failed" };
|
|
34
|
+
}
|
|
35
|
+
var DocmanClient = class _DocmanClient {
|
|
36
|
+
baseUrl;
|
|
37
|
+
accessTokenFn;
|
|
38
|
+
internalKey;
|
|
39
|
+
retries;
|
|
40
|
+
timeoutMs;
|
|
41
|
+
cachedToken = null;
|
|
42
|
+
constructor(config) {
|
|
43
|
+
this.baseUrl = config.baseUrl.replace(/\/$/, "");
|
|
44
|
+
this.accessTokenFn = config.accessTokenFn;
|
|
45
|
+
this.internalKey = config.internalKey;
|
|
46
|
+
this.retries = config.retries ?? DEFAULT_RETRIES;
|
|
47
|
+
this.timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Create a client from environment variables.
|
|
51
|
+
*
|
|
52
|
+
* Reads DOCMAN_URL (injected automatically when you declare docman as an
|
|
53
|
+
* internalDependency in catalog-info.yaml). Auth priority:
|
|
54
|
+
* 1. BIO_CLIENT_ID + BIO_CLIENT_SECRET → client_credentials token
|
|
55
|
+
* 2. INTERNAL_SERVICE_KEY → internal key header
|
|
56
|
+
* 3. No auth → local dev / testing
|
|
57
|
+
*
|
|
58
|
+
* catalog-info.yaml:
|
|
59
|
+
* spec:
|
|
60
|
+
* internalDependencies:
|
|
61
|
+
* - service: docman
|
|
62
|
+
* port: 3000
|
|
63
|
+
*/
|
|
64
|
+
static fromEnv() {
|
|
65
|
+
const baseUrl = process.env.DOCMAN_URL;
|
|
66
|
+
if (!baseUrl) {
|
|
67
|
+
throw new DocmanError(
|
|
68
|
+
"DOCMAN_URL is not set. Add docman as an internalDependency in catalog-info.yaml",
|
|
69
|
+
500,
|
|
70
|
+
"CONFIG_ERROR"
|
|
71
|
+
);
|
|
72
|
+
}
|
|
73
|
+
const clientId = process.env.BIO_CLIENT_ID;
|
|
74
|
+
const clientSecret = process.env.BIO_CLIENT_SECRET;
|
|
75
|
+
const bioIdUrl = process.env.BIO_ID_URL ?? "https://bio.tawa.insureco.io";
|
|
76
|
+
if (clientId && clientSecret) {
|
|
77
|
+
return new _DocmanClient({
|
|
78
|
+
baseUrl,
|
|
79
|
+
accessTokenFn: async () => {
|
|
80
|
+
const res = await fetch(`${bioIdUrl}/api/oauth/token`, {
|
|
81
|
+
method: "POST",
|
|
82
|
+
headers: { "Content-Type": "application/json" },
|
|
83
|
+
body: JSON.stringify({
|
|
84
|
+
grant_type: "client_credentials",
|
|
85
|
+
client_id: clientId,
|
|
86
|
+
client_secret: clientSecret
|
|
87
|
+
})
|
|
88
|
+
});
|
|
89
|
+
if (!res.ok) {
|
|
90
|
+
throw new DocmanError("Failed to obtain Bio-ID access token", res.status, "AUTH_ERROR");
|
|
91
|
+
}
|
|
92
|
+
const data = await res.json();
|
|
93
|
+
return data.access_token;
|
|
94
|
+
}
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
const internalKey = process.env.INTERNAL_SERVICE_KEY;
|
|
98
|
+
if (internalKey) {
|
|
99
|
+
return new _DocmanClient({ baseUrl, internalKey });
|
|
100
|
+
}
|
|
101
|
+
return new _DocmanClient({ baseUrl });
|
|
102
|
+
}
|
|
103
|
+
// ─── Auth ────────────────────────────────────────────────
|
|
104
|
+
async authHeaders() {
|
|
105
|
+
if (this.accessTokenFn) {
|
|
106
|
+
if (!this.cachedToken || isTokenExpired(this.cachedToken)) {
|
|
107
|
+
this.cachedToken = await this.accessTokenFn();
|
|
108
|
+
}
|
|
109
|
+
return { Authorization: `Bearer ${this.cachedToken}` };
|
|
110
|
+
}
|
|
111
|
+
if (this.internalKey) {
|
|
112
|
+
return { "X-Internal-Key": this.internalKey };
|
|
113
|
+
}
|
|
114
|
+
return {};
|
|
115
|
+
}
|
|
116
|
+
// ─── Core fetch ──────────────────────────────────────────
|
|
117
|
+
async rawFetch(method, path, body, attempt = 0) {
|
|
118
|
+
const headers = await this.authHeaders();
|
|
119
|
+
const controller = new AbortController();
|
|
120
|
+
const timer = setTimeout(() => controller.abort(), this.timeoutMs);
|
|
121
|
+
let response;
|
|
122
|
+
try {
|
|
123
|
+
response = await fetch(`${this.baseUrl}${path}`, {
|
|
124
|
+
method,
|
|
125
|
+
headers: body !== void 0 ? { ...headers, "Content-Type": "application/json" } : headers,
|
|
126
|
+
body: body !== void 0 ? JSON.stringify(body) : void 0,
|
|
127
|
+
signal: controller.signal
|
|
128
|
+
});
|
|
129
|
+
} catch (err) {
|
|
130
|
+
clearTimeout(timer);
|
|
131
|
+
if (attempt < this.retries) {
|
|
132
|
+
await sleep(backoff(attempt));
|
|
133
|
+
return this.rawFetch(method, path, body, attempt + 1);
|
|
134
|
+
}
|
|
135
|
+
throw new DocmanError(`Network error: ${err.message}`, 0, "NETWORK_ERROR");
|
|
136
|
+
} finally {
|
|
137
|
+
clearTimeout(timer);
|
|
138
|
+
}
|
|
139
|
+
if (response.status >= 500 && attempt < this.retries) {
|
|
140
|
+
await sleep(backoff(attempt));
|
|
141
|
+
return this.rawFetch(method, path, body, attempt + 1);
|
|
142
|
+
}
|
|
143
|
+
const envelope = await response.json();
|
|
144
|
+
if (!response.ok || !envelope.success) {
|
|
145
|
+
const { code, message } = extractError(envelope);
|
|
146
|
+
throw new DocmanError(message, response.status, code);
|
|
147
|
+
}
|
|
148
|
+
return envelope;
|
|
149
|
+
}
|
|
150
|
+
async fetchData(method, path, body) {
|
|
151
|
+
const envelope = await this.rawFetch(method, path, body);
|
|
152
|
+
return envelope.data;
|
|
153
|
+
}
|
|
154
|
+
async fetchList(path) {
|
|
155
|
+
const envelope = await this.rawFetch("GET", path);
|
|
156
|
+
return {
|
|
157
|
+
data: envelope.data ?? [],
|
|
158
|
+
meta: envelope.meta ?? { total: 0, page: 1, limit: 20 }
|
|
159
|
+
};
|
|
160
|
+
}
|
|
161
|
+
buildQuery(params) {
|
|
162
|
+
const pairs = Object.entries(params).filter(([, v]) => v !== void 0).map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(String(v))}`);
|
|
163
|
+
return pairs.length > 0 ? `?${pairs.join("&")}` : "";
|
|
164
|
+
}
|
|
165
|
+
/** Fetch with FormData body (multipart), return raw binary buffer. */
|
|
166
|
+
async fetchBinary(method, path, formData, attempt = 0) {
|
|
167
|
+
const headers = await this.authHeaders();
|
|
168
|
+
const controller = new AbortController();
|
|
169
|
+
const timer = setTimeout(() => controller.abort(), this.timeoutMs);
|
|
170
|
+
let response;
|
|
171
|
+
try {
|
|
172
|
+
response = await fetch(`${this.baseUrl}${path}`, {
|
|
173
|
+
method,
|
|
174
|
+
headers,
|
|
175
|
+
body: formData,
|
|
176
|
+
signal: controller.signal
|
|
177
|
+
});
|
|
178
|
+
} catch (err) {
|
|
179
|
+
clearTimeout(timer);
|
|
180
|
+
if (attempt < this.retries) {
|
|
181
|
+
await sleep(backoff(attempt));
|
|
182
|
+
return this.fetchBinary(method, path, formData, attempt + 1);
|
|
183
|
+
}
|
|
184
|
+
throw new DocmanError(`Network error: ${err.message}`, 0, "NETWORK_ERROR");
|
|
185
|
+
} finally {
|
|
186
|
+
clearTimeout(timer);
|
|
187
|
+
}
|
|
188
|
+
if (response.status >= 500 && attempt < this.retries) {
|
|
189
|
+
await sleep(backoff(attempt));
|
|
190
|
+
return this.fetchBinary(method, path, formData, attempt + 1);
|
|
191
|
+
}
|
|
192
|
+
if (!response.ok) {
|
|
193
|
+
const envelope = await response.json();
|
|
194
|
+
const { code, message } = extractError(envelope);
|
|
195
|
+
throw new DocmanError(message, response.status, code);
|
|
196
|
+
}
|
|
197
|
+
return Buffer.from(await response.arrayBuffer());
|
|
198
|
+
}
|
|
199
|
+
/** POST multipart form and parse the JSON response envelope. */
|
|
200
|
+
async fetchMultipartJson(path, formData) {
|
|
201
|
+
const headers = await this.authHeaders();
|
|
202
|
+
const response = await fetch(`${this.baseUrl}${path}`, {
|
|
203
|
+
method: "POST",
|
|
204
|
+
headers,
|
|
205
|
+
body: formData
|
|
206
|
+
});
|
|
207
|
+
const envelope = await response.json();
|
|
208
|
+
if (!response.ok || !envelope.success) {
|
|
209
|
+
const { code, message } = extractError(envelope);
|
|
210
|
+
throw new DocmanError(message, response.status, code);
|
|
211
|
+
}
|
|
212
|
+
return envelope.data;
|
|
213
|
+
}
|
|
214
|
+
/** PUT multipart form and parse the JSON response envelope. */
|
|
215
|
+
async putMultipartJson(path, formData) {
|
|
216
|
+
const headers = await this.authHeaders();
|
|
217
|
+
const response = await fetch(`${this.baseUrl}${path}`, {
|
|
218
|
+
method: "PUT",
|
|
219
|
+
headers,
|
|
220
|
+
body: formData
|
|
221
|
+
});
|
|
222
|
+
const envelope = await response.json();
|
|
223
|
+
if (!response.ok || !envelope.success) {
|
|
224
|
+
const { code, message } = extractError(envelope);
|
|
225
|
+
throw new DocmanError(message, response.status, code);
|
|
226
|
+
}
|
|
227
|
+
return envelope.data;
|
|
228
|
+
}
|
|
229
|
+
// ─── HTML Templates ──────────────────────────────────────
|
|
230
|
+
async createHtmlTemplate(options) {
|
|
231
|
+
return this.fetchData("POST", "/templates/html", options);
|
|
232
|
+
}
|
|
233
|
+
async listHtmlTemplates(query = {}) {
|
|
234
|
+
return this.fetchList(`/templates/html${this.buildQuery(query)}`);
|
|
235
|
+
}
|
|
236
|
+
async getHtmlTemplate(id) {
|
|
237
|
+
return this.fetchData("GET", `/templates/html/${encodeURIComponent(id)}`);
|
|
238
|
+
}
|
|
239
|
+
async updateHtmlTemplate(id, options) {
|
|
240
|
+
return this.fetchData("PUT", `/templates/html/${encodeURIComponent(id)}`, options);
|
|
241
|
+
}
|
|
242
|
+
async deleteHtmlTemplate(id) {
|
|
243
|
+
return this.fetchData("DELETE", `/templates/html/${encodeURIComponent(id)}`);
|
|
244
|
+
}
|
|
245
|
+
// ─── PDF Templates ───────────────────────────────────────
|
|
246
|
+
/**
|
|
247
|
+
* Upload a PDF form template.
|
|
248
|
+
* @param file Raw PDF bytes (Buffer or Uint8Array)
|
|
249
|
+
* @param options Name, description, and optional coordinates/isSystem flags
|
|
250
|
+
*/
|
|
251
|
+
async uploadPdfTemplate(file, options = {}) {
|
|
252
|
+
const form = new FormData();
|
|
253
|
+
const filename = options.name ?? "template.pdf";
|
|
254
|
+
form.append("file", new Blob([toUint8(file)], { type: "application/pdf" }), filename);
|
|
255
|
+
if (options.name) form.append("name", options.name);
|
|
256
|
+
if (options.description) form.append("description", options.description);
|
|
257
|
+
if (options.coordinates) form.append("coordinates", JSON.stringify(options.coordinates));
|
|
258
|
+
if (options.isSystem !== void 0) form.append("isSystem", String(options.isSystem));
|
|
259
|
+
return this.fetchMultipartJson("/templates/pdf", form);
|
|
260
|
+
}
|
|
261
|
+
async listPdfTemplates(query = {}) {
|
|
262
|
+
return this.fetchList(`/templates/pdf${this.buildQuery(query)}`);
|
|
263
|
+
}
|
|
264
|
+
async getPdfTemplate(id) {
|
|
265
|
+
return this.fetchData("GET", `/templates/pdf/${encodeURIComponent(id)}`);
|
|
266
|
+
}
|
|
267
|
+
async getPdfTemplateFields(id) {
|
|
268
|
+
return this.fetchData("GET", `/templates/pdf/${encodeURIComponent(id)}/fields`);
|
|
269
|
+
}
|
|
270
|
+
async getPdfTemplateDownloadUrl(id) {
|
|
271
|
+
const data = await this.fetchData("GET", `/templates/pdf/${encodeURIComponent(id)}/download`);
|
|
272
|
+
return data.url;
|
|
273
|
+
}
|
|
274
|
+
/**
|
|
275
|
+
* Update a PDF template's metadata, and optionally replace the PDF file.
|
|
276
|
+
* @param file If provided, replaces the stored PDF and re-extracts form fields
|
|
277
|
+
*/
|
|
278
|
+
async updatePdfTemplate(id, options, file) {
|
|
279
|
+
if (file) {
|
|
280
|
+
const form = new FormData();
|
|
281
|
+
form.append("file", new Blob([toUint8(file)], { type: "application/pdf" }), "template.pdf");
|
|
282
|
+
if (options.name) form.append("name", options.name);
|
|
283
|
+
if (options.description) form.append("description", options.description);
|
|
284
|
+
if (options.coordinates) form.append("coordinates", JSON.stringify(options.coordinates));
|
|
285
|
+
return this.putMultipartJson(`/templates/pdf/${encodeURIComponent(id)}`, form);
|
|
286
|
+
}
|
|
287
|
+
return this.fetchData("PUT", `/templates/pdf/${encodeURIComponent(id)}`, options);
|
|
288
|
+
}
|
|
289
|
+
async deletePdfTemplate(id) {
|
|
290
|
+
return this.fetchData("DELETE", `/templates/pdf/${encodeURIComponent(id)}`);
|
|
291
|
+
}
|
|
292
|
+
// ─── Template Groups ─────────────────────────────────────
|
|
293
|
+
async createTemplateGroup(options) {
|
|
294
|
+
return this.fetchData("POST", "/template-groups", options);
|
|
295
|
+
}
|
|
296
|
+
async listTemplateGroups(query = {}) {
|
|
297
|
+
return this.fetchList(`/template-groups${this.buildQuery(query)}`);
|
|
298
|
+
}
|
|
299
|
+
async getTemplateGroup(id) {
|
|
300
|
+
return this.fetchData("GET", `/template-groups/${encodeURIComponent(id)}`);
|
|
301
|
+
}
|
|
302
|
+
async updateTemplateGroup(id, options) {
|
|
303
|
+
return this.fetchData("PUT", `/template-groups/${encodeURIComponent(id)}`, options);
|
|
304
|
+
}
|
|
305
|
+
async deleteTemplateGroup(id) {
|
|
306
|
+
await this.fetchData("DELETE", `/template-groups/${encodeURIComponent(id)}`);
|
|
307
|
+
}
|
|
308
|
+
// ─── Document Generation ─────────────────────────────────
|
|
309
|
+
/**
|
|
310
|
+
* Generate a document and store it in S3.
|
|
311
|
+
* Returns a presigned download URL and a public share URL.
|
|
312
|
+
*/
|
|
313
|
+
async generate(options) {
|
|
314
|
+
return this.fetchData("POST", "/documents/generate", {
|
|
315
|
+
templateIds: options.templateIds,
|
|
316
|
+
templateData: options.data,
|
|
317
|
+
name: options.name,
|
|
318
|
+
description: options.description
|
|
319
|
+
});
|
|
320
|
+
}
|
|
321
|
+
/**
|
|
322
|
+
* Generate a document and stream the PDF buffer directly.
|
|
323
|
+
* Nothing is stored — useful for previews or on-the-fly delivery.
|
|
324
|
+
*/
|
|
325
|
+
async generatePassthrough(options) {
|
|
326
|
+
const headers = await this.authHeaders();
|
|
327
|
+
const controller = new AbortController();
|
|
328
|
+
const timer = setTimeout(() => controller.abort(), this.timeoutMs);
|
|
329
|
+
let response;
|
|
330
|
+
try {
|
|
331
|
+
response = await fetch(`${this.baseUrl}/documents/generate/passthrough`, {
|
|
332
|
+
method: "POST",
|
|
333
|
+
headers: { ...headers, "Content-Type": "application/json" },
|
|
334
|
+
body: JSON.stringify({
|
|
335
|
+
templateIds: options.templateIds,
|
|
336
|
+
templateData: options.data,
|
|
337
|
+
name: options.name,
|
|
338
|
+
description: options.description
|
|
339
|
+
}),
|
|
340
|
+
signal: controller.signal
|
|
341
|
+
});
|
|
342
|
+
} catch (err) {
|
|
343
|
+
clearTimeout(timer);
|
|
344
|
+
throw new DocmanError(`Network error: ${err.message}`, 0, "NETWORK_ERROR");
|
|
345
|
+
} finally {
|
|
346
|
+
clearTimeout(timer);
|
|
347
|
+
}
|
|
348
|
+
if (!response.ok) {
|
|
349
|
+
const envelope = await response.json();
|
|
350
|
+
const { code, message } = extractError(envelope);
|
|
351
|
+
throw new DocmanError(message, response.status, code);
|
|
352
|
+
}
|
|
353
|
+
return Buffer.from(await response.arrayBuffer());
|
|
354
|
+
}
|
|
355
|
+
async listDocuments(query = {}) {
|
|
356
|
+
return this.fetchList(`/documents${this.buildQuery(query)}`);
|
|
357
|
+
}
|
|
358
|
+
async getDocument(id) {
|
|
359
|
+
return this.fetchData("GET", `/documents/${encodeURIComponent(id)}`);
|
|
360
|
+
}
|
|
361
|
+
/** Get a presigned S3 download URL for a stored document (1-hour TTL). */
|
|
362
|
+
async downloadUrl(id) {
|
|
363
|
+
const data = await this.fetchData("GET", `/documents/${encodeURIComponent(id)}/download`);
|
|
364
|
+
return data.url;
|
|
365
|
+
}
|
|
366
|
+
async getVersions(id) {
|
|
367
|
+
return this.fetchData("GET", `/documents/${encodeURIComponent(id)}/versions`);
|
|
368
|
+
}
|
|
369
|
+
/** Re-render a stored document using the original template data. */
|
|
370
|
+
async regenerate(id) {
|
|
371
|
+
return this.fetchData("POST", `/documents/${encodeURIComponent(id)}/regenerate`);
|
|
372
|
+
}
|
|
373
|
+
// ─── PDF Operations ──────────────────────────────────────
|
|
374
|
+
/**
|
|
375
|
+
* Merge two or more PDF buffers into a single PDF.
|
|
376
|
+
* Returns the merged PDF as a Buffer.
|
|
377
|
+
*/
|
|
378
|
+
async merge(buffers) {
|
|
379
|
+
if (buffers.length < 2) {
|
|
380
|
+
throw new DocmanError("At least 2 PDF buffers are required for merge", 400, "VALIDATION_ERROR");
|
|
381
|
+
}
|
|
382
|
+
const form = new FormData();
|
|
383
|
+
for (const buf of buffers) {
|
|
384
|
+
form.append("files", new Blob([toUint8(buf)], { type: "application/pdf" }), "file.pdf");
|
|
385
|
+
}
|
|
386
|
+
return this.fetchBinary("POST", "/operations/merge", form);
|
|
387
|
+
}
|
|
388
|
+
/**
|
|
389
|
+
* Split a PDF into parts by page ranges.
|
|
390
|
+
* Returns an array of SplitPart with buffer, range, and size info.
|
|
391
|
+
*/
|
|
392
|
+
async split(buffer, ranges) {
|
|
393
|
+
if (ranges.length === 0) {
|
|
394
|
+
throw new DocmanError("At least 1 page range is required", 400, "VALIDATION_ERROR");
|
|
395
|
+
}
|
|
396
|
+
const form = new FormData();
|
|
397
|
+
form.append("file", new Blob([toUint8(buffer)], { type: "application/pdf" }), "file.pdf");
|
|
398
|
+
form.append("ranges", JSON.stringify(ranges));
|
|
399
|
+
const headers = await this.authHeaders();
|
|
400
|
+
const response = await fetch(`${this.baseUrl}/operations/split`, {
|
|
401
|
+
method: "POST",
|
|
402
|
+
headers,
|
|
403
|
+
body: form
|
|
404
|
+
});
|
|
405
|
+
if (!response.ok) {
|
|
406
|
+
const envelope = await response.json();
|
|
407
|
+
const { code, message } = extractError(envelope);
|
|
408
|
+
throw new DocmanError(message, response.status, code);
|
|
409
|
+
}
|
|
410
|
+
const contentType = response.headers.get("content-type") ?? "";
|
|
411
|
+
if (contentType.includes("application/json")) {
|
|
412
|
+
const json = await response.json();
|
|
413
|
+
return json.data.map((part) => ({
|
|
414
|
+
index: part.index,
|
|
415
|
+
range: part.range,
|
|
416
|
+
buffer: Buffer.from(part.base64, "base64"),
|
|
417
|
+
sizeBytes: part.sizeBytes
|
|
418
|
+
}));
|
|
419
|
+
}
|
|
420
|
+
const buf = Buffer.from(await response.arrayBuffer());
|
|
421
|
+
return [{ index: 0, range: ranges[0], buffer: buf, sizeBytes: buf.length }];
|
|
422
|
+
}
|
|
423
|
+
/**
|
|
424
|
+
* Batch-introspect PDF form fields for multiple templates.
|
|
425
|
+
* Returns a map of templateId → field list.
|
|
426
|
+
*/
|
|
427
|
+
async introspectFields(templateIds) {
|
|
428
|
+
return this.fetchData(
|
|
429
|
+
"POST",
|
|
430
|
+
"/templates/pdf/fields",
|
|
431
|
+
{ templateIds }
|
|
432
|
+
);
|
|
433
|
+
}
|
|
434
|
+
/** Get the page count of a PDF buffer. */
|
|
435
|
+
async pageCount(buffer) {
|
|
436
|
+
const form = new FormData();
|
|
437
|
+
form.append("file", new Blob([toUint8(buffer)], { type: "application/pdf" }), "file.pdf");
|
|
438
|
+
const headers = await this.authHeaders();
|
|
439
|
+
const response = await fetch(`${this.baseUrl}/operations/page-count`, {
|
|
440
|
+
method: "POST",
|
|
441
|
+
headers,
|
|
442
|
+
body: form
|
|
443
|
+
});
|
|
444
|
+
if (!response.ok) {
|
|
445
|
+
const envelope = await response.json();
|
|
446
|
+
const { code, message } = extractError(envelope);
|
|
447
|
+
throw new DocmanError(message, response.status, code);
|
|
448
|
+
}
|
|
449
|
+
const json = await response.json();
|
|
450
|
+
return json.data.pages;
|
|
451
|
+
}
|
|
452
|
+
};
|
|
453
|
+
|
|
454
|
+
export {
|
|
455
|
+
DocmanClient
|
|
456
|
+
};
|
|
457
|
+
//# sourceMappingURL=chunk-DBVEE4WX.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/client.ts"],"sourcesContent":["import { DocmanError } from './errors.js'\nimport type {\n DocmanClientConfig,\n HtmlTemplate,\n CreateHtmlTemplateOptions,\n UpdateHtmlTemplateOptions,\n HtmlTemplateListQuery,\n PdfTemplate,\n PdfField,\n CreatePdfTemplateOptions,\n UpdatePdfTemplateOptions,\n PdfTemplateListQuery,\n TemplateGroup,\n CreateTemplateGroupOptions,\n UpdateTemplateGroupOptions,\n DocmanDocument,\n DocumentVersion,\n GenerateOptions,\n GenerateResult,\n ListQuery,\n ListResult,\n ListMeta,\n PageRange,\n SplitPart,\n} from './types.js'\n\n// ─── Internal ────────────────────────────────────────────\n\n/**\n * DOM's BlobPart requires ArrayBuffer (not SharedArrayBuffer).\n * Node.js Buffer is always backed by ArrayBuffer in practice, so this cast is safe.\n */\nfunction toUint8(b: Buffer | Uint8Array): Uint8Array<ArrayBuffer> {\n return b as unknown as Uint8Array<ArrayBuffer>\n}\n\nconst DEFAULT_RETRIES = 2\nconst DEFAULT_TIMEOUT_MS = 15_000\nconst TOKEN_BUFFER_SECONDS = 30\n\ninterface ApiEnvelope<T> {\n readonly success: boolean\n readonly data?: T\n readonly error?: { code: string; message: string } | string\n readonly meta?: ListMeta\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms))\n}\n\nfunction backoff(attempt: number): number {\n const base = Math.min(1000 * 2 ** attempt, 5_000)\n return base * (0.5 + Math.random() * 0.5)\n}\n\nfunction isTokenExpired(token: string, bufferSeconds = TOKEN_BUFFER_SECONDS): boolean {\n try {\n const parts = token.split('.')\n if (parts.length !== 3) return true\n const payload = JSON.parse(Buffer.from(parts[1], 'base64url').toString()) as { exp?: number }\n const now = Math.floor(Date.now() / 1000)\n return (payload.exp ?? 0) <= now + bufferSeconds\n } catch {\n return true\n }\n}\n\nfunction extractError(envelope: ApiEnvelope<unknown>): { code: string; message: string } {\n const err = envelope.error\n if (typeof err === 'object' && err !== null) return err\n return { code: 'REQUEST_ERROR', message: err ?? 'Request failed' }\n}\n\n// ─── DocmanClient ─────────────────────────────────────────\n\nexport class DocmanClient {\n private readonly baseUrl: string\n private readonly accessTokenFn?: () => Promise<string>\n private readonly internalKey?: string\n private readonly retries: number\n private readonly timeoutMs: number\n private cachedToken: string | null = null\n\n constructor(config: DocmanClientConfig) {\n this.baseUrl = config.baseUrl.replace(/\\/$/, '')\n this.accessTokenFn = config.accessTokenFn\n this.internalKey = config.internalKey\n this.retries = config.retries ?? DEFAULT_RETRIES\n this.timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS\n }\n\n /**\n * Create a client from environment variables.\n *\n * Reads DOCMAN_URL (injected automatically when you declare docman as an\n * internalDependency in catalog-info.yaml). Auth priority:\n * 1. BIO_CLIENT_ID + BIO_CLIENT_SECRET → client_credentials token\n * 2. INTERNAL_SERVICE_KEY → internal key header\n * 3. No auth → local dev / testing\n *\n * catalog-info.yaml:\n * spec:\n * internalDependencies:\n * - service: docman\n * port: 3000\n */\n static fromEnv(): DocmanClient {\n const baseUrl = process.env.DOCMAN_URL\n if (!baseUrl) {\n throw new DocmanError(\n 'DOCMAN_URL is not set. Add docman as an internalDependency in catalog-info.yaml',\n 500,\n 'CONFIG_ERROR',\n )\n }\n\n const clientId = process.env.BIO_CLIENT_ID\n const clientSecret = process.env.BIO_CLIENT_SECRET\n const bioIdUrl = process.env.BIO_ID_URL ?? 'https://bio.tawa.insureco.io'\n\n if (clientId && clientSecret) {\n return new DocmanClient({\n baseUrl,\n accessTokenFn: async () => {\n const res = await fetch(`${bioIdUrl}/api/oauth/token`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n grant_type: 'client_credentials',\n client_id: clientId,\n client_secret: clientSecret,\n }),\n })\n if (!res.ok) {\n throw new DocmanError('Failed to obtain Bio-ID access token', res.status, 'AUTH_ERROR')\n }\n const data = await res.json() as { access_token: string }\n return data.access_token\n },\n })\n }\n\n const internalKey = process.env.INTERNAL_SERVICE_KEY\n if (internalKey) {\n return new DocmanClient({ baseUrl, internalKey })\n }\n\n return new DocmanClient({ baseUrl })\n }\n\n // ─── Auth ────────────────────────────────────────────────\n\n private async authHeaders(): Promise<Record<string, string>> {\n if (this.accessTokenFn) {\n if (!this.cachedToken || isTokenExpired(this.cachedToken)) {\n this.cachedToken = await this.accessTokenFn()\n }\n return { Authorization: `Bearer ${this.cachedToken}` }\n }\n\n if (this.internalKey) {\n return { 'X-Internal-Key': this.internalKey }\n }\n\n return {}\n }\n\n // ─── Core fetch ──────────────────────────────────────────\n\n private async rawFetch<T>(\n method: string,\n path: string,\n body?: unknown,\n attempt = 0,\n ): Promise<ApiEnvelope<T>> {\n const headers = await this.authHeaders()\n const controller = new AbortController()\n const timer = setTimeout(() => controller.abort(), this.timeoutMs)\n\n let response: Response\n try {\n response = await fetch(`${this.baseUrl}${path}`, {\n method,\n headers: body !== undefined\n ? { ...headers, 'Content-Type': 'application/json' }\n : headers,\n body: body !== undefined ? JSON.stringify(body) : undefined,\n signal: controller.signal,\n })\n } catch (err) {\n clearTimeout(timer)\n if (attempt < this.retries) {\n await sleep(backoff(attempt))\n return this.rawFetch<T>(method, path, body, attempt + 1)\n }\n throw new DocmanError(`Network error: ${(err as Error).message}`, 0, 'NETWORK_ERROR')\n } finally {\n clearTimeout(timer)\n }\n\n if (response.status >= 500 && attempt < this.retries) {\n await sleep(backoff(attempt))\n return this.rawFetch<T>(method, path, body, attempt + 1)\n }\n\n const envelope = await response.json() as ApiEnvelope<T>\n\n if (!response.ok || !envelope.success) {\n const { code, message } = extractError(envelope)\n throw new DocmanError(message, response.status, code)\n }\n\n return envelope\n }\n\n private async fetchData<T>(method: string, path: string, body?: unknown): Promise<T> {\n const envelope = await this.rawFetch<T>(method, path, body)\n return envelope.data as T\n }\n\n private async fetchList<T>(path: string): Promise<ListResult<T>> {\n const envelope = await this.rawFetch<T[]>('GET', path)\n return {\n data: envelope.data ?? [],\n meta: envelope.meta ?? { total: 0, page: 1, limit: 20 },\n }\n }\n\n private buildQuery<T extends object>(params: T): string {\n const pairs = Object.entries(params)\n .filter(([, v]) => v !== undefined)\n .map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(String(v))}`)\n return pairs.length > 0 ? `?${pairs.join('&')}` : ''\n }\n\n /** Fetch with FormData body (multipart), return raw binary buffer. */\n private async fetchBinary(\n method: string,\n path: string,\n formData: FormData,\n attempt = 0,\n ): Promise<Buffer> {\n const headers = await this.authHeaders()\n const controller = new AbortController()\n const timer = setTimeout(() => controller.abort(), this.timeoutMs)\n\n let response: Response\n try {\n response = await fetch(`${this.baseUrl}${path}`, {\n method,\n headers,\n body: formData,\n signal: controller.signal,\n })\n } catch (err) {\n clearTimeout(timer)\n if (attempt < this.retries) {\n await sleep(backoff(attempt))\n return this.fetchBinary(method, path, formData, attempt + 1)\n }\n throw new DocmanError(`Network error: ${(err as Error).message}`, 0, 'NETWORK_ERROR')\n } finally {\n clearTimeout(timer)\n }\n\n if (response.status >= 500 && attempt < this.retries) {\n await sleep(backoff(attempt))\n return this.fetchBinary(method, path, formData, attempt + 1)\n }\n\n if (!response.ok) {\n const envelope = await response.json() as ApiEnvelope<never>\n const { code, message } = extractError(envelope)\n throw new DocmanError(message, response.status, code)\n }\n\n return Buffer.from(await response.arrayBuffer())\n }\n\n /** POST multipart form and parse the JSON response envelope. */\n private async fetchMultipartJson<T>(path: string, formData: FormData): Promise<T> {\n const headers = await this.authHeaders()\n\n const response = await fetch(`${this.baseUrl}${path}`, {\n method: 'POST',\n headers,\n body: formData,\n })\n\n const envelope = await response.json() as ApiEnvelope<T>\n if (!response.ok || !envelope.success) {\n const { code, message } = extractError(envelope)\n throw new DocmanError(message, response.status, code)\n }\n\n return envelope.data as T\n }\n\n /** PUT multipart form and parse the JSON response envelope. */\n private async putMultipartJson<T>(path: string, formData: FormData): Promise<T> {\n const headers = await this.authHeaders()\n\n const response = await fetch(`${this.baseUrl}${path}`, {\n method: 'PUT',\n headers,\n body: formData,\n })\n\n const envelope = await response.json() as ApiEnvelope<T>\n if (!response.ok || !envelope.success) {\n const { code, message } = extractError(envelope)\n throw new DocmanError(message, response.status, code)\n }\n\n return envelope.data as T\n }\n\n // ─── HTML Templates ──────────────────────────────────────\n\n async createHtmlTemplate(options: CreateHtmlTemplateOptions): Promise<HtmlTemplate> {\n return this.fetchData<HtmlTemplate>('POST', '/templates/html', options)\n }\n\n async listHtmlTemplates(query: HtmlTemplateListQuery = {}): Promise<ListResult<HtmlTemplate>> {\n return this.fetchList<HtmlTemplate>(`/templates/html${this.buildQuery(query)}`)\n }\n\n async getHtmlTemplate(id: string): Promise<HtmlTemplate> {\n return this.fetchData<HtmlTemplate>('GET', `/templates/html/${encodeURIComponent(id)}`)\n }\n\n async updateHtmlTemplate(id: string, options: UpdateHtmlTemplateOptions): Promise<HtmlTemplate> {\n return this.fetchData<HtmlTemplate>('PUT', `/templates/html/${encodeURIComponent(id)}`, options)\n }\n\n async deleteHtmlTemplate(id: string): Promise<HtmlTemplate> {\n return this.fetchData<HtmlTemplate>('DELETE', `/templates/html/${encodeURIComponent(id)}`)\n }\n\n // ─── PDF Templates ───────────────────────────────────────\n\n /**\n * Upload a PDF form template.\n * @param file Raw PDF bytes (Buffer or Uint8Array)\n * @param options Name, description, and optional coordinates/isSystem flags\n */\n async uploadPdfTemplate(\n file: Buffer | Uint8Array,\n options: CreatePdfTemplateOptions = {},\n ): Promise<PdfTemplate> {\n const form = new FormData()\n const filename = options.name ?? 'template.pdf'\n form.append('file', new Blob([toUint8(file)], { type: 'application/pdf' }), filename)\n if (options.name) form.append('name', options.name)\n if (options.description) form.append('description', options.description)\n if (options.coordinates) form.append('coordinates', JSON.stringify(options.coordinates))\n if (options.isSystem !== undefined) form.append('isSystem', String(options.isSystem))\n\n return this.fetchMultipartJson<PdfTemplate>('/templates/pdf', form)\n }\n\n async listPdfTemplates(query: PdfTemplateListQuery = {}): Promise<ListResult<PdfTemplate>> {\n return this.fetchList<PdfTemplate>(`/templates/pdf${this.buildQuery(query)}`)\n }\n\n async getPdfTemplate(id: string): Promise<PdfTemplate> {\n return this.fetchData<PdfTemplate>('GET', `/templates/pdf/${encodeURIComponent(id)}`)\n }\n\n async getPdfTemplateFields(id: string): Promise<readonly PdfField[]> {\n return this.fetchData<PdfField[]>('GET', `/templates/pdf/${encodeURIComponent(id)}/fields`)\n }\n\n async getPdfTemplateDownloadUrl(id: string): Promise<string> {\n const data = await this.fetchData<{ url: string }>('GET', `/templates/pdf/${encodeURIComponent(id)}/download`)\n return data.url\n }\n\n /**\n * Update a PDF template's metadata, and optionally replace the PDF file.\n * @param file If provided, replaces the stored PDF and re-extracts form fields\n */\n async updatePdfTemplate(\n id: string,\n options: UpdatePdfTemplateOptions,\n file?: Buffer | Uint8Array,\n ): Promise<PdfTemplate> {\n if (file) {\n const form = new FormData()\n form.append('file', new Blob([toUint8(file)], { type: 'application/pdf' }), 'template.pdf')\n if (options.name) form.append('name', options.name)\n if (options.description) form.append('description', options.description)\n if (options.coordinates) form.append('coordinates', JSON.stringify(options.coordinates))\n\n return this.putMultipartJson<PdfTemplate>(`/templates/pdf/${encodeURIComponent(id)}`, form)\n }\n\n return this.fetchData<PdfTemplate>('PUT', `/templates/pdf/${encodeURIComponent(id)}`, options)\n }\n\n async deletePdfTemplate(id: string): Promise<PdfTemplate> {\n return this.fetchData<PdfTemplate>('DELETE', `/templates/pdf/${encodeURIComponent(id)}`)\n }\n\n // ─── Template Groups ─────────────────────────────────────\n\n async createTemplateGroup(options: CreateTemplateGroupOptions): Promise<TemplateGroup> {\n return this.fetchData<TemplateGroup>('POST', '/template-groups', options)\n }\n\n async listTemplateGroups(query: ListQuery = {}): Promise<ListResult<TemplateGroup>> {\n return this.fetchList<TemplateGroup>(`/template-groups${this.buildQuery(query)}`)\n }\n\n async getTemplateGroup(id: string): Promise<TemplateGroup> {\n return this.fetchData<TemplateGroup>('GET', `/template-groups/${encodeURIComponent(id)}`)\n }\n\n async updateTemplateGroup(id: string, options: UpdateTemplateGroupOptions): Promise<TemplateGroup> {\n return this.fetchData<TemplateGroup>('PUT', `/template-groups/${encodeURIComponent(id)}`, options)\n }\n\n async deleteTemplateGroup(id: string): Promise<void> {\n await this.fetchData<{ deleted: boolean }>('DELETE', `/template-groups/${encodeURIComponent(id)}`)\n }\n\n // ─── Document Generation ─────────────────────────────────\n\n /**\n * Generate a document and store it in S3.\n * Returns a presigned download URL and a public share URL.\n */\n async generate(options: GenerateOptions): Promise<GenerateResult> {\n return this.fetchData<GenerateResult>('POST', '/documents/generate', {\n templateIds: options.templateIds,\n templateData: options.data,\n name: options.name,\n description: options.description,\n })\n }\n\n /**\n * Generate a document and stream the PDF buffer directly.\n * Nothing is stored — useful for previews or on-the-fly delivery.\n */\n async generatePassthrough(options: GenerateOptions): Promise<Buffer> {\n const headers = await this.authHeaders()\n const controller = new AbortController()\n const timer = setTimeout(() => controller.abort(), this.timeoutMs)\n\n let response: Response\n try {\n response = await fetch(`${this.baseUrl}/documents/generate/passthrough`, {\n method: 'POST',\n headers: { ...headers, 'Content-Type': 'application/json' },\n body: JSON.stringify({\n templateIds: options.templateIds,\n templateData: options.data,\n name: options.name,\n description: options.description,\n }),\n signal: controller.signal,\n })\n } catch (err) {\n clearTimeout(timer)\n throw new DocmanError(`Network error: ${(err as Error).message}`, 0, 'NETWORK_ERROR')\n } finally {\n clearTimeout(timer)\n }\n\n if (!response.ok) {\n const envelope = await response.json() as ApiEnvelope<never>\n const { code, message } = extractError(envelope)\n throw new DocmanError(message, response.status, code)\n }\n\n return Buffer.from(await response.arrayBuffer())\n }\n\n async listDocuments(query: ListQuery = {}): Promise<ListResult<DocmanDocument>> {\n return this.fetchList<DocmanDocument>(`/documents${this.buildQuery(query)}`)\n }\n\n async getDocument(id: string): Promise<DocmanDocument> {\n return this.fetchData<DocmanDocument>('GET', `/documents/${encodeURIComponent(id)}`)\n }\n\n /** Get a presigned S3 download URL for a stored document (1-hour TTL). */\n async downloadUrl(id: string): Promise<string> {\n const data = await this.fetchData<{ url: string }>('GET', `/documents/${encodeURIComponent(id)}/download`)\n return data.url\n }\n\n async getVersions(id: string): Promise<readonly DocumentVersion[]> {\n return this.fetchData<DocumentVersion[]>('GET', `/documents/${encodeURIComponent(id)}/versions`)\n }\n\n /** Re-render a stored document using the original template data. */\n async regenerate(id: string): Promise<GenerateResult> {\n return this.fetchData<GenerateResult>('POST', `/documents/${encodeURIComponent(id)}/regenerate`)\n }\n\n // ─── PDF Operations ──────────────────────────────────────\n\n /**\n * Merge two or more PDF buffers into a single PDF.\n * Returns the merged PDF as a Buffer.\n */\n async merge(buffers: readonly (Buffer | Uint8Array)[]): Promise<Buffer> {\n if (buffers.length < 2) {\n throw new DocmanError('At least 2 PDF buffers are required for merge', 400, 'VALIDATION_ERROR')\n }\n const form = new FormData()\n for (const buf of buffers) {\n form.append('files', new Blob([toUint8(buf)], { type: 'application/pdf' }), 'file.pdf')\n }\n return this.fetchBinary('POST', '/operations/merge', form)\n }\n\n /**\n * Split a PDF into parts by page ranges.\n * Returns an array of SplitPart with buffer, range, and size info.\n */\n async split(buffer: Buffer | Uint8Array, ranges: readonly PageRange[]): Promise<readonly SplitPart[]> {\n if (ranges.length === 0) {\n throw new DocmanError('At least 1 page range is required', 400, 'VALIDATION_ERROR')\n }\n\n const form = new FormData()\n form.append('file', new Blob([toUint8(buffer)], { type: 'application/pdf' }), 'file.pdf')\n form.append('ranges', JSON.stringify(ranges))\n\n const headers = await this.authHeaders()\n const response = await fetch(`${this.baseUrl}/operations/split`, {\n method: 'POST',\n headers,\n body: form,\n })\n\n if (!response.ok) {\n const envelope = await response.json() as ApiEnvelope<never>\n const { code, message } = extractError(envelope)\n throw new DocmanError(message, response.status, code)\n }\n\n const contentType = response.headers.get('content-type') ?? ''\n\n if (contentType.includes('application/json')) {\n type SplitResponse = {\n success: true\n data: Array<{ index: number; range: PageRange; base64: string; sizeBytes: number }>\n }\n const json = await response.json() as SplitResponse\n return json.data.map((part) => ({\n index: part.index,\n range: part.range,\n buffer: Buffer.from(part.base64, 'base64'),\n sizeBytes: part.sizeBytes,\n }))\n }\n\n // Single range — binary response\n const buf = Buffer.from(await response.arrayBuffer())\n return [{ index: 0, range: ranges[0], buffer: buf, sizeBytes: buf.length }]\n }\n\n /**\n * Batch-introspect PDF form fields for multiple templates.\n * Returns a map of templateId → field list.\n */\n async introspectFields(templateIds: readonly string[]): Promise<Record<string, readonly PdfField[]>> {\n return this.fetchData<Record<string, readonly PdfField[]>>(\n 'POST',\n '/templates/pdf/fields',\n { templateIds },\n )\n }\n\n /** Get the page count of a PDF buffer. */\n async pageCount(buffer: Buffer | Uint8Array): Promise<number> {\n const form = new FormData()\n form.append('file', new Blob([toUint8(buffer)], { type: 'application/pdf' }), 'file.pdf')\n\n const headers = await this.authHeaders()\n const response = await fetch(`${this.baseUrl}/operations/page-count`, {\n method: 'POST',\n headers,\n body: form,\n })\n\n if (!response.ok) {\n const envelope = await response.json() as ApiEnvelope<never>\n const { code, message } = extractError(envelope)\n throw new DocmanError(message, response.status, code)\n }\n\n const json = await response.json() as { success: true; data: { pages: number } }\n return json.data.pages\n }\n}\n"],"mappings":";;;;;AAgCA,SAAS,QAAQ,GAAiD;AAChE,SAAO;AACT;AAEA,IAAM,kBAAkB;AACxB,IAAM,qBAAqB;AAC3B,IAAM,uBAAuB;AAS7B,SAAS,MAAM,IAA2B;AACxC,SAAO,IAAI,QAAQ,CAAC,YAAY,WAAW,SAAS,EAAE,CAAC;AACzD;AAEA,SAAS,QAAQ,S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AA8C;AAC5D,UAAM,OAAO,IAAI,SAAS;AAC1B,SAAK,OAAO,QAAQ,IAAI,KAAK,CAAC,QAAQ,MAAM,CAAC,GAAG,EAAE,MAAM,kBAAkB,CAAC,GAAG,UAAU;AAExF,UAAM,UAAU,MAAM,KAAK,YAAY;AACvC,UAAM,WAAW,MAAM,MAAM,GAAG,KAAK,OAAO,0BAA0B;AAAA,MACpE,QAAQ;AAAA,MACR;AAAA,MACA,MAAM;AAAA,IACR,CAAC;AAED,QAAI,CAAC,SAAS,IAAI;AAChB,YAAM,WAAW,MAAM,SAAS,KAAK;AACrC,YAAM,EAAE,MAAM,QAAQ,IAAI,aAAa,QAAQ;AAC/C,YAAM,IAAI,YAAY,SAAS,SAAS,QAAQ,IAAI;AAAA,IACtD;AAEA,UAAM,OAAO,MAAM,SAAS,KAAK;AACjC,WAAO,KAAK,KAAK;AAAA,EACnB;AACF;","names":[]}
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import { D as DocmanClientConfig, C as CreateHtmlTemplateOptions, H as HtmlTemplate, f as HtmlTemplateListQuery, h as ListResult, U as UpdateHtmlTemplateOptions, a as CreatePdfTemplateOptions, j as PdfTemplate, k as PdfTemplateListQuery, i as PdfField, o as UpdatePdfTemplateOptions, b as CreateTemplateGroupOptions, m as TemplateGroup, g as ListQuery, p as UpdateTemplateGroupOptions, G as GenerateOptions, e as GenerateResult, c as DocmanDocument, d as DocumentVersion, P as PageRange, l as SplitPart } from './types-DvQ8gX3k.cjs';
|
|
2
|
+
|
|
3
|
+
declare class DocmanClient {
|
|
4
|
+
private readonly baseUrl;
|
|
5
|
+
private readonly accessTokenFn?;
|
|
6
|
+
private readonly internalKey?;
|
|
7
|
+
private readonly retries;
|
|
8
|
+
private readonly timeoutMs;
|
|
9
|
+
private cachedToken;
|
|
10
|
+
constructor(config: DocmanClientConfig);
|
|
11
|
+
/**
|
|
12
|
+
* Create a client from environment variables.
|
|
13
|
+
*
|
|
14
|
+
* Reads DOCMAN_URL (injected automatically when you declare docman as an
|
|
15
|
+
* internalDependency in catalog-info.yaml). Auth priority:
|
|
16
|
+
* 1. BIO_CLIENT_ID + BIO_CLIENT_SECRET → client_credentials token
|
|
17
|
+
* 2. INTERNAL_SERVICE_KEY → internal key header
|
|
18
|
+
* 3. No auth → local dev / testing
|
|
19
|
+
*
|
|
20
|
+
* catalog-info.yaml:
|
|
21
|
+
* spec:
|
|
22
|
+
* internalDependencies:
|
|
23
|
+
* - service: docman
|
|
24
|
+
* port: 3000
|
|
25
|
+
*/
|
|
26
|
+
static fromEnv(): DocmanClient;
|
|
27
|
+
private authHeaders;
|
|
28
|
+
private rawFetch;
|
|
29
|
+
private fetchData;
|
|
30
|
+
private fetchList;
|
|
31
|
+
private buildQuery;
|
|
32
|
+
/** Fetch with FormData body (multipart), return raw binary buffer. */
|
|
33
|
+
private fetchBinary;
|
|
34
|
+
/** POST multipart form and parse the JSON response envelope. */
|
|
35
|
+
private fetchMultipartJson;
|
|
36
|
+
/** PUT multipart form and parse the JSON response envelope. */
|
|
37
|
+
private putMultipartJson;
|
|
38
|
+
createHtmlTemplate(options: CreateHtmlTemplateOptions): Promise<HtmlTemplate>;
|
|
39
|
+
listHtmlTemplates(query?: HtmlTemplateListQuery): Promise<ListResult<HtmlTemplate>>;
|
|
40
|
+
getHtmlTemplate(id: string): Promise<HtmlTemplate>;
|
|
41
|
+
updateHtmlTemplate(id: string, options: UpdateHtmlTemplateOptions): Promise<HtmlTemplate>;
|
|
42
|
+
deleteHtmlTemplate(id: string): Promise<HtmlTemplate>;
|
|
43
|
+
/**
|
|
44
|
+
* Upload a PDF form template.
|
|
45
|
+
* @param file Raw PDF bytes (Buffer or Uint8Array)
|
|
46
|
+
* @param options Name, description, and optional coordinates/isSystem flags
|
|
47
|
+
*/
|
|
48
|
+
uploadPdfTemplate(file: Buffer | Uint8Array, options?: CreatePdfTemplateOptions): Promise<PdfTemplate>;
|
|
49
|
+
listPdfTemplates(query?: PdfTemplateListQuery): Promise<ListResult<PdfTemplate>>;
|
|
50
|
+
getPdfTemplate(id: string): Promise<PdfTemplate>;
|
|
51
|
+
getPdfTemplateFields(id: string): Promise<readonly PdfField[]>;
|
|
52
|
+
getPdfTemplateDownloadUrl(id: string): Promise<string>;
|
|
53
|
+
/**
|
|
54
|
+
* Update a PDF template's metadata, and optionally replace the PDF file.
|
|
55
|
+
* @param file If provided, replaces the stored PDF and re-extracts form fields
|
|
56
|
+
*/
|
|
57
|
+
updatePdfTemplate(id: string, options: UpdatePdfTemplateOptions, file?: Buffer | Uint8Array): Promise<PdfTemplate>;
|
|
58
|
+
deletePdfTemplate(id: string): Promise<PdfTemplate>;
|
|
59
|
+
createTemplateGroup(options: CreateTemplateGroupOptions): Promise<TemplateGroup>;
|
|
60
|
+
listTemplateGroups(query?: ListQuery): Promise<ListResult<TemplateGroup>>;
|
|
61
|
+
getTemplateGroup(id: string): Promise<TemplateGroup>;
|
|
62
|
+
updateTemplateGroup(id: string, options: UpdateTemplateGroupOptions): Promise<TemplateGroup>;
|
|
63
|
+
deleteTemplateGroup(id: string): Promise<void>;
|
|
64
|
+
/**
|
|
65
|
+
* Generate a document and store it in S3.
|
|
66
|
+
* Returns a presigned download URL and a public share URL.
|
|
67
|
+
*/
|
|
68
|
+
generate(options: GenerateOptions): Promise<GenerateResult>;
|
|
69
|
+
/**
|
|
70
|
+
* Generate a document and stream the PDF buffer directly.
|
|
71
|
+
* Nothing is stored — useful for previews or on-the-fly delivery.
|
|
72
|
+
*/
|
|
73
|
+
generatePassthrough(options: GenerateOptions): Promise<Buffer>;
|
|
74
|
+
listDocuments(query?: ListQuery): Promise<ListResult<DocmanDocument>>;
|
|
75
|
+
getDocument(id: string): Promise<DocmanDocument>;
|
|
76
|
+
/** Get a presigned S3 download URL for a stored document (1-hour TTL). */
|
|
77
|
+
downloadUrl(id: string): Promise<string>;
|
|
78
|
+
getVersions(id: string): Promise<readonly DocumentVersion[]>;
|
|
79
|
+
/** Re-render a stored document using the original template data. */
|
|
80
|
+
regenerate(id: string): Promise<GenerateResult>;
|
|
81
|
+
/**
|
|
82
|
+
* Merge two or more PDF buffers into a single PDF.
|
|
83
|
+
* Returns the merged PDF as a Buffer.
|
|
84
|
+
*/
|
|
85
|
+
merge(buffers: readonly (Buffer | Uint8Array)[]): Promise<Buffer>;
|
|
86
|
+
/**
|
|
87
|
+
* Split a PDF into parts by page ranges.
|
|
88
|
+
* Returns an array of SplitPart with buffer, range, and size info.
|
|
89
|
+
*/
|
|
90
|
+
split(buffer: Buffer | Uint8Array, ranges: readonly PageRange[]): Promise<readonly SplitPart[]>;
|
|
91
|
+
/**
|
|
92
|
+
* Batch-introspect PDF form fields for multiple templates.
|
|
93
|
+
* Returns a map of templateId → field list.
|
|
94
|
+
*/
|
|
95
|
+
introspectFields(templateIds: readonly string[]): Promise<Record<string, readonly PdfField[]>>;
|
|
96
|
+
/** Get the page count of a PDF buffer. */
|
|
97
|
+
pageCount(buffer: Buffer | Uint8Array): Promise<number>;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
export { DocmanClient as D };
|