craterview 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (4) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +273 -0
  3. package/index.ts +731 -0
  4. package/package.json +30 -0
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright 2026 CraterView
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,273 @@
1
+ # craterview
2
+
3
+ TypeScript client for the [CraterView](https://craterview.ai) image enhancement and
4
+ restoration API.
5
+
6
+ ```bash
7
+ npm install craterview
8
+ ```
9
+
10
+ Node 18 or newer, or any modern browser. **Zero runtime dependencies** — `fetch`, `Blob`
11
+ and `crypto.getRandomValues` are standard in both, so the client installs without dragging
12
+ a transitive tree behind it.
13
+
14
+ ## Quickstart
15
+
16
+ ```ts
17
+ import { CraterView } from "craterview";
18
+
19
+ const cv = new CraterView({ apiKey: "cv_..." });
20
+ const job = await cv.run(file, { style: "photo" });
21
+ const blob = await job.blob();
22
+ ```
23
+
24
+ `run()` collapses the upload → submit → poll sequence into one call. That sequence is the
25
+ API's shape rather than an accident, but it is not something every caller should have to
26
+ reimplement.
27
+
28
+ ## An API key
29
+
30
+ Keys begin with `cv_` and are issued from your dashboard.
31
+
32
+ ```ts
33
+ const cv = new CraterView({ apiKey: process.env.CRATERVIEW_API_KEY });
34
+ ```
35
+
36
+ A key carries your whole allowance and does not expire. **Do not ship one to a browser** —
37
+ it is extractable from anything you send there. Call the API from your server and give the
38
+ browser a session instead.
39
+
40
+ ## The one call
41
+
42
+ ```ts
43
+ const job = await cv.run(image, { // Blob | ArrayBuffer | Uint8Array
44
+ model: "cv-restore-v1", // default
45
+ wait: 30, // seconds to hold the connection open
46
+ timeoutMs: 600_000, // total before giving up
47
+ style: "photo", // model parameters pass straight through
48
+ });
49
+ ```
50
+
51
+ It waits server-side first, so a job that finishes quickly costs a single round trip, then
52
+ falls back to polling for anything slower. A job that fails throws `JobFailed`.
53
+
54
+ Which parameters a model accepts is published by the API rather than hard-coded here — see
55
+ `cv.models()`.
56
+
57
+ ## The explicit path
58
+
59
+ Useful when you want to hold the key, submit later, or fan out.
60
+
61
+ ```ts
62
+ const inputKey = await cv.upload(file); // → "inputs/..."
63
+ let job = await cv.submit(inputKey, { style: "photo" });
64
+ job = await cv.waitFor(job, 600_000);
65
+ const blob = await job.blob();
66
+ ```
67
+
68
+ Image bytes never pass through the API. `upload()` PUTs them straight to object storage on
69
+ a presigned URL and `blob()` GETs the result the same way; the API moves keys, not pixels.
70
+
71
+ ## Retries are yours to write
72
+
73
+ **This client does not retry.** That is deliberate: only the caller knows where one logical
74
+ request ends and the next begins, and a retry the client invented would be a second job you
75
+ are billed for.
76
+
77
+ What it gives you instead is a key generator. Make one key per *logical request* and reuse
78
+ it for every attempt at that request:
79
+
80
+ ```ts
81
+ import { newIdempotencyKey, CraterViewError } from "craterview";
82
+
83
+ const key = newIdempotencyKey(); // once, before the first attempt
84
+ let job;
85
+ for (let attempt = 0; attempt < 3; attempt++) {
86
+ try {
87
+ job = await cv.submit(inputKey, { idempotencyKey: key, style: "photo" });
88
+ break;
89
+ } catch (e) {
90
+ if (e instanceof CraterViewError) throw e; // the server answered; do not retry
91
+ continue; // same key, so at most one job is created
92
+ }
93
+ }
94
+ ```
95
+
96
+ Generating a fresh key per attempt defeats the point entirely — the server has nothing to
97
+ match against and every attempt starts its own job. Reusing a key with a *different* body
98
+ is rejected with 409 rather than quietly handing back the earlier result. Claims are kept
99
+ for 24 hours; past that the same key starts new work.
100
+
101
+ ## Errors
102
+
103
+ Everything thrown by this client extends `CraterViewError`, so one `catch` handles the lot.
104
+ `.status` carries the HTTP status where there was one.
105
+
106
+ | Class | Meaning |
107
+ |---|---|
108
+ | `RateLimited` | 429. `.retryAfter` is seconds until the window rolls over. |
109
+ | `JobFailed` | The job ran and did not succeed. `.message` says what you can do about it; `.errorCode` is the half to branch on. |
110
+ | `CraterViewError` | Everything else, including 4xx and 5xx from the API. |
111
+
112
+ These subclass `Error` under an ES2020 target so `instanceof` works. Compiling this package
113
+ down to ES5 silently breaks that, and `catch (e) { if (e instanceof RateLimited) }` — the
114
+ exact code you write to handle a 429 — would never match.
115
+
116
+ ## `Job`
117
+
118
+ Every field the API publishes on a job is exposed here.
119
+
120
+ | | |
121
+ |---|---|
122
+ | `id`, `model`, `status` | `status` is one of `queued`, `running`, `succeeded`, `failed` |
123
+ | `createdAt` | `Date`, or `null` |
124
+ | `succeeded`, `done` | `done` covers both terminal states |
125
+ | `error` | Set when the job failed. Safe to show a user |
126
+ | `errorCode` | The same fact, as a stable identifier. Branch on this, show the other |
127
+ | `credits` | **What you were billed** |
128
+ | `etaSeconds` | The estimate made at submit. Absent once the job has settled |
129
+ | `community` | True when the job is on the community queue: served after priority work, taking a small share of it |
130
+ | `outputUrl`, `downloadUrl` | The result, presigned. One to display, one to save |
131
+ | `thumbUrl` | A small JPEG of the result, for listings. Null when none was drawn |
132
+ | `inputUrl` | The file you sent. Null once it has expired — inputs go after a day |
133
+ | `contentType` | The result's media type |
134
+ | `outputBytes` | The result's size in bytes |
135
+ | `blob()`, `arrayBuffer()` | Download the result |
136
+
137
+ `result` is the whole of what the job produced, and the five rows above it that describe the
138
+ file are getters onto `result.output` rather than separate fields — the API states those links
139
+ once. A model with no file to hand back returns its answer in `result` and leaves every one of
140
+ them null.
141
+
142
+ `credits` is the only figure about cost the API states, and the price is fixed and published
143
+ per model, so an invoice reconciles against `credits` alone. For how long a job took, subtract
144
+ `createdAt` from `finishedAt` — that is the wait you had, queue included.
145
+
146
+ **Uploads declare their size.** `upload()` and `run()` take the length from the `Blob`
147
+ they are about to send and declare it; the API signs it into the presigned URL, so storage
148
+ accepts exactly that length and nothing else. You do not pass it — it is read off the data
149
+ in hand, which is what makes it impossible to get wrong.
150
+
151
+ **Running out of credit does not stop you.** A job submitted against a balance of zero is
152
+ accepted, charged and run — it simply waits in the community queue for capacity that paid
153
+ work is not using, and comes back with `community` set. There is no payment error to
154
+ handle: credit buys a place at the front of the queue rather than the right to submit.
155
+ `etaSeconds` covers the whole wait, queue time included, so a community job simply reports
156
+ a longer one.
157
+
158
+ `outputUrl` and `downloadUrl` are the same object signed two ways; the content disposition
159
+ is signed in, so the second cannot be derived from the first. Both expire, so fetch the
160
+ result rather than storing the link.
161
+
162
+ `thumbUrl` and `inputUrl` are for building a job listing: a few-hundred-pixel preview so a
163
+ page of results costs kilobytes, and the original so a result can be shown against what made
164
+ it. They keep very different company on expiry — the preview lives as long as the result,
165
+ while inputs are deleted a day in — so treat a missing `inputUrl` as normal rather than as an
166
+ error.
167
+
168
+ ## Webhooks
169
+
170
+ Pass `webhookUrl` on submit — an absolute `http` or `https` URL, refused at submit if it is
171
+ not one — and we `POST` to it once the job settles. Verify every delivery before you act on
172
+ it: anyone who learns your URL can send you a plausible-looking body.
173
+
174
+ ```ts
175
+ import { CraterView, verifyWebhook, InvalidSignature } from "craterview";
176
+
177
+ const secret = await new CraterView({ apiKey: "cv_..." }).webhookSecret();
178
+
179
+ app.post("/hooks/craterview",
180
+ express.raw({ type: "application/json" }), // the bytes, not a parsed object
181
+ async (req, res) => {
182
+ let event;
183
+ try {
184
+ event = await verifyWebhook(req.body, req.headers, secret);
185
+ } catch (e) {
186
+ if (e instanceof InvalidSignature) return res.sendStatus(400);
187
+ throw e;
188
+ }
189
+
190
+ // Answer now and work afterwards. A slow endpoint is retried while it is still
191
+ // working, so treat deliveries as at-least-once and make this idempotent on `id`.
192
+ res.sendStatus(200);
193
+ await enqueue(event.id);
194
+ });
195
+ ```
196
+
197
+ Every copy of a delivery states the same thing, so the first one you accept is the whole
198
+ answer — later copies of an `id` you have already handled can be dropped rather than
199
+ reconciled.
200
+
201
+ **Pass the raw body.** Most frameworks parse JSON for you, and re-serialising it changes the
202
+ bytes the signature was computed over — hence `express.raw` above.
203
+
204
+ `verifyWebhook` is async because it uses WebCrypto, which is what lets it run unchanged in
205
+ Node, a browser, and edge runtimes without a crypto dependency.
206
+
207
+ The body is a `WebhookEvent`, which carries the same fields a job read does, by the same names
208
+ — including `result` and the links inside it. The one difference is what happens to a field
209
+ that does not apply: a callback states every key and sets it `null`, where a job read leaves
210
+ it out.
211
+
212
+ The links expire like any others. A delivery normally arrives within seconds of the job
213
+ settling and they are good for an hour, but a subscriber that queues work for later should
214
+ read the job again rather than storing them.
215
+
216
+ ### Rotating the secret
217
+
218
+ ```ts
219
+ const next = await cv.rotateWebhookSecret();
220
+ ```
221
+
222
+ The old secret keeps being sent alongside the new one for a day, and `verifyWebhook` accepts
223
+ either — so deploy the new one whenever suits rather than the moment you asked for it.
224
+
225
+ ## Managing keys
226
+
227
+ ```ts
228
+ await cv.keys(); // every key on the account, by prefix; revoked ones stay
229
+ await cv.createKey("staging"); // the value is in this response and nowhere else
230
+ await cv.revokeKey("key_..."); // immediate, and not reversible
231
+ ```
232
+
233
+ Several keys on one account is the ordinary arrangement — one per service or environment, so
234
+ revoking one leaves the others working. They share the account's credits and history.
235
+
236
+ To rotate without downtime: create the new key, move your clients onto it, then revoke the
237
+ old one. You cannot revoke the key you are calling with.
238
+
239
+ ## Everything else
240
+
241
+ ```ts
242
+ await cv.models(); // models, parameter schemas, queue depth
243
+ await cv.job("job_..."); // one job by id
244
+ await cv.usage(); // credit balance, spend and job counts
245
+
246
+ for await (const job of cv.jobs({ limit: 50, status: "succeeded" })) {
247
+ console.log(job.id, job.status); // newest first, paging transparently
248
+ }
249
+ ```
250
+
251
+ ## Configuration
252
+
253
+ ```ts
254
+ new CraterView({
255
+ apiKey: undefined,
256
+ baseUrl: "https://api.craterview.ai",
257
+ });
258
+ ```
259
+
260
+ `baseUrl` is what you change to point at a local gateway.
261
+
262
+ ## Versioning
263
+
264
+ Semver, from `0.1.0` on. A release that removes an exported member, renames a field on `Job`
265
+ or `ModelInfo`, or changes the type of one, gets a minor bump while this is `0.x` and a major
266
+ bump after `1.0.0`; anything purely additive gets a patch. Pin what you depend on.
267
+
268
+ The API this wraps adds fields to its responses without warning, so treat an unfamiliar key in
269
+ `result` or a `status` you do not recognise as something to ignore rather than to fail on.
270
+
271
+ ## License
272
+
273
+ Apache-2.0. See [LICENSE](LICENSE).
package/index.ts ADDED
@@ -0,0 +1,731 @@
1
+ /**
2
+ * CraterView.ai TypeScript client.
3
+ *
4
+ * import { CraterView } from "craterview";
5
+ *
6
+ * const cv = new CraterView({ apiKey: "cv_..." });
7
+ * const job = await cv.run(file, { style: "photo" });
8
+ * const blob = await job.blob();
9
+ *
10
+ * Zero dependencies: fetch and Blob are standard in Node 18+ and every browser, so the
11
+ * client stays installable anywhere without dragging a transitive tree behind it.
12
+ *
13
+ * **This file is published.** It goes to GitHub and npm, and `main` points at the source, so
14
+ * every comment here ships and a doc-comment on an exported member appears in a consumer's
15
+ * editor. Write for someone who can see this package and nothing else: what the client does
16
+ * and what a caller has to know, never how the service behind it is built.
17
+ */
18
+
19
+ // Mirrored from package.json, which is the number a release bumps. It cannot be imported
20
+ // from there — this ships as TypeScript, so the import would have to resolve in the
21
+ // consumer's toolchain — so test/version.test.ts asserts the two agree.
22
+ export const VERSION = "0.1.0";
23
+ const DEFAULT_BASE_URL = "https://api.craterview.ai";
24
+ // The server rejects a longer wait outright, so asking for one costs a 422 rather than a
25
+ // longer wait. Keep in step with MAX_WAIT_SECONDS in the gateway.
26
+ const MAX_SERVER_WAIT = 30;
27
+
28
+ /**
29
+ * A random key for safely repeating a submission.
30
+ *
31
+ * Generate one per *logical request* and reuse it for every attempt at that request:
32
+ *
33
+ * const key = newIdempotencyKey(); // once, before the first attempt
34
+ * for (let attempt = 0; attempt < 3; attempt++) {
35
+ * try {
36
+ * job = await cv.submit(inputKey, { idempotencyKey: key, style: "photo" });
37
+ * break;
38
+ * } catch (e) {
39
+ * if (!(e instanceof CraterViewError)) continue; // same key, at most one job
40
+ * throw e;
41
+ * }
42
+ * }
43
+ *
44
+ * Generating a fresh key per attempt defeats the purpose entirely — the server has
45
+ * nothing to match against and each attempt starts its own job. That is the mistake this
46
+ * function exists to make harder, not easier: it is deliberately not called for you,
47
+ * because only the caller knows where one request ends and the next begins.
48
+ *
49
+ * Reusing a key with a *different* request body is rejected with 409 rather than silently
50
+ * returning the earlier result.
51
+ *
52
+ * This client does not retry on your behalf. The loop above is yours to write.
53
+ */
54
+ export function newIdempotencyKey(): string {
55
+ const bytes = new Uint8Array(24);
56
+ // Present in Node 18+ and every browser. Math.random is not a substitute: two clients
57
+ // starting together would draw the same sequence and collide on the server.
58
+ globalThis.crypto.getRandomValues(bytes);
59
+ const base64 = btoa(String.fromCharCode(...bytes));
60
+ return `idem_${base64.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "")}`;
61
+ }
62
+
63
+ export class CraterViewError extends Error {
64
+ constructor(message: string, readonly status?: number) {
65
+ super(message);
66
+ this.name = "CraterViewError";
67
+ }
68
+ }
69
+
70
+ /**
71
+ * 429 — too fast, or too much at once. Two different limits answer with this: the key's
72
+ * request rate, and the account's cap on jobs queued or running at the same time, which
73
+ * exists so one caller cannot occupy the whole fleet.
74
+ *
75
+ * `retryAfter` is seconds to wait, and how good a number it is depends on which limit you
76
+ * hit: exact for the rate limit, where it is when the window rolls over, and a hint for
77
+ * the in-flight cap, where a slot frees when one of your own jobs finishes and the server
78
+ * can only quote the model's typical duration. `usage()` reports the cap and what you
79
+ * currently hold against it.
80
+ */
81
+ export class RateLimited extends CraterViewError {
82
+ constructor(message: string, readonly retryAfter?: number) {
83
+ super(message, 429);
84
+ this.name = "RateLimited";
85
+ }
86
+ }
87
+
88
+ /**
89
+ * The job ran and did not succeed.
90
+ *
91
+ * `message` says what you can do about it and `errorCode` is the half to branch on, because
92
+ * the prose is written for a person and gets reworded. `inference_failed` means the fault was
93
+ * ours, the credits were refunded, and the same call is worth making again.
94
+ *
95
+ * An unfamiliar code is a failure with no special handling, not an error in itself: new ones
96
+ * appear as new things become worth telling apart.
97
+ */
98
+ export class JobFailed extends CraterViewError {
99
+ constructor(message: string, readonly errorCode?: string) {
100
+ super(message);
101
+ this.name = "JobFailed";
102
+ }
103
+ }
104
+
105
+ export const SIGNATURE_HEADER = "CV-Signature";
106
+ export const TIMESTAMP_HEADER = "CV-Timestamp";
107
+
108
+ /**
109
+ * How far out of date a delivery's timestamp may be before {@link verifyWebhook} refuses it.
110
+ * Generous enough to cover a delivery that was retried before it reached you, tight enough
111
+ * that a copy captured earlier is no longer accepted.
112
+ */
113
+ export const DEFAULT_TOLERANCE_SECONDS = 300;
114
+
115
+ /**
116
+ * A delivery did not verify. Do not act on the body.
117
+ *
118
+ * Thrown for every reason a delivery can fail to check out — a wrong signature, a missing
119
+ * header, a timestamp too old — because from a receiver's point of view they are one
120
+ * outcome: this is not something we sent, so it does not get to do anything.
121
+ */
122
+ export class InvalidSignature extends CraterViewError {}
123
+
124
+ /**
125
+ * Check that a callback really came from CraterView, and return its parsed body.
126
+ *
127
+ * app.post("/hooks/craterview", async (req, res) => {
128
+ * const raw = await rawBody(req); // the bytes, not req.body
129
+ * const event = await verifyWebhook(raw, req.headers, MY_SECRET);
130
+ * res.sendStatus(200); // answer first, work afterwards
131
+ * });
132
+ *
133
+ * Throws {@link InvalidSignature} if it does not check out. **Verify before you parse**, and
134
+ * pass the raw body exactly as received — most frameworks parse JSON for you, and
135
+ * re-serialising it changes the bytes the signature was computed over. In Express that means
136
+ * `express.raw({ type: "application/json" })` on this route.
137
+ *
138
+ * Async because it uses WebCrypto, which is what makes this work unchanged in Node and in a
139
+ * browser or edge runtime without pulling in a crypto dependency.
140
+ *
141
+ * Get your secret from {@link CraterView.webhookSecret}, or from the dashboard.
142
+ */
143
+ export async function verifyWebhook(
144
+ body: string | Uint8Array | ArrayBuffer,
145
+ headers: Record<string, string | string[] | undefined> | Headers,
146
+ secret: string,
147
+ options: { toleranceSeconds?: number } = {},
148
+ ): Promise<WebhookEvent> {
149
+ const { toleranceSeconds = DEFAULT_TOLERANCE_SECONDS } = options;
150
+
151
+ const signature = readHeader(headers, SIGNATURE_HEADER);
152
+ const timestamp = readHeader(headers, TIMESTAMP_HEADER);
153
+ if (!signature || !timestamp) {
154
+ throw new InvalidSignature("delivery is missing its signature headers");
155
+ }
156
+
157
+ const sentAt = Number(timestamp);
158
+ if (!Number.isFinite(sentAt)) {
159
+ throw new InvalidSignature("delivery has an unreadable timestamp");
160
+ }
161
+ // Both directions. A clock ahead of ours is as much a reason to distrust a delivery as one
162
+ // behind it, and only checking the past accepts anything dated next year.
163
+ const age = Date.now() / 1000 - sentAt;
164
+ if (toleranceSeconds && Math.abs(age) > toleranceSeconds) {
165
+ throw new InvalidSignature(`delivery is ${age.toFixed(0)}s out of date`);
166
+ }
167
+
168
+ const bytes = toBytes(body);
169
+ const signed = new Uint8Array(timestamp.length + 1 + bytes.length);
170
+ signed.set(new TextEncoder().encode(`${timestamp}.`), 0);
171
+ signed.set(bytes, timestamp.length + 1);
172
+
173
+ const key = await crypto.subtle.importKey(
174
+ "raw", new TextEncoder().encode(secret),
175
+ { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
176
+ const mac = await crypto.subtle.sign("HMAC", key, signed);
177
+ const expected = "sha256=" + Array.from(new Uint8Array(mac))
178
+ .map((b) => b.toString(16).padStart(2, "0")).join("");
179
+
180
+ // A list, because a rotated secret keeps signing alongside its replacement for a while —
181
+ // so accept the delivery if any entry matches, and you can deploy a new secret whenever
182
+ // suits rather than the moment you asked for one.
183
+ const matched = signature.split(",").some((entry) => timingSafeEqual(expected, entry.trim()));
184
+ if (!matched) throw new InvalidSignature("signature does not match");
185
+
186
+ try {
187
+ return JSON.parse(new TextDecoder().decode(bytes)) as WebhookEvent;
188
+ } catch {
189
+ throw new InvalidSignature("delivery verified but its body is not JSON");
190
+ }
191
+ }
192
+
193
+ /** One header, however the caller's framework spells its container. */
194
+ function readHeader(
195
+ headers: Record<string, string | string[] | undefined> | Headers,
196
+ name: string,
197
+ ): string | undefined {
198
+ if (typeof (headers as Headers).get === "function") {
199
+ return (headers as Headers).get(name) ?? undefined;
200
+ }
201
+ const plain = headers as Record<string, string | string[] | undefined>;
202
+ const found = plain[name] ?? plain[name.toLowerCase()];
203
+ return Array.isArray(found) ? found[0] : found;
204
+ }
205
+
206
+ function toBytes(body: string | Uint8Array | ArrayBuffer): Uint8Array {
207
+ if (typeof body === "string") return new TextEncoder().encode(body);
208
+ return body instanceof ArrayBuffer ? new Uint8Array(body) : body;
209
+ }
210
+
211
+ /**
212
+ * Compare without returning early. A comparison that stops at the first difference leaks,
213
+ * one character at a time, how much of a guess was right.
214
+ */
215
+ function timingSafeEqual(a: string, b: string): boolean {
216
+ if (a.length !== b.length) return false;
217
+ let differing = 0;
218
+ for (let i = 0; i < a.length; i++) differing |= a.charCodeAt(i) ^ b.charCodeAt(i);
219
+ return differing === 0;
220
+ }
221
+
222
+ /**
223
+ * One entry from the model catalogue, exactly as it arrives. Snake case is the wire's, as
224
+ * with `JobData` — there is no wrapper class here because there is no behaviour to add.
225
+ */
226
+ export interface ModelInfo {
227
+ /** The public name, and what you pass as `model` when submitting. */
228
+ name: string;
229
+ version: string;
230
+ title: string;
231
+ description: string;
232
+ accepts: string[];
233
+ /**
234
+ * The media type a result usually comes back as, and advisory: a model that keeps the
235
+ * format you sent returns what you sent. Null on a model that returns no file at all,
236
+ * whose answer is in the job's own fields.
237
+ */
238
+ produces: string | null;
239
+ /**
240
+ * Announced, and not in service yet: submitting to this model is refused with 409 until
241
+ * it launches. Everything else here — the price, the schema, the ceilings — is final, so
242
+ * an integration written now needs no change on the day it opens.
243
+ */
244
+ coming_soon?: boolean;
245
+ /**
246
+ * Whether video for this model is on its way, which is why `accepts` names no video type
247
+ * yet. False on a model that takes video already and on one that never will — those two
248
+ * look identical in `accepts` alone.
249
+ */
250
+ video_coming_soon?: boolean;
251
+ max_input_bytes: number;
252
+ /**
253
+ * The ceilings **your key** is held to, not the model's widest. Community work is bounded
254
+ * more tightly than paid work, so these move when `community` below does — check them
255
+ * before uploading rather than learning them from a rejected job.
256
+ *
257
+ * Two axes, and they are the two a job is made of. `max_frame_megapixels` bounds one
258
+ * frame, which is what a GPU actually holds, and applies to images too since a still is one
259
+ * frame. `max_frames` bounds how many frames one job may carry. Zero means that axis is
260
+ * unbounded for you.
261
+ *
262
+ * For a duration, divide: `max_frames / reference_fps` is the longest clip you may send, in
263
+ * seconds. It is not published as its own field on purpose — one limit with two spellings
264
+ * is one that can disagree with itself, and frames are what the platform counts, enforces
265
+ * and bills on.
266
+ */
267
+ max_frame_megapixels: number;
268
+ max_frames: number;
269
+ /** Whole credits. The price is flat and knowable before you send anything. */
270
+ credits_per_image: number;
271
+ /** Whole credits. Null means this model takes stills only. */
272
+ credits_per_video_second?: number | null;
273
+ reference_fps: number;
274
+ params_schema: Record<string, unknown>;
275
+ /**
276
+ * Work ahead of you **on the queue your key would use** — not a platform-wide total.
277
+ * Read it with `community`, which says which queue that is.
278
+ */
279
+ queue_depth: number;
280
+ /**
281
+ * Whether your key's work goes to the community queue, which is served after priority
282
+ * work and takes a small share of it. False once the account holds credit.
283
+ *
284
+ * The same field, meaning the same thing, as `Job.community` — these are the two places
285
+ * the API describes a wait, and they describe it the same way.
286
+ */
287
+ community: boolean;
288
+ /** Of `params_schema`, the ones that apply to still images only. */
289
+ image_only_params: string[];
290
+ /** A representative job, for sizing a progress indicator before any eta arrives. */
291
+ }
292
+
293
+ /** One key on the account. Never the key itself — only the prefix, which identifies it. */
294
+ export interface KeyInfo {
295
+ id: string;
296
+ /** The first few characters. Enough to tell one key from another, not enough to use. */
297
+ prefix: string;
298
+ name: string;
299
+ created_at: string | null;
300
+ /** When it stopped working, or null while it still does. */
301
+ revoked_at: string | null;
302
+ rate_limit_per_minute: number;
303
+ /** Whether this is the key you are calling with. It cannot be revoked while it is. */
304
+ current: boolean;
305
+ }
306
+
307
+ /** A freshly minted key. The only response that carries a usable value. */
308
+ export interface NewKey {
309
+ id: string;
310
+ /** The key itself, returned once and never again. */
311
+ key: string;
312
+ prefix: string;
313
+ name: string;
314
+ rate_limit_per_minute: number;
315
+ }
316
+
317
+ /** The body of a callback, once {@link verifyWebhook} has checked it came from us. */
318
+ export interface WebhookEvent {
319
+ id: string;
320
+ custom_id: string | null;
321
+ model: string | null;
322
+ status: JobStatus;
323
+ error: string | null;
324
+ error_code: string | null;
325
+ community: boolean;
326
+ credits: number | null;
327
+ created_at: string | null;
328
+ finished_at: string | null;
329
+ result: Record<string, unknown> | null;
330
+ }
331
+
332
+ export type JobStatus = "queued" | "running" | "succeeded" | "failed";
333
+
334
+ /** The API's job representation, exactly as it arrives. Snake case is the wire's. */
335
+ export interface JobData {
336
+ id: string;
337
+ model: string;
338
+ status: JobStatus;
339
+ /**
340
+ * Whatever you passed as `customId` at submit, handed straight back. Stored and echoed;
341
+ * nothing on the platform interprets it, and jobs cannot be looked up by it.
342
+ */
343
+ custom_id?: string | null;
344
+ created_at?: string | null;
345
+ finished_at?: string | null;
346
+ error?: string | null;
347
+ /**
348
+ * The stable half of `error` — branch on this rather than on the sentence, which is
349
+ * written for a person and may be reworded. `inference_failed` means the platform
350
+ * declined to explain the failure, and a retry is worth trying.
351
+ */
352
+ error_code?: string | null;
353
+ /**
354
+ * Everything this job produced, in one object: the model's own answer, plus an `output`
355
+ * section carrying the file's links when the model produced one. Some models return only
356
+ * the answer and no file, so read this rather than assuming there is something to
357
+ * download.
358
+ *
359
+ * This is the only place those links are sent. `outputUrl` and the accessors beside it
360
+ * read them out of `result.output`.
361
+ */
362
+ result?: Record<string, unknown> | null;
363
+ input_url?: string | null;
364
+ /** Whole credits. TypeScript cannot say integer, but the API only ever sends one. */
365
+ credits?: number | null;
366
+ eta_seconds?: number | null;
367
+ /** Retained past the ordinary expiry because its owner asked, links and all. */
368
+ kept?: boolean;
369
+ community?: boolean;
370
+ /**
371
+ * Whether an automated check thought this image may fall outside what the service
372
+ * allows. Absent means it was not checked.
373
+ */
374
+ flagged?: boolean | null;
375
+ }
376
+
377
+ /**
378
+ * A submitted job. Mirrors the API's job representation field for field.
379
+ *
380
+ * `credits` is what you were billed, and it is the only figure about cost the API states.
381
+ * For how long a job took, `finishedAt` minus `createdAt` is the wait you actually had,
382
+ * queue included — both are here and both are on the webhook, which states the same fields
383
+ * by the same names.
384
+ *
385
+ * `result` is the whole of what the job produced. Where the model wrote a file,
386
+ * `result.output` carries its links, and `outputUrl` / `downloadUrl` / `thumbUrl` /
387
+ * `contentType` / `outputBytes` read out of it. `outputUrl` and `downloadUrl` are the same
388
+ * object signed two ways: one to display, one to hand a person as a file. The disposition
389
+ * is signed in, so the second cannot be derived from the first without the storage
390
+ * credential. Both are presigned and expire — fetch the result rather than storing the link.
391
+ *
392
+ * `thumbUrl` is a small JPEG of the result, for showing a page of jobs without downloading
393
+ * a page of full-size outputs. `inputUrl` is the file you sent, so a result can be shown
394
+ * against what it was made from. The two expire on very different clocks: the preview goes
395
+ * with the result, while inputs are deleted after a day — much sooner than the output — so
396
+ * `inputUrl` is null for most of a job's life and code that reads it should expect nothing
397
+ * there.
398
+ *
399
+ * `etaSeconds` is the whole of what is reported about waiting: how long until the result,
400
+ * counting time spent waiting for a GPU as well as time spent on one. An estimate and never
401
+ * a promise — read it as guidance, not a deadline. Absent once a job has settled.
402
+ *
403
+ * `community` says the job was submitted against a balance of zero and is on the queue
404
+ * served after priority work, which takes a small share of it rather than only what is left.
405
+ * Nothing is refused for want of credit — credit buys a place at the front of the queue, not
406
+ * the right to submit — so an empty balance means a longer wait and never an error.
407
+ */
408
+ export class Job {
409
+ constructor(private readonly data: JobData) {}
410
+
411
+ get id() { return this.data.id; }
412
+ get model() { return this.data.model; }
413
+ get status() { return this.data.status; }
414
+ get error() { return this.data.error ?? null; }
415
+ /** The stable half of `error`. Branch on this; show the other. */
416
+ get errorCode() { return this.data.error_code ?? null; }
417
+ get credits() { return this.data.credits ?? null; }
418
+ get etaSeconds() { return this.data.eta_seconds ?? null; }
419
+ /** Your own name for this job, or null if you did not send one. */
420
+ get customId() { return this.data.custom_id ?? null; }
421
+ // Defaulted rather than nulled: a gateway too old to send the field is not running a
422
+ // community queue at all, so its jobs are paid work.
423
+ get community() { return this.data.community ?? false; }
424
+ // Nulled rather than defaulted, unlike `community` above: absent means the image was not
425
+ // checked, and `false` would say it was checked and cleared. The two are different
426
+ // answers and only one of them is true.
427
+ get flagged() { return this.data.flagged ?? null; }
428
+ /** The whole answer, including where the file is when there is one. */
429
+ get result() { return this.data.result ?? null; }
430
+ /**
431
+ * The `output` section of the result, or an empty object.
432
+ *
433
+ * Empty both for a job that has not finished and for one whose model produces no file at
434
+ * all — a detector's answer is entirely `result` fields. The accessors below therefore
435
+ * return null rather than throwing: "no file yet" and "never going to be one" is the
436
+ * caller's distinction to draw from `status`, not this library's.
437
+ */
438
+ private get output(): Record<string, unknown> {
439
+ const out = (this.data.result ?? {})["output"];
440
+ return (out && typeof out === "object") ? out as Record<string, unknown> : {};
441
+ }
442
+
443
+ get outputUrl() { return (this.output["url"] as string) ?? null; }
444
+ /**
445
+ * The same object signed to save rather than display. Not derivable from `outputUrl`:
446
+ * the disposition is signed in, so re-signing needs the storage credential.
447
+ */
448
+ get downloadUrl() { return (this.output["download_url"] as string) ?? null; }
449
+ get thumbUrl() { return (this.output["thumbnail_url"] as string) ?? null; }
450
+ get inputUrl() { return this.data.input_url ?? null; }
451
+ get contentType() { return (this.output["content_type"] as string) ?? null; }
452
+ get outputBytes() { return (this.output["bytes"] as number) ?? null; }
453
+
454
+ /** Null when absent or unparseable — never a bad Date, which compares false to itself. */
455
+ get createdAt(): Date | null { return this.moment(this.data.created_at); }
456
+
457
+ /** When the job settled, or null while it is still queued or running. */
458
+ get finishedAt(): Date | null { return this.moment(this.data.finished_at); }
459
+
460
+ private moment(value: string | null | undefined): Date | null {
461
+ if (!value) return null;
462
+ const parsed = new Date(value);
463
+ return Number.isNaN(parsed.getTime()) ? null : parsed;
464
+ }
465
+
466
+ get succeeded() { return this.data.status === "succeeded"; }
467
+ get done() { return this.data.status === "succeeded" || this.data.status === "failed"; }
468
+
469
+ /** Download the result. */
470
+ async blob(): Promise<Blob> {
471
+ const url = this.outputUrl;
472
+ if (!url) {
473
+ throw new CraterViewError(`job ${this.id} has no result (status ${this.status})`);
474
+ }
475
+ const resp = await fetch(url);
476
+ if (!resp.ok) throw new CraterViewError(`downloading result failed: ${resp.status}`);
477
+ return await resp.blob();
478
+ }
479
+
480
+ async arrayBuffer(): Promise<ArrayBuffer> {
481
+ return await (await this.blob()).arrayBuffer();
482
+ }
483
+ }
484
+
485
+ export interface CraterViewOptions {
486
+ apiKey?: string;
487
+ baseUrl?: string;
488
+ }
489
+
490
+ export interface SubmitOptions {
491
+ wait?: number;
492
+ idempotencyKey?: string;
493
+ /**
494
+ * Where to POST the signed callback once this job settles. An absolute `http` or `https`
495
+ * URL — anything else is refused when you submit, rather than becoming a delivery that
496
+ * fails somewhere you cannot see.
497
+ */
498
+ webhookUrl?: string;
499
+ /**
500
+ * Your own name for this job, returned on every read of it and on the webhook. Named here
501
+ * rather than swept up by the index signature below on purpose: anything left to that
502
+ * becomes a model parameter, is checked against the model's schema, and would be refused.
503
+ */
504
+ customId?: string;
505
+ model?: string;
506
+ [param: string]: unknown;
507
+ }
508
+
509
+ export class CraterView {
510
+ private readonly baseUrl: string;
511
+ private readonly headers: Record<string, string>;
512
+
513
+ constructor(options: CraterViewOptions = {}) {
514
+ this.baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\/$/, "");
515
+ this.headers = { "User-Agent": `craterview-ts/${VERSION}` };
516
+ if (options.apiKey) this.headers["Authorization"] = `Bearer ${options.apiKey}`;
517
+ }
518
+
519
+ private async request<T>(method: string, path: string, body?: unknown,
520
+ extraHeaders: Record<string, string> = {}): Promise<T> {
521
+ const resp = await fetch(`${this.baseUrl}${path}`, {
522
+ method,
523
+ headers: { ...this.headers, ...extraHeaders,
524
+ ...(body ? { "Content-Type": "application/json" } : {}) },
525
+ body: body ? JSON.stringify(body) : undefined,
526
+ });
527
+
528
+ if (!resp.ok) {
529
+ const detail = await this.detail(resp);
530
+ if (resp.status === 429) {
531
+ throw new RateLimited(detail, Number(resp.headers.get("Retry-After") ?? 0));
532
+ }
533
+ throw new CraterViewError(detail, resp.status);
534
+ }
535
+ // A 204 carries no body, so asking for JSON throws on a call that succeeded.
536
+ if (resp.status === 204) return undefined as T;
537
+ return await resp.json() as T;
538
+ }
539
+
540
+ private async detail(resp: Response): Promise<string> {
541
+ try {
542
+ const body = await resp.json() as { detail?: string };
543
+ return body.detail ?? `HTTP ${resp.status}`;
544
+ } catch {
545
+ return `HTTP ${resp.status}`;
546
+ }
547
+ }
548
+
549
+ /**
550
+ * Available models: parameter schemas, prices, limits, and your queue.
551
+ *
552
+ * Prices are published here, so the cost of a job is knowable before submitting it.
553
+ *
554
+ * Needs a key, and not only because the figures are live: `queue_depth` and `community`
555
+ * are answered **for the queue your key would use**. The API looks up the account's
556
+ * balance and reports the queue a job from this key would land in — so two keys asking
557
+ * at the same moment can get different numbers, and buying credit changes yours.
558
+ *
559
+ * A model that is available is not always listed — a model in trial, or being retired,
560
+ * stays usable by name while absent from this catalogue.
561
+ */
562
+ async models(): Promise<ModelInfo[]> {
563
+ return await this.request("GET", "/v1/models") as ModelInfo[];
564
+ }
565
+
566
+ /**
567
+ * Put an image in storage and return its key. Bytes go straight to object storage on a
568
+ * presigned URL, never through the API.
569
+ */
570
+ async upload(image: Blob | ArrayBuffer | Uint8Array, contentType?: string): Promise<string> {
571
+ const blob = image instanceof Blob
572
+ ? image
573
+ : new Blob([image as BlobPart], { type: contentType ?? "image/png" });
574
+ const type = contentType ?? blob.type ?? "image/png";
575
+
576
+ // Declared, then signed into the URL, so it has to be the size actually sent — storage
577
+ // refuses any other with a signature error. Taken from the Blob rather than trusted from
578
+ // a caller: it is the same object the PUT below sends.
579
+ const slot = await this.request<{ input_key: string; upload_url: string }>(
580
+ "POST", "/v1/uploads", { content_type: type, content_length: blob.size });
581
+
582
+ const put = await fetch(slot.upload_url, {
583
+ method: "PUT", body: blob, headers: { "Content-Type": type },
584
+ });
585
+ if (!put.ok) throw new CraterViewError(`upload failed: ${put.status}`);
586
+ return slot.input_key;
587
+ }
588
+
589
+ /**
590
+ * Queue a job. `wait` holds the response open for a settled result.
591
+ *
592
+ * Pass `idempotencyKey` — see `newIdempotencyKey` — if you intend to retry this
593
+ * submission. Without one, a repeat after a failed or uncertain request starts a second
594
+ * job and is billed for both.
595
+ */
596
+ async submit(inputKey: string, options: SubmitOptions = {}): Promise<Job> {
597
+ const { wait = 0, idempotencyKey, webhookUrl, customId, model = "cv-restore-v1",
598
+ ...params } = options;
599
+ // Annotated, not inferred: without this the two branches unify to a type whose key
600
+ // may be `undefined`, which is not assignable to Record<string, string>.
601
+ const headers: Record<string, string> = idempotencyKey
602
+ ? { "Idempotency-Key": idempotencyKey }
603
+ : {};
604
+ const data = await this.request<JobData>("POST", `/v1/jobs?wait=${wait}`, {
605
+ model, input_key: inputKey, params,
606
+ ...(webhookUrl ? { webhook_url: webhookUrl } : {}),
607
+ ...(customId ? { custom_id: customId } : {}),
608
+ }, headers);
609
+ return new Job(data);
610
+ }
611
+
612
+ async job(id: string): Promise<Job> {
613
+ return new Job(await this.request<JobData>("GET", `/v1/jobs/${id}`));
614
+ }
615
+
616
+ /**
617
+ * The account's job history, newest first, paging transparently.
618
+ *
619
+ * Scoped to the account rather than to this key, so a key sees every job the account has
620
+ * run and not only the ones it submitted itself.
621
+ */
622
+ async *jobs(options: { limit?: number; status?: JobStatus } = {}): AsyncGenerator<Job> {
623
+ let before: string | undefined;
624
+ for (;;) {
625
+ const params = new URLSearchParams({ limit: String(options.limit ?? 50) });
626
+ if (options.status) params.set("status", options.status);
627
+ if (before) params.set("before", before);
628
+
629
+ const page = await this.request<{ data: JobData[]; has_more: boolean; next_before?: string }>(
630
+ "GET", `/v1/jobs?${params}`);
631
+ for (const item of page.data) yield new Job(item);
632
+ if (!page.has_more || !page.next_before) return;
633
+ // A cursor that does not advance would loop forever, hammering the API from inside
634
+ // the caller's app with no error to show for it. Stop instead.
635
+ if (page.next_before === before) return;
636
+ before = page.next_before;
637
+ }
638
+ }
639
+
640
+ /**
641
+ * The account's credit balance, what it has spent, and what is in flight.
642
+ *
643
+ * All-time, not monthly: credits are granted and deplete rather than renewing. Counts
644
+ * committed work rather than completed, so a queued job is already in the figures —
645
+ * otherwise this and the balance a submission is checked against would disagree.
646
+ *
647
+ * `credits_remaining` is always a number, floored at zero. `jobs_in_flight` and
648
+ * `max_jobs_in_flight` are the state of the queue and are what a 429 on submit is about.
649
+ *
650
+ * Account-wide, so every key on an account reports the same figures.
651
+ */
652
+ async usage(): Promise<unknown> {
653
+ return await this.request("GET", "/v1/usage");
654
+ }
655
+
656
+ /**
657
+ * The secret your callbacks are signed with, created the first time you ask.
658
+ *
659
+ * Pass it to {@link verifyWebhook}. Unlike an API key this can be read back whenever you
660
+ * need it — but treat it as a credential all the same: anyone holding it can produce a
661
+ * delivery your receiver will accept as genuine.
662
+ */
663
+ async webhookSecret(): Promise<string> {
664
+ const body = await this.request("GET", "/v1/webhooks/secret") as { secret: string };
665
+ return body.secret;
666
+ }
667
+
668
+ /**
669
+ * Replace the signing secret and return the new one.
670
+ *
671
+ * The secret you were using keeps being sent alongside it for a window, so deliveries in
672
+ * that period carry a signature under each and {@link verifyWebhook} accepts either.
673
+ * Deploy the new one whenever suits; nothing fails in between.
674
+ */
675
+ async rotateWebhookSecret(): Promise<string> {
676
+ const body = await this.request("POST", "/v1/webhooks/secret/rotate") as { secret: string };
677
+ return body.secret;
678
+ }
679
+
680
+ /** Every key on the account, including revoked ones, by prefix rather than value. */
681
+ async keys(): Promise<KeyInfo[]> {
682
+ return await this.request("GET", "/v1/keys") as KeyInfo[];
683
+ }
684
+
685
+ /**
686
+ * Mint another key. **The value is in this response and nowhere else** — keys are stored
687
+ * as hashes, so one that is not written down has to be replaced rather than recovered.
688
+ *
689
+ * Several keys on an account is the ordinary arrangement, one per service or environment.
690
+ * They share the account's credits and history. This is also how you rotate without
691
+ * downtime: create the new key, move your clients onto it, then revoke the old one.
692
+ */
693
+ async createKey(name = "api"): Promise<NewKey> {
694
+ return await this.request("POST", "/v1/keys", { name }) as NewKey;
695
+ }
696
+
697
+ /**
698
+ * Stop a key working. Immediate, and not reversible.
699
+ *
700
+ * You cannot revoke the key this client is authenticating with — the call would succeed
701
+ * and leave you unable to make another.
702
+ */
703
+ async revokeKey(keyId: string): Promise<void> {
704
+ await this.request("DELETE", `/v1/keys/${encodeURIComponent(keyId)}`);
705
+ }
706
+
707
+ async waitFor(job: Job | string, timeoutMs = 600_000, pollMs = 1000): Promise<Job> {
708
+ const id = typeof job === "string" ? job : job.id;
709
+ const deadline = Date.now() + timeoutMs;
710
+ while (Date.now() < deadline) {
711
+ const current = await this.job(id);
712
+ if (current.done) return current;
713
+ await new Promise((r) => setTimeout(r, pollMs));
714
+ }
715
+ throw new CraterViewError(`job ${id} did not finish within ${timeoutMs}ms`);
716
+ }
717
+
718
+ /**
719
+ * Upload, submit and wait, in one call — the common case. Uses server-side waiting
720
+ * first so a fast job costs a single round trip, then polls for anything slower.
721
+ */
722
+ async run(image: Blob | ArrayBuffer | Uint8Array,
723
+ options: SubmitOptions & { timeoutMs?: number } = {}): Promise<Job> {
724
+ const { timeoutMs = 600_000, wait = MAX_SERVER_WAIT, ...rest } = options;
725
+ const inputKey = await this.upload(image);
726
+ let job = await this.submit(inputKey, { ...rest, wait: Math.min(wait, MAX_SERVER_WAIT) });
727
+ if (!job.done) job = await this.waitFor(job, timeoutMs);
728
+ if (!job.succeeded) throw new JobFailed(job.error ?? "job failed", job.errorCode ?? undefined);
729
+ return job;
730
+ }
731
+ }
package/package.json ADDED
@@ -0,0 +1,30 @@
1
+ {
2
+ "name": "craterview",
3
+ "version": "0.1.0",
4
+ "dependencies": {},
5
+ "description": "TypeScript client for the CraterView image enhancement API",
6
+ "type": "module",
7
+ "main": "index.ts",
8
+ "types": "index.ts",
9
+ "files": [
10
+ "index.ts",
11
+ "README.md",
12
+ "LICENSE"
13
+ ],
14
+ "license": "Apache-2.0",
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "git+https://github.com/craterviewai/craterview-ts.git"
18
+ },
19
+ "homepage": "https://craterview.ai",
20
+ "bugs": "https://github.com/craterviewai/craterview-ts/issues",
21
+ "scripts": {
22
+ "typecheck": "tsc --noEmit",
23
+ "test": "vitest run"
24
+ },
25
+ "devDependencies": {
26
+ "@types/node": "^26.2.0",
27
+ "typescript": "^7.0.2",
28
+ "vitest": "^4.1.11"
29
+ }
30
+ }