@format.dev/client 0.0.0 → 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 +26 -20
- package/dist/index.cjs +309 -0
- package/dist/index.d.cts +148 -0
- package/dist/index.d.cts.map +1 -0
- package/dist/index.d.mts +148 -0
- package/dist/index.d.mts.map +1 -0
- package/dist/index.mjs +309 -0
- package/dist/index.mjs.map +1 -0
- package/dist/web.cjs +288 -0
- package/dist/web.d.cts +119 -0
- package/dist/web.d.cts.map +1 -0
- package/dist/web.d.mts +119 -0
- package/dist/web.d.mts.map +1 -0
- package/dist/web.mjs +287 -0
- package/dist/web.mjs.map +1 -0
- package/package.json +73 -34
- package/index.d.ts +0 -2
- package/index.js +0 -3
package/README.md
CHANGED
|
@@ -1,32 +1,38 @@
|
|
|
1
1
|
# @format.dev/client
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The JavaScript client for the Format API. Send a document's HTML and assets, and receive the rendered PDF.
|
|
4
4
|
|
|
5
|
-
|
|
6
|
-
package: it contains no implementation, and installing it gets you an empty
|
|
7
|
-
module.
|
|
5
|
+
See the [client documentation](https://format.dev/docs/api-reference/api-client) for options, asset handling and more examples.
|
|
8
6
|
|
|
9
|
-
##
|
|
7
|
+
## Installation
|
|
10
8
|
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
workflow rather than through a token somebody holds.
|
|
9
|
+
```sh
|
|
10
|
+
npm install @format.dev/client
|
|
11
|
+
```
|
|
15
12
|
|
|
16
|
-
|
|
13
|
+
## Usage
|
|
17
14
|
|
|
18
|
-
|
|
15
|
+
```ts
|
|
16
|
+
import { FormatClient } from '@format.dev/client'
|
|
17
|
+
import { invoice } from './_generated'
|
|
19
18
|
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
availability. That is why the deprecation warning is there.
|
|
19
|
+
const client = new FormatClient({ apiKey: 'fmt_...' })
|
|
20
|
+
const doc = await invoice.render({ customerName: 'Ada Lovelace' })
|
|
23
21
|
|
|
24
|
-
|
|
25
|
-
|
|
22
|
+
const res = await client.pdf(doc)
|
|
23
|
+
await res.toFile('invoice.pdf')
|
|
24
|
+
```
|
|
26
25
|
|
|
27
|
-
|
|
26
|
+
The example uses a compiled renderer in `./_generated`. You can also pass an HTML string to `pdf()`. When no `apiKey` is passed, the client reads the `FORMAT_API_KEY` environment variable.
|
|
28
27
|
|
|
29
|
-
|
|
30
|
-
- https://github.com/format-hq/format-js
|
|
28
|
+
## In the browser
|
|
31
29
|
|
|
32
|
-
|
|
30
|
+
```ts
|
|
31
|
+
import { FormatClient } from '@format.dev/client/web'
|
|
32
|
+
|
|
33
|
+
const client = new FormatClient({ apiKey })
|
|
34
|
+
const res = await client.pdf(doc)
|
|
35
|
+
const pdf = await res.blob()
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
When using the web client in a browser, pass your API key explicitly. That key is visible to anyone using the page. To keep it private, make requests from your server.
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,309 @@
|
|
|
1
|
+
let node_stream = require("node:stream");
|
|
2
|
+
let formdata_node = require("formdata-node");
|
|
3
|
+
let form_data_encoder = require("form-data-encoder");
|
|
4
|
+
let stream = require("stream");
|
|
5
|
+
|
|
6
|
+
//#region package.json
|
|
7
|
+
var version = "0.1.0";
|
|
8
|
+
|
|
9
|
+
//#endregion
|
|
10
|
+
//#region src/constants.ts
|
|
11
|
+
const REGION_MAP = { GLOBAL: "https://api.format.dev" };
|
|
12
|
+
const API_PREFIX = "/v1";
|
|
13
|
+
const CLIENT_IDENTIFIER = `@format.dev/client/${version}`;
|
|
14
|
+
const DEFAULTS = { baseUrl: REGION_MAP.GLOBAL };
|
|
15
|
+
|
|
16
|
+
//#endregion
|
|
17
|
+
//#region src/helpers.ts
|
|
18
|
+
function isWebReadable(x) {
|
|
19
|
+
return typeof globalThis.ReadableStream !== "undefined" && x != null && typeof x.getReader === "function";
|
|
20
|
+
}
|
|
21
|
+
function isBlobLike(x) {
|
|
22
|
+
return x != null && typeof x === "object" && typeof x.arrayBuffer === "function" && typeof x.stream === "function" && typeof x.size === "number" && typeof x.type === "string";
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* The API origin requests go to. `environmentBaseUrl` is the `FORMAT_BASE_URL`
|
|
26
|
+
* the Node build reads from its environment. The web build does not read
|
|
27
|
+
* environment variables, so it passes nothing.
|
|
28
|
+
*/
|
|
29
|
+
function resolveBaseUrl(opts, environmentBaseUrl) {
|
|
30
|
+
return (opts.baseUrl ?? (opts.region ? REGION_MAP[opts.region] : void 0) ?? environmentBaseUrl ?? DEFAULTS.baseUrl).replace(/\/+$/, "");
|
|
31
|
+
}
|
|
32
|
+
/** The render endpoint under an API origin. The origin carries no version, so the prefix is added here. */
|
|
33
|
+
function renderUrl(baseUrl) {
|
|
34
|
+
return `${baseUrl}${API_PREFIX}/render`;
|
|
35
|
+
}
|
|
36
|
+
/** The `tags` form field: trimmed, empty tags dropped, duplicates removed, sent as a JSON array. */
|
|
37
|
+
function serializeTags(tags) {
|
|
38
|
+
return JSON.stringify(Array.from(new Set(tags.map((t) => t.trim()).filter(Boolean))));
|
|
39
|
+
}
|
|
40
|
+
function parseFilenameFromContentDisposition(header) {
|
|
41
|
+
if (!header) return;
|
|
42
|
+
const mExt = header.match(/filename\*\s*=\s*([^;]+)/i);
|
|
43
|
+
if (mExt) {
|
|
44
|
+
const v = mExt[1].trim();
|
|
45
|
+
const m = /^([A-Za-z0-9._-]+)''(.+)$/.exec(v);
|
|
46
|
+
if (m) {
|
|
47
|
+
const value = stripQuotes(m[2]);
|
|
48
|
+
try {
|
|
49
|
+
return decodeURIComponent(value);
|
|
50
|
+
} catch {
|
|
51
|
+
return value;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
const mQuoted = header.match(/filename\s*=\s*"([^"]*)"/i);
|
|
56
|
+
if (mQuoted) return mQuoted[1];
|
|
57
|
+
const mBare = header.match(/filename\s*=\s*([^;]+)/i);
|
|
58
|
+
if (mBare) return mBare[1].trim();
|
|
59
|
+
}
|
|
60
|
+
function parseContentType(header) {
|
|
61
|
+
if (!header) return;
|
|
62
|
+
const [mime] = header.split(";", 1);
|
|
63
|
+
return mime?.trim().toLowerCase();
|
|
64
|
+
}
|
|
65
|
+
async function safeJson(body) {
|
|
66
|
+
try {
|
|
67
|
+
return JSON.parse(body);
|
|
68
|
+
} catch {
|
|
69
|
+
return { raw: body };
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
function timeoutSignal(ms, reason = /* @__PURE__ */ new Error("Timeout")) {
|
|
73
|
+
if (AbortSignal.timeout) return AbortSignal.timeout(ms);
|
|
74
|
+
const ac = new AbortController();
|
|
75
|
+
setTimeout(() => ac.abort(reason), ms);
|
|
76
|
+
return ac.signal;
|
|
77
|
+
}
|
|
78
|
+
function anySignal(signals) {
|
|
79
|
+
if (AbortSignal.any) return AbortSignal.any(signals);
|
|
80
|
+
const ac = new AbortController();
|
|
81
|
+
const aborted = signals.find((signal) => signal.aborted);
|
|
82
|
+
if (aborted) {
|
|
83
|
+
ac.abort(aborted.reason);
|
|
84
|
+
return ac.signal;
|
|
85
|
+
}
|
|
86
|
+
const onAbort = (event) => {
|
|
87
|
+
for (const signal of signals) signal.removeEventListener("abort", onAbort);
|
|
88
|
+
ac.abort(event.target.reason);
|
|
89
|
+
};
|
|
90
|
+
for (const s of signals) s.addEventListener("abort", onAbort, { once: true });
|
|
91
|
+
return ac.signal;
|
|
92
|
+
}
|
|
93
|
+
function getAbortErrorOrElse(signal, cause) {
|
|
94
|
+
return signal?.aborted ? signal.reason instanceof Error ? signal.reason : /* @__PURE__ */ new Error("Aborted with unknown reason") : new Error(cause instanceof Error ? cause.message : "Unknown internal error", { cause });
|
|
95
|
+
}
|
|
96
|
+
function concatUint8Array(parts, total) {
|
|
97
|
+
if (parts.length === 1 && parts[0].byteLength === total) return parts[0];
|
|
98
|
+
let offset = 0;
|
|
99
|
+
const out = new Uint8Array(total);
|
|
100
|
+
for (const p of parts) {
|
|
101
|
+
out.set(p, offset);
|
|
102
|
+
offset += p.byteLength;
|
|
103
|
+
}
|
|
104
|
+
return out;
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* The key a client sends, or a thrown error naming how to supply one.
|
|
108
|
+
* `environmentApiKey` is the `FORMAT_API_KEY` the Node build reads from its
|
|
109
|
+
* environment. The web build passes nothing, so its callers have to
|
|
110
|
+
* pass `apiKey` explicitly.
|
|
111
|
+
*/
|
|
112
|
+
function resolveApiKey(explicitApiKey, environmentApiKey, howToSupply) {
|
|
113
|
+
if (explicitApiKey) return explicitApiKey;
|
|
114
|
+
if (environmentApiKey) return environmentApiKey;
|
|
115
|
+
throw new Error(`Format API key is required. ${howToSupply ?? "Pass `apiKey` explicitly."}`);
|
|
116
|
+
}
|
|
117
|
+
function stripQuotes(input) {
|
|
118
|
+
if (input.length >= 2 && input[0] === "\"" && input[input.length - 1] === "\"") return input.slice(1, -1);
|
|
119
|
+
return input;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
//#endregion
|
|
123
|
+
//#region src/node-assets.ts
|
|
124
|
+
function toFileLike(webStream, name, type) {
|
|
125
|
+
return {
|
|
126
|
+
name,
|
|
127
|
+
type,
|
|
128
|
+
[Symbol.toStringTag]: "File",
|
|
129
|
+
stream() {
|
|
130
|
+
return webStream;
|
|
131
|
+
}
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
function isNodeReadable(x) {
|
|
135
|
+
return x != null && typeof x.pipe === "function" && typeof x.read === "function";
|
|
136
|
+
}
|
|
137
|
+
/**
|
|
138
|
+
* Normalize assets into something FormData#set accepts (File or File-like)
|
|
139
|
+
* whilst retaining multipart streaming where possible
|
|
140
|
+
*/
|
|
141
|
+
function assetsToFormDataValue(input, filename = "assets.zip", mime = "application/zip") {
|
|
142
|
+
if (isBlobLike(input)) return new formdata_node.File([input], filename, { type: mime });
|
|
143
|
+
if (input instanceof Uint8Array || input instanceof ArrayBuffer || Buffer?.isBuffer?.(input)) return new formdata_node.File([input], filename, { type: mime });
|
|
144
|
+
if (isWebReadable(input)) return toFileLike(input, filename, mime);
|
|
145
|
+
if (isNodeReadable(input)) return toFileLike(stream.Readable.toWeb(input), filename, mime);
|
|
146
|
+
throw new TypeError("Unsupported assets type");
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
//#endregion
|
|
150
|
+
//#region src/error.ts
|
|
151
|
+
/**
|
|
152
|
+
* Thrown when the Format API returns a non-2xx response. Contains the HTTP status code and parsed error body.
|
|
153
|
+
*/
|
|
154
|
+
var FormatError = class extends Error {
|
|
155
|
+
constructor(status, detail) {
|
|
156
|
+
super(`Format API: Error ${status}`);
|
|
157
|
+
this.status = status;
|
|
158
|
+
this.detail = detail;
|
|
159
|
+
}
|
|
160
|
+
};
|
|
161
|
+
|
|
162
|
+
//#endregion
|
|
163
|
+
//#region src/response.ts
|
|
164
|
+
/**
|
|
165
|
+
* The error a non-2xx response becomes.
|
|
166
|
+
*
|
|
167
|
+
* Reads at most about 1MB of the body, so an unexpectedly large error response
|
|
168
|
+
* cannot exhaust memory, and parses it as JSON where it can. A body that is not
|
|
169
|
+
* JSON arrives as `{ raw: body }`.
|
|
170
|
+
*/
|
|
171
|
+
async function formatErrorFrom(res) {
|
|
172
|
+
const status = res.status ?? 0;
|
|
173
|
+
let size = 0;
|
|
174
|
+
const limit = 1e6;
|
|
175
|
+
const chunks = [];
|
|
176
|
+
const reader = res.body?.getReader();
|
|
177
|
+
try {
|
|
178
|
+
if (reader) while (size < limit) {
|
|
179
|
+
const { done, value } = await reader.read();
|
|
180
|
+
if (done || !value?.length) break;
|
|
181
|
+
chunks.push(value);
|
|
182
|
+
size += value.byteLength;
|
|
183
|
+
}
|
|
184
|
+
} finally {
|
|
185
|
+
try {
|
|
186
|
+
await reader?.cancel();
|
|
187
|
+
} catch {}
|
|
188
|
+
}
|
|
189
|
+
const buf = concatUint8Array(chunks, size);
|
|
190
|
+
return new FormatError(status, await safeJson(new TextDecoder("utf-8", { fatal: false }).decode(buf)));
|
|
191
|
+
}
|
|
192
|
+
/** What a successful response says about the PDF, read from its headers. */
|
|
193
|
+
function responseDetails(res) {
|
|
194
|
+
const rawContentLength = res.headers.get("content-length");
|
|
195
|
+
const contentType = parseContentType(res.headers.get("content-type"));
|
|
196
|
+
return {
|
|
197
|
+
filename: parseFilenameFromContentDisposition(res.headers.get("content-disposition")),
|
|
198
|
+
contentLength: rawContentLength ? parseInt(rawContentLength) : void 0,
|
|
199
|
+
contentType,
|
|
200
|
+
traceparent: res.headers.get("traceparent") || void 0,
|
|
201
|
+
isPdf: contentType === "application/pdf"
|
|
202
|
+
};
|
|
203
|
+
}
|
|
204
|
+
/**
|
|
205
|
+
* Assign to the Response itself: a Proxy breaks the native methods' brand
|
|
206
|
+
* checks in browsers and Node 24.
|
|
207
|
+
*/
|
|
208
|
+
function augmentResponse(res) {
|
|
209
|
+
return Object.assign(res, responseDetails(res));
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
//#endregion
|
|
213
|
+
//#region src/document-assets.ts
|
|
214
|
+
/**
|
|
215
|
+
* A compiled document cannot cancel its asset lookup. Reject promptly on abort
|
|
216
|
+
* and cancel any stream that arrives afterwards so its source can release it.
|
|
217
|
+
*/
|
|
218
|
+
async function documentAssets(doc, signal) {
|
|
219
|
+
if (signal.aborted) throw getAbortErrorOrElse(signal);
|
|
220
|
+
const pending = doc.getAssetsWebStream();
|
|
221
|
+
return new Promise((resolve, reject) => {
|
|
222
|
+
const onAbort = () => {
|
|
223
|
+
signal.removeEventListener("abort", onAbort);
|
|
224
|
+
reject(getAbortErrorOrElse(signal));
|
|
225
|
+
};
|
|
226
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
227
|
+
if (signal.aborted) onAbort();
|
|
228
|
+
pending.then((stream$1) => {
|
|
229
|
+
signal.removeEventListener("abort", onAbort);
|
|
230
|
+
if (signal.aborted) {
|
|
231
|
+
stream$1?.cancel(signal.reason).catch(() => {});
|
|
232
|
+
return;
|
|
233
|
+
}
|
|
234
|
+
resolve(stream$1);
|
|
235
|
+
}, (error) => {
|
|
236
|
+
signal.removeEventListener("abort", onAbort);
|
|
237
|
+
reject(error);
|
|
238
|
+
});
|
|
239
|
+
});
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
//#endregion
|
|
243
|
+
//#region src/client.ts
|
|
244
|
+
const USER_AGENT = `${CLIENT_IDENTIFIER} (${process.platform}) node ${process.version}`;
|
|
245
|
+
var FormatClient = class {
|
|
246
|
+
baseUrl;
|
|
247
|
+
renderTimeoutMs;
|
|
248
|
+
apiKey;
|
|
249
|
+
constructor(opts = {}) {
|
|
250
|
+
this.apiKey = resolveApiKey(opts.apiKey, process.env.FORMAT_API_KEY, "Pass `apiKey` explicitly or set `FORMAT_API_KEY` in your environment.");
|
|
251
|
+
this.baseUrl = resolveBaseUrl(opts, process.env.FORMAT_BASE_URL);
|
|
252
|
+
this.renderTimeoutMs = opts.renderTimeoutMs ?? 12e4;
|
|
253
|
+
}
|
|
254
|
+
async pdf(doc, options) {
|
|
255
|
+
const renderTimeoutSignal = timeoutSignal(this.renderTimeoutMs);
|
|
256
|
+
const combinedSignal = options?.signal ? anySignal([options.signal, renderTimeoutSignal]) : renderTimeoutSignal;
|
|
257
|
+
const isFormatDoc = typeof doc !== "string";
|
|
258
|
+
const html = isFormatDoc ? doc.html : doc;
|
|
259
|
+
const form = new formdata_node.FormData();
|
|
260
|
+
form.set("html", html);
|
|
261
|
+
if (options?.tags) form.set("tags", serializeTags(options.tags));
|
|
262
|
+
let assets = options?.assets;
|
|
263
|
+
if (!assets && isFormatDoc) assets = await documentAssets(doc, combinedSignal);
|
|
264
|
+
if (assets) form.set("assets", assetsToFormDataValue(assets));
|
|
265
|
+
const encoder = new form_data_encoder.FormDataEncoder(form);
|
|
266
|
+
const headers = {
|
|
267
|
+
...encoder.headers,
|
|
268
|
+
Authorization: `Bearer ${this.apiKey}`,
|
|
269
|
+
"User-Agent": USER_AGENT,
|
|
270
|
+
"X-Format-Client": CLIENT_IDENTIFIER
|
|
271
|
+
};
|
|
272
|
+
let res;
|
|
273
|
+
if (combinedSignal.aborted) throw getAbortErrorOrElse(combinedSignal);
|
|
274
|
+
try {
|
|
275
|
+
res = await fetch(renderUrl(this.baseUrl), {
|
|
276
|
+
method: "POST",
|
|
277
|
+
headers,
|
|
278
|
+
body: node_stream.Readable.toWeb(node_stream.Readable.from(encoder)),
|
|
279
|
+
signal: combinedSignal,
|
|
280
|
+
duplex: "half",
|
|
281
|
+
credentials: "omit"
|
|
282
|
+
});
|
|
283
|
+
} catch (err) {
|
|
284
|
+
throw getAbortErrorOrElse(combinedSignal, err);
|
|
285
|
+
}
|
|
286
|
+
if (!res.ok) throw await formatErrorFrom(res);
|
|
287
|
+
const toFile = async (filePath, options$1) => {
|
|
288
|
+
if (res.bodyUsed) throw new Error("Response body already consumed");
|
|
289
|
+
if (!res.body) throw new Error("Response body is empty");
|
|
290
|
+
const [{ pipeline }, { createWriteStream }, fs, path] = await Promise.all([
|
|
291
|
+
import("node:stream/promises"),
|
|
292
|
+
import("node:fs"),
|
|
293
|
+
import("node:fs/promises"),
|
|
294
|
+
import("node:path")
|
|
295
|
+
]);
|
|
296
|
+
await fs.mkdir(path.dirname(filePath), { recursive: true });
|
|
297
|
+
await pipeline(node_stream.Readable.fromWeb(res.body), createWriteStream(filePath, { mode: options$1?.mode }));
|
|
298
|
+
return {
|
|
299
|
+
path: filePath,
|
|
300
|
+
bytes: (await fs.stat(filePath)).size
|
|
301
|
+
};
|
|
302
|
+
};
|
|
303
|
+
return Object.assign(augmentResponse(res), { toFile });
|
|
304
|
+
}
|
|
305
|
+
};
|
|
306
|
+
|
|
307
|
+
//#endregion
|
|
308
|
+
exports.FormatClient = FormatClient;
|
|
309
|
+
exports.FormatError = FormatError;
|
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
import { createWriteStream } from "node:fs";
|
|
2
|
+
import { Readable } from "node:stream";
|
|
3
|
+
import { FormatDocument } from "@format.dev/types";
|
|
4
|
+
|
|
5
|
+
//#region src/types.d.ts
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Regional API endpoint. Controls which data center handles your render requests.
|
|
9
|
+
*
|
|
10
|
+
* - `GLOBAL` — Default. Routes to the nearest available region.
|
|
11
|
+
* - `US` — Routes to the US data center.
|
|
12
|
+
* - `EU` — Routes to the EU data center.
|
|
13
|
+
*
|
|
14
|
+
* @default 'GLOBAL'
|
|
15
|
+
*/
|
|
16
|
+
type FormatRegion = 'GLOBAL';
|
|
17
|
+
/**
|
|
18
|
+
* Accepted asset input types. The client normalizes all of these into a multipart form upload.
|
|
19
|
+
*
|
|
20
|
+
* - `Blob` — Web API Blob
|
|
21
|
+
* - `Uint8Array` or `ArrayBuffer` — Raw binary data
|
|
22
|
+
* - `ReadableStream<Uint8Array>` — Web ReadableStream (e.g. from `getAssetsWebStream()`)
|
|
23
|
+
*/
|
|
24
|
+
type AssetLike$1 = Blob | Uint8Array | ArrayBuffer | ReadableStream<Uint8Array>;
|
|
25
|
+
/**
|
|
26
|
+
* Options for creating a FormatClient instance.
|
|
27
|
+
*/
|
|
28
|
+
type FormatOptions = {
|
|
29
|
+
/**
|
|
30
|
+
* Your Format API key. If not provided, the Node client reads the `FORMAT_API_KEY` environment variable. Required by the web client.
|
|
31
|
+
*/
|
|
32
|
+
apiKey?: string;
|
|
33
|
+
/**
|
|
34
|
+
* Override the base API URL. If not provided, defaults to the URL for the selected `region`, or the global endpoint.
|
|
35
|
+
* @internal
|
|
36
|
+
* @example 'https://api.format.dev'
|
|
37
|
+
*/
|
|
38
|
+
baseUrl?: string;
|
|
39
|
+
/**
|
|
40
|
+
* Maximum time in milliseconds allowed for the render to complete. Prevents long-running renders from hanging indefinitely.
|
|
41
|
+
* @default 120000
|
|
42
|
+
*/
|
|
43
|
+
renderTimeoutMs?: number;
|
|
44
|
+
/**
|
|
45
|
+
* Region to route API requests to. Overrides the default global endpoint.
|
|
46
|
+
* @internal
|
|
47
|
+
* @default 'GLOBAL'
|
|
48
|
+
*/
|
|
49
|
+
region?: FormatRegion;
|
|
50
|
+
};
|
|
51
|
+
/**
|
|
52
|
+
* Options for the `pdf()` method. All fields are optional.
|
|
53
|
+
*/
|
|
54
|
+
type FormatPdfOptions$1 = {
|
|
55
|
+
/**
|
|
56
|
+
* Override the document's assets stream. Use this when you build the assets zip at runtime
|
|
57
|
+
* instead of relying on the compile-time output.
|
|
58
|
+
*/
|
|
59
|
+
assets?: AssetLike$1;
|
|
60
|
+
/**
|
|
61
|
+
* Metadata tags attached to this render. Useful for filtering and analytics in the Format dashboard. Duplicate and empty tags are removed automatically.
|
|
62
|
+
* @example ['invoice', 'customer-123']
|
|
63
|
+
*/
|
|
64
|
+
tags?: string[];
|
|
65
|
+
/**
|
|
66
|
+
* Abort signal to cancel the request. Combined with the client's `renderTimeoutMs` — whichever fires first wins.
|
|
67
|
+
*/
|
|
68
|
+
signal?: AbortSignal;
|
|
69
|
+
};
|
|
70
|
+
/**
|
|
71
|
+
* Extended `Response` returned by `FormatClient.pdf()`, with metadata extracted from response headers.
|
|
72
|
+
*/
|
|
73
|
+
type FormatResponse$1 = Response & {
|
|
74
|
+
/**
|
|
75
|
+
* Suggested filename from the `Content-Disposition` header, if present.
|
|
76
|
+
* @example 'document.pdf'
|
|
77
|
+
*/
|
|
78
|
+
filename?: string;
|
|
79
|
+
/**
|
|
80
|
+
* Size of the PDF in bytes, from the `Content-Length` header. Only present on successful PDF responses.
|
|
81
|
+
*/
|
|
82
|
+
contentLength?: number;
|
|
83
|
+
/**
|
|
84
|
+
* MIME type of the response. `application/pdf` for successful renders, `application/json` for errors.
|
|
85
|
+
*/
|
|
86
|
+
contentType?: string;
|
|
87
|
+
/**
|
|
88
|
+
* Traceparent ID for distributed tracing, if returned by the API. Useful for correlating client and server logs.
|
|
89
|
+
*/
|
|
90
|
+
traceparent?: string;
|
|
91
|
+
/**
|
|
92
|
+
* Whether the response is a PDF. Derived from `contentType === 'application/pdf'`.
|
|
93
|
+
*/
|
|
94
|
+
isPdf: boolean;
|
|
95
|
+
};
|
|
96
|
+
//#endregion
|
|
97
|
+
//#region src/node-types.d.ts
|
|
98
|
+
/**
|
|
99
|
+
* Accepts the web asset types, plus Node.js `Buffer` and `Readable` streams,
|
|
100
|
+
* including `ReadStream` from `fs.createReadStream`.
|
|
101
|
+
*/
|
|
102
|
+
type AssetLike = AssetLike$1 | Readable;
|
|
103
|
+
type WriteStreamOptions = Extract<Parameters<typeof createWriteStream>[1], object>;
|
|
104
|
+
type FormatPdfOptions = Omit<FormatPdfOptions$1, 'assets'> & {
|
|
105
|
+
/**
|
|
106
|
+
* Override the document's assets stream. Use this when you build the assets zip at runtime
|
|
107
|
+
* instead of relying on the compile-time output.
|
|
108
|
+
* @example fs.createReadStream('./assets.zip')
|
|
109
|
+
*/
|
|
110
|
+
assets?: AssetLike;
|
|
111
|
+
};
|
|
112
|
+
type FormatResponse = FormatResponse$1 & {
|
|
113
|
+
/**
|
|
114
|
+
* Save the PDF stream directly to a file. Creates parent directories if they don't exist.
|
|
115
|
+
* @platform node
|
|
116
|
+
* @example await response.toFile('./output/invoice.pdf')
|
|
117
|
+
*/
|
|
118
|
+
toFile(filePath: string, options?: WriteStreamOptions): Promise<{
|
|
119
|
+
path: string;
|
|
120
|
+
bytes: number;
|
|
121
|
+
}>;
|
|
122
|
+
};
|
|
123
|
+
//#endregion
|
|
124
|
+
//#region src/client.d.ts
|
|
125
|
+
declare class FormatClient {
|
|
126
|
+
private readonly baseUrl;
|
|
127
|
+
private readonly renderTimeoutMs;
|
|
128
|
+
private readonly apiKey;
|
|
129
|
+
constructor(opts?: FormatOptions);
|
|
130
|
+
pdf(doc: string | FormatDocument, options?: FormatPdfOptions): Promise<FormatResponse>;
|
|
131
|
+
}
|
|
132
|
+
//#endregion
|
|
133
|
+
//#region src/error.d.ts
|
|
134
|
+
/**
|
|
135
|
+
* Thrown when the Format API returns a non-2xx response. Contains the HTTP status code and parsed error body.
|
|
136
|
+
*/
|
|
137
|
+
declare class FormatError extends Error {
|
|
138
|
+
/** HTTP status code from the API response. */
|
|
139
|
+
status: number;
|
|
140
|
+
/** Parsed error response body. Typically a JSON object with error details, or `{ raw: string }` if the body couldn't be parsed. */
|
|
141
|
+
detail: unknown;
|
|
142
|
+
constructor(/** HTTP status code from the API response. */
|
|
143
|
+
status: number, /** Parsed error response body. Typically a JSON object with error details, or `{ raw: string }` if the body couldn't be parsed. */
|
|
144
|
+
detail: unknown);
|
|
145
|
+
}
|
|
146
|
+
//#endregion
|
|
147
|
+
export { type AssetLike, FormatClient, type FormatDocument, FormatError, type FormatOptions, type FormatPdfOptions, type FormatRegion, type FormatResponse };
|
|
148
|
+
//# sourceMappingURL=index.d.cts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.cts","names":[],"sources":["../src/types.ts","../src/node-types.ts","../src/client.ts","../src/error.ts"],"sourcesContent":[],"mappings":";;;;;;;;;;;AASA;AASA;;;AAA4C,KAThC,YAAA,GASgC,QAAA;;;;AAK5C;AAgCA;AAsBA;;KA3DY,WAAA,GAAY,OAAO,aAAa,cAAc,eAAe;;ACJzE;AACA;AAA2D,KDQ/C,aAAA,GCR+C;EAAlB;;;EAE7B,MAAA,CAAA,EAAA,MAAA;EAAwB;;;;AASpC;EAA6B,OAAA,CAAA,EAAA,MAAA;EAMO;;;;;;ACZpC;;;;EAe8E,MAAA,CAAA,EFYpE,YEZoE;CAAR;;;;AChCzD,KHoDD,kBAAA,GGpDqB;;;;;WHyDvB;;;;;;;;;WAWA;;;;;KAME,gBAAA,GAAiB;;;;;;;;;;;;;;;;;;;;;;;;;;AApE7B;AASA;;AAA+B,KCJnB,SAAA,GAAY,WDIO,GCJQ,QDIR;AAAa,KCHhC,kBAAA,GAAqB,ODGW,CCHH,UDGG,CAAA,OCHe,iBDGf,CAAA,CAAA,CAAA,CAAA,EAAA,MAAA,CAAA;AAA6B,KCD7D,gBAAA,GAAmB,IDC0C,CCDrC,kBDCqC,EAAA,QAAA,CAAA,GAAA;EAAf;;AAK1D;AAgCA;AAsBA;WCtDU;;KAGE,cAAA,GAAiB;EAZjB;AACZ;;;;EAAwC,MAAA,CAAA,QAAA,EAAA,MAAA,EAAA,OAAA,CAAA,EAiBJ,kBAjBI,CAAA,EAiBiB,OAjBjB,CAAA;IAE5B,IAAA,EAAA,MAAA;IAAwB,KAAA,EAAA,MAAA;EAAL,CAAA,CAAA;CAMrB;;;cCHG,YAAA;;;;EFXD,WAAA,CAAA,IAAY,CAAA,EEgBL,aFhBK;EASZ,GAAA,CAAA,GAAA,EAAA,MAAS,GEiBI,cFjBJ,EAAA,OAAA,CAAA,EEiB8B,gBFjB9B,CAAA,EEiBiD,OFjBjD,CEiByD,cFjBzD,CAAA;;;;;;;cGfR,WAAA,SAAoB,KAAA;;EHMrB,MAAA,EAAA,MAAA;EASA;EAAY,MAAA,EAAA,OAAA;EAAO,WAAA,CAAa;EAA6B,MAAA,EAAA,MAAA,EAAf;EAAc,MAAA,EAAA,OAAA;AAKxE"}
|
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
import { Readable } from "node:stream";
|
|
2
|
+
import { createWriteStream } from "node:fs";
|
|
3
|
+
import { FormatDocument } from "@format.dev/types";
|
|
4
|
+
|
|
5
|
+
//#region src/types.d.ts
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Regional API endpoint. Controls which data center handles your render requests.
|
|
9
|
+
*
|
|
10
|
+
* - `GLOBAL` — Default. Routes to the nearest available region.
|
|
11
|
+
* - `US` — Routes to the US data center.
|
|
12
|
+
* - `EU` — Routes to the EU data center.
|
|
13
|
+
*
|
|
14
|
+
* @default 'GLOBAL'
|
|
15
|
+
*/
|
|
16
|
+
type FormatRegion = 'GLOBAL';
|
|
17
|
+
/**
|
|
18
|
+
* Accepted asset input types. The client normalizes all of these into a multipart form upload.
|
|
19
|
+
*
|
|
20
|
+
* - `Blob` — Web API Blob
|
|
21
|
+
* - `Uint8Array` or `ArrayBuffer` — Raw binary data
|
|
22
|
+
* - `ReadableStream<Uint8Array>` — Web ReadableStream (e.g. from `getAssetsWebStream()`)
|
|
23
|
+
*/
|
|
24
|
+
type AssetLike$1 = Blob | Uint8Array | ArrayBuffer | ReadableStream<Uint8Array>;
|
|
25
|
+
/**
|
|
26
|
+
* Options for creating a FormatClient instance.
|
|
27
|
+
*/
|
|
28
|
+
type FormatOptions = {
|
|
29
|
+
/**
|
|
30
|
+
* Your Format API key. If not provided, the Node client reads the `FORMAT_API_KEY` environment variable. Required by the web client.
|
|
31
|
+
*/
|
|
32
|
+
apiKey?: string;
|
|
33
|
+
/**
|
|
34
|
+
* Override the base API URL. If not provided, defaults to the URL for the selected `region`, or the global endpoint.
|
|
35
|
+
* @internal
|
|
36
|
+
* @example 'https://api.format.dev'
|
|
37
|
+
*/
|
|
38
|
+
baseUrl?: string;
|
|
39
|
+
/**
|
|
40
|
+
* Maximum time in milliseconds allowed for the render to complete. Prevents long-running renders from hanging indefinitely.
|
|
41
|
+
* @default 120000
|
|
42
|
+
*/
|
|
43
|
+
renderTimeoutMs?: number;
|
|
44
|
+
/**
|
|
45
|
+
* Region to route API requests to. Overrides the default global endpoint.
|
|
46
|
+
* @internal
|
|
47
|
+
* @default 'GLOBAL'
|
|
48
|
+
*/
|
|
49
|
+
region?: FormatRegion;
|
|
50
|
+
};
|
|
51
|
+
/**
|
|
52
|
+
* Options for the `pdf()` method. All fields are optional.
|
|
53
|
+
*/
|
|
54
|
+
type FormatPdfOptions$1 = {
|
|
55
|
+
/**
|
|
56
|
+
* Override the document's assets stream. Use this when you build the assets zip at runtime
|
|
57
|
+
* instead of relying on the compile-time output.
|
|
58
|
+
*/
|
|
59
|
+
assets?: AssetLike$1;
|
|
60
|
+
/**
|
|
61
|
+
* Metadata tags attached to this render. Useful for filtering and analytics in the Format dashboard. Duplicate and empty tags are removed automatically.
|
|
62
|
+
* @example ['invoice', 'customer-123']
|
|
63
|
+
*/
|
|
64
|
+
tags?: string[];
|
|
65
|
+
/**
|
|
66
|
+
* Abort signal to cancel the request. Combined with the client's `renderTimeoutMs` — whichever fires first wins.
|
|
67
|
+
*/
|
|
68
|
+
signal?: AbortSignal;
|
|
69
|
+
};
|
|
70
|
+
/**
|
|
71
|
+
* Extended `Response` returned by `FormatClient.pdf()`, with metadata extracted from response headers.
|
|
72
|
+
*/
|
|
73
|
+
type FormatResponse$1 = Response & {
|
|
74
|
+
/**
|
|
75
|
+
* Suggested filename from the `Content-Disposition` header, if present.
|
|
76
|
+
* @example 'document.pdf'
|
|
77
|
+
*/
|
|
78
|
+
filename?: string;
|
|
79
|
+
/**
|
|
80
|
+
* Size of the PDF in bytes, from the `Content-Length` header. Only present on successful PDF responses.
|
|
81
|
+
*/
|
|
82
|
+
contentLength?: number;
|
|
83
|
+
/**
|
|
84
|
+
* MIME type of the response. `application/pdf` for successful renders, `application/json` for errors.
|
|
85
|
+
*/
|
|
86
|
+
contentType?: string;
|
|
87
|
+
/**
|
|
88
|
+
* Traceparent ID for distributed tracing, if returned by the API. Useful for correlating client and server logs.
|
|
89
|
+
*/
|
|
90
|
+
traceparent?: string;
|
|
91
|
+
/**
|
|
92
|
+
* Whether the response is a PDF. Derived from `contentType === 'application/pdf'`.
|
|
93
|
+
*/
|
|
94
|
+
isPdf: boolean;
|
|
95
|
+
};
|
|
96
|
+
//#endregion
|
|
97
|
+
//#region src/node-types.d.ts
|
|
98
|
+
/**
|
|
99
|
+
* Accepts the web asset types, plus Node.js `Buffer` and `Readable` streams,
|
|
100
|
+
* including `ReadStream` from `fs.createReadStream`.
|
|
101
|
+
*/
|
|
102
|
+
type AssetLike = AssetLike$1 | Readable;
|
|
103
|
+
type WriteStreamOptions = Extract<Parameters<typeof createWriteStream>[1], object>;
|
|
104
|
+
type FormatPdfOptions = Omit<FormatPdfOptions$1, 'assets'> & {
|
|
105
|
+
/**
|
|
106
|
+
* Override the document's assets stream. Use this when you build the assets zip at runtime
|
|
107
|
+
* instead of relying on the compile-time output.
|
|
108
|
+
* @example fs.createReadStream('./assets.zip')
|
|
109
|
+
*/
|
|
110
|
+
assets?: AssetLike;
|
|
111
|
+
};
|
|
112
|
+
type FormatResponse = FormatResponse$1 & {
|
|
113
|
+
/**
|
|
114
|
+
* Save the PDF stream directly to a file. Creates parent directories if they don't exist.
|
|
115
|
+
* @platform node
|
|
116
|
+
* @example await response.toFile('./output/invoice.pdf')
|
|
117
|
+
*/
|
|
118
|
+
toFile(filePath: string, options?: WriteStreamOptions): Promise<{
|
|
119
|
+
path: string;
|
|
120
|
+
bytes: number;
|
|
121
|
+
}>;
|
|
122
|
+
};
|
|
123
|
+
//#endregion
|
|
124
|
+
//#region src/client.d.ts
|
|
125
|
+
declare class FormatClient {
|
|
126
|
+
private readonly baseUrl;
|
|
127
|
+
private readonly renderTimeoutMs;
|
|
128
|
+
private readonly apiKey;
|
|
129
|
+
constructor(opts?: FormatOptions);
|
|
130
|
+
pdf(doc: string | FormatDocument, options?: FormatPdfOptions): Promise<FormatResponse>;
|
|
131
|
+
}
|
|
132
|
+
//#endregion
|
|
133
|
+
//#region src/error.d.ts
|
|
134
|
+
/**
|
|
135
|
+
* Thrown when the Format API returns a non-2xx response. Contains the HTTP status code and parsed error body.
|
|
136
|
+
*/
|
|
137
|
+
declare class FormatError extends Error {
|
|
138
|
+
/** HTTP status code from the API response. */
|
|
139
|
+
status: number;
|
|
140
|
+
/** Parsed error response body. Typically a JSON object with error details, or `{ raw: string }` if the body couldn't be parsed. */
|
|
141
|
+
detail: unknown;
|
|
142
|
+
constructor(/** HTTP status code from the API response. */
|
|
143
|
+
status: number, /** Parsed error response body. Typically a JSON object with error details, or `{ raw: string }` if the body couldn't be parsed. */
|
|
144
|
+
detail: unknown);
|
|
145
|
+
}
|
|
146
|
+
//#endregion
|
|
147
|
+
export { type AssetLike, FormatClient, type FormatDocument, FormatError, type FormatOptions, type FormatPdfOptions, type FormatRegion, type FormatResponse };
|
|
148
|
+
//# sourceMappingURL=index.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":[],"sources":["../src/types.ts","../src/node-types.ts","../src/client.ts","../src/error.ts"],"sourcesContent":[],"mappings":";;;;;;;;;;;AASA;AASA;;;AAA4C,KAThC,YAAA,GASgC,QAAA;;;;AAK5C;AAgCA;AAsBA;;KA3DY,WAAA,GAAY,OAAO,aAAa,cAAc,eAAe;;ACJzE;AACA;AAA2D,KDQ/C,aAAA,GCR+C;EAAlB;;;EAE7B,MAAA,CAAA,EAAA,MAAA;EAAwB;;;;AASpC;EAA6B,OAAA,CAAA,EAAA,MAAA;EAMO;;;;;;ACZpC;;;;EAe8E,MAAA,CAAA,EFYpE,YEZoE;CAAR;;;;AChCzD,KHoDD,kBAAA,GGpDqB;;;;;WHyDvB;;;;;;;;;WAWA;;;;;KAME,gBAAA,GAAiB;;;;;;;;;;;;;;;;;;;;;;;;;;AApE7B;AASA;;AAA+B,KCJnB,SAAA,GAAY,WDIO,GCJQ,QDIR;AAAa,KCHhC,kBAAA,GAAqB,ODGW,CCHH,UDGG,CAAA,OCHe,iBDGf,CAAA,CAAA,CAAA,CAAA,EAAA,MAAA,CAAA;AAA6B,KCD7D,gBAAA,GAAmB,IDC0C,CCDrC,kBDCqC,EAAA,QAAA,CAAA,GAAA;EAAf;;AAK1D;AAgCA;AAsBA;WCtDU;;KAGE,cAAA,GAAiB;EAZjB;AACZ;;;;EAAwC,MAAA,CAAA,QAAA,EAAA,MAAA,EAAA,OAAA,CAAA,EAiBJ,kBAjBI,CAAA,EAiBiB,OAjBjB,CAAA;IAE5B,IAAA,EAAA,MAAA;IAAwB,KAAA,EAAA,MAAA;EAAL,CAAA,CAAA;CAMrB;;;cCHG,YAAA;;;;EFXD,WAAA,CAAA,IAAY,CAAA,EEgBL,aFhBK;EASZ,GAAA,CAAA,GAAA,EAAA,MAAS,GEiBI,cFjBJ,EAAA,OAAA,CAAA,EEiB8B,gBFjB9B,CAAA,EEiBiD,OFjBjD,CEiByD,cFjBzD,CAAA;;;;;;;cGfR,WAAA,SAAoB,KAAA;;EHMrB,MAAA,EAAA,MAAA;EASA;EAAY,MAAA,EAAA,OAAA;EAAO,WAAA,CAAa;EAA6B,MAAA,EAAA,MAAA,EAAf;EAAc,MAAA,EAAA,OAAA;AAKxE"}
|