@mynthio/sdk 0.0.49 → 0.0.51

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/handler.js CHANGED
@@ -1,67 +1,5 @@
1
- import { a as toImageUpscaleResult, c as toImageRateResult, i as taskFailureFromWebhook, l as toImageGenerationResult, o as toImageReviewResult, r as completedTaskFromWebhook, s as toImageRemoveBackgroundResult, t as toVideoGenerationResult, u as toImageAltResult } from "./video-generation-result.js";
2
- //#region src/webhooks/utils.ts
3
- /** Environment variable used when no webhook secret is passed explicitly. */
4
- const WEBHOOK_SECRET_ENV_VAR = "MYNTH_WEBHOOK_SECRET";
5
- /** Hex-encoded HMAC-SHA256 digests are always 32 bytes. */
6
- const SIGNATURE_PATTERN = /^[0-9a-f]{64}$/i;
7
- const TIMESTAMP_PATTERN = /^\d{1,15}$/;
8
- const encoder = new TextEncoder();
9
- /** Read the webhook secret without assuming a Node.js runtime. */
10
- function getWebhookSecretFromEnv() {
11
- if (typeof process !== "undefined" && process.env) return process.env[WEBHOOK_SECRET_ENV_VAR];
12
- }
13
- function parseSignatureHeader(signatureHeader) {
14
- let timestamp;
15
- const signatures = [];
16
- for (const part of signatureHeader.split(",")) {
17
- const separator = part.indexOf("=");
18
- if (separator === -1) continue;
19
- const key = part.slice(0, separator).trim();
20
- const value = part.slice(separator + 1).trim();
21
- if (key === "t" && TIMESTAMP_PATTERN.test(value)) timestamp = value;
22
- else if (key === "v1" && SIGNATURE_PATTERN.test(value)) signatures.push(hexToBytes(value));
23
- }
24
- if (timestamp === void 0 || signatures.length === 0) return null;
25
- return {
26
- timestamp,
27
- signatures
28
- };
29
- }
30
- /**
31
- * Verify a Mynth HMAC-SHA256 signature against the raw request body.
32
- *
33
- * Rejects timestamps more than five minutes from `now` to limit replays. The
34
- * comparison runs inside Web Crypto, so it does not leak timing information.
35
- */
36
- async function verifySignature(body, signatureHeader, secret, now = Date.now()) {
37
- const parsed = parseSignatureHeader(signatureHeader);
38
- if (!parsed) return false;
39
- const ageSeconds = Math.floor(now / 1e3) - Number(parsed.timestamp);
40
- if (Math.abs(ageSeconds) > 300) return false;
41
- const key = await crypto.subtle.importKey("raw", encoder.encode(secret), {
42
- name: "HMAC",
43
- hash: "SHA-256"
44
- }, false, ["verify"]);
45
- const message = concatBytes(encoder.encode(`${parsed.timestamp}.`), body);
46
- for (const signature of parsed.signatures) if (await crypto.subtle.verify("HMAC", key, signature, message)) return true;
47
- return false;
48
- }
49
- function hexToBytes(hex) {
50
- const bytes = new Uint8Array(hex.length / 2);
51
- for (let i = 0; i < bytes.length; i++) bytes[i] = Number.parseInt(hex.slice(i * 2, i * 2 + 2), 16);
52
- return bytes;
53
- }
54
- function concatBytes(a, b) {
55
- const bytes = new Uint8Array(a.length + b.length);
56
- bytes.set(a);
57
- bytes.set(b, a.length);
58
- return bytes;
59
- }
60
- //#endregion
1
+ import { _ as toImageAltResult, a as parseWebhookEvent, c as toVideoGenerationResult, d as taskFailureFromWebhook, f as toImageUpscaleResult, g as toImageGenerationResult, h as toImageRateResult, i as getWebhookSecretFromEnv, m as toImageRemoveBackgroundResult, n as WEBHOOK_SIGNATURE_HEADER, p as toImageReviewResult, r as WEBHOOK_TIMESTAMP_HEADER, s as verifySignature, t as WEBHOOK_ID_HEADER, u as completedTaskFromWebhook } from "./utils.js";
61
2
  //#region src/webhooks/handler.ts
62
- const WEBHOOK_EVENT_HEADER = "X-Mynth-Event";
63
- const WEBHOOK_DELIVERY_HEADER = "X-Mynth-Delivery";
64
- const WEBHOOK_SIGNATURE_HEADER = "X-Mynth-Signature";
65
3
  /** Maps every webhook event to the callback name the framework helpers accept. */
66
4
  const EVENT_HANDLER_NAMES = {
67
5
  "task.image.generate.completed": "imageTaskCompleted",
@@ -79,78 +17,87 @@ const EVENT_HANDLER_NAMES = {
79
17
  "task.video.generate.completed": "videoTaskCompleted",
80
18
  "task.video.generate.failed": "videoTaskFailed"
81
19
  };
82
- /** Builds each event's callback argument from its payload. */
20
+ /** Builds each event's callback argument from the event. */
83
21
  const EVENT_ARGUMENTS = {
84
- "task.image.generate.completed": (payload) => toImageGenerationResult(completedTaskFromWebhook(payload)),
85
- "task.image.generate.failed": (payload) => ({
86
- ...taskFailureFromWebhook(payload),
87
- metadata: payload.request.metadata
22
+ "task.image.generate.completed": (event) => toImageGenerationResult(completedTaskFromWebhook(event)),
23
+ "task.image.generate.failed": (event) => ({
24
+ ...taskFailureFromWebhook(event),
25
+ metadata: event.data.request.metadata
88
26
  }),
89
- "task.image.rate.completed": (payload) => toImageRateResult(completedTaskFromWebhook(payload)),
27
+ "task.image.rate.completed": (event) => toImageRateResult(completedTaskFromWebhook(event)),
90
28
  "task.image.rate.failed": taskFailureFromWebhook,
91
- "task.image.alt.completed": (payload) => toImageAltResult(completedTaskFromWebhook(payload)),
29
+ "task.image.alt.completed": (event) => toImageAltResult(completedTaskFromWebhook(event)),
92
30
  "task.image.alt.failed": taskFailureFromWebhook,
93
- "task.image.review.completed": (payload) => toImageReviewResult(completedTaskFromWebhook(payload)),
31
+ "task.image.review.completed": (event) => toImageReviewResult(completedTaskFromWebhook(event)),
94
32
  "task.image.review.failed": taskFailureFromWebhook,
95
- "task.image.remove_background.completed": (payload) => toImageRemoveBackgroundResult(completedTaskFromWebhook(payload)),
96
- "task.image.remove_background.failed": (payload) => ({
97
- ...taskFailureFromWebhook(payload),
98
- metadata: payload.request.metadata
33
+ "task.image.remove_background.completed": (event) => toImageRemoveBackgroundResult(completedTaskFromWebhook(event)),
34
+ "task.image.remove_background.failed": (event) => ({
35
+ ...taskFailureFromWebhook(event),
36
+ metadata: event.data.request.metadata
99
37
  }),
100
- "task.image.upscale.completed": (payload) => toImageUpscaleResult(completedTaskFromWebhook(payload)),
101
- "task.image.upscale.failed": (payload) => ({
102
- ...taskFailureFromWebhook(payload),
103
- metadata: payload.request.metadata
38
+ "task.image.upscale.completed": (event) => toImageUpscaleResult(completedTaskFromWebhook(event)),
39
+ "task.image.upscale.failed": (event) => ({
40
+ ...taskFailureFromWebhook(event),
41
+ metadata: event.data.request.metadata
104
42
  }),
105
- "task.video.generate.completed": (payload) => toVideoGenerationResult(completedTaskFromWebhook(payload)),
106
- "task.video.generate.failed": (payload) => ({
107
- ...taskFailureFromWebhook(payload),
108
- metadata: payload.request.metadata
43
+ "task.video.generate.completed": (event) => toVideoGenerationResult(completedTaskFromWebhook(event)),
44
+ "task.video.generate.failed": (event) => ({
45
+ ...taskFailureFromWebhook(event),
46
+ metadata: event.data.request.metadata
109
47
  })
110
48
  };
111
49
  /**
112
- * Verify a signed Mynth webhook request and dispatch it to the matching callback.
50
+ * Verify a Mynth webhook request and dispatch its event to the matching callback.
113
51
  *
114
- * Answers `400` for a missing delivery ID, a missing or invalid signature, a
115
- * stale timestamp, a malformed body, or an `X-Mynth-Event` header that does
116
- * not match the body.
117
- * Answers `200` for signed events without a callback. Callback errors, and
118
- * payloads that do not build into a result, propagate, so the framework
119
- * answers `5xx` and Mynth retries the delivery.
52
+ * Signed deliveries (registered webhooks) answer `400` for a missing header, a
53
+ * missing or invalid signature, a timestamp more than five minutes off, a
54
+ * malformed body, or a body `id` other than `webhook-id`. Unsigned deliveries
55
+ * (custom URLs) are accepted only with the `unsigned` option, and answer `401`
56
+ * when its `verify` refuses them.
57
+ *
58
+ * Answers `200` for events without a callback, including event types newer
59
+ * than this SDK. Callback errors, and events that do not build into a result,
60
+ * propagate, so the framework answers `5xx` and Mynth retries the delivery.
120
61
  */
121
62
  async function handleWebhookRequest(request, eventHandlers, createContext, options) {
122
- const webhookSecret = options.webhookSecret ?? getWebhookSecretFromEnv();
123
- if (!webhookSecret) throw new Error("MYNTH_WEBHOOK_SECRET is required. Either pass it as an option or set the environment variable.");
124
- const event = request.headers.get(WEBHOOK_EVENT_HEADER);
125
- const deliveryId = request.headers.get(WEBHOOK_DELIVERY_HEADER);
126
- const signature = request.headers.get(WEBHOOK_SIGNATURE_HEADER);
127
- if (!event || !deliveryId || !signature) return badRequest();
63
+ const id = request.headers.get(WEBHOOK_ID_HEADER);
64
+ const timestamp = request.headers.get(WEBHOOK_TIMESTAMP_HEADER);
65
+ if (!id || !timestamp) return badRequest();
128
66
  const body = new Uint8Array(await request.arrayBuffer());
129
- if (!await verifySignature(body, signature, webhookSecret)) return badRequest();
130
- const payload = parsePayload(body);
131
- if (!payload || payload.event !== event) return badRequest();
132
- if (!Object.hasOwn(EVENT_HANDLER_NAMES, payload.event)) return ok();
133
- const handler = eventHandlers[EVENT_HANDLER_NAMES[payload.event]];
67
+ if (options.unsigned) {
68
+ if (!await options.unsigned.verify(request)) return unauthorized();
69
+ } else {
70
+ const secret = options.webhookSecret ?? getWebhookSecretFromEnv();
71
+ if (!secret) throw new Error("MYNTH_WEBHOOK_SECRET is required. Either pass it as an option or set the environment variable.");
72
+ const signature = request.headers.get(WEBHOOK_SIGNATURE_HEADER);
73
+ if (!signature) return badRequest();
74
+ if (!await verifySignature({
75
+ id,
76
+ timestamp,
77
+ signature,
78
+ body,
79
+ secret
80
+ })) return badRequest();
81
+ }
82
+ const event = parseWebhookEvent(body, id);
83
+ if (!event) return badRequest();
84
+ const context = createContext(event);
85
+ await eventHandlers.onEvent?.(event, context);
86
+ if (!Object.hasOwn(EVENT_HANDLER_NAMES, event.type)) return ok();
87
+ const handler = eventHandlers[EVENT_HANDLER_NAMES[event.type]];
134
88
  if (!handler) return ok();
135
- const toArgument = EVENT_ARGUMENTS[payload.event];
136
- await handler(toArgument(payload), createContext(deliveryId));
89
+ const toArgument = EVENT_ARGUMENTS[event.type];
90
+ await handler(toArgument(event), context);
137
91
  return ok();
138
92
  }
139
- function parsePayload(body) {
140
- let payload;
141
- try {
142
- payload = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(body));
143
- } catch {
144
- return null;
145
- }
146
- if (typeof payload !== "object" || payload === null || !("event" in payload) || typeof payload.event !== "string" || !("task" in payload) || typeof payload.task !== "object" || payload.task === null || !("id" in payload.task) || typeof payload.task.id !== "string") return null;
147
- return payload;
148
- }
149
93
  function ok() {
150
94
  return new Response("OK", { status: 200 });
151
95
  }
152
96
  function badRequest() {
153
97
  return new Response("Bad Request", { status: 400 });
154
98
  }
99
+ function unauthorized() {
100
+ return new Response("Unauthorized", { status: 401 });
101
+ }
155
102
  //#endregion
156
103
  export { handleWebhookRequest as t };
package/dist/index.d.ts CHANGED
@@ -6,14 +6,19 @@ import { _ as AvailableVideoModel, a as ImageRemoveBackgroundResult, b as VideoR
6
6
  export declare class MynthAPIError extends Error {
7
7
  /** HTTP status code of the failed request */
8
8
  readonly status: number;
9
- /** Error code from the API response, if available */
9
+ /** Error code from the API response, if available, e.g. `insufficient_balance` */
10
10
  readonly code?: string | undefined;
11
11
  /**
12
- * One entry per invalid field when `code` is `VALIDATION_ERROR` and the
13
- * request failed its schema. `message` already states all of them.
12
+ * One entry per invalid or unknown field when `code` is `validation_error`.
13
+ * `message` already states all of them.
14
14
  */
15
15
  readonly issues?: ReadonlyArray<MynthAPIErrorIssue> | undefined;
16
- constructor(message: string, status: number, code?: string, issues?: ReadonlyArray<MynthAPIErrorIssue>);
16
+ /**
17
+ * The task the request created before it failed, when `code` is
18
+ * `public_access_token_failed`. It will run: follow it rather than resending.
19
+ */
20
+ readonly taskId?: string | undefined;
21
+ constructor(message: string, status: number, code?: string, issues?: ReadonlyArray<MynthAPIErrorIssue>, taskId?: string);
17
22
  }
18
23
  type MynthAPIErrorIssue = {
19
24
  /** Where the problem is, e.g. `["size", "scale"]`. Empty for the body as a whole. */
@@ -156,6 +161,53 @@ export declare class TaskAsync<ResultT> {
156
161
  private sleep;
157
162
  }
158
163
  //#endregion
164
+ //#region src/webhooks/utils.d.ts
165
+ /** The headers of a webhook request, from a `Headers` or a Node-style header object. */
166
+ type WebhookHeaders = Headers | Record<string, string | string[] | undefined>;
167
+ //#endregion
168
+ //#region src/webhooks/verify.d.ts
169
+ /** A webhook request failed verification: unsigned, wrongly signed, stale, or not an event. */
170
+ export declare class MynthWebhookVerificationError extends Error {
171
+ constructor(message: string);
172
+ }
173
+ /** A webhook request as it arrived. */
174
+ type MynthWebhookRequest = {
175
+ /**
176
+ * The raw body, exactly as received. Parsing and serializing the JSON again
177
+ * can change the bytes, and the signature covers the bytes.
178
+ */
179
+ body: string | Uint8Array | ArrayBuffer;
180
+ /** A `Headers` object, or a Node-style header record such as `req.headers`. */
181
+ headers: WebhookHeaders;
182
+ };
183
+ /**
184
+ * Verify a signed Mynth webhook and return its event.
185
+ *
186
+ * Checks the Standard Webhooks signature over `webhook-id`, `webhook-timestamp`
187
+ * and the raw body, rejects a timestamp more than five minutes off, and checks
188
+ * that the body's `id` is the `webhook-id`. Deduplicate on `event.id`: every
189
+ * delivery of the event repeats it.
190
+ *
191
+ * An event type newer than this SDK is returned as is, so keep a `default`
192
+ * branch when you switch on `event.type`.
193
+ *
194
+ * @param secret - The webhook's `whsec_` secret. Defaults to MYNTH_WEBHOOK_SECRET.
195
+ * @throws {MynthWebhookVerificationError} If the request is not a valid, signed event
196
+ * @throws {Error} If there is no secret, or it is not a `whsec_` secret
197
+ *
198
+ * @example
199
+ * ```typescript
200
+ * const event = await verifyWebhook({ body: await request.text(), headers: request.headers });
201
+ *
202
+ * switch (event.type) {
203
+ * case "task.image.generate.completed":
204
+ * console.log(event.data.result.images);
205
+ * break;
206
+ * }
207
+ * ```
208
+ */
209
+ export declare function verifyWebhook(request: MynthWebhookRequest, secret?: string | undefined): Promise<MynthSDKTypes.WebhookEvent>;
210
+ //#endregion
159
211
  //#region src/index.d.ts
160
212
  /**
161
213
  * Configuration options for the Mynth client.
@@ -297,6 +349,7 @@ declare class MynthImage {
297
349
  * ```typescript
298
350
  * const taskAsync = await image.generateAsync({
299
351
  * prompt: "A futuristic cityscape",
352
+ * generate_public_access_token: true,
300
353
  * });
301
354
  *
302
355
  * return { id: taskAsync.id, access: taskAsync.access };
@@ -427,7 +480,10 @@ declare class MynthImage {
427
480
  *
428
481
  * @example
429
482
  * ```typescript
430
- * const taskAsync = await image.removeBackgroundAsync({ url: "https://..." });
483
+ * const taskAsync = await image.removeBackgroundAsync({
484
+ * url: "https://...",
485
+ * generate_public_access_token: true,
486
+ * });
431
487
  *
432
488
  * return { id: taskAsync.id, access: taskAsync.access };
433
489
  * ```
@@ -439,7 +495,7 @@ declare class MynthImage {
439
495
  *
440
496
  * Mynth picks the model. `effort` sets the price, so it has no default. The
441
497
  * upscaled image can be at most 4096x4096 pixels; a larger request fails
442
- * with `OUTPUT_TOO_LARGE` and is not charged.
498
+ * with `output_too_large` and is not charged.
443
499
  *
444
500
  * @param request - Image URL or local file, size, and effort, plus optional output, destination, webhook, and metadata
445
501
  * @returns An ImageUpscaleResult with the enlarged image
@@ -459,7 +515,12 @@ declare class MynthImage {
459
515
  *
460
516
  * @example
461
517
  * ```typescript
462
- * const taskAsync = await image.upscaleAsync({ url: "https://...", size: "2x", effort: "low" });
518
+ * const taskAsync = await image.upscaleAsync({
519
+ * url: "https://...",
520
+ * size: "2x",
521
+ * effort: "low",
522
+ * generate_public_access_token: true,
523
+ * });
463
524
  *
464
525
  * return { id: taskAsync.id, access: taskAsync.access };
465
526
  * ```
@@ -523,7 +584,8 @@ declare class MynthVideo {
523
584
  * Start video generation without waiting for completion.
524
585
  *
525
586
  * The preferred entry point for server code: hand `taskAsync.id` and
526
- * `taskAsync.access.publicAccessToken` to the browser, or register a webhook,
587
+ * `taskAsync.access.publicAccessToken` to the browser (pass
588
+ * `generate_public_access_token: true` to get one), or register a webhook,
527
589
  * instead of holding a connection open for the length of a render.
528
590
  *
529
591
  * @param request - Video generation request parameters
@@ -534,6 +596,7 @@ declare class MynthVideo {
534
596
  * const taskAsync = await video.generateAsync({
535
597
  * model: "prunaai/p-video",
536
598
  * prompt: "A neon city street in the rain",
599
+ * generate_public_access_token: true,
537
600
  * });
538
601
  *
539
602
  * return { id: taskAsync.id, access: taskAsync.access };
@@ -560,11 +623,11 @@ declare class MynthVideo {
560
623
  * video pins a concrete model, the returned estimate is exact.
561
624
  *
562
625
  * @param request - The same request you would pass to `generate()`
563
- * @returns The estimated cost in USD
626
+ * @returns The estimated cost in USD, as the API returns it
564
627
  *
565
628
  * @example
566
629
  * ```typescript
567
- * const { estimatedCost } = await video.estimate({
630
+ * const { estimated_cost } = await video.estimate({
568
631
  * model: "google/gemini-omni-flash-1.1",
569
632
  * prompt: "A timelapse of clouds over a canyon",
570
633
  * duration: 10,
@@ -636,4 +699,4 @@ declare class Mynth {
636
699
  get video(): MynthVideo;
637
700
  }
638
701
  //#endregion
639
- export { AVAILABLE_MODELS, AVAILABLE_VIDEO_MODELS, type AvailableModel, type AvailableVideoModel, type ImageAltResult, type ImageGenerationResult, type ImageRateResult, type ImageRemoveBackgroundResult, type ImageReviewResult, type ImageUpscaleResult, type ModelCapability, Mynth, Mynth as default, type MynthAPIErrorIssue, type MynthCompletedTask, type MynthGeneratedImage, MynthImage, type MynthModel, type MynthModelPricing, MynthModels, type MynthOptions, type MynthOutputImage, type MynthOutputVideo, type MynthRequestOptions, type MynthSDKTypes, type MynthTaskFailure, MynthVideo, type TaskAsyncAccess, type TaskAsyncWaitOptions, type VideoGenerationResult, type VideoInputRole, type VideoResolutionTier };
702
+ export { AVAILABLE_MODELS, AVAILABLE_VIDEO_MODELS, type AvailableModel, type AvailableVideoModel, type ImageAltResult, type ImageGenerationResult, type ImageRateResult, type ImageRemoveBackgroundResult, type ImageReviewResult, type ImageUpscaleResult, type ModelCapability, Mynth, Mynth as default, type MynthAPIErrorIssue, type MynthCompletedTask, type MynthGeneratedImage, MynthImage, type MynthModel, type MynthModelPricing, MynthModels, type MynthOptions, type MynthOutputImage, type MynthOutputVideo, type MynthRequestOptions, type MynthSDKTypes, type MynthTaskFailure, MynthVideo, type MynthWebhookRequest, type TaskAsyncAccess, type TaskAsyncWaitOptions, type VideoGenerationResult, type VideoInputRole, type VideoResolutionTier };
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { a as toImageUpscaleResult, c as toImageRateResult, l as toImageGenerationResult, n as completedTaskFromData, o as toImageReviewResult, s as toImageRemoveBackgroundResult, t as toVideoGenerationResult, u as toImageAltResult } from "./video-generation-result.js";
1
+ import { _ as toImageAltResult, a as parseWebhookEvent, c as toVideoGenerationResult, f as toImageUpscaleResult, g as toImageGenerationResult, h as toImageRateResult, i as getWebhookSecretFromEnv, l as completedTaskFromData, m as toImageRemoveBackgroundResult, n as WEBHOOK_SIGNATURE_HEADER, o as readHeader, p as toImageReviewResult, r as WEBHOOK_TIMESTAMP_HEADER, s as verifySignature, t as WEBHOOK_ID_HEADER } from "./utils.js";
2
2
  //#region src/constants.ts
3
3
  /** Base URL for the Mynth API */
4
4
  const API_URL = "https://api.mynth.io";
@@ -400,24 +400,31 @@ const AVAILABLE_VIDEO_MODELS = [
400
400
  var MynthAPIError = class extends Error {
401
401
  /** HTTP status code of the failed request */
402
402
  status;
403
- /** Error code from the API response, if available */
403
+ /** Error code from the API response, if available, e.g. `insufficient_balance` */
404
404
  code;
405
405
  /**
406
- * One entry per invalid field when `code` is `VALIDATION_ERROR` and the
407
- * request failed its schema. `message` already states all of them.
406
+ * One entry per invalid or unknown field when `code` is `validation_error`.
407
+ * `message` already states all of them.
408
408
  */
409
409
  issues;
410
- constructor(message, status, code, issues) {
410
+ /**
411
+ * The task the request created before it failed, when `code` is
412
+ * `public_access_token_failed`. It will run: follow it rather than resending.
413
+ */
414
+ taskId;
415
+ constructor(message, status, code, issues, taskId) {
411
416
  super(message);
412
417
  this.name = "MynthAPIError";
413
418
  this.status = status;
414
419
  this.code = code;
415
420
  this.issues = issues;
421
+ this.taskId = taskId;
416
422
  }
417
423
  };
418
424
  function createApiError(data, status) {
419
- const errorResponse = typeof data === "object" && data !== null ? data : {};
420
- return new MynthAPIError(typeof errorResponse.message === "string" && errorResponse.message || typeof errorResponse.error === "string" && errorResponse.error || `Request failed with status ${status}`, status, typeof errorResponse.code === "string" ? errorResponse.code : void 0, Array.isArray(errorResponse.issues) ? errorResponse.issues : void 0);
425
+ const body = typeof data === "object" && data !== null ? data : {};
426
+ const error = typeof body.error === "object" && body.error !== null ? body.error : {};
427
+ return new MynthAPIError(typeof error.message === "string" && error.message || `Request failed with status ${status}`, status, typeof error.code === "string" ? error.code : void 0, Array.isArray(error.issues) ? error.issues : void 0, typeof error.task_id === "string" ? error.task_id : void 0);
421
428
  }
422
429
  /** An error body that is not JSON (a proxy's HTML page, say) still yields an API error. */
423
430
  async function readErrorBody(response) {
@@ -825,6 +832,67 @@ async function resolveInputs(client, inputs, { signal } = {}) {
825
832
  });
826
833
  }
827
834
  //#endregion
835
+ //#region src/webhooks/verify.ts
836
+ /** A webhook request failed verification: unsigned, wrongly signed, stale, or not an event. */
837
+ var MynthWebhookVerificationError = class extends Error {
838
+ constructor(message) {
839
+ super(message);
840
+ this.name = "MynthWebhookVerificationError";
841
+ }
842
+ };
843
+ function toBytes(body) {
844
+ if (typeof body === "string") return new TextEncoder().encode(body);
845
+ return body instanceof Uint8Array ? body : new Uint8Array(body);
846
+ }
847
+ /**
848
+ * Verify a signed Mynth webhook and return its event.
849
+ *
850
+ * Checks the Standard Webhooks signature over `webhook-id`, `webhook-timestamp`
851
+ * and the raw body, rejects a timestamp more than five minutes off, and checks
852
+ * that the body's `id` is the `webhook-id`. Deduplicate on `event.id`: every
853
+ * delivery of the event repeats it.
854
+ *
855
+ * An event type newer than this SDK is returned as is, so keep a `default`
856
+ * branch when you switch on `event.type`.
857
+ *
858
+ * @param secret - The webhook's `whsec_` secret. Defaults to MYNTH_WEBHOOK_SECRET.
859
+ * @throws {MynthWebhookVerificationError} If the request is not a valid, signed event
860
+ * @throws {Error} If there is no secret, or it is not a `whsec_` secret
861
+ *
862
+ * @example
863
+ * ```typescript
864
+ * const event = await verifyWebhook({ body: await request.text(), headers: request.headers });
865
+ *
866
+ * switch (event.type) {
867
+ * case "task.image.generate.completed":
868
+ * console.log(event.data.result.images);
869
+ * break;
870
+ * }
871
+ * ```
872
+ */
873
+ async function verifyWebhook(request, secret = getWebhookSecretFromEnv()) {
874
+ if (!secret) throw new Error("MYNTH_WEBHOOK_SECRET is required. Either pass the secret or set the environment variable.");
875
+ const id = readHeader(request.headers, WEBHOOK_ID_HEADER);
876
+ const timestamp = readHeader(request.headers, WEBHOOK_TIMESTAMP_HEADER);
877
+ const signature = readHeader(request.headers, WEBHOOK_SIGNATURE_HEADER);
878
+ if (!id || !timestamp || !signature) throw new MynthWebhookVerificationError(`Missing ${[
879
+ !id && "webhook-id",
880
+ !timestamp && "webhook-timestamp",
881
+ !signature && "webhook-signature"
882
+ ].filter(Boolean).join(", ")} header. Only registered webhooks are signed.`);
883
+ const body = toBytes(request.body);
884
+ if (!await verifySignature({
885
+ id,
886
+ timestamp,
887
+ signature,
888
+ body,
889
+ secret
890
+ })) throw new MynthWebhookVerificationError("The webhook signature does not match, or its timestamp is more than five minutes off.");
891
+ const event = parseWebhookEvent(body, id);
892
+ if (!event) throw new MynthWebhookVerificationError("The webhook body is not a Mynth event for this webhook-id.");
893
+ return event;
894
+ }
895
+ //#endregion
828
896
  //#region src/index.ts
829
897
  /**
830
898
  * Attempts to read the API key from environment variables.
@@ -928,6 +996,7 @@ var MynthImage = class {
928
996
  * ```typescript
929
997
  * const taskAsync = await image.generateAsync({
930
998
  * prompt: "A futuristic cityscape",
999
+ * generate_public_access_token: true,
931
1000
  * });
932
1001
  *
933
1002
  * return { id: taskAsync.id, access: taskAsync.access };
@@ -943,9 +1012,9 @@ var MynthImage = class {
943
1012
  inputs,
944
1013
  destination: request.destination ?? this.defaultDestination
945
1014
  }, { signal })).data;
946
- return new TaskAsync(data.taskId, {
1015
+ return new TaskAsync(data.task_id, {
947
1016
  client: this.client,
948
- pat: data.access?.publicAccessToken,
1017
+ pat: data.public_access_token,
949
1018
  resultFactory: (data) => toImageGenerationResult(completedTaskFromData(data, "Image generation"))
950
1019
  });
951
1020
  }
@@ -1013,7 +1082,7 @@ var MynthImage = class {
1013
1082
  ...rest,
1014
1083
  url
1015
1084
  })).data;
1016
- return new TaskAsync(data.taskId, {
1085
+ return new TaskAsync(data.task_id, {
1017
1086
  client: this.client,
1018
1087
  resultFactory: (taskData) => toImageRateResult(completedTaskFromData(taskData, "Image rate"))
1019
1088
  });
@@ -1055,7 +1124,7 @@ var MynthImage = class {
1055
1124
  async createAltTask(request) {
1056
1125
  const url = await this.resolveUrlOrFile(request);
1057
1126
  const data = (await this.client.post(ALT_IMAGE_PATH, { url })).data;
1058
- return new TaskAsync(data.taskId, {
1127
+ return new TaskAsync(data.task_id, {
1059
1128
  client: this.client,
1060
1129
  resultFactory: (taskData) => toImageAltResult(completedTaskFromData(taskData, "Image alt"))
1061
1130
  });
@@ -1092,7 +1161,7 @@ var MynthImage = class {
1092
1161
  ...rest,
1093
1162
  url
1094
1163
  })).data;
1095
- return new TaskAsync(data.taskId, {
1164
+ return new TaskAsync(data.task_id, {
1096
1165
  client: this.client,
1097
1166
  resultFactory: (taskData) => toImageReviewResult(completedTaskFromData(taskData, "Image review"))
1098
1167
  });
@@ -1123,7 +1192,10 @@ var MynthImage = class {
1123
1192
  *
1124
1193
  * @example
1125
1194
  * ```typescript
1126
- * const taskAsync = await image.removeBackgroundAsync({ url: "https://..." });
1195
+ * const taskAsync = await image.removeBackgroundAsync({
1196
+ * url: "https://...",
1197
+ * generate_public_access_token: true,
1198
+ * });
1127
1199
  *
1128
1200
  * return { id: taskAsync.id, access: taskAsync.access };
1129
1201
  * ```
@@ -1139,9 +1211,9 @@ var MynthImage = class {
1139
1211
  url,
1140
1212
  destination: request.destination ?? this.defaultDestination
1141
1213
  })).data;
1142
- return new TaskAsync(data.taskId, {
1214
+ return new TaskAsync(data.task_id, {
1143
1215
  client: this.client,
1144
- pat: data.access?.publicAccessToken,
1216
+ pat: data.public_access_token,
1145
1217
  resultFactory: (taskData) => toImageRemoveBackgroundResult(completedTaskFromData(taskData, "Image remove background"))
1146
1218
  });
1147
1219
  }
@@ -1150,7 +1222,7 @@ var MynthImage = class {
1150
1222
  *
1151
1223
  * Mynth picks the model. `effort` sets the price, so it has no default. The
1152
1224
  * upscaled image can be at most 4096x4096 pixels; a larger request fails
1153
- * with `OUTPUT_TOO_LARGE` and is not charged.
1225
+ * with `output_too_large` and is not charged.
1154
1226
  *
1155
1227
  * @param request - Image URL or local file, size, and effort, plus optional output, destination, webhook, and metadata
1156
1228
  * @returns An ImageUpscaleResult with the enlarged image
@@ -1172,7 +1244,12 @@ var MynthImage = class {
1172
1244
  *
1173
1245
  * @example
1174
1246
  * ```typescript
1175
- * const taskAsync = await image.upscaleAsync({ url: "https://...", size: "2x", effort: "low" });
1247
+ * const taskAsync = await image.upscaleAsync({
1248
+ * url: "https://...",
1249
+ * size: "2x",
1250
+ * effort: "low",
1251
+ * generate_public_access_token: true,
1252
+ * });
1176
1253
  *
1177
1254
  * return { id: taskAsync.id, access: taskAsync.access };
1178
1255
  * ```
@@ -1188,9 +1265,9 @@ var MynthImage = class {
1188
1265
  url,
1189
1266
  destination: request.destination ?? this.defaultDestination
1190
1267
  })).data;
1191
- return new TaskAsync(data.taskId, {
1268
+ return new TaskAsync(data.task_id, {
1192
1269
  client: this.client,
1193
- pat: data.access?.publicAccessToken,
1270
+ pat: data.public_access_token,
1194
1271
  resultFactory: (taskData) => toImageUpscaleResult(completedTaskFromData(taskData, "Image upscale"))
1195
1272
  });
1196
1273
  }
@@ -1260,7 +1337,8 @@ var MynthVideo = class {
1260
1337
  * Start video generation without waiting for completion.
1261
1338
  *
1262
1339
  * The preferred entry point for server code: hand `taskAsync.id` and
1263
- * `taskAsync.access.publicAccessToken` to the browser, or register a webhook,
1340
+ * `taskAsync.access.publicAccessToken` to the browser (pass
1341
+ * `generate_public_access_token: true` to get one), or register a webhook,
1264
1342
  * instead of holding a connection open for the length of a render.
1265
1343
  *
1266
1344
  * @param request - Video generation request parameters
@@ -1271,6 +1349,7 @@ var MynthVideo = class {
1271
1349
  * const taskAsync = await video.generateAsync({
1272
1350
  * model: "prunaai/p-video",
1273
1351
  * prompt: "A neon city street in the rain",
1352
+ * generate_public_access_token: true,
1274
1353
  * });
1275
1354
  *
1276
1355
  * return { id: taskAsync.id, access: taskAsync.access };
@@ -1301,11 +1380,11 @@ var MynthVideo = class {
1301
1380
  * video pins a concrete model, the returned estimate is exact.
1302
1381
  *
1303
1382
  * @param request - The same request you would pass to `generate()`
1304
- * @returns The estimated cost in USD
1383
+ * @returns The estimated cost in USD, as the API returns it
1305
1384
  *
1306
1385
  * @example
1307
1386
  * ```typescript
1308
- * const { estimatedCost } = await video.estimate({
1387
+ * const { estimated_cost } = await video.estimate({
1309
1388
  * model: "google/gemini-omni-flash-1.1",
1310
1389
  * prompt: "A timelapse of clouds over a canyon",
1311
1390
  * duration: 10,
@@ -1326,9 +1405,9 @@ var MynthVideo = class {
1326
1405
  }
1327
1406
  async createGenerationTask(request) {
1328
1407
  const data = (await this.client.post(GENERATE_VIDEO_PATH, await this.toRequestBody(request))).data;
1329
- return new TaskAsync(data.taskId, {
1408
+ return new TaskAsync(data.task_id, {
1330
1409
  client: this.client,
1331
- pat: data.access?.publicAccessToken,
1410
+ pat: data.public_access_token,
1332
1411
  polling: VIDEO_POLLING,
1333
1412
  resultFactory: (taskData) => toVideoGenerationResult(completedTaskFromData(taskData, "Video generation"))
1334
1413
  });
@@ -1407,4 +1486,4 @@ var Mynth = class {
1407
1486
  }
1408
1487
  };
1409
1488
  //#endregion
1410
- export { AVAILABLE_MODELS, AVAILABLE_VIDEO_MODELS, Mynth, Mynth as default, MynthAPIError, MynthImage, MynthModels, MynthVideo, TaskAsync, TaskAsyncFetchError, TaskAsyncTaskFailedError, TaskAsyncTaskFetchError, TaskAsyncTimeoutError, TaskAsyncUnauthorizedError };
1489
+ export { AVAILABLE_MODELS, AVAILABLE_VIDEO_MODELS, Mynth, Mynth as default, MynthAPIError, MynthImage, MynthModels, MynthVideo, MynthWebhookVerificationError, TaskAsync, TaskAsyncFetchError, TaskAsyncTaskFailedError, TaskAsyncTaskFetchError, TaskAsyncTimeoutError, TaskAsyncUnauthorizedError, verifyWebhook };
@@ -1,18 +1,19 @@
1
+ import { p as MynthSDKTypes } from "../video-generation-result.js";
1
2
  import { n as WebhookHandlerOptions, t as WebhookEventHandlers } from "../handler.js";
2
3
  //#region src/next/index.d.ts
3
4
  export type MynthWebhookHandlerContext = {
4
5
  /** The original request received by the Next.js Route Handler. */
5
6
  request: Request;
6
7
  /**
7
- * The `X-Mynth-Delivery` ID. Every retry of a delivery repeats it, so store
8
- * it and skip IDs you have already handled.
8
+ * The verified event. `event.id` is the `webhook-id`: every delivery of the
9
+ * event repeats it, so store it and skip IDs you have already handled.
9
10
  */
10
- deliveryId: string;
11
+ event: MynthSDKTypes.WebhookEvent;
11
12
  };
12
13
  export type MynthWebhookEventHandlers = WebhookEventHandlers<MynthWebhookHandlerContext>;
13
14
  export type MynthWebhookHandlerOptions = WebhookHandlerOptions;
14
15
  /**
15
- * Create a Next.js App Router handler for signed Mynth webhooks.
16
+ * Create a Next.js App Router handler for Mynth webhooks.
16
17
  *
17
18
  * @example
18
19
  * ```ts
@@ -20,8 +21,8 @@ export type MynthWebhookHandlerOptions = WebhookHandlerOptions;
20
21
  * import { mynthWebhookHandler } from "@mynthio/sdk/next";
21
22
  *
22
23
  * export const POST = mynthWebhookHandler({
23
- * imageTaskCompleted: async (result, { deliveryId }) => {
24
- * console.log(deliveryId, result.taskId);
24
+ * imageTaskCompleted: async (result, { event }) => {
25
+ * console.log(event.id, result.taskId);
25
26
  * },
26
27
  * });
27
28
  * ```