@zpdf/sdk 0.0.0-stage → 0.3.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/dist/http.js ADDED
@@ -0,0 +1,156 @@
1
+ import { ZPDFConnectionError, ZPDFError } from "./errors.js";
2
+ import { randomUUID } from "./runtime.js";
3
+ function sleep(milliseconds, signal) {
4
+ return new Promise((resolve, reject) => {
5
+ const timer = setTimeout(resolve, milliseconds);
6
+ signal?.addEventListener("abort", () => {
7
+ clearTimeout(timer);
8
+ reject(signal.reason instanceof Error ? signal.reason : new Error("Aborted"));
9
+ }, { once: true });
10
+ });
11
+ }
12
+ export function buildUrl(baseUrl, path, query) {
13
+ const pairs = [];
14
+ for (const [name, value] of Object.entries(query ?? {})) {
15
+ if (value === undefined)
16
+ continue;
17
+ // Brackets stay literal: the API reads metadata[order]=… as written.
18
+ const encodedName = encodeURIComponent(name).replace(/%5B/g, "[").replace(/%5D/g, "]");
19
+ pairs.push(`${encodedName}=${encodeURIComponent(String(value))}`);
20
+ }
21
+ return `${baseUrl}${path}${pairs.length > 0 ? `?${pairs.join("&")}` : ""}`;
22
+ }
23
+ async function errorFromResponse(response) {
24
+ const text = await response.text().catch(() => "");
25
+ const requestId = response.headers.get("request-id") ?? undefined;
26
+ const retryAfter = Number(response.headers.get("retry-after"));
27
+ let parsed;
28
+ try {
29
+ parsed = JSON.parse(text);
30
+ }
31
+ catch {
32
+ parsed = undefined;
33
+ }
34
+ const error = parsed?.error;
35
+ if (error !== undefined && typeof error === "object" && typeof error.code === "string") {
36
+ return new ZPDFError({
37
+ status: response.status,
38
+ type: typeof error.type === "string" ? error.type : "api_error",
39
+ code: error.code,
40
+ message: typeof error.message === "string" ? error.message : `HTTP ${response.status}`,
41
+ param: typeof error.param === "string" ? error.param : undefined,
42
+ details: error.details ?? undefined,
43
+ requestId: typeof error.request_id === "string" ? error.request_id : requestId,
44
+ docUrl: typeof error.doc_url === "string" ? error.doc_url : undefined,
45
+ retryAfterSeconds: Number.isFinite(retryAfter) && retryAfter > 0 ? retryAfter : undefined,
46
+ });
47
+ }
48
+ return new ZPDFError({
49
+ status: response.status,
50
+ type: response.status >= 500 ? "api_error" : "invalid_request_error",
51
+ code: "unexpected_response",
52
+ message: `The API answered HTTP ${response.status} without an error object.`,
53
+ requestId,
54
+ });
55
+ }
56
+ function shouldRetry(error) {
57
+ if (error instanceof ZPDFConnectionError)
58
+ return true;
59
+ if (!(error instanceof ZPDFError))
60
+ return false;
61
+ if (error.code === "idempotency_in_progress")
62
+ return true;
63
+ if (error.status === 429)
64
+ return error.retryAfterSeconds === undefined || error.retryAfterSeconds <= 60;
65
+ return error.status >= 500;
66
+ }
67
+ export async function send(config, request) {
68
+ const headers = { accept: "application/json" };
69
+ if (config.userAgent !== undefined)
70
+ headers["user-agent"] = config.userAgent;
71
+ if (request.auth !== false) {
72
+ if (config.apiKey === undefined || config.apiKey === "") {
73
+ throw new ZPDFError({
74
+ status: 401,
75
+ type: "authentication_error",
76
+ code: "key_missing",
77
+ message: "No API key. Pass new ZPDF({ apiKey }) or set ZPDF_API_KEY. Sign up with zpdf.signup.start({ email }).",
78
+ });
79
+ }
80
+ headers.authorization = `Bearer ${config.apiKey}`;
81
+ }
82
+ let body;
83
+ if (request.form !== undefined) {
84
+ body = request.form;
85
+ }
86
+ else if (request.body !== undefined) {
87
+ headers["content-type"] = "application/json";
88
+ body = JSON.stringify(request.body);
89
+ }
90
+ if (request.method === "POST" && request.idempotent !== false && request.readOnly !== true) {
91
+ headers["idempotency-key"] = request.options?.idempotencyKey ?? (await randomUUID());
92
+ }
93
+ const url = buildUrl(config.baseUrl, request.path, request.query);
94
+ const timeoutMs = request.options?.timeoutMs ?? config.timeoutMs;
95
+ // A POST the API does not replay is sent once: a second attempt could act twice.
96
+ const attempts = request.method === "POST" && request.idempotent === false ? 1 : config.maxRetries + 1;
97
+ let lastError;
98
+ for (let attempt = 0; attempt < attempts; attempt++) {
99
+ if (attempt > 0) {
100
+ const retryAfter = lastError instanceof ZPDFError ? lastError.retryAfterSeconds : undefined;
101
+ const backoff = Math.min(8000, 500 * 2 ** (attempt - 1)) * (0.75 + Math.random() * 0.5);
102
+ await sleep(retryAfter !== undefined ? retryAfter * 1000 : backoff, request.options?.signal);
103
+ }
104
+ const controller = new AbortController();
105
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
106
+ const outer = request.options?.signal;
107
+ const onAbort = () => controller.abort();
108
+ outer?.addEventListener("abort", onAbort, { once: true });
109
+ try {
110
+ if (outer?.aborted === true)
111
+ controller.abort();
112
+ let response;
113
+ try {
114
+ response = await config.fetch(url, {
115
+ method: request.method,
116
+ headers,
117
+ body,
118
+ signal: controller.signal,
119
+ });
120
+ }
121
+ catch (error) {
122
+ if (outer?.aborted === true)
123
+ throw error;
124
+ throw new ZPDFConnectionError(controller.signal.aborted
125
+ ? `No answer from ${request.method} ${request.path} within ${timeoutMs} ms.`
126
+ : `Could not reach ${config.baseUrl}: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
127
+ }
128
+ if (!response.ok) {
129
+ throw await errorFromResponse(response);
130
+ }
131
+ if (request.expect === "bytes") {
132
+ return new Uint8Array(await response.arrayBuffer());
133
+ }
134
+ if (request.expect === "text") {
135
+ return (await response.text());
136
+ }
137
+ const text = await response.text();
138
+ try {
139
+ return (text === "" ? {} : JSON.parse(text));
140
+ }
141
+ catch (error) {
142
+ throw new ZPDFConnectionError(`${request.method} ${request.path} answered ${response.status} with a body that is not JSON.`, { cause: error });
143
+ }
144
+ }
145
+ catch (error) {
146
+ lastError = error;
147
+ if (outer?.aborted === true || !shouldRetry(error))
148
+ throw error;
149
+ }
150
+ finally {
151
+ clearTimeout(timer);
152
+ outer?.removeEventListener("abort", onAbort);
153
+ }
154
+ }
155
+ throw lastError;
156
+ }
@@ -0,0 +1,13 @@
1
+ export { ZPDF, DEFAULT_BASE_URL } from "./client.js";
2
+ export { DOCS_URL } from "./config.js";
3
+ export type { ZPDFOptions } from "./client.js";
4
+ export { ZPDFError, ZPDFConnectionError, ZPDFWebhookSignatureError } from "./errors.js";
5
+ export type { ZPDFErrorType } from "./errors.js";
6
+ export type { FetchLike, RequestOptions } from "./http.js";
7
+ export { override, overrideOps } from "./overrides.js";
8
+ export type { AddFieldOverride, AppendOverride, CssOverride, InsertAfterOverride, InsertBeforeOverride, Override, OverrideOp, PrependOverride, RegionOverride, RemoveOverride, ReplaceFileOverride, ReplaceOverride, SetAssetOverride, SetPageOverride, } from "./overrides.js";
9
+ export type { AutoPaging, ListResult } from "./pagination.js";
10
+ export { signWebhook, verifyWebhook } from "./webhooks.js";
11
+ export type { HeadersInput, VerifyWebhookParams } from "./webhooks.js";
12
+ export { VERSION } from "./version.js";
13
+ export type * from "./types.js";
package/dist/index.js ADDED
@@ -0,0 +1,6 @@
1
+ export { ZPDF, DEFAULT_BASE_URL } from "./client.js";
2
+ export { DOCS_URL } from "./config.js";
3
+ export { ZPDFError, ZPDFConnectionError, ZPDFWebhookSignatureError } from "./errors.js";
4
+ export { override, overrideOps } from "./overrides.js";
5
+ export { signWebhook, verifyWebhook } from "./webhooks.js";
6
+ export { VERSION } from "./version.js";
@@ -0,0 +1,122 @@
1
+ /**
2
+ * Overrides: an ordered list of operations on a template, sent with a generate
3
+ * request and applied before the data is filled in. The stored template does
4
+ * not change.
5
+ *
6
+ * A region is any element carrying `data-region="name"`. Operations run
7
+ * strictly in list order; each sees the template as the previous one left it.
8
+ *
9
+ * await zpdf.documents.generate({
10
+ * template: "invoice",
11
+ * data,
12
+ * overrides: [
13
+ * override.addField("lc_number", { type: "string", required: true }),
14
+ * override.append("notes", "<p>Issued under documentary credit {{lc_number}}.</p>"),
15
+ * override.remove("col-unit-price"),
16
+ * ],
17
+ * })
18
+ */
19
+ import type { FieldDecl, PageDecl } from "./types.js";
20
+ /** Replaces the region's element with the fragment. */
21
+ export interface ReplaceOverride {
22
+ op: "replace";
23
+ region: string;
24
+ html: string;
25
+ }
26
+ /** Removes every element carrying that region name. */
27
+ export interface RemoveOverride {
28
+ op: "remove";
29
+ region: string;
30
+ }
31
+ /** Adds a fragment just before the region's element. */
32
+ export interface InsertBeforeOverride {
33
+ op: "insert_before";
34
+ region: string;
35
+ html: string;
36
+ }
37
+ /** Adds a fragment just after the region's element. */
38
+ export interface InsertAfterOverride {
39
+ op: "insert_after";
40
+ region: string;
41
+ html: string;
42
+ }
43
+ /** Adds a fragment inside the region, at the end. */
44
+ export interface AppendOverride {
45
+ op: "append";
46
+ region: string;
47
+ html: string;
48
+ }
49
+ /** Adds a fragment inside the region, at the start. */
50
+ export interface PrependOverride {
51
+ op: "prepend";
52
+ region: string;
53
+ html: string;
54
+ }
55
+ /** Appends CSS after the template's own, so it wins on equal specificity. */
56
+ export interface CssOverride {
57
+ op: "css";
58
+ css: string;
59
+ }
60
+ /** Points a named asset (logo, stamp, signature) at a different stored file, by id or name. */
61
+ export interface SetAssetOverride {
62
+ op: "set_asset";
63
+ name: string;
64
+ asset: string;
65
+ }
66
+ /** Changes page size, orientation, margin, header or footer. */
67
+ export interface SetPageOverride {
68
+ op: "set_page";
69
+ page: PageDecl;
70
+ }
71
+ /**
72
+ * Declares one more input, so a fragment can use it. `name` may be dotted to
73
+ * add a field to an object or to the rows of an array (`packages.lot`).
74
+ */
75
+ export interface AddFieldOverride {
76
+ op: "add_field";
77
+ name: string;
78
+ field: FieldDecl;
79
+ }
80
+ /** Replaces the template's whole HTML or CSS file. */
81
+ export interface ReplaceFileOverride {
82
+ op: "replace_file";
83
+ file: "html" | "css";
84
+ content: string;
85
+ }
86
+ /** One override operation. The list sent as `overrides` is applied in order. */
87
+ export type Override = ReplaceOverride | RemoveOverride | InsertBeforeOverride | InsertAfterOverride | AppendOverride | PrependOverride | CssOverride | SetAssetOverride | SetPageOverride | AddFieldOverride | ReplaceFileOverride;
88
+ export type OverrideOp = Override["op"];
89
+ /** Every `op` the API accepts, in the order the documentation lists them. */
90
+ export declare const overrideOps: readonly ["replace", "remove", "insert_before", "insert_after", "append", "prepend", "css", "set_asset", "set_page", "add_field", "replace_file"];
91
+ /** Operations that target a `data-region`. */
92
+ export type RegionOverride = Extract<Override, {
93
+ region: string;
94
+ }>;
95
+ /**
96
+ * Builders for override operations. Each returns the plain object the API
97
+ * takes, so builders and literals mix freely in one list.
98
+ */
99
+ export declare const override: {
100
+ /** Replaces the region's element with `html`. */
101
+ readonly replace: (region: string, html: string) => ReplaceOverride;
102
+ /** Removes every element carrying the region name. */
103
+ readonly remove: (region: string) => RemoveOverride;
104
+ /** Adds `html` just before the region. */
105
+ readonly insertBefore: (region: string, html: string) => InsertBeforeOverride;
106
+ /** Adds `html` just after the region. */
107
+ readonly insertAfter: (region: string, html: string) => InsertAfterOverride;
108
+ /** Adds `html` inside the region, at the end. */
109
+ readonly append: (region: string, html: string) => AppendOverride;
110
+ /** Adds `html` inside the region, at the start. */
111
+ readonly prepend: (region: string, html: string) => PrependOverride;
112
+ /** Appends CSS after the template's own. */
113
+ readonly css: (css: string) => CssOverride;
114
+ /** Points the asset `name` at another stored asset, by id or name. */
115
+ readonly setAsset: (name: string, asset: string) => SetAssetOverride;
116
+ /** Changes page size, orientation, margin, header or footer. */
117
+ readonly setPage: (page: PageDecl) => SetPageOverride;
118
+ /** Declares one more input field. `name` may be dotted (`packages.lot`). */
119
+ readonly addField: (name: string, field: FieldDecl) => AddFieldOverride;
120
+ /** Replaces the whole HTML or CSS file. */
121
+ readonly replaceFile: (file: "html" | "css", content: string) => ReplaceFileOverride;
122
+ };
@@ -0,0 +1,72 @@
1
+ /**
2
+ * Overrides: an ordered list of operations on a template, sent with a generate
3
+ * request and applied before the data is filled in. The stored template does
4
+ * not change.
5
+ *
6
+ * A region is any element carrying `data-region="name"`. Operations run
7
+ * strictly in list order; each sees the template as the previous one left it.
8
+ *
9
+ * await zpdf.documents.generate({
10
+ * template: "invoice",
11
+ * data,
12
+ * overrides: [
13
+ * override.addField("lc_number", { type: "string", required: true }),
14
+ * override.append("notes", "<p>Issued under documentary credit {{lc_number}}.</p>"),
15
+ * override.remove("col-unit-price"),
16
+ * ],
17
+ * })
18
+ */
19
+ /** Every `op` the API accepts, in the order the documentation lists them. */
20
+ export const overrideOps = [
21
+ "replace",
22
+ "remove",
23
+ "insert_before",
24
+ "insert_after",
25
+ "append",
26
+ "prepend",
27
+ "css",
28
+ "set_asset",
29
+ "set_page",
30
+ "add_field",
31
+ "replace_file",
32
+ ];
33
+ /**
34
+ * Builders for override operations. Each returns the plain object the API
35
+ * takes, so builders and literals mix freely in one list.
36
+ */
37
+ export const override = {
38
+ /** Replaces the region's element with `html`. */
39
+ replace: (region, html) => ({ op: "replace", region, html }),
40
+ /** Removes every element carrying the region name. */
41
+ remove: (region) => ({ op: "remove", region }),
42
+ /** Adds `html` just before the region. */
43
+ insertBefore: (region, html) => ({
44
+ op: "insert_before",
45
+ region,
46
+ html,
47
+ }),
48
+ /** Adds `html` just after the region. */
49
+ insertAfter: (region, html) => ({
50
+ op: "insert_after",
51
+ region,
52
+ html,
53
+ }),
54
+ /** Adds `html` inside the region, at the end. */
55
+ append: (region, html) => ({ op: "append", region, html }),
56
+ /** Adds `html` inside the region, at the start. */
57
+ prepend: (region, html) => ({ op: "prepend", region, html }),
58
+ /** Appends CSS after the template's own. */
59
+ css: (css) => ({ op: "css", css }),
60
+ /** Points the asset `name` at another stored asset, by id or name. */
61
+ setAsset: (name, asset) => ({ op: "set_asset", name, asset }),
62
+ /** Changes page size, orientation, margin, header or footer. */
63
+ setPage: (page) => ({ op: "set_page", page }),
64
+ /** Declares one more input field. `name` may be dotted (`packages.lot`). */
65
+ addField: (name, field) => ({ op: "add_field", name, field }),
66
+ /** Replaces the whole HTML or CSS file. */
67
+ replaceFile: (file, content) => ({
68
+ op: "replace_file",
69
+ file,
70
+ content,
71
+ }),
72
+ };
@@ -0,0 +1,20 @@
1
+ import type { Page } from "./types.js";
2
+ /** Every item of a list, across pages, as an async iterator. */
3
+ export interface AutoPaging<T> extends AsyncIterable<T> {
4
+ /** Reads pages until `limit` items are collected or the list ends. */
5
+ all(options?: {
6
+ limit?: number;
7
+ }): Promise<T[]>;
8
+ }
9
+ /**
10
+ * What a list method returns: a promise of the first page that is also an
11
+ * async iterator over every item.
12
+ *
13
+ * const page = await zpdf.documents.list({ template: "invoice" })
14
+ * for await (const document of zpdf.documents.list({ template: "invoice" })) { … }
15
+ * const first200 = await zpdf.documents.list().all({ limit: 200 })
16
+ */
17
+ export type ListResult<T> = Promise<Page<T>> & AutoPaging<T>;
18
+ export declare function makeList<T, P extends {
19
+ starting_after?: string;
20
+ }>(fetchPage: (params: P) => Promise<Page<T>>, params: P): ListResult<T>;
@@ -0,0 +1,32 @@
1
+ export function makeList(fetchPage, params) {
2
+ let first;
3
+ const firstPage = () => (first ?? (first = fetchPage(params)));
4
+ async function* iterate() {
5
+ let page = await firstPage();
6
+ for (;;) {
7
+ yield* page.data;
8
+ if (!page.has_more || page.next_cursor === null)
9
+ return;
10
+ page = await fetchPage({ ...params, starting_after: page.next_cursor });
11
+ }
12
+ }
13
+ const result = {
14
+ then: (resolve, reject) => firstPage().then(resolve, reject),
15
+ catch: (reject) => firstPage().catch(reject),
16
+ finally: (done) => firstPage().finally(done),
17
+ [Symbol.asyncIterator]: () => iterate(),
18
+ async all(options) {
19
+ const items = [];
20
+ const limit = options?.limit ?? Infinity;
21
+ if (limit <= 0)
22
+ return items;
23
+ for await (const item of iterate()) {
24
+ items.push(item);
25
+ if (items.length >= limit)
26
+ break;
27
+ }
28
+ return items;
29
+ },
30
+ };
31
+ return result;
32
+ }
@@ -0,0 +1,5 @@
1
+ /** WebCrypto in every runtime: global on edge runtimes and Node 19+, from `node:crypto` on Node 18. */
2
+ export declare function getWebCrypto(): Promise<Crypto>;
3
+ export declare function randomUUID(): Promise<string>;
4
+ export declare function base64ToBytes(text: string): Uint8Array;
5
+ export declare function bytesToBase64(bytes: Uint8Array): string;
@@ -0,0 +1,31 @@
1
+ /** WebCrypto in every runtime: global on edge runtimes and Node 19+, from `node:crypto` on Node 18. */
2
+ export async function getWebCrypto() {
3
+ const existing = globalThis.crypto;
4
+ if (existing?.subtle !== undefined) {
5
+ return existing;
6
+ }
7
+ const nodeCrypto = "node:crypto";
8
+ const module = (await import(nodeCrypto));
9
+ return module.webcrypto;
10
+ }
11
+ export async function randomUUID() {
12
+ const crypto = await getWebCrypto();
13
+ if (typeof crypto.randomUUID === "function") {
14
+ return crypto.randomUUID();
15
+ }
16
+ const bytes = crypto.getRandomValues(new Uint8Array(16));
17
+ return Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
18
+ }
19
+ export function base64ToBytes(text) {
20
+ const binary = atob(text);
21
+ const bytes = new Uint8Array(binary.length);
22
+ for (let index = 0; index < binary.length; index++)
23
+ bytes[index] = binary.charCodeAt(index);
24
+ return bytes;
25
+ }
26
+ export function bytesToBase64(bytes) {
27
+ let binary = "";
28
+ for (const byte of bytes)
29
+ binary += String.fromCharCode(byte);
30
+ return btoa(binary);
31
+ }