@gepetto/sdk 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,171 @@
1
- # Temporary Holding Version
1
+ # Gepetto SDK
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 official TypeScript / JavaScript SDK of the [Gepetto API v2](https://docs.gepettoapp.com): real estate photo editing. Enhance a photo, declutter a room, furnish it, change the sky, restyle it, repaint walls and floors, upscale. One call, an image URL in return.
4
+
5
+ ```bash
6
+ npm install @gepetto/sdk
7
+ ```
8
+
9
+ Node 20 or later (also Bun, Deno and serverless runtimes with `fetch`). Zero dependencies. ESM and CommonJS. Fully typed.
10
+
11
+ ## Quickstart
12
+
13
+ ```ts
14
+ import { Gepetto } from '@gepetto/sdk';
15
+
16
+ const gepetto = new Gepetto(); // reads GEPETTO_API_KEY
17
+
18
+ const job = await gepetto.furnish({
19
+ url: 'https://assets.gepettoapp.com/raw-images/b85e2aa5-ac29-44a0-93eb-2de0a40f7905.png',
20
+ roomId: 'living_room',
21
+ styleId: 'scandinave',
22
+ });
23
+
24
+ console.log(job.output); // https://assets.gepettoapp.com/api/v2/jobs/.../output.jpg
25
+ ```
26
+
27
+ No key yet? A free test key (200 real renders, no watermark) in two commands:
28
+
29
+ ```bash
30
+ npx @gepetto/cli login # opens a page: check the code, click "Authorize"
31
+ npx @gepetto/cli init # writes GEPETTO_API_KEY to .env
32
+ ```
33
+
34
+ CommonJS: `const { Gepetto } = require('@gepetto/sdk');`
35
+
36
+ ## What you get
37
+
38
+ - **The method waits for the image.** Each tool resolves with the finished job, whose `output` is the image URL (typed as a `string`, never `null`). A failed render throws, and is never charged.
39
+ - **Your editor knows the ids.** `roomId`, `styleId`, `skyId`, `furnitureId`, `wallType`, `floorType` and `finishId` are suggested as you type, and any other string is still accepted, so an id added on the server works before the SDK is updated.
40
+ - **Wrong combinations do not compile.** A mask with neither `roomId` nor `furnitureId`, a `floorType` on `surface: 'walls'`, a typo in a field: TypeScript says so before the API does.
41
+ - **Retries are safe.** Every render is sent with an idempotency key (yours, or one generated). A network error, a `429` or a `5xx` is retried with the same key: a render is never started, nor billed, twice.
42
+ - **Long renders just work.** If the connection drops while the image is being made, the SDK picks up the same job and waits for it.
43
+ - **The names are those of the API.** What the [docs](https://docs.gepettoapp.com) say of an endpoint is true of the method: same fields, same ids, same error codes.
44
+
45
+ ## Tools
46
+
47
+ The `url` (and `mask`) of every tool is a public http(s) URL of a JPEG, PNG, WebP or HEIC image: upload the photo to your own storage first. The output URL is public too; copy the image if you keep it.
48
+
49
+ | Method | What it does |
50
+ | --- | --- |
51
+ | `enhance({ url, straighten? })` | Light and colours corrected at the size of the photo, nothing redrawn |
52
+ | `declutter({ url, keepKitchen?, keepBathroom?, keepFireplace? })` | The whole room emptied |
53
+ | `declutter({ url, mask })` | What the mask covers removed |
54
+ | `furnish({ url, roomId, styleId })` | The whole room furnished |
55
+ | `furnish({ url, mask, roomId, styleId })` | The zone of the mask furnished as a room |
56
+ | `furnish({ url, mask, furnitureId, styleId? })` | One piece of furniture in the zone |
57
+ | `sunshine({ url, skyId, lightProjection?, poolLight?, addLeafs? })` | A blue sky and the matching light |
58
+ | `creativeRedesign({ url, roomId, styleId, preserveFloor? })` | The room redesigned in a style |
59
+ | `surfaces({ url, surface: 'walls', wallType, customWallColor?, preserveCeiling? })` | Walls repainted |
60
+ | `surfaces({ url, surface: 'floor', floorType, includeBaseboard? })` | Floor changed |
61
+ | `surfaces({ url, surface: 'finish', finishId })` | A finish applied |
62
+ | `upscale({ url, resolution? })` | Enlarged to about 4 (`2k`) or 16 megapixels (`4k`, default) |
63
+
64
+ A mask is a black image with the zone painted in white, drawn on the photo. Output sizes are in the docs (Images and masks).
65
+
66
+ Every tool takes a second argument:
67
+
68
+ ```ts
69
+ await gepetto.enhance(
70
+ { url, straighten: true },
71
+ {
72
+ idempotencyKey: `${photo.id}:enhance`, // one key per photo and per tool
73
+ timeout: 120_000, // ms, for this call (default: the client's, 10 minutes)
74
+ signal, // an AbortSignal: stops waiting (the render goes on)
75
+ },
76
+ );
77
+ ```
78
+
79
+ A key always answers the job it first started, whatever the tool and even if that render failed: use one key per photo and per tool, and a new key to try a failed render again.
80
+
81
+ ## Lists
82
+
83
+ The valid ids, with their names in French, English, Spanish, Portuguese and German:
84
+
85
+ ```ts
86
+ await gepetto.listRooms(); // [{ id: 'living_room', name_en: 'Living room', modes: ['auto', 'zone'], ... }]
87
+ await gepetto.listStyles();
88
+ await gepetto.listFurnitures(); // grouped by type: { interior: [...], kitchen: [...], ... }
89
+ await gepetto.listSkies();
90
+ await gepetto.listSurfaces(); // { walls, floors, finishes }
91
+ ```
92
+
93
+ A room with the `auto` mode can be furnished whole; with `zone`, it can furnish the zone of a mask.
94
+
95
+ ## Errors
96
+
97
+ Everything throws a `GepettoError`. Its `message` says what to do next, its `code` is stable:
98
+
99
+ ```ts
100
+ import { Gepetto, GepettoError } from '@gepetto/sdk';
101
+
102
+ try {
103
+ await gepetto.furnish({ url, roomId: 'bedrom', styleId: 'modern' });
104
+ } catch (e) {
105
+ if (e instanceof GepettoError) {
106
+ e.code; // 'unknown_room'
107
+ e.message; // 'No room "bedrom". The list, with the modes of each room, is on GET /v2/rooms.'
108
+ e.param; // 'roomId'
109
+ e.status; // 400
110
+ e.jobId; // set when the error concerns a render (failed renders are not charged)
111
+ }
112
+ }
113
+ ```
114
+
115
+ The codes are listed in the docs (Errors). The SDK adds `connection_error`, `timeout`, `aborted`, `invalid_response` and `invalid_signature`.
116
+
117
+ ## Webhooks
118
+
119
+ To send many photos, do not hold a connection per render: pass a `webhook`. The method then returns at once with the job in `pending`, and Gepetto POSTs the finished job (success or failure) to your URL.
120
+
121
+ ```ts
122
+ const job = await gepetto.enhance({ url, webhook: 'https://your-server.com/gepetto-webhook' });
123
+ job.status; // 'pending'
124
+ ```
125
+
126
+ Check that a webhook comes from Gepetto with the raw body:
127
+
128
+ ```ts
129
+ import express from 'express';
130
+ import { verifyWebhook } from '@gepetto/sdk';
131
+
132
+ app.post('/gepetto-webhook', express.raw({ type: 'application/json' }), async (req, res) => {
133
+ const job = await verifyWebhook({
134
+ body: req.body, // the raw body, not parsed
135
+ signature: req.get('Gepetto-Signature'),
136
+ secret: process.env.GEPETTO_WEBHOOK_SECRET, // webhook_secret of gepetto.account()
137
+ });
138
+ if (job.status === 'success') save(job.output);
139
+ res.sendStatus(200);
140
+ });
141
+ ```
142
+
143
+ Test and live keys have different webhook secrets. `npx @gepetto/cli webhook test <url>` sends a signed success and a signed failure to your endpoint.
144
+
145
+ ## Jobs, account
146
+
147
+ ```ts
148
+ await gepetto.getJob(id); // a job as it is now
149
+ await gepetto.waitForJob(id); // until it is finished (throws if the render failed)
150
+ await gepetto.listJobs({ status: 'error' }); // the latest failures, with their reason
151
+ await gepetto.account(); // key type, test renders left, webhook secret
152
+ await gepetto.usage(); // renders and consumption of the period
153
+ await gepetto.subscribe(); // the payment link of the subscription
154
+ gepetto.isTest; // true with a test key
155
+ ```
156
+
157
+ ## Options
158
+
159
+ ```ts
160
+ new Gepetto({
161
+ apiKey: 'live_...', // default: GEPETTO_API_KEY
162
+ timeout: 600_000, // ms per call, waiting included (default 10 minutes)
163
+ maxRetries: 2, // on a network error, a 429 or a 5xx (default 2)
164
+ });
165
+ ```
166
+
167
+ Keep the key on your server: it gives access to your account and bills it. The SDK refuses to run in a web page.
168
+
169
+ ## Pricing
170
+
171
+ Test keys are free: 200 renders per account. Live keys: 100 € excl. tax per month including 100 € of renders, then the price of each render. Only successful renders are charged. Details: [docs.gepettoapp.com](https://docs.gepettoapp.com).
package/dist/index.cjs ADDED
@@ -0,0 +1,385 @@
1
+ "use strict";
2
+ /**
3
+ * Official TypeScript / JavaScript SDK of the Gepetto API v2: real estate photo editing.
4
+ * Docs: https://docs.gepettoapp.com
5
+ *
6
+ * Methods and fields have the names of the API: what the docs say of an endpoint is true of the method.
7
+ */
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.Gepetto = exports.GepettoError = exports.VERSION = void 0;
10
+ exports.verifyWebhook = verifyWebhook;
11
+ exports.VERSION = '0.1.0';
12
+ const DEFAULT_BASE_URL = 'https://europe-west1-gepettoai.cloudfunctions.net/v2';
13
+ /** A render is stopped by the API after 450 s: 10 minutes covers it, retries included. */
14
+ const DEFAULT_TIMEOUT_MS = 10 * 60 * 1000;
15
+ const DEFAULT_MAX_RETRIES = 2;
16
+ const POLL_INTERVAL_MS = 2500;
17
+ /**
18
+ * Every failure: an invalid request, a failed render (not charged), a network problem. `message` says what to do
19
+ * next; `code` is stable, for your code.
20
+ */
21
+ class GepettoError extends Error {
22
+ code;
23
+ /** HTTP status, or null when the API was not reached. */
24
+ status;
25
+ /** The request field at fault, when there is one. */
26
+ param;
27
+ /** The job, when the error concerns a render (it can be followed with `getJob`). */
28
+ jobId;
29
+ job;
30
+ constructor(init) {
31
+ super(init.message, init.cause === undefined ? undefined : { cause: init.cause });
32
+ this.name = 'GepettoError';
33
+ this.code = init.code;
34
+ this.status = init.status ?? null;
35
+ if (init.param)
36
+ this.param = init.param;
37
+ if (init.jobId)
38
+ this.jobId = init.jobId;
39
+ if (init.job)
40
+ this.job = init.job;
41
+ }
42
+ }
43
+ exports.GepettoError = GepettoError;
44
+ const env = (name) => globalThis.process?.env?.[name] || undefined;
45
+ class Gepetto {
46
+ baseUrl;
47
+ timeout;
48
+ maxRetries;
49
+ #apiKey;
50
+ #fetch;
51
+ /**
52
+ * ```ts
53
+ * const gepetto = new Gepetto(); // reads GEPETTO_API_KEY
54
+ * const gepetto = new Gepetto('test_...');
55
+ * const gepetto = new Gepetto({ apiKey, timeout: 120_000 });
56
+ * ```
57
+ */
58
+ constructor(apiKeyOrOptions, options = {}) {
59
+ const opts = typeof apiKeyOrOptions === 'string' ? { ...options, apiKey: apiKeyOrOptions } : { ...apiKeyOrOptions };
60
+ const apiKey = (opts.apiKey ?? env('GEPETTO_API_KEY'))?.trim();
61
+ if (!apiKey) {
62
+ throw new GepettoError({
63
+ code: 'missing_api_key',
64
+ message: 'No API key: pass it to new Gepetto(...) or set GEPETTO_API_KEY. Get a free test key with `npx @gepetto/cli login` then `npx @gepetto/cli init`.',
65
+ });
66
+ }
67
+ if (typeof globalThis.window !== 'undefined' && typeof globalThis.document !== 'undefined' && !opts.dangerouslyAllowBrowser) {
68
+ throw new GepettoError({
69
+ code: 'invalid_parameter',
70
+ message: 'The Gepetto SDK runs on a server: in a web page, the API key would be readable by anyone. Call your own backend from the page.',
71
+ });
72
+ }
73
+ const f = opts.fetch ?? globalThis.fetch;
74
+ if (typeof f !== 'function') {
75
+ throw new GepettoError({ code: 'invalid_parameter', message: 'No global fetch: use Node 20 or later, or pass `fetch` in the options.' });
76
+ }
77
+ this.#apiKey = apiKey;
78
+ this.#fetch = f;
79
+ this.baseUrl = (opts.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/, '');
80
+ this.timeout = opts.timeout ?? DEFAULT_TIMEOUT_MS;
81
+ this.maxRetries = Math.max(0, opts.maxRetries ?? DEFAULT_MAX_RETRIES);
82
+ }
83
+ /** True with a test key: renders are free (200 per account) and `priceCents` is 0. */
84
+ get isTest() {
85
+ return this.#apiKey.startsWith('test_');
86
+ }
87
+ declutter(params, options) {
88
+ return this.#render('/declutter', params, options);
89
+ }
90
+ furnish(params, options) {
91
+ return this.#render('/furnish', params, options);
92
+ }
93
+ sunshine(params, options) {
94
+ return this.#render('/sunshine', params, options);
95
+ }
96
+ creativeRedesign(params, options) {
97
+ return this.#render('/creative-redesign', params, options);
98
+ }
99
+ surfaces(params, options) {
100
+ return this.#render('/surfaces', params, options);
101
+ }
102
+ enhance(params, options) {
103
+ return this.#render('/enhance', params, options);
104
+ }
105
+ upscale(params, options) {
106
+ return this.#render('/upscale', params, options);
107
+ }
108
+ // --- Jobs
109
+ /** A job as it is now. */
110
+ async getJob(id, options = {}) {
111
+ return this.#json(await this.#send('GET', `/job/${encodeURIComponent(id)}`, { signal: options.signal }));
112
+ }
113
+ /** Waits until the job is finished. Resolves with it, or throws a GepettoError if the render failed. */
114
+ async waitForJob(id, options = {}) {
115
+ const deadline = Date.now() + (options.timeout ?? this.timeout);
116
+ const job = await this.#poll(id, deadline, options.signal, options.interval ?? POLL_INTERVAL_MS);
117
+ return this.#finished(job);
118
+ }
119
+ /** The latest jobs of the key's type (test or live), newest first. `status: 'error'` for the failures. */
120
+ async listJobs(params = {}) {
121
+ const query = new URLSearchParams();
122
+ if (params.status)
123
+ query.set('status', params.status);
124
+ if (params.limit)
125
+ query.set('limit', String(params.limit));
126
+ const qs = query.toString();
127
+ return this.#json(await this.#send('GET', `/jobs${qs ? `?${qs}` : ''}`, {}));
128
+ }
129
+ // --- Lists: the valid ids of the parameters (the editor suggests the known ones)
130
+ listRooms() {
131
+ return this.#get('/rooms');
132
+ }
133
+ listStyles() {
134
+ return this.#get('/styles');
135
+ }
136
+ listFurnitures() {
137
+ return this.#get('/furnitures');
138
+ }
139
+ listSkies() {
140
+ return this.#get('/skies');
141
+ }
142
+ /** Wall colours, floors and finishes, for `surfaces`. */
143
+ listSurfaces() {
144
+ return this.#get('/surfaces');
145
+ }
146
+ // --- Account
147
+ /** The account of the key, its test renders, the subscription, and the webhook secret of this key type. */
148
+ account() {
149
+ return this.#get('/account');
150
+ }
151
+ /** Renders and consumption of the current period. */
152
+ usage() {
153
+ return this.#get('/usage');
154
+ }
155
+ /** The payment link of the subscription (100 € excl. tax per month including 100 € of renders). A test key is
156
+ * enough; once paid, the live key is on https://app.gepettoapp.com/easy/account/api. */
157
+ async subscribe() {
158
+ return this.#json(await this.#send('POST', '/subscribe', { body: {}, idempotencyKey: uniqueId() }));
159
+ }
160
+ // --- Internals
161
+ async #get(path) {
162
+ return this.#json(await this.#send('GET', path, {}));
163
+ }
164
+ /** Sends a render, then waits for it unless a webhook was given. */
165
+ async #render(path, params, options = {}) {
166
+ const body = {};
167
+ for (const [k, v] of Object.entries(params)) {
168
+ if (v === undefined)
169
+ continue;
170
+ body[k] = v instanceof URL ? v.toString() : v;
171
+ }
172
+ const deadline = Date.now() + (options.timeout ?? this.timeout);
173
+ const idempotencyKey = options.idempotencyKey ?? uniqueId();
174
+ // The same key on every attempt: a retry answers the job already created, never a second render. It also covers
175
+ // a connection dropped while the render runs (Node closes a response that sends no headers for 300 s): the
176
+ // retry gets the running job, which is then followed with GET /job/{id}.
177
+ const sent = await this.#send('POST', path, { body, idempotencyKey, signal: options.signal, deadline, retryConnection: true });
178
+ if (sent.status === 502 && sent.data?.id) {
179
+ throw apiError(sent, { jobId: sent.data.id });
180
+ }
181
+ const job = this.#json(sent);
182
+ if (body.webhook)
183
+ return job;
184
+ const done = job.status === 'pending' || job.status === 'processing'
185
+ ? await this.#poll(job.id, deadline, options.signal, POLL_INTERVAL_MS)
186
+ : job;
187
+ return this.#finished(done);
188
+ }
189
+ #finished(job) {
190
+ if (job.status === 'success' && job.output)
191
+ return job;
192
+ throw new GepettoError({
193
+ code: job.error?.code ?? 'render_failed',
194
+ message: job.error?.message ?? 'The render failed. You were not charged. Try again.',
195
+ jobId: job.id,
196
+ job,
197
+ });
198
+ }
199
+ async #poll(id, deadline, signal, interval) {
200
+ for (;;) {
201
+ const job = this.#json(await this.#send('GET', `/job/${encodeURIComponent(id)}`, { signal, deadline }));
202
+ if (job.status === 'success' || job.status === 'error')
203
+ return job;
204
+ if (Date.now() + interval >= deadline) {
205
+ throw new GepettoError({
206
+ code: 'timeout',
207
+ message: `Job ${id} is still ${job.status}: stopped waiting (timeout). It goes on: follow it with getJob('${id}') or waitForJob('${id}').`,
208
+ jobId: id,
209
+ job,
210
+ });
211
+ }
212
+ await sleep(interval, signal);
213
+ }
214
+ }
215
+ /** The body of a 2xx answer, else a GepettoError. */
216
+ #json(sent) {
217
+ if (sent.status >= 200 && sent.status < 300) {
218
+ if (sent.data === undefined) {
219
+ throw new GepettoError({ code: 'invalid_response', status: sent.status, message: 'The API answered something that is not JSON.' });
220
+ }
221
+ return sent.data;
222
+ }
223
+ throw apiError(sent);
224
+ }
225
+ /** One request, retried on a network error, a 429 or a 5xx other than a failed render (502). */
226
+ async #send(method, path, init) {
227
+ const deadline = init.deadline ?? Date.now() + this.timeout;
228
+ // GET is safe to repeat; a POST only with an idempotency key
229
+ const retryable = method === 'GET' || !!init.idempotencyKey;
230
+ const headers = {
231
+ Authorization: `Bearer ${this.#apiKey}`,
232
+ Accept: 'application/json',
233
+ 'User-Agent': `gepetto-sdk/${exports.VERSION}`,
234
+ };
235
+ if (init.body !== undefined)
236
+ headers['Content-Type'] = 'application/json';
237
+ if (init.idempotencyKey)
238
+ headers['Idempotency-Key'] = init.idempotencyKey;
239
+ for (let attempt = 0;; attempt++) {
240
+ throwIfAborted(init.signal);
241
+ const remaining = deadline - Date.now();
242
+ if (remaining <= 0)
243
+ throw timeoutError();
244
+ const controller = new AbortController();
245
+ let timedOut = false;
246
+ const timer = setTimeout(() => { timedOut = true; controller.abort(); }, remaining);
247
+ const onAbort = () => controller.abort();
248
+ init.signal?.addEventListener('abort', onAbort, { once: true });
249
+ try {
250
+ const res = await this.#fetch(`${this.baseUrl}${path}`, {
251
+ method,
252
+ headers,
253
+ body: init.body === undefined ? undefined : JSON.stringify(init.body),
254
+ signal: controller.signal,
255
+ });
256
+ const text = await res.text();
257
+ let data;
258
+ try {
259
+ data = text ? JSON.parse(text) : null;
260
+ }
261
+ catch {
262
+ data = undefined;
263
+ }
264
+ const transient = res.status === 429 || (res.status >= 500 && res.status !== 502);
265
+ if (transient && retryable && attempt < this.maxRetries && Date.now() < deadline) {
266
+ await sleep(backoff(attempt), init.signal);
267
+ continue;
268
+ }
269
+ return { status: res.status, data };
270
+ }
271
+ catch (e) {
272
+ if (e instanceof GepettoError)
273
+ throw e;
274
+ throwIfAborted(init.signal);
275
+ if (timedOut)
276
+ throw timeoutError();
277
+ const maxAttempts = init.retryConnection ? Math.max(this.maxRetries, 2) : this.maxRetries;
278
+ if (retryable && attempt < maxAttempts && Date.now() < deadline) {
279
+ await sleep(backoff(attempt), init.signal);
280
+ continue;
281
+ }
282
+ throw new GepettoError({
283
+ code: 'connection_error',
284
+ message: `Could not reach the Gepetto API (${String(e?.cause?.code ?? e?.message ?? e)}).${init.idempotencyKey ? ` Retry with the same idempotencyKey (${init.idempotencyKey}): a render already started is not run twice.` : ''}`,
285
+ cause: e,
286
+ });
287
+ }
288
+ finally {
289
+ clearTimeout(timer);
290
+ init.signal?.removeEventListener('abort', onAbort);
291
+ }
292
+ }
293
+ }
294
+ }
295
+ exports.Gepetto = Gepetto;
296
+ exports.default = Gepetto;
297
+ /**
298
+ * Checks that a webhook comes from Gepetto, and returns its job. Throws a GepettoError `invalid_signature` otherwise.
299
+ *
300
+ * ```ts
301
+ * app.post('/gepetto-webhook', express.raw({ type: 'application/json' }), async (req, res) => {
302
+ * const job = await verifyWebhook({ body: req.body, signature: req.get('Gepetto-Signature') });
303
+ * res.sendStatus(200);
304
+ * });
305
+ * ```
306
+ */
307
+ async function verifyWebhook(params) {
308
+ const secret = params.secret ?? env('GEPETTO_WEBHOOK_SECRET');
309
+ if (!secret) {
310
+ throw new GepettoError({ code: 'invalid_parameter', message: 'No webhook secret: pass `secret` (webhook_secret of account()) or set GEPETTO_WEBHOOK_SECRET.' });
311
+ }
312
+ const invalid = (why) => new GepettoError({ code: 'invalid_signature', status: null, message: `Invalid webhook signature: ${why}.` });
313
+ if (!params.signature)
314
+ throw invalid('no Gepetto-Signature header');
315
+ const parts = Object.fromEntries(params.signature.split(',').map((p) => {
316
+ const i = p.indexOf('=');
317
+ return [p.slice(0, i).trim(), p.slice(i + 1).trim()];
318
+ }));
319
+ const t = Number(parts.t);
320
+ if (!parts.t || !Number.isFinite(t) || !parts.v1)
321
+ throw invalid('malformed header');
322
+ if (Math.abs(Date.now() / 1000 - t) > (params.tolerance ?? 300))
323
+ throw invalid('timestamp too old');
324
+ const raw = typeof params.body === 'string' ? params.body : new TextDecoder().decode(params.body);
325
+ const subtle = globalThis.crypto?.subtle;
326
+ if (!subtle)
327
+ throw new GepettoError({ code: 'invalid_parameter', message: 'Web Crypto is missing: use Node 20 or later.' });
328
+ const enc = new TextEncoder();
329
+ const key = await subtle.importKey('raw', enc.encode(secret), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);
330
+ const mac = new Uint8Array(await subtle.sign('HMAC', key, enc.encode(`${parts.t}.${raw}`)));
331
+ const expected = Array.from(mac, (b) => b.toString(16).padStart(2, '0')).join('');
332
+ if (!timingSafeEqual(expected, parts.v1))
333
+ throw invalid('signature mismatch (wrong secret, or the body was modified)');
334
+ try {
335
+ return JSON.parse(raw);
336
+ }
337
+ catch {
338
+ throw invalid('the body is not JSON');
339
+ }
340
+ }
341
+ // --- Helpers -------------------------------------------------------------------------------------------------------
342
+ function apiError(sent, extra = {}) {
343
+ const d = sent.data && typeof sent.data === 'object' ? sent.data : {};
344
+ return new GepettoError({
345
+ code: d.code ?? (sent.status === 429 ? 'rate_limited' : 'invalid_response'),
346
+ message: d.message ?? `The API answered HTTP ${sent.status}.`,
347
+ status: sent.status,
348
+ param: d.param,
349
+ jobId: extra.jobId ?? d.id,
350
+ });
351
+ }
352
+ function timeoutError() {
353
+ return new GepettoError({ code: 'timeout', message: 'The call took longer than its timeout. A render already started goes on: find it with listJobs().' });
354
+ }
355
+ function throwIfAborted(signal) {
356
+ if (signal?.aborted)
357
+ throw new GepettoError({ code: 'aborted', message: 'Aborted by the signal.', cause: signal.reason });
358
+ }
359
+ function sleep(ms, signal) {
360
+ return new Promise((resolve, reject) => {
361
+ if (signal?.aborted)
362
+ return reject(new GepettoError({ code: 'aborted', message: 'Aborted by the signal.', cause: signal.reason }));
363
+ const timer = setTimeout(() => { signal?.removeEventListener('abort', onAbort); resolve(); }, ms);
364
+ const onAbort = () => { clearTimeout(timer); reject(new GepettoError({ code: 'aborted', message: 'Aborted by the signal.', cause: signal?.reason })); };
365
+ signal?.addEventListener('abort', onAbort, { once: true });
366
+ });
367
+ }
368
+ /** 1 s, 2 s, 4 s... with a little jitter. */
369
+ function backoff(attempt) {
370
+ return Math.min(8000, 1000 * 2 ** attempt) * (0.8 + Math.random() * 0.4);
371
+ }
372
+ function uniqueId() {
373
+ const c = globalThis.crypto;
374
+ if (c?.randomUUID)
375
+ return c.randomUUID();
376
+ return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}-${Math.random().toString(36).slice(2)}`;
377
+ }
378
+ function timingSafeEqual(a, b) {
379
+ if (a.length !== b.length)
380
+ return false;
381
+ let diff = 0;
382
+ for (let i = 0; i < a.length; i++)
383
+ diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
384
+ return diff === 0;
385
+ }