@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/CHANGELOG.md ADDED
@@ -0,0 +1,65 @@
1
+ # Changelog
2
+
3
+ ## 0.3.0
4
+
5
+ ### Packages
6
+
7
+ - The first release on npm, as two packages at the same version: **`@zpdf/sdk`**, the TypeScript SDK (`import { ZPDF } from "@zpdf/sdk"`), and **`@zpdf/cli`**, the `zpdf` command (`npx @zpdf/cli <command>`, or `npm install -g @zpdf/cli`). `@zpdf/cli` depends on `@zpdf/sdk` at exactly its own version. The SDK no longer installs a `zpdf` command; its CLI code is exported as `@zpdf/sdk/cli` for `@zpdf/cli`.
8
+ - The SDK's user agent is `zpdf-sdk-node/<version>`.
9
+
10
+ ### Added
11
+
12
+ - **Plan and billing.** `zpdf.billing.get()` returns the business's plan status: the plan, its state, the month's document allowance and how much is used, when the count resets, the paid period's end, whether a cancellation is pending and whether charging is on. `zpdf.billing.checkout()` returns a link an owner opens to move the business to the paid plan. CLI: `zpdf billing get` and `zpdf billing checkout`.
13
+ - `BillingStatus`, `BillingState`, `CheckoutLink` and `PlanCode` type exports.
14
+ - `document_limit_reached` carries `details.resets`, `details.billing_enabled`, `details.upgrade_available` and `details.checkout`, so a caller knows when documents can be made again and whether an upgrade lifts the limit.
15
+ - Error codes documented: `billing_unavailable`, `plan_already_paid`, `subscription_missing`, `subscription_ended`.
16
+ - **Rename a key.** `zpdf.keys.update(id, { name })` calls `PATCH /keys/{id}`; the secret does not change. CLI: `zpdf keys rename <id> --name <name>`. `KeyUpdateParams` type export.
17
+ - **Change a webhook endpoint.** `zpdf.webhookEndpoints.update(id, { url?, enabled_events? })` calls `PATCH /webhook_endpoints/{id}`. The signing secret stays; a new URL makes the endpoint `unverified` and is sent a challenge at once. CLI: `zpdf webhooks update <id> --url <url> --event <type>`. `WebhookEndpointUpdateParams` type export.
18
+ - `Member` has `founder` (the person whose sign-up created the business) and `you` (the signed-in member reading the list in the console; `false` for a key). `zpdf members list` shows `founder`.
19
+ - `zpdf.engine()` returns `isolation`: what the render service measured about its own sandbox, network, file system and per-render process. `EngineIsolation` type export.
20
+ - Error codes documented: `render_memory_limit`, `render_crashed`.
21
+
22
+ ### Fixed
23
+
24
+ - Documented: a body that is not valid JSON, or is not sent as JSON, answers `400 body_invalid` as a JSON error on every route, and one over 8 MB answers `413 request_too_large`. The deployed API answered malformed JSON with an HTML page.
25
+
26
+ ## 0.2.0
27
+
28
+ The API's rough edges, fixed before the package's shape is fixed. Licence: Apache-2.0.
29
+
30
+ ### Breaking
31
+
32
+ - **Every list is paginated.** `keys.list`, `members.list`, `templates.list`, `shareLinks.list`, `assets.list`, `webhookEndpoints.list` and `examples.list` return at most `limit` items (20 by default, 100 at most) where they returned everything. Each takes `{ limit, starting_after }` and returns a `ListResult`, as `documents.list` and `events.list` do: await it for one page, iterate it (`for await`) for every item, or call `.all()`.
33
+ - **List signatures.** The lists that took only request options take params first: `zpdf.keys.list(params?, options?)`, `zpdf.shareLinks.list(documentId, params?, options?)`, and the same for `assets`, `webhookEndpoints`, `members` and `examples`.
34
+ - **`templates.versions(key)` is replaced by `templateVersions.list(key)`**, and the CLI's `zpdf templates versions <key>` by `zpdf template-versions list <key>`.
35
+ - **`documents.validate` returns a `DocumentValidation`** whose `object` is `"document_validation"` (it was `"validation"`). The `Validation` type is renamed to `DocumentValidation`.
36
+ - **`TemplateVersionSummary` and `TemplateVersion` are the `template_version` object** (`object`, `id`, `template`, `current` added). The version embedded in a template is `EmbeddedTemplateVersion`.
37
+ - **Licence**: Apache-2.0 (0.1.0 was MIT).
38
+
39
+ ### Added
40
+
41
+ - `zpdf.templateVersions.list(key, params?)` and `zpdf.templateVersions.get(key, number)`; `zpdf template-versions list <key>` and `zpdf template-versions get <key> <number>`.
42
+ - `documents.validate` calls `POST /documents/validate` and is retried like a read.
43
+ - `--limit`, `--starting-after` and `--all` on every CLI list command: `examples`, `templates`, `template-versions`, `documents`, `share-links`, `assets`, `webhooks`, `events`, `keys`, `members`.
44
+ - A lost create response does not lose its secret: `keys.create`, `webhookEndpoints.create` and `shareLinks.create` return the `secret` or `url` again when repeated with the same `idempotencyKey` and params within 24 hours. `zpdf keys create`, `zpdf webhooks create` and `zpdf share-links create` take `--idempotency-key`.
45
+ - `zpdf fetch <url>` downloads a signed URL (a `download_url`, a page image, a share link's file), as `zpdf.fetchFile` does. Signed URLs and share links answer the API's JSON error, so both report `url_expired` and `share_link_unavailable` by code.
46
+ - `--dry-run` on every command prints the HTTP request it sends, without the key, and sends nothing.
47
+ - `ListParams`, `TemplateListParams`, `MemberRole` and `DOCS_URL` exports.
48
+ - Error codes documented: `owner_session_required`, `member_is_founder`, `share_link_unavailable`, `cursor_invalid`, and `parameter_unknown` on `PUT /templates/{key}`.
49
+
50
+ ### Changed
51
+
52
+ - `apiKey` defaults to `ZPDF_API_KEY`, then `ZPDF_SECRET_KEY`. The CLI reads the same two, then its config file; an empty value counts as unset.
53
+ - The default base URL (`DEFAULT_BASE_URL`) comes from `src/config.ts`, which `scripts/zpdf-build-docs.mjs` writes from `zpdf.config.json`.
54
+ - Members: the SDK and the CLI list the team. Inviting, changing a role and removing a member are done by an owner signed in to the console; the API refuses a secret key on those with `owner_session_required`.
55
+
56
+ ## 0.1.0
57
+
58
+ The first release: the TypeScript SDK and the `zpdf` command line in one package.
59
+
60
+ - `ZPDF` client with a typed method for every operation of the v1 API: sign-up, examples, templates, documents, share links, assets, webhook endpoints, events, keys, business, usage and members.
61
+ - Typed overrides: the `Override` union and the `override` builders.
62
+ - `ZPDFError` with the API's status, type, code, message, param, details and request id.
63
+ - Idempotency keys on every `POST`, retries, and async iteration over paginated lists.
64
+ - `verifyWebhook` and `signWebhook`, on WebCrypto.
65
+ - `zpdf` CLI: a command for every operation, `--json`, `zpdf login`, stable exit codes.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright (c) 2026 zpdf
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,277 @@
1
- # Temporary Holding Version
1
+ # zpdf
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The API for agents to generate documents. A template is HTML, CSS and a JSON declaration of its data; a request turns data into a PDF; an **override** changes the template for one document without touching the stored version.
4
+
5
+ Two npm packages, released together at the same version:
6
+
7
+ - **`@zpdf/sdk`**, this package, the TypeScript SDK: `import { ZPDF } from "@zpdf/sdk"`. No dependencies. ESM with types. Node 18+ and edge runtimes (it uses the global `fetch` and WebCrypto). Importing it never loads the CLI.
8
+ - **`@zpdf/cli`**, the `zpdf` command: `npx @zpdf/cli <command>`, or `zpdf <command>` after `npm install -g @zpdf/cli`. A command for every API operation, `--json` output, `--dry-run`, stable exit codes, no prompts.
9
+
10
+ Every call three ways (CLI, TypeScript, curl) is in the docs: https://zpdf.ai/docs
11
+
12
+ ## Install
13
+
14
+ ```bash
15
+ npm install @zpdf/sdk # the SDK
16
+ npm install -g @zpdf/cli # the zpdf command
17
+ npx @zpdf/cli --help # or run the command without installing
18
+ ```
19
+
20
+ ## Quickstart
21
+
22
+ ```bash
23
+ npx @zpdf/cli signup start agent@example.com # emails a 6-digit code
24
+ npx @zpdf/cli signup verify agent@example.com 123456 # prints the secret key once, and stores it
25
+ export ZPDF_API_KEY=zp_sk_…
26
+ ```
27
+
28
+ Signing up means agreeing to the [Terms](https://zpdf.ai/terms), the [Privacy Policy](https://zpdf.ai/privacy) and the [Acceptable Use Policy](https://zpdf.ai/acceptable-use).
29
+
30
+ ```ts
31
+ import { writeFile } from "node:fs/promises"
32
+ import { override, ZPDF } from "@zpdf/sdk"
33
+
34
+ const zpdf = new ZPDF({ apiKey: process.env.ZPDF_API_KEY })
35
+
36
+ // 1. Save a template (here, the invoice example).
37
+ const example = await zpdf.examples.get("invoice")
38
+ const template = await zpdf.templates.save("invoice", {
39
+ html: example.html,
40
+ css: example.css,
41
+ inputs: example.inputs,
42
+ })
43
+ console.log(template.version.regions) // the data-region names overrides can target
44
+
45
+ // 2. Generate a document.
46
+ const data = example.inputs.example!
47
+ const document = await zpdf.documents.generate({ template: "invoice", number: "INV-2041", data })
48
+ await writeFile("invoice.pdf", await zpdf.documents.download(document.id))
49
+
50
+ // 3. Change it for one document with overrides. The stored template is unchanged.
51
+ const changed = await zpdf.documents.generate({
52
+ template: "invoice",
53
+ number: "INV-2042",
54
+ data: { ...data, lc_number: "LC-88213" },
55
+ overrides: [
56
+ override.addField("lc_number", { type: "string", required: true }),
57
+ override.append("notes", "<p>Issued under documentary credit {{lc_number}}.</p>"),
58
+ override.remove("col-unit-price"),
59
+ ],
60
+ })
61
+ ```
62
+
63
+ The same from a terminal, with the command installed (`npm install -g @zpdf/cli`):
64
+
65
+ ```bash
66
+ zpdf examples pull invoice --dir .
67
+ zpdf templates push invoice --dir .
68
+ jq .example inputs.json > data.json # the template's own example as the data
69
+ zpdf documents generate invoice --data data.json --number INV-2041 -o invoice.pdf
70
+ jq '.example + {lc_number: "LC-88213"}' inputs.json > data-lc.json
71
+ zpdf documents generate invoice --data data-lc.json --number INV-2042 \
72
+ --override 'add_field:lc_number=string!' \
73
+ --override 'append:notes=<p>Issued under documentary credit {{lc_number}}.</p>' \
74
+ --override remove:col-unit-price -o invoice-lc.pdf
75
+ ```
76
+
77
+ ## The client
78
+
79
+ ```ts
80
+ const zpdf = new ZPDF({
81
+ apiKey: "zp_sk_…", // default: the ZPDF_API_KEY environment variable
82
+ baseUrl: "https://…/v1", // default: ZPDF_API, then DEFAULT_BASE_URL
83
+ maxRetries: 2, // network errors, 429 and 5xx
84
+ timeoutMs: 60_000, // per attempt
85
+ fetch, // a fetch to use instead of the global one
86
+ })
87
+ ```
88
+
89
+ Objects and parameters use the API's own snake_case names (`make_current`, `download_url`), so a value read from the SDK, from curl and from `zpdf --json` is the same value. When `ZPDF_API_KEY` is not set, the client reads `ZPDF_SECRET_KEY`.
90
+
91
+ | Resource | Methods |
92
+ | ----------------------- | ------------------------------------------------------------------------------------------------------- |
93
+ | `zpdf.signup` | `start`, `verify` |
94
+ | `zpdf.examples` | `list`, `get`, `file` |
95
+ | `zpdf.templates` | `save`, `list`, `get`, `update` |
96
+ | `zpdf.templateVersions` | `list`, `get` |
97
+ | `zpdf.documents` | `generate`, `validate`, `list`, `get`, `download`, `pageImage`, `delete`, `regenerate`, `promote` |
98
+ | `zpdf.shareLinks` | `create`, `list`, `revoke` |
99
+ | `zpdf.assets` | `upload`, `list`, `get`, `delete` |
100
+ | `zpdf.webhookEndpoints` | `create`, `list`, `verify`, `update`, `delete` |
101
+ | `zpdf.events` | `list` |
102
+ | `zpdf.keys` | `list`, `create`, `update`, `revoke` |
103
+ | `zpdf.business` | `get` |
104
+ | `zpdf.usage` | `get` |
105
+ | `zpdf.billing` | `get` (the plan, its state and the month's allowance), `checkout` (the link an owner opens to upgrade) |
106
+ | `zpdf.members` | `list` |
107
+ | `zpdf` | `info`, `engine`, `fetchFile` (reads a signed `download_url`, page image or share link's file to bytes) |
108
+
109
+ Every method takes a last argument `{ idempotencyKey?, signal?, timeoutMs? }`.
110
+
111
+ Inviting, changing and removing members is done by an owner signed in to the console. The API refuses a secret key on those operations with `owner_session_required`, so the client has `members.list` only.
112
+
113
+ ## Overrides
114
+
115
+ An override is one operation on the template; a request carries an ordered list. Region operations target an element by its `data-region` name. `template.version.regions` lists the names.
116
+
117
+ ```ts
118
+ import { override, type Override } from "@zpdf/sdk"
119
+
120
+ const overrides: Override[] = [
121
+ override.replace("letterhead", '<header data-region="letterhead"><h1>Invoice {{number}}</h1></header>'),
122
+ override.remove("col-unit-price"),
123
+ override.insertBefore("notes", "<p>Before the notes.</p>"),
124
+ override.insertAfter("notes", "<p>After the notes.</p>"),
125
+ override.append("notes", "<p>Inside, at the end.</p>"),
126
+ override.prepend("notes", "<p>Inside, at the start.</p>"),
127
+ override.css("table { font-size: 8pt; }"),
128
+ override.setAsset("logo", "partner_logo"),
129
+ override.setPage({ size: "Letter", orientation: "landscape", margin: "12mm" }),
130
+ override.addField("lc_number", { type: "string", required: true }),
131
+ override.replaceFile("css", "body { margin: 0; }"),
132
+ { op: "remove", region: "notes" }, // the plain JSON form is the same type
133
+ ]
134
+ ```
135
+
136
+ `Override` is a discriminated union on `op`, so a missing `html`, an unknown `op` or a page size that does not exist is a compile error.
137
+
138
+ ## Validate, versions, promote
139
+
140
+ ```ts
141
+ // Every check short of rendering. Makes no document; throws the error generate would throw.
142
+ const validation = await zpdf.documents.validate({ template: "invoice", data, overrides })
143
+ console.log(validation.valid, validation.version, validation.regions)
144
+
145
+ // Keep a document's overrides as the template's next version.
146
+ const promoted = await zpdf.documents.promote(document.id, { make_current: true, note: "Credit clause" })
147
+
148
+ // A template's history: summaries newest first, then any version in full.
149
+ for await (const version of zpdf.templateVersions.list("invoice")) console.log(version.number, version.note)
150
+ const first = await zpdf.templateVersions.get("invoice", 1)
151
+ console.log(first.html, first.css, first.inputs)
152
+ ```
153
+
154
+ ## Errors
155
+
156
+ ```ts
157
+ import { ZPDFError } from "@zpdf/sdk"
158
+
159
+ try {
160
+ await zpdf.documents.generate({ template: "invoice", data, overrides: [override.remove("note")] })
161
+ } catch (error) {
162
+ if (error instanceof ZPDFError && error.code === "override_region_missing") {
163
+ console.log(error.details?.did_you_mean) // "notes"
164
+ } else {
165
+ throw error
166
+ }
167
+ }
168
+ ```
169
+
170
+ `ZPDFError` carries the API's `status`, `type`, `code`, `message`, `param`, `details`, `requestId` and `docUrl`, plus `retryAfterSeconds` on a 429 and `problems` (the entries of `details.problems`: one per fault in a template, an override list or the data). Branch on `code`; quote `requestId` to support. A request that got no answer throws `ZPDFConnectionError`. `fetchFile` throws `url_expired` for a signed URL past its time and `share_link_unavailable` for a share link that is expired, revoked or unknown.
171
+
172
+ ## Idempotency and retries
173
+
174
+ Every `POST` that makes something carries an `Idempotency-Key`: yours (`{ idempotencyKey: "invoice-INV-2041" }`) or a generated one. The same key with the same body within 24 hours returns the first result, so the client's retries (network errors, `429` after `Retry-After`, `5xx`; twice by default) cannot make a duplicate. Sign-up is never retried.
175
+
176
+ A replay returns what is otherwise shown once: a new key's `secret`, a webhook endpoint's `secret` and a share link's `url`. A lost response does not lose the secret:
177
+
178
+ ```ts
179
+ const key = await zpdf.keys.create({ name: "packing-agent" }, { idempotencyKey: "key-packing-agent-1" })
180
+ const again = await zpdf.keys.create({ name: "packing-agent" }, { idempotencyKey: "key-packing-agent-1" })
181
+ console.log(again.secret === key.secret) // true
182
+ ```
183
+
184
+ ## Pagination
185
+
186
+ Every list method (`examples`, `templates`, `templateVersions`, `documents`, `shareLinks`, `assets`, `webhookEndpoints`, `events`, `keys`, `members`) takes `limit` (1 to 100, default 20) and `starting_after`, and returns a promise of one page that is also an async iterator over every item:
187
+
188
+ ```ts
189
+ const page = await zpdf.documents.list({ template: "invoice", limit: 50 }) // { data, has_more, next_cursor }
190
+ for await (const each of zpdf.documents.list({ template: "invoice" })) console.log(each.id)
191
+ const first200 = await zpdf.documents.list().all({ limit: 200 })
192
+ const keys = await zpdf.keys.list().all()
193
+ ```
194
+
195
+ ## Webhooks
196
+
197
+ ```ts
198
+ import { verifyWebhook } from "@zpdf/sdk"
199
+
200
+ export async function handle(request: Request): Promise<Response> {
201
+ const event = await verifyWebhook({
202
+ body: await request.text(),
203
+ headers: request.headers,
204
+ secret: process.env.ZPDF_WEBHOOK_SECRET!,
205
+ })
206
+ if (event.type === "endpoint.verification") return Response.json({ challenge: event.data.challenge })
207
+ return new Response(null, { status: 204 })
208
+ }
209
+ ```
210
+
211
+ `verifyWebhook` checks the `webhook-signature` (HMAC-SHA256 over `{webhook-id}.{webhook-timestamp}.{body}`) and refuses a timestamp more than 300 seconds old; it throws `ZPDFWebhookSignatureError`. Pass the raw body, not parsed JSON.
212
+
213
+ ## The command line
214
+
215
+ ```text
216
+ zpdf signup start|verify zpdf login, zpdf logout
217
+ zpdf templates push|list|get|pull|update
218
+ zpdf template-versions list|get
219
+ zpdf documents generate|validate|list|get|download|open|delete|regenerate|promote
220
+ zpdf share-links create|list|revoke zpdf fetch <signed url>
221
+ zpdf assets upload|list|get|delete
222
+ zpdf webhooks create|list|verify|update|delete|check
223
+ zpdf events list zpdf keys list|create|rename|revoke
224
+ zpdf business, zpdf usage, zpdf members list
225
+ zpdf billing get|checkout
226
+ zpdf examples list|get|file|pull zpdf info, zpdf engine
227
+ ```
228
+
229
+ `zpdf render` is `zpdf documents generate`. `zpdf <command> --help` shows the arguments, the flags and one example.
230
+
231
+ ```bash
232
+ zpdf documents validate invoice --data data.json --override remove:col-unit-price
233
+ zpdf template-versions list invoice
234
+ zpdf template-versions get invoice 2
235
+ zpdf keys list --limit 5
236
+ zpdf documents list --all --json
237
+ zpdf keys create --name packing-agent --idempotency-key key-packing-agent-1
238
+ zpdf documents generate invoice --data data.json --dry-run
239
+ ```
240
+
241
+ The contract, for agents and scripts:
242
+
243
+ 1. **stdout is only the result.** Progress, warnings and human-readable errors go to stderr.
244
+ 2. **`--json` prints exactly one JSON value on stdout**: the API's own object, with its own names.
245
+ 3. **`--json` errors are one object on stdout**: `{ "error": { "type", "code", "message", "param", "request_id" } }`, with `details` and `doc_url` when the API sent them.
246
+ 4. **Exit codes:** `0` success, `1` failure (the API's message is printed), `2` usage, `3` authentication (no key, key refused), `4` permission.
247
+ 5. **No prompts.** Nothing reads the terminal. Stdin is read only when asked (`--data -`, `--key -`, `--body -`).
248
+ 6. **The key** comes from `ZPDF_API_KEY`, then from `~/.zpdf/config.json`, written with mode 600 by `zpdf login --key zp_sk_…` and by `zpdf signup verify` (`ZPDF_CONFIG_PATH` moves the file). The base URL comes from `--api-url`, `ZPDF_API`, then the config file.
249
+ 7. **Secrets shown once** (a new key, a webhook signing secret, a share link's URL) are printed on stdout once, with a note on stderr. With `--idempotency-key`, the same command within 24 hours prints the same secret again.
250
+ 8. **Every list command** takes `--limit`, `--starting-after` and `--all`.
251
+ 9. **`--dry-run`** prints the HTTP request a command sends as one JSON object, without the key, and sends nothing.
252
+
253
+ `--override` takes one operation; repeat it, in order:
254
+
255
+ ```text
256
+ remove:REGION replace:REGION=HTML css=CSS
257
+ append:REGION=HTML prepend:REGION=HTML set_asset:NAME=ASSET
258
+ insert_before:REGION=HTML insert_after:REGION=HTML set_page:size=Letter,margin=12mm
259
+ add_field:NAME=TYPE (TYPE! makes it required) replace_file:html=HTML
260
+ ```
261
+
262
+ A value that starts with `@` is read from that file (`append:notes=@clause.html`); an argument that starts with `{` is one operation as JSON; `--overrides ops.json` reads a whole list.
263
+
264
+ ## Develop
265
+
266
+ ```bash
267
+ npm run check # typecheck and unit tests (mocked fetch)
268
+ npm run build
269
+ node scripts/check-doc-samples.mjs # every CLI, TypeScript and curl sample in the docs is real
270
+ node scripts/verify-live.mjs # the built SDK and CLI against the deployed API
271
+ ```
272
+
273
+ This README and `docs/SDK.md` are written by `node scripts/zpdf-build-docs.mjs` (run from the repository root) from `docs-src/_package/`, with the addresses in `zpdf.config.json`.
274
+
275
+ ## Licence
276
+
277
+ Apache-2.0. See [LICENSE](./LICENSE).
@@ -0,0 +1,53 @@
1
+ import { ZPDF } from "../index.js";
2
+ import { type FlagSpec, type FlagValues } from "./parse.js";
3
+ /** Everything a command touches outside its arguments, so tests can replace it. */
4
+ export interface Io {
5
+ env: Record<string, string | undefined>;
6
+ stdout(data: string | Uint8Array): void;
7
+ stderr(text: string): void;
8
+ readFile(path: string): Uint8Array;
9
+ writeFile(path: string, data: string | Uint8Array): void;
10
+ fileExists(path: string): boolean;
11
+ readStdin(): Promise<string>;
12
+ /** Opens a file or URL with the system's default application. */
13
+ open(target: string): Promise<void>;
14
+ }
15
+ export interface Context {
16
+ args: Record<string, string>;
17
+ flags: FlagValues;
18
+ io: Io;
19
+ /** The client, built from the environment and the config file. */
20
+ zpdf: ZPDF;
21
+ /** Prints one line on stdout (human output only; `--json` prints the returned value instead). */
22
+ line(text: string): void;
23
+ /** Prints one line on stderr: progress, warnings, where a file went. */
24
+ note(text: string): void;
25
+ }
26
+ export interface Command {
27
+ /** For example `templates push`. */
28
+ name: string;
29
+ aliases?: string[];
30
+ summary: string;
31
+ /** The API operation, as the reference writes it. */
32
+ operation: string;
33
+ args?: {
34
+ name: string;
35
+ help: string;
36
+ optional?: boolean;
37
+ }[];
38
+ flags?: FlagSpec[];
39
+ example: string;
40
+ /** More help, shown after the flags. */
41
+ notes?: string;
42
+ /** Runs the command and returns the value `--json` prints. */
43
+ run(context: Context): Promise<unknown>;
44
+ /** Prints the value for a person. Default: its scalar fields, one per line. */
45
+ human?(value: never, context: Context): void;
46
+ }
47
+ export declare function table(context: Context, columns: string[], rows: Record<string, unknown>[]): void;
48
+ /** `name: value` lines for the listed fields that are present. */
49
+ export declare function fields(context: Context, value: Record<string, unknown>, names: string[]): void;
50
+ export declare const commands: Command[];
51
+ /** The key in the environment: `ZPDF_API_KEY`, then `ZPDF_SECRET_KEY`. An empty value counts as unset. */
52
+ export declare function environmentKey(env: Record<string, string | undefined>): string | undefined;
53
+ export declare function registerFetch(io: Io, fetch: ((input: string, init?: RequestInit) => Promise<Response>) | undefined): void;