@format.dev/client 0.0.0 → 0.1.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/web.d.cts ADDED
@@ -0,0 +1,119 @@
1
+ import { FormatDocument } from "@format.dev/types";
2
+
3
+ //#region src/types.d.ts
4
+
5
+ /**
6
+ * Regional API endpoint. Controls which data center handles your render requests.
7
+ *
8
+ * - `GLOBAL` — Default. Routes to the nearest available region.
9
+ * - `US` — Routes to the US data center.
10
+ * - `EU` — Routes to the EU data center.
11
+ *
12
+ * @default 'GLOBAL'
13
+ */
14
+ type FormatRegion = 'GLOBAL';
15
+ /**
16
+ * Accepted asset input types. The client normalizes all of these into a multipart form upload.
17
+ *
18
+ * - `Blob` — Web API Blob
19
+ * - `Uint8Array` or `ArrayBuffer` — Raw binary data
20
+ * - `ReadableStream<Uint8Array>` — Web ReadableStream (e.g. from `getAssetsWebStream()`)
21
+ */
22
+ type AssetLike = Blob | Uint8Array | ArrayBuffer | ReadableStream<Uint8Array>;
23
+ /**
24
+ * Options for creating a FormatClient instance.
25
+ */
26
+ type FormatOptions = {
27
+ /**
28
+ * Your Format API key. If not provided, the Node client reads the `FORMAT_API_KEY` environment variable. Required by the web client.
29
+ */
30
+ apiKey?: string;
31
+ /**
32
+ * Override the base API URL. If not provided, defaults to the URL for the selected `region`, or the global endpoint.
33
+ * @internal
34
+ * @example 'https://api.format.dev'
35
+ */
36
+ baseUrl?: string;
37
+ /**
38
+ * Maximum time in milliseconds allowed for the render to complete. Prevents long-running renders from hanging indefinitely.
39
+ * @default 120000
40
+ */
41
+ renderTimeoutMs?: number;
42
+ /**
43
+ * Region to route API requests to. Overrides the default global endpoint.
44
+ * @internal
45
+ * @default 'GLOBAL'
46
+ */
47
+ region?: FormatRegion;
48
+ };
49
+ /**
50
+ * Options for the `pdf()` method. All fields are optional.
51
+ */
52
+ type FormatPdfOptions = {
53
+ /**
54
+ * Override the document's assets stream. Use this when you build the assets zip at runtime
55
+ * instead of relying on the compile-time output.
56
+ */
57
+ assets?: AssetLike;
58
+ /**
59
+ * Metadata tags attached to this render. Useful for filtering and analytics in the Format dashboard. Duplicate and empty tags are removed automatically.
60
+ * @example ['invoice', 'customer-123']
61
+ */
62
+ tags?: string[];
63
+ /**
64
+ * Abort signal to cancel the request. Combined with the client's `renderTimeoutMs` — whichever fires first wins.
65
+ */
66
+ signal?: AbortSignal;
67
+ };
68
+ /**
69
+ * Extended `Response` returned by `FormatClient.pdf()`, with metadata extracted from response headers.
70
+ */
71
+ type FormatResponse = Response & {
72
+ /**
73
+ * Suggested filename from the `Content-Disposition` header, if present.
74
+ * @example 'document.pdf'
75
+ */
76
+ filename?: string;
77
+ /**
78
+ * Size of the PDF in bytes, from the `Content-Length` header. Only present on successful PDF responses.
79
+ */
80
+ contentLength?: number;
81
+ /**
82
+ * MIME type of the response. `application/pdf` for successful renders, `application/json` for errors.
83
+ */
84
+ contentType?: string;
85
+ /**
86
+ * Traceparent ID for distributed tracing, if returned by the API. Useful for correlating client and server logs.
87
+ */
88
+ traceparent?: string;
89
+ /**
90
+ * Whether the response is a PDF. Derived from `contentType === 'application/pdf'`.
91
+ */
92
+ isPdf: boolean;
93
+ };
94
+ //#endregion
95
+ //#region src/web-client.d.ts
96
+ declare class FormatClient {
97
+ private readonly baseUrl;
98
+ private readonly renderTimeoutMs;
99
+ private readonly apiKey;
100
+ constructor(opts: FormatOptions);
101
+ pdf(doc: string | FormatDocument, options?: FormatPdfOptions): Promise<FormatResponse>;
102
+ }
103
+ //#endregion
104
+ //#region src/error.d.ts
105
+ /**
106
+ * Thrown when the Format API returns a non-2xx response. Contains the HTTP status code and parsed error body.
107
+ */
108
+ declare class FormatError extends Error {
109
+ /** HTTP status code from the API response. */
110
+ status: number;
111
+ /** Parsed error response body. Typically a JSON object with error details, or `{ raw: string }` if the body couldn't be parsed. */
112
+ detail: unknown;
113
+ constructor(/** HTTP status code from the API response. */
114
+ status: number, /** Parsed error response body. Typically a JSON object with error details, or `{ raw: string }` if the body couldn't be parsed. */
115
+ detail: unknown);
116
+ }
117
+ //#endregion
118
+ export { type AssetLike, FormatClient, type FormatDocument, FormatError, type FormatOptions, type FormatPdfOptions, type FormatRegion, type FormatResponse };
119
+ //# sourceMappingURL=web.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"web.d.cts","names":[],"sources":["../src/types.ts","../src/web-client.ts","../src/error.ts"],"sourcesContent":[],"mappings":";;;;;;;AASA;AASA;;;;;AAA0D,KAT9C,YAAA,GAS8C,QAAA;;AAK1D;AAgCA;AAsBA;;;;ACTa,KDlDD,SAAA,GAAY,ICkDC,GDlDM,UCkDN,GDlDmB,WCkDnB,GDlDiC,cCkDjC,CDlDgD,UCkDhD,CAAA;;;;AAWqD,KDxDlE,aAAA,GCwDkE;EAAR;;;;;AC5EtE;;;;;;;;;;;;;;;WF4CU;;;;;KAQE,gBAAA;;;;;WAKF;;;;;;;;;WAWA;;;;;KAME,cAAA,GAAiB;;;;;;;;;;;;;;;;;;;;;;;;;cCThB,YAAA;;ED3DD,iBAAY,eAAA;EASZ,iBAAS,MAAA;EAAG,WAAA,CAAA,IAAA,ECuDL,aDvDK;EAAO,GAAA,CAAA,GAAA,EAAA,MAAA,GC6DN,cD7DM,EAAA,OAAA,CAAA,EC6DoB,gBD7DpB,CAAA,EC6DuC,OD7DvC,CC6D+C,cD7D/C,CAAA;;;;;;;AATnB,cENC,WAAA,SAAoB,KAAA,CFMT;EASZ;EAAY,MAAA,EAAA,MAAA;EAAO;EAAa,MAAA,EAAA,OAAA;EAA6B,WAAA,CAAf;EAAc,MAAA,EAAA,MAAA,EAK5D;EAgCA,MAAA,EAAA,OAAA;AAsBZ"}
package/dist/web.d.mts ADDED
@@ -0,0 +1,119 @@
1
+ import { FormatDocument } from "@format.dev/types";
2
+
3
+ //#region src/types.d.ts
4
+
5
+ /**
6
+ * Regional API endpoint. Controls which data center handles your render requests.
7
+ *
8
+ * - `GLOBAL` — Default. Routes to the nearest available region.
9
+ * - `US` — Routes to the US data center.
10
+ * - `EU` — Routes to the EU data center.
11
+ *
12
+ * @default 'GLOBAL'
13
+ */
14
+ type FormatRegion = 'GLOBAL';
15
+ /**
16
+ * Accepted asset input types. The client normalizes all of these into a multipart form upload.
17
+ *
18
+ * - `Blob` — Web API Blob
19
+ * - `Uint8Array` or `ArrayBuffer` — Raw binary data
20
+ * - `ReadableStream<Uint8Array>` — Web ReadableStream (e.g. from `getAssetsWebStream()`)
21
+ */
22
+ type AssetLike = Blob | Uint8Array | ArrayBuffer | ReadableStream<Uint8Array>;
23
+ /**
24
+ * Options for creating a FormatClient instance.
25
+ */
26
+ type FormatOptions = {
27
+ /**
28
+ * Your Format API key. If not provided, the Node client reads the `FORMAT_API_KEY` environment variable. Required by the web client.
29
+ */
30
+ apiKey?: string;
31
+ /**
32
+ * Override the base API URL. If not provided, defaults to the URL for the selected `region`, or the global endpoint.
33
+ * @internal
34
+ * @example 'https://api.format.dev'
35
+ */
36
+ baseUrl?: string;
37
+ /**
38
+ * Maximum time in milliseconds allowed for the render to complete. Prevents long-running renders from hanging indefinitely.
39
+ * @default 120000
40
+ */
41
+ renderTimeoutMs?: number;
42
+ /**
43
+ * Region to route API requests to. Overrides the default global endpoint.
44
+ * @internal
45
+ * @default 'GLOBAL'
46
+ */
47
+ region?: FormatRegion;
48
+ };
49
+ /**
50
+ * Options for the `pdf()` method. All fields are optional.
51
+ */
52
+ type FormatPdfOptions = {
53
+ /**
54
+ * Override the document's assets stream. Use this when you build the assets zip at runtime
55
+ * instead of relying on the compile-time output.
56
+ */
57
+ assets?: AssetLike;
58
+ /**
59
+ * Metadata tags attached to this render. Useful for filtering and analytics in the Format dashboard. Duplicate and empty tags are removed automatically.
60
+ * @example ['invoice', 'customer-123']
61
+ */
62
+ tags?: string[];
63
+ /**
64
+ * Abort signal to cancel the request. Combined with the client's `renderTimeoutMs` — whichever fires first wins.
65
+ */
66
+ signal?: AbortSignal;
67
+ };
68
+ /**
69
+ * Extended `Response` returned by `FormatClient.pdf()`, with metadata extracted from response headers.
70
+ */
71
+ type FormatResponse = Response & {
72
+ /**
73
+ * Suggested filename from the `Content-Disposition` header, if present.
74
+ * @example 'document.pdf'
75
+ */
76
+ filename?: string;
77
+ /**
78
+ * Size of the PDF in bytes, from the `Content-Length` header. Only present on successful PDF responses.
79
+ */
80
+ contentLength?: number;
81
+ /**
82
+ * MIME type of the response. `application/pdf` for successful renders, `application/json` for errors.
83
+ */
84
+ contentType?: string;
85
+ /**
86
+ * Traceparent ID for distributed tracing, if returned by the API. Useful for correlating client and server logs.
87
+ */
88
+ traceparent?: string;
89
+ /**
90
+ * Whether the response is a PDF. Derived from `contentType === 'application/pdf'`.
91
+ */
92
+ isPdf: boolean;
93
+ };
94
+ //#endregion
95
+ //#region src/web-client.d.ts
96
+ declare class FormatClient {
97
+ private readonly baseUrl;
98
+ private readonly renderTimeoutMs;
99
+ private readonly apiKey;
100
+ constructor(opts: FormatOptions);
101
+ pdf(doc: string | FormatDocument, options?: FormatPdfOptions): Promise<FormatResponse>;
102
+ }
103
+ //#endregion
104
+ //#region src/error.d.ts
105
+ /**
106
+ * Thrown when the Format API returns a non-2xx response. Contains the HTTP status code and parsed error body.
107
+ */
108
+ declare class FormatError extends Error {
109
+ /** HTTP status code from the API response. */
110
+ status: number;
111
+ /** Parsed error response body. Typically a JSON object with error details, or `{ raw: string }` if the body couldn't be parsed. */
112
+ detail: unknown;
113
+ constructor(/** HTTP status code from the API response. */
114
+ status: number, /** Parsed error response body. Typically a JSON object with error details, or `{ raw: string }` if the body couldn't be parsed. */
115
+ detail: unknown);
116
+ }
117
+ //#endregion
118
+ export { type AssetLike, FormatClient, type FormatDocument, FormatError, type FormatOptions, type FormatPdfOptions, type FormatRegion, type FormatResponse };
119
+ //# sourceMappingURL=web.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"web.d.mts","names":[],"sources":["../src/types.ts","../src/web-client.ts","../src/error.ts"],"sourcesContent":[],"mappings":";;;;;;;AASA;AASA;;;;;AAA0D,KAT9C,YAAA,GAS8C,QAAA;;AAK1D;AAgCA;AAsBA;;;;ACTa,KDlDD,SAAA,GAAY,ICkDC,GDlDM,UCkDN,GDlDmB,WCkDnB,GDlDiC,cCkDjC,CDlDgD,UCkDhD,CAAA;;;;AAWqD,KDxDlE,aAAA,GCwDkE;EAAR;;;;;AC5EtE;;;;;;;;;;;;;;;WF4CU;;;;;KAQE,gBAAA;;;;;WAKF;;;;;;;;;WAWA;;;;;KAME,cAAA,GAAiB;;;;;;;;;;;;;;;;;;;;;;;;;cCThB,YAAA;;ED3DD,iBAAY,eAAA;EASZ,iBAAS,MAAA;EAAG,WAAA,CAAA,IAAA,ECuDL,aDvDK;EAAO,GAAA,CAAA,GAAA,EAAA,MAAA,GC6DN,cD7DM,EAAA,OAAA,CAAA,EC6DoB,gBD7DpB,CAAA,EC6DuC,OD7DvC,CC6D+C,cD7D/C,CAAA;;;;;;;AATnB,cENC,WAAA,SAAoB,KAAA,CFMT;EASZ;EAAY,MAAA,EAAA,MAAA;EAAO;EAAa,MAAA,EAAA,OAAA;EAA6B,WAAA,CAAf;EAAc,MAAA,EAAA,MAAA,EAK5D;EAgCA,MAAA,EAAA,OAAA;AAsBZ"}
package/dist/web.mjs ADDED
@@ -0,0 +1,287 @@
1
+ //#region package.json
2
+ var version = "0.1.1";
3
+
4
+ //#endregion
5
+ //#region src/constants.ts
6
+ const REGION_MAP = { GLOBAL: "https://api.format.dev" };
7
+ const API_PREFIX = "/v1";
8
+ const CLIENT_IDENTIFIER = `@format.dev/client/${version}`;
9
+ const DEFAULTS = { baseUrl: REGION_MAP.GLOBAL };
10
+
11
+ //#endregion
12
+ //#region src/helpers.ts
13
+ function isWebReadable(x) {
14
+ return typeof globalThis.ReadableStream !== "undefined" && x != null && typeof x.getReader === "function";
15
+ }
16
+ function isBlobLike(x) {
17
+ return x != null && typeof x === "object" && typeof x.arrayBuffer === "function" && typeof x.stream === "function" && typeof x.size === "number" && typeof x.type === "string";
18
+ }
19
+ /**
20
+ * The API origin requests go to. `environmentBaseUrl` is the `FORMAT_BASE_URL`
21
+ * the Node build reads from its environment. The web build does not read
22
+ * environment variables, so it passes nothing.
23
+ */
24
+ function resolveBaseUrl(opts, environmentBaseUrl) {
25
+ return (opts.baseUrl ?? (opts.region ? REGION_MAP[opts.region] : void 0) ?? environmentBaseUrl ?? DEFAULTS.baseUrl).replace(/\/+$/, "");
26
+ }
27
+ /** The render endpoint under an API origin. The origin carries no version, so the prefix is added here. */
28
+ function renderUrl(baseUrl) {
29
+ return `${baseUrl}${API_PREFIX}/render`;
30
+ }
31
+ /** The `tags` form field: trimmed, empty tags dropped, duplicates removed, sent as a JSON array. */
32
+ function serializeTags(tags) {
33
+ return JSON.stringify(Array.from(new Set(tags.map((t) => t.trim()).filter(Boolean))));
34
+ }
35
+ function parseFilenameFromContentDisposition(header) {
36
+ if (!header) return;
37
+ const mExt = header.match(/filename\*\s*=\s*([^;]+)/i);
38
+ if (mExt) {
39
+ const v = mExt[1].trim();
40
+ const m = /^([A-Za-z0-9._-]+)''(.+)$/.exec(v);
41
+ if (m) {
42
+ const value = stripQuotes(m[2]);
43
+ try {
44
+ return decodeURIComponent(value);
45
+ } catch {
46
+ return value;
47
+ }
48
+ }
49
+ }
50
+ const mQuoted = header.match(/filename\s*=\s*"([^"]*)"/i);
51
+ if (mQuoted) return mQuoted[1];
52
+ const mBare = header.match(/filename\s*=\s*([^;]+)/i);
53
+ if (mBare) return mBare[1].trim();
54
+ }
55
+ function parseContentType(header) {
56
+ if (!header) return;
57
+ const [mime] = header.split(";", 1);
58
+ return mime?.trim().toLowerCase();
59
+ }
60
+ async function safeJson(body) {
61
+ try {
62
+ return JSON.parse(body);
63
+ } catch {
64
+ return { raw: body };
65
+ }
66
+ }
67
+ function timeoutSignal(ms, reason = /* @__PURE__ */ new Error("Timeout")) {
68
+ if (AbortSignal.timeout) return AbortSignal.timeout(ms);
69
+ const ac = new AbortController();
70
+ setTimeout(() => ac.abort(reason), ms);
71
+ return ac.signal;
72
+ }
73
+ function anySignal(signals) {
74
+ if (AbortSignal.any) return AbortSignal.any(signals);
75
+ const ac = new AbortController();
76
+ const aborted = signals.find((signal) => signal.aborted);
77
+ if (aborted) {
78
+ ac.abort(aborted.reason);
79
+ return ac.signal;
80
+ }
81
+ const onAbort = (event) => {
82
+ for (const signal of signals) signal.removeEventListener("abort", onAbort);
83
+ ac.abort(event.target.reason);
84
+ };
85
+ for (const s of signals) s.addEventListener("abort", onAbort, { once: true });
86
+ return ac.signal;
87
+ }
88
+ function getAbortErrorOrElse(signal, cause) {
89
+ 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 });
90
+ }
91
+ function concatUint8Array(parts, total) {
92
+ if (parts.length === 1 && parts[0].byteLength === total) return parts[0];
93
+ let offset = 0;
94
+ const out = new Uint8Array(total);
95
+ for (const p of parts) {
96
+ out.set(p, offset);
97
+ offset += p.byteLength;
98
+ }
99
+ return out;
100
+ }
101
+ /**
102
+ * The key a client sends, or a thrown error naming how to supply one.
103
+ * `environmentApiKey` is the `FORMAT_API_KEY` the Node build reads from its
104
+ * environment. The web build passes nothing, so its callers have to
105
+ * pass `apiKey` explicitly.
106
+ */
107
+ function resolveApiKey(explicitApiKey, environmentApiKey, howToSupply) {
108
+ if (explicitApiKey) return explicitApiKey;
109
+ if (environmentApiKey) return environmentApiKey;
110
+ throw new Error(`Format API key is required. ${howToSupply ?? "Pass `apiKey` explicitly."}`);
111
+ }
112
+ function stripQuotes(input) {
113
+ if (input.length >= 2 && input[0] === "\"" && input[input.length - 1] === "\"") return input.slice(1, -1);
114
+ return input;
115
+ }
116
+
117
+ //#endregion
118
+ //#region src/error.ts
119
+ /**
120
+ * Thrown when the Format API returns a non-2xx response. Contains the HTTP status code and parsed error body.
121
+ */
122
+ var FormatError = class extends Error {
123
+ constructor(status, detail) {
124
+ super(`Format API: Error ${status}`);
125
+ this.status = status;
126
+ this.detail = detail;
127
+ }
128
+ };
129
+
130
+ //#endregion
131
+ //#region src/response.ts
132
+ /**
133
+ * The error a non-2xx response becomes.
134
+ *
135
+ * Reads at most about 1MB of the body, so an unexpectedly large error response
136
+ * cannot exhaust memory, and parses it as JSON where it can. A body that is not
137
+ * JSON arrives as `{ raw: body }`.
138
+ */
139
+ async function formatErrorFrom(res) {
140
+ const status = res.status ?? 0;
141
+ let size = 0;
142
+ const limit = 1e6;
143
+ const chunks = [];
144
+ const reader = res.body?.getReader();
145
+ try {
146
+ if (reader) while (size < limit) {
147
+ const { done, value } = await reader.read();
148
+ if (done || !value?.length) break;
149
+ chunks.push(value);
150
+ size += value.byteLength;
151
+ }
152
+ } finally {
153
+ try {
154
+ await reader?.cancel();
155
+ } catch {}
156
+ }
157
+ const buf = concatUint8Array(chunks, size);
158
+ return new FormatError(status, await safeJson(new TextDecoder("utf-8", { fatal: false }).decode(buf)));
159
+ }
160
+ /** What a successful response says about the PDF, read from its headers. */
161
+ function responseDetails(res) {
162
+ const rawContentLength = res.headers.get("content-length");
163
+ const contentType = parseContentType(res.headers.get("content-type"));
164
+ return {
165
+ filename: parseFilenameFromContentDisposition(res.headers.get("content-disposition")),
166
+ contentLength: rawContentLength ? parseInt(rawContentLength) : void 0,
167
+ contentType,
168
+ traceparent: res.headers.get("traceparent") || void 0,
169
+ isPdf: contentType === "application/pdf"
170
+ };
171
+ }
172
+ /**
173
+ * Assign to the Response itself: a Proxy breaks the native methods' brand
174
+ * checks in browsers and Node 24.
175
+ */
176
+ function augmentResponse(res) {
177
+ return Object.assign(res, responseDetails(res));
178
+ }
179
+
180
+ //#endregion
181
+ //#region src/document-assets.ts
182
+ /**
183
+ * A compiled document cannot cancel its asset lookup. Reject promptly on abort
184
+ * and cancel any stream that arrives afterwards so its source can release it.
185
+ */
186
+ async function documentAssets(doc, signal) {
187
+ if (signal.aborted) throw getAbortErrorOrElse(signal);
188
+ const pending = doc.getAssetsWebStream();
189
+ return new Promise((resolve, reject) => {
190
+ const onAbort = () => {
191
+ signal.removeEventListener("abort", onAbort);
192
+ reject(getAbortErrorOrElse(signal));
193
+ };
194
+ signal.addEventListener("abort", onAbort, { once: true });
195
+ if (signal.aborted) onAbort();
196
+ pending.then((stream) => {
197
+ signal.removeEventListener("abort", onAbort);
198
+ if (signal.aborted) {
199
+ stream?.cancel(signal.reason).catch(() => {});
200
+ return;
201
+ }
202
+ resolve(stream);
203
+ }, (error) => {
204
+ signal.removeEventListener("abort", onAbort);
205
+ reject(error);
206
+ });
207
+ });
208
+ }
209
+
210
+ //#endregion
211
+ //#region src/web-client.ts
212
+ const ASSETS_FILENAME = "assets.zip";
213
+ const ASSETS_TYPE = "application/zip";
214
+ async function readStream(stream, signal) {
215
+ const reader = stream.getReader();
216
+ const onAbort = () => void reader.cancel(signal.reason).catch(() => {});
217
+ const chunks = [];
218
+ signal.addEventListener("abort", onAbort, { once: true });
219
+ try {
220
+ if (signal.aborted) {
221
+ onAbort();
222
+ throw getAbortErrorOrElse(signal);
223
+ }
224
+ for (;;) {
225
+ const { done, value } = await reader.read();
226
+ if (signal.aborted) throw getAbortErrorOrElse(signal);
227
+ if (done) return chunks;
228
+ chunks.push(new Uint8Array(value));
229
+ }
230
+ } finally {
231
+ signal.removeEventListener("abort", onAbort);
232
+ reader.releaseLock();
233
+ }
234
+ }
235
+ /** The assets archive as a Blob for native FormData. */
236
+ async function assetsToBlob(input, signal) {
237
+ if (isBlobLike(input)) return input.type === ASSETS_TYPE ? input : new Blob([input], { type: ASSETS_TYPE });
238
+ if (input instanceof ArrayBuffer) return new Blob([input], { type: ASSETS_TYPE });
239
+ if (ArrayBuffer.isView(input)) return new Blob([new Uint8Array(input)], { type: ASSETS_TYPE });
240
+ if (isWebReadable(input)) return new Blob(await readStream(input, signal), { type: ASSETS_TYPE });
241
+ throw new TypeError("Unsupported assets type. Pass a Blob, an ArrayBuffer, a Uint8Array or a ReadableStream.");
242
+ }
243
+ var FormatClient = class {
244
+ baseUrl;
245
+ renderTimeoutMs;
246
+ apiKey;
247
+ constructor(opts) {
248
+ this.apiKey = resolveApiKey(opts?.apiKey);
249
+ this.baseUrl = resolveBaseUrl(opts);
250
+ this.renderTimeoutMs = opts.renderTimeoutMs ?? 12e4;
251
+ }
252
+ async pdf(doc, options) {
253
+ const renderTimeoutSignal = timeoutSignal(this.renderTimeoutMs);
254
+ const combinedSignal = options?.signal ? anySignal([options.signal, renderTimeoutSignal]) : renderTimeoutSignal;
255
+ const isFormatDoc = typeof doc !== "string";
256
+ const html = isFormatDoc ? doc.html : doc;
257
+ const form = new FormData();
258
+ form.set("html", html);
259
+ if (options?.tags) form.set("tags", serializeTags(options.tags));
260
+ let assets = options?.assets;
261
+ if (!assets && isFormatDoc) assets = await documentAssets(doc, combinedSignal);
262
+ if (assets) form.set("assets", await assetsToBlob(assets, combinedSignal), ASSETS_FILENAME);
263
+ if (combinedSignal.aborted) throw getAbortErrorOrElse(combinedSignal);
264
+ let res;
265
+ try {
266
+ res = await fetch(renderUrl(this.baseUrl), {
267
+ method: "POST",
268
+ headers: {
269
+ Authorization: `Bearer ${this.apiKey}`,
270
+ "X-Format-Client": CLIENT_IDENTIFIER
271
+ },
272
+ body: form,
273
+ signal: combinedSignal,
274
+ credentials: "omit",
275
+ mode: "cors"
276
+ });
277
+ } catch (err) {
278
+ throw getAbortErrorOrElse(combinedSignal, err);
279
+ }
280
+ if (!res.ok) throw await formatErrorFrom(res);
281
+ return augmentResponse(res);
282
+ }
283
+ };
284
+
285
+ //#endregion
286
+ export { FormatClient, FormatError };
287
+ //# sourceMappingURL=web.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"web.mjs","names":["REGION_MAP: Record<FormatRegion, string>","status: number","detail: unknown","chunks: Uint8Array[]","chunks: Uint8Array<ArrayBuffer>[]","res: Response"],"sources":["../package.json","../src/constants.ts","../src/helpers.ts","../src/error.ts","../src/response.ts","../src/document-assets.ts","../src/web-client.ts"],"sourcesContent":["{\n\t\"name\": \"@format.dev/client\",\n\t\"version\": \"0.1.1\",\n\t\"license\": \"MIT\",\n\t\"description\": \"The JavaScript client for the Format API.\",\n\t\"author\": \"the format.dev developers\",\n\t\"repository\": {\n\t\t\"type\": \"git\",\n\t\t\"url\": \"git+https://github.com/format-hq/format-js.git\",\n\t\t\"directory\": \"packages/client\"\n\t},\n\t\"type\": \"module\",\n\t\"main\": \"./dist/index.cjs\",\n\t\"module\": \"./dist/index.mjs\",\n\t\"types\": \"./dist/index.d.mts\",\n\t\"exports\": {\n\t\t\".\": {\n\t\t\t\"browser\": {\n\t\t\t\t\"types\": {\n\t\t\t\t\t\"import\": \"./dist/web.d.mts\",\n\t\t\t\t\t\"require\": \"./dist/web.d.cts\"\n\t\t\t\t},\n\t\t\t\t\"import\": \"./dist/web.mjs\",\n\t\t\t\t\"require\": \"./dist/web.cjs\",\n\t\t\t\t\"default\": \"./dist/web.mjs\"\n\t\t\t},\n\t\t\t\"types\": {\n\t\t\t\t\"import\": \"./dist/index.d.mts\",\n\t\t\t\t\"require\": \"./dist/index.d.cts\"\n\t\t\t},\n\t\t\t\"import\": \"./dist/index.mjs\",\n\t\t\t\"require\": \"./dist/index.cjs\",\n\t\t\t\"default\": \"./dist/index.mjs\"\n\t\t},\n\t\t\"./web\": {\n\t\t\t\"types\": {\n\t\t\t\t\"import\": \"./dist/web.d.mts\",\n\t\t\t\t\"require\": \"./dist/web.d.cts\"\n\t\t\t},\n\t\t\t\"import\": \"./dist/web.mjs\",\n\t\t\t\"require\": \"./dist/web.cjs\",\n\t\t\t\"default\": \"./dist/web.mjs\"\n\t\t}\n\t},\n\t\"files\": [\n\t\t\"dist\",\n\t\t\"LICENSE\"\n\t],\n\t\"publishConfig\": {\n\t\t\"access\": \"public\"\n\t},\n\t\"sideEffects\": false,\n\t\"scripts\": {\n\t\t\"clean\": \"rimraf dist\",\n\t\t\"build\": \"tsdown\",\n\t\t\"dev\": \"tsdown --watch\",\n\t\t\"typecheck\": \"tsc -p tsconfig.json --noEmit && tsc -p tsconfig.web.json --noEmit\"\n\t},\n\t\"dependencies\": {\n\t\t\"@format.dev/types\": \"workspace:*\",\n\t\t\"form-data-encoder\": \"^4.1.0\",\n\t\t\"formdata-node\": \"^6.0.3\",\n\t\t\"is-stream\": \"^4.0.1\"\n\t},\n\t\"devDependencies\": {\n\t\t\"@types/node\": \"^24.2.1\",\n\t\t\"rimraf\": \"^6.0.1\",\n\t\t\"tsdown\": \"0.17.0-beta.6\",\n\t\t\"typescript\": \"^5\"\n\t},\n\t\"engines\": {\n\t\t\"node\": \">=18.17.0\"\n\t}\n}\n","import type { FormatRegion } from './types'\nimport { version } from '../package.json'\n\nexport const REGION_MAP: Record<FormatRegion, string> = {\n\tGLOBAL: 'https://api.format.dev'\n\t// US: 'https://us.api.format.dev',\n\t// EU: 'https://eu.api.format.dev'\n} as const\n\n// API version prefix used by renderUrl() in helpers.ts. Keep it in sync with the API route.\nexport const API_PREFIX = '/v1'\n\nexport const CLIENT_IDENTIFIER = `@format.dev/client/${version}`\n\n// Shared by the Node and web builds, so nothing here may read `process` or any\n// other Node global. The Node build adds its own User-Agent in client.ts.\nexport const DEFAULTS = {\n\tbaseUrl: REGION_MAP.GLOBAL\n} as const\n","// Shared by both builds. Keep Node imports and globals in the Node entry.\nimport { API_PREFIX, DEFAULTS, REGION_MAP } from './constants'\nimport type { FormatOptions } from './types'\n\nexport function isWebReadable(x: any): x is ReadableStream<Uint8Array> {\n\treturn typeof globalThis.ReadableStream !== 'undefined' && x != null && typeof (x as any).getReader === 'function'\n}\n\nexport function isBlobLike(x: any): x is Blob {\n\treturn (\n\t\tx != null &&\n\t\ttypeof x === 'object' &&\n\t\ttypeof (x as any).arrayBuffer === 'function' &&\n\t\ttypeof (x as any).stream === 'function' &&\n\t\ttypeof (x as any).size === 'number' &&\n\t\ttypeof (x as any).type === 'string'\n\t)\n}\n\n/**\n * The API origin requests go to. `environmentBaseUrl` is the `FORMAT_BASE_URL`\n * the Node build reads from its environment. The web build does not read\n * environment variables, so it passes nothing.\n */\nexport function resolveBaseUrl(opts: FormatOptions, environmentBaseUrl?: string) {\n\tconst baseUrl =\n\t\topts.baseUrl ?? (opts.region ? REGION_MAP[opts.region] : undefined) ?? environmentBaseUrl ?? DEFAULTS.baseUrl\n\n\treturn baseUrl.replace(/\\/+$/, '') // strip trailing slash\n}\n\n/** The render endpoint under an API origin. The origin carries no version, so the prefix is added here. */\nexport function renderUrl(baseUrl: string): string {\n\treturn `${baseUrl}${API_PREFIX}/render`\n}\n\n/** The `tags` form field: trimmed, empty tags dropped, duplicates removed, sent as a JSON array. */\nexport function serializeTags(tags: string[]): string {\n\treturn JSON.stringify(Array.from(new Set(tags.map(t => t.trim()).filter(Boolean))))\n}\n\n// extract suggested filename from Content-Disposition\nexport function parseFilenameFromContentDisposition(header: string | null): string | undefined {\n\tif (!header) return\n\n\t// RFC 5987: filename*=UTF-8''file%20name.pdf\n\tconst mExt = header.match(/filename\\*\\s*=\\s*([^;]+)/i)\n\tif (mExt) {\n\t\tconst v = mExt[1].trim()\n\t\tconst m = /^([A-Za-z0-9._-]+)''(.+)$/.exec(v) // charset'lang'value\n\t\tif (m) {\n\t\t\tconst value = stripQuotes(m[2])\n\t\t\ttry {\n\t\t\t\treturn decodeURIComponent(value)\n\t\t\t} catch {\n\t\t\t\treturn value\n\t\t\t}\n\t\t}\n\t}\n\n\t// quoted filename=\"a;b.pdf\"\n\tconst mQuoted = header.match(/filename\\s*=\\s*\"([^\"]*)\"/i)\n\tif (mQuoted) return mQuoted[1]\n\n\t// bare filename=a.pdf\n\tconst mBare = header.match(/filename\\s*=\\s*([^;]+)/i)\n\tif (mBare) return mBare[1].trim()\n\n\treturn\n}\n\n// parse and normalize MIME (strip params, lowercase)\nexport function parseContentType(header: string | null): string | undefined {\n\tif (!header) {\n\t\treturn\n\t}\n\n\tconst [mime] = header.split(';', 1)\n\treturn mime?.trim().toLowerCase()\n}\n\nexport async function safeJson(body: string) {\n\ttry {\n\t\treturn JSON.parse(body)\n\t} catch {\n\t\treturn { raw: body }\n\t}\n}\n\nexport function firstHeader(header: string | string[] | null): string | undefined {\n\treturn Array.isArray(header) ? header[0] : header || undefined\n}\n\nexport function timeoutSignal(ms: number, reason = new Error('Timeout')): AbortSignal {\n\tif ((AbortSignal as any).timeout) {\n\t\treturn AbortSignal.timeout(ms)\n\t}\n\n\tconst ac = new AbortController()\n\n\tsetTimeout(() => ac.abort(reason), ms)\n\n\treturn ac.signal\n}\n\nexport function anySignal(signals: AbortSignal[]): AbortSignal {\n\tif ((AbortSignal as any).any) {\n\t\treturn AbortSignal.any(signals)\n\t}\n\n\tconst ac = new AbortController()\n\tconst aborted = signals.find(signal => signal.aborted)\n\tif (aborted) {\n\t\tac.abort(aborted.reason)\n\t\treturn ac.signal\n\t}\n\n\tconst onAbort = (event: Event) => {\n\t\tfor (const signal of signals) signal.removeEventListener('abort', onAbort)\n\t\tac.abort((event.target as AbortSignal).reason)\n\t}\n\n\tfor (const s of signals) {\n\t\ts.addEventListener('abort', onAbort, { once: true })\n\t}\n\n\treturn ac.signal\n}\n\nexport function getAbortErrorOrElse(signal: AbortSignal | undefined, cause?: unknown): Error {\n\treturn signal?.aborted\n\t\t? signal.reason instanceof Error\n\t\t\t? signal.reason\n\t\t\t: new Error('Aborted with unknown reason')\n\t\t: new Error(cause instanceof Error ? cause.message : 'Unknown internal error', { cause })\n}\n\nexport function concatUint8Array(parts: Uint8Array[], total: number): Uint8Array {\n\tif (parts.length === 1 && parts[0].byteLength === total) {\n\t\treturn parts[0]\n\t}\n\n\tlet offset = 0\n\tconst out = new Uint8Array(total)\n\n\tfor (const p of parts) {\n\t\tout.set(p, offset)\n\t\toffset += p.byteLength\n\t}\n\n\treturn out\n}\n\n/**\n * The key a client sends, or a thrown error naming how to supply one.\n * `environmentApiKey` is the `FORMAT_API_KEY` the Node build reads from its\n * environment. The web build passes nothing, so its callers have to\n * pass `apiKey` explicitly.\n */\nexport function resolveApiKey(\n\texplicitApiKey: string | undefined,\n\tenvironmentApiKey?: string,\n\thowToSupply?: string\n): string {\n\tif (explicitApiKey) {\n\t\treturn explicitApiKey\n\t}\n\n\tif (environmentApiKey) {\n\t\treturn environmentApiKey\n\t}\n\n\tthrow new Error(`Format API key is required. ${howToSupply ?? 'Pass `apiKey` explicitly.'}`)\n}\n\nfunction stripQuotes(input: string): string {\n\tif (input.length >= 2 && input[0] === '\"' && input[input.length - 1] === '\"') return input.slice(1, -1)\n\treturn input\n}\n","/**\n * Thrown when the Format API returns a non-2xx response. Contains the HTTP status code and parsed error body.\n */\nexport class FormatError extends Error {\n\tconstructor(\n\t\t/** HTTP status code from the API response. */\n\t\tpublic status: number,\n\t\t/** Parsed error response body. Typically a JSON object with error details, or `{ raw: string }` if the body couldn't be parsed. */\n\t\tpublic detail: unknown\n\t) {\n\t\tsuper(`Format API: Error ${status}`)\n\t}\n}\n","// Response handling shared by the Node and web builds.\nimport { FormatError } from './error'\nimport { concatUint8Array, parseContentType, parseFilenameFromContentDisposition, safeJson } from './helpers'\nimport type { FormatResponse } from './types'\n\n/**\n * The error a non-2xx response becomes.\n *\n * Reads at most about 1MB of the body, so an unexpectedly large error response\n * cannot exhaust memory, and parses it as JSON where it can. A body that is not\n * JSON arrives as `{ raw: body }`.\n */\nexport async function formatErrorFrom(res: Response): Promise<FormatError> {\n\tconst status = res.status ?? 0\n\n\t// read at most ~1MB of error body to avoid unbounded memory usage\n\tlet size = 0\n\tconst limit = 1_000_000\n\tconst chunks: Uint8Array[] = []\n\tconst reader = res.body?.getReader()\n\n\ttry {\n\t\tif (reader) {\n\t\t\twhile (size < limit) {\n\t\t\t\tconst { done, value } = await reader.read()\n\t\t\t\tif (done || !value?.length) break\n\t\t\t\tchunks.push(value)\n\t\t\t\tsize += value.byteLength\n\t\t\t}\n\t\t}\n\t} finally {\n\t\ttry {\n\t\t\tawait reader?.cancel()\n\t\t} catch {\n\t\t\t// ignore\n\t\t}\n\t}\n\n\t// avoid Buffer.concat so we are web/browser-friendly\n\tconst buf = concatUint8Array(chunks, size)\n\tconst body = new TextDecoder('utf-8', { fatal: false }).decode(buf)\n\tconst detail = await safeJson(body)\n\n\treturn new FormatError(status, detail)\n}\n\n/** What a successful response says about the PDF, read from its headers. */\nfunction responseDetails(res: Response): Omit<FormatResponse, keyof Response> {\n\tconst rawContentLength = res.headers.get('content-length')\n\tconst contentType = parseContentType(res.headers.get('content-type'))\n\n\treturn {\n\t\tfilename: parseFilenameFromContentDisposition(res.headers.get('content-disposition')),\n\t\tcontentLength: rawContentLength ? parseInt(rawContentLength) : undefined,\n\t\tcontentType,\n\t\ttraceparent: res.headers.get('traceparent') || undefined,\n\t\tisPdf: contentType === 'application/pdf'\n\t}\n}\n\n/**\n * Assign to the Response itself: a Proxy breaks the native methods' brand\n * checks in browsers and Node 24.\n */\nexport function augmentResponse(res: Response): FormatResponse {\n\treturn Object.assign(res, responseDetails(res))\n}\n","import { getAbortErrorOrElse } from './helpers'\nimport type { FormatDocument } from './types'\n\n/**\n * A compiled document cannot cancel its asset lookup. Reject promptly on abort\n * and cancel any stream that arrives afterwards so its source can release it.\n */\nexport async function documentAssets(\n\tdoc: FormatDocument,\n\tsignal: AbortSignal\n): Promise<ReadableStream<Uint8Array> | undefined> {\n\tif (signal.aborted) throw getAbortErrorOrElse(signal)\n\tconst pending = doc.getAssetsWebStream()\n\n\treturn new Promise((resolve, reject) => {\n\t\tconst onAbort = () => {\n\t\t\tsignal.removeEventListener('abort', onAbort)\n\t\t\treject(getAbortErrorOrElse(signal))\n\t\t}\n\t\tsignal.addEventListener('abort', onAbort, { once: true })\n\t\tif (signal.aborted) onAbort()\n\t\tpending.then(\n\t\t\tstream => {\n\t\t\t\tsignal.removeEventListener('abort', onAbort)\n\t\t\t\tif (signal.aborted) {\n\t\t\t\t\tvoid stream?.cancel(signal.reason).catch(() => {})\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tresolve(stream)\n\t\t\t},\n\t\t\terror => {\n\t\t\t\tsignal.removeEventListener('abort', onAbort)\n\t\t\t\treject(error)\n\t\t\t}\n\t\t)\n\t})\n}\n","import {\n\tanySignal,\n\tgetAbortErrorOrElse,\n\tisBlobLike,\n\tisWebReadable,\n\trenderUrl,\n\tresolveApiKey,\n\tresolveBaseUrl,\n\tserializeTags,\n\ttimeoutSignal\n} from './helpers'\nimport { augmentResponse, formatErrorFrom } from './response'\nimport { CLIENT_IDENTIFIER } from './constants'\nimport { documentAssets } from './document-assets'\nimport type { AssetLike, FormatOptions, FormatDocument, FormatPdfOptions, FormatResponse } from './types'\n\nconst ASSETS_FILENAME = 'assets.zip'\nconst ASSETS_TYPE = 'application/zip'\n\n// Cancelling the reader releases a stalled read as well as its underlying source.\nasync function readStream(stream: ReadableStream<Uint8Array>, signal: AbortSignal): Promise<Uint8Array<ArrayBuffer>[]> {\n\tconst reader = stream.getReader()\n\tconst onAbort = () => void reader.cancel(signal.reason).catch(() => {})\n\tconst chunks: Uint8Array<ArrayBuffer>[] = []\n\n\tsignal.addEventListener('abort', onAbort, { once: true })\n\n\ttry {\n\t\tif (signal.aborted) {\n\t\t\tonAbort()\n\t\t\tthrow getAbortErrorOrElse(signal)\n\t\t}\n\n\t\tfor (;;) {\n\t\t\tconst { done, value } = await reader.read()\n\t\t\tif (signal.aborted) throw getAbortErrorOrElse(signal)\n\t\t\tif (done) return chunks\n\t\t\tchunks.push(new Uint8Array(value))\n\t\t}\n\t} finally {\n\t\tsignal.removeEventListener('abort', onAbort)\n\t\treader.releaseLock()\n\t}\n}\n\n/** The assets archive as a Blob for native FormData. */\nasync function assetsToBlob(input: AssetLike, signal: AbortSignal): Promise<Blob> {\n\tif (isBlobLike(input)) {\n\t\treturn input.type === ASSETS_TYPE ? input : new Blob([input], { type: ASSETS_TYPE })\n\t}\n\n\tif (input instanceof ArrayBuffer) {\n\t\treturn new Blob([input], { type: ASSETS_TYPE })\n\t}\n\n\tif (ArrayBuffer.isView(input)) {\n\t\treturn new Blob([new Uint8Array(input)], {\n\t\t\ttype: ASSETS_TYPE\n\t\t})\n\t}\n\n\tif (isWebReadable(input)) {\n\t\treturn new Blob(await readStream(input, signal), { type: ASSETS_TYPE })\n\t}\n\n\tthrow new TypeError('Unsupported assets type. Pass a Blob, an ArrayBuffer, a Uint8Array or a ReadableStream.')\n}\n\nexport class FormatClient {\n\tprivate readonly baseUrl: string\n\tprivate readonly renderTimeoutMs: number\n\tprivate readonly apiKey: string\n\n\tconstructor(opts: FormatOptions) {\n\t\tthis.apiKey = resolveApiKey(opts?.apiKey)\n\t\tthis.baseUrl = resolveBaseUrl(opts)\n\t\tthis.renderTimeoutMs = opts.renderTimeoutMs ?? 120_000\n\t}\n\n\tasync pdf(doc: string | FormatDocument, options?: FormatPdfOptions): Promise<FormatResponse> {\n\t\t// Include asset preparation in the timeout: native FormData needs the\n\t\t// complete Blob before the client can send the request.\n\t\tconst renderTimeoutSignal = timeoutSignal(this.renderTimeoutMs)\n\t\tconst combinedSignal = options?.signal ? anySignal([options.signal, renderTimeoutSignal]) : renderTimeoutSignal\n\n\t\tconst isFormatDoc = typeof doc !== 'string'\n\t\tconst html = isFormatDoc ? doc.html : doc\n\n\t\tconst form = new FormData()\n\t\tform.set('html', html)\n\n\t\tif (options?.tags) {\n\t\t\tform.set('tags', serializeTags(options.tags))\n\t\t}\n\n\t\tlet assets = options?.assets\n\t\tif (!assets && isFormatDoc) {\n\t\t\tassets = await documentAssets(doc, combinedSignal)\n\t\t}\n\n\t\tif (assets) {\n\t\t\tform.set('assets', await assetsToBlob(assets, combinedSignal), ASSETS_FILENAME)\n\t\t}\n\n\t\t// an abort that landed while the form was being built sends nothing\n\t\tif (combinedSignal.aborted) throw getAbortErrorOrElse(combinedSignal)\n\n\t\tlet res: Response\n\n\t\ttry {\n\t\t\t// Let the browser set the multipart boundary. The explicit bearer key\n\t\t\t// authenticates the request. Cookies would prevent wildcard CORS.\n\t\t\tres = await fetch(renderUrl(this.baseUrl), {\n\t\t\t\tmethod: 'POST',\n\t\t\t\theaders: {\n\t\t\t\t\tAuthorization: `Bearer ${this.apiKey}`,\n\t\t\t\t\t'X-Format-Client': CLIENT_IDENTIFIER\n\t\t\t\t},\n\t\t\t\tbody: form,\n\t\t\t\tsignal: combinedSignal,\n\t\t\t\tcredentials: 'omit',\n\t\t\t\tmode: 'cors'\n\t\t\t})\n\t\t} catch (err) {\n\t\t\tthrow getAbortErrorOrElse(combinedSignal, err)\n\t\t}\n\n\t\tif (!res.ok) {\n\t\t\tthrow await formatErrorFrom(res)\n\t\t}\n\n\t\treturn augmentResponse(res)\n\t}\n}\n"],"mappings":";cAEY;;;;ACCZ,MAAaA,aAA2C,EACvD,QAAQ,0BAGR;AAGD,MAAa,aAAa;AAE1B,MAAa,oBAAoB,sBAAsB;AAIvD,MAAa,WAAW,EACvB,SAAS,WAAW,QACpB;;;;ACdD,SAAgB,cAAc,GAAyC;AACtE,QAAO,OAAO,WAAW,mBAAmB,eAAe,KAAK,QAAQ,OAAQ,EAAU,cAAc;;AAGzG,SAAgB,WAAW,GAAmB;AAC7C,QACC,KAAK,QACL,OAAO,MAAM,YACb,OAAQ,EAAU,gBAAgB,cAClC,OAAQ,EAAU,WAAW,cAC7B,OAAQ,EAAU,SAAS,YAC3B,OAAQ,EAAU,SAAS;;;;;;;AAS7B,SAAgB,eAAe,MAAqB,oBAA6B;AAIhF,SAFC,KAAK,YAAY,KAAK,SAAS,WAAW,KAAK,UAAU,WAAc,sBAAsB,SAAS,SAExF,QAAQ,QAAQ,GAAG;;;AAInC,SAAgB,UAAU,SAAyB;AAClD,QAAO,GAAG,UAAU,WAAW;;;AAIhC,SAAgB,cAAc,MAAwB;AACrD,QAAO,KAAK,UAAU,MAAM,KAAK,IAAI,IAAI,KAAK,KAAI,MAAK,EAAE,MAAM,CAAC,CAAC,OAAO,QAAQ,CAAC,CAAC,CAAC;;AAIpF,SAAgB,oCAAoC,QAA2C;AAC9F,KAAI,CAAC,OAAQ;CAGb,MAAM,OAAO,OAAO,MAAM,4BAA4B;AACtD,KAAI,M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