@mynthio/sdk 0.0.48 → 0.0.50

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.
@@ -2,7 +2,7 @@ import { t as handleWebhookRequest } from "../handler.js";
2
2
  import { httpActionGeneric } from "convex/server";
3
3
  //#region src/convex/index.ts
4
4
  /**
5
- * Create a Convex HTTP action for signed Mynth webhooks.
5
+ * Create a Convex HTTP action for Mynth webhooks.
6
6
  *
7
7
  * @example
8
8
  * ```typescript
@@ -18,10 +18,10 @@ import { httpActionGeneric } from "convex/server";
18
18
  * path: "/mynth-webhook",
19
19
  * method: "POST",
20
20
  * handler: mynthWebhookAction({
21
- * imageTaskCompleted: async (payload, { context }) => {
21
+ * imageTaskCompleted: async (result, { context }) => {
22
22
  * await context.runMutation(internal.images.save, {
23
- * taskId: payload.task.id,
24
- * images: payload.result.images,
23
+ * taskId: result.taskId,
24
+ * images: result.images,
25
25
  * });
26
26
  * },
27
27
  * }),
@@ -31,10 +31,10 @@ import { httpActionGeneric } from "convex/server";
31
31
  * ```
32
32
  */
33
33
  function mynthWebhookAction(eventHandlers, options = {}) {
34
- return httpActionGeneric((context, request) => handleWebhookRequest(request, eventHandlers, (deliveryId) => ({
34
+ return httpActionGeneric((context, request) => handleWebhookRequest(request, eventHandlers, (event) => ({
35
35
  context,
36
36
  request,
37
- deliveryId
37
+ event
38
38
  }), options));
39
39
  }
40
40
  //#endregion
package/dist/handler.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { t as MynthSDKTypes } from "./types.js";
1
+ import { a as ImageRemoveBackgroundResult, f as MynthTaskFailure, i as ImageReviewResult, o as ImageRateResult, p as MynthSDKTypes, r as ImageUpscaleResult, s as ImageGenerationResult, t as VideoGenerationResult, u as ImageAltResult } from "./video-generation-result.js";
2
2
  //#region src/webhooks/handler.d.ts
3
3
  /** Maps every webhook event to the callback name the framework helpers accept. */
4
4
  declare const EVENT_HANDLER_NAMES: {
@@ -17,14 +17,48 @@ declare const EVENT_HANDLER_NAMES: {
17
17
  readonly "task.video.generate.completed": "videoTaskCompleted";
18
18
  readonly "task.video.generate.failed": "videoTaskFailed";
19
19
  };
20
- type WebhookEvent = MynthSDKTypes.WebhookPayload["event"];
21
- /** Event callbacks shared by every framework helper, keyed by handler name. */
22
- type WebhookEventHandlers<TContext> = { [TEvent in WebhookEvent as (typeof EVENT_HANDLER_NAMES)[TEvent]]?: (payload: Extract<MynthSDKTypes.WebhookPayload, {
23
- event: TEvent;
24
- }>, context: TContext) => void | Promise<void>; };
20
+ type WebhookEventType = MynthSDKTypes.WebhookEventType;
21
+ /**
22
+ * What each event's callback receives: the same result that polling returns,
23
+ * or a {@link MynthTaskFailure}.
24
+ */
25
+ type WebhookEventArguments = {
26
+ "task.image.generate.completed": ImageGenerationResult;
27
+ "task.image.generate.failed": MynthTaskFailure<MynthSDKTypes.ImageGenerationRequest>;
28
+ "task.image.rate.completed": ImageRateResult<string>;
29
+ "task.image.rate.failed": MynthTaskFailure<MynthSDKTypes.ImageRateRequest>;
30
+ "task.image.alt.completed": ImageAltResult;
31
+ "task.image.alt.failed": MynthTaskFailure<MynthSDKTypes.ImageAltRequest>;
32
+ "task.image.review.completed": ImageReviewResult;
33
+ "task.image.review.failed": MynthTaskFailure<MynthSDKTypes.ImageReviewRequest>;
34
+ "task.image.remove_background.completed": ImageRemoveBackgroundResult;
35
+ "task.image.remove_background.failed": MynthTaskFailure<MynthSDKTypes.ImageRemoveBackgroundRequest>;
36
+ "task.image.upscale.completed": ImageUpscaleResult;
37
+ "task.image.upscale.failed": MynthTaskFailure<MynthSDKTypes.ImageUpscaleRequest>;
38
+ "task.video.generate.completed": VideoGenerationResult;
39
+ "task.video.generate.failed": MynthTaskFailure<MynthSDKTypes.VideoGenerationRequest>;
40
+ };
41
+ /**
42
+ * Event callbacks shared by every framework helper, keyed by handler name,
43
+ * and `onEvent`, which receives every event, including types newer than this
44
+ * SDK, before its typed callback runs. `TContext` carries the verified event:
45
+ * deduplicate on `event.id`, which every delivery repeats.
46
+ */
47
+ type WebhookEventHandlers<TContext> = { [TType in WebhookEventType as (typeof EVENT_HANDLER_NAMES)[TType]]?: (argument: WebhookEventArguments[TType], context: TContext) => void | Promise<void>; } & {
48
+ onEvent?: (event: MynthSDKTypes.WebhookEvent, context: TContext) => void | Promise<void>;
49
+ };
25
50
  type WebhookHandlerOptions = {
26
51
  /** Defaults to MYNTH_WEBHOOK_SECRET, read when each request arrives. */
27
52
  webhookSecret?: string;
53
+ /**
54
+ * Accept unsigned deliveries: a custom webhook URL set on the request.
55
+ * Signatures are not checked at all; `verify` decides instead, usually by
56
+ * checking a secret token you put in the URL. Answers `401` when it returns
57
+ * `false`. Without this, an unsigned delivery answers `400`.
58
+ */
59
+ unsigned?: {
60
+ verify: (request: Request) => boolean | Promise<boolean>;
61
+ };
28
62
  };
29
63
  //#endregion
30
64
  export { WebhookHandlerOptions as n, WebhookEventHandlers as t };
package/dist/handler.js CHANGED
@@ -1,66 +1,5 @@
1
- //#region src/webhooks/utils.ts
2
- /** Environment variable used when no webhook secret is passed explicitly. */
3
- const WEBHOOK_SECRET_ENV_VAR = "MYNTH_WEBHOOK_SECRET";
4
- /** Hex-encoded HMAC-SHA256 digests are always 32 bytes. */
5
- const SIGNATURE_PATTERN = /^[0-9a-f]{64}$/i;
6
- const TIMESTAMP_PATTERN = /^\d{1,15}$/;
7
- const encoder = new TextEncoder();
8
- /** Read the webhook secret without assuming a Node.js runtime. */
9
- function getWebhookSecretFromEnv() {
10
- if (typeof process !== "undefined" && process.env) return process.env[WEBHOOK_SECRET_ENV_VAR];
11
- }
12
- function parseSignatureHeader(signatureHeader) {
13
- let timestamp;
14
- const signatures = [];
15
- for (const part of signatureHeader.split(",")) {
16
- const separator = part.indexOf("=");
17
- if (separator === -1) continue;
18
- const key = part.slice(0, separator).trim();
19
- const value = part.slice(separator + 1).trim();
20
- if (key === "t" && TIMESTAMP_PATTERN.test(value)) timestamp = value;
21
- else if (key === "v1" && SIGNATURE_PATTERN.test(value)) signatures.push(hexToBytes(value));
22
- }
23
- if (timestamp === void 0 || signatures.length === 0) return null;
24
- return {
25
- timestamp,
26
- signatures
27
- };
28
- }
29
- /**
30
- * Verify a Mynth HMAC-SHA256 signature against the raw request body.
31
- *
32
- * Rejects timestamps more than five minutes from `now` to limit replays. The
33
- * comparison runs inside Web Crypto, so it does not leak timing information.
34
- */
35
- async function verifySignature(body, signatureHeader, secret, now = Date.now()) {
36
- const parsed = parseSignatureHeader(signatureHeader);
37
- if (!parsed) return false;
38
- const ageSeconds = Math.floor(now / 1e3) - Number(parsed.timestamp);
39
- if (Math.abs(ageSeconds) > 300) return false;
40
- const key = await crypto.subtle.importKey("raw", encoder.encode(secret), {
41
- name: "HMAC",
42
- hash: "SHA-256"
43
- }, false, ["verify"]);
44
- const message = concatBytes(encoder.encode(`${parsed.timestamp}.`), body);
45
- for (const signature of parsed.signatures) if (await crypto.subtle.verify("HMAC", key, signature, message)) return true;
46
- return false;
47
- }
48
- function hexToBytes(hex) {
49
- const bytes = new Uint8Array(hex.length / 2);
50
- for (let i = 0; i < bytes.length; i++) bytes[i] = Number.parseInt(hex.slice(i * 2, i * 2 + 2), 16);
51
- return bytes;
52
- }
53
- function concatBytes(a, b) {
54
- const bytes = new Uint8Array(a.length + b.length);
55
- bytes.set(a);
56
- bytes.set(b, a.length);
57
- return bytes;
58
- }
59
- //#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";
60
2
  //#region src/webhooks/handler.ts
61
- const WEBHOOK_EVENT_HEADER = "X-Mynth-Event";
62
- const WEBHOOK_DELIVERY_HEADER = "X-Mynth-Delivery";
63
- const WEBHOOK_SIGNATURE_HEADER = "X-Mynth-Signature";
64
3
  /** Maps every webhook event to the callback name the framework helpers accept. */
65
4
  const EVENT_HANDLER_NAMES = {
66
5
  "task.image.generate.completed": "imageTaskCompleted",
@@ -78,40 +17,78 @@ const EVENT_HANDLER_NAMES = {
78
17
  "task.video.generate.completed": "videoTaskCompleted",
79
18
  "task.video.generate.failed": "videoTaskFailed"
80
19
  };
20
+ /** Builds each event's callback argument from the event. */
21
+ const EVENT_ARGUMENTS = {
22
+ "task.image.generate.completed": (event) => toImageGenerationResult(completedTaskFromWebhook(event)),
23
+ "task.image.generate.failed": (event) => ({
24
+ ...taskFailureFromWebhook(event),
25
+ metadata: event.data.request.metadata
26
+ }),
27
+ "task.image.rate.completed": (event) => toImageRateResult(completedTaskFromWebhook(event)),
28
+ "task.image.rate.failed": taskFailureFromWebhook,
29
+ "task.image.alt.completed": (event) => toImageAltResult(completedTaskFromWebhook(event)),
30
+ "task.image.alt.failed": taskFailureFromWebhook,
31
+ "task.image.review.completed": (event) => toImageReviewResult(completedTaskFromWebhook(event)),
32
+ "task.image.review.failed": taskFailureFromWebhook,
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
37
+ }),
38
+ "task.image.upscale.completed": (event) => toImageUpscaleResult(completedTaskFromWebhook(event)),
39
+ "task.image.upscale.failed": (event) => ({
40
+ ...taskFailureFromWebhook(event),
41
+ metadata: event.data.request.metadata
42
+ }),
43
+ "task.video.generate.completed": (event) => toVideoGenerationResult(completedTaskFromWebhook(event)),
44
+ "task.video.generate.failed": (event) => ({
45
+ ...taskFailureFromWebhook(event),
46
+ metadata: event.data.request.metadata
47
+ })
48
+ };
81
49
  /**
82
- * 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.
51
+ *
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.
83
57
  *
84
- * Answers `400` for a missing delivery ID, a missing or invalid signature, a
85
- * stale timestamp, a malformed body, or an `X-Mynth-Event` header that does
86
- * not match the body.
87
- * Answers `200` for signed events without a callback. Callback errors
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,
88
60
  * propagate, so the framework answers `5xx` and Mynth retries the delivery.
89
61
  */
90
62
  async function handleWebhookRequest(request, eventHandlers, createContext, options) {
91
- const webhookSecret = options.webhookSecret ?? getWebhookSecretFromEnv();
92
- if (!webhookSecret) throw new Error("MYNTH_WEBHOOK_SECRET is required. Either pass it as an option or set the environment variable.");
93
- const event = request.headers.get(WEBHOOK_EVENT_HEADER);
94
- const deliveryId = request.headers.get(WEBHOOK_DELIVERY_HEADER);
95
- const signature = request.headers.get(WEBHOOK_SIGNATURE_HEADER);
96
- 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();
97
66
  const body = new Uint8Array(await request.arrayBuffer());
98
- if (!await verifySignature(body, signature, webhookSecret)) return badRequest();
99
- const payload = parsePayload(body);
100
- if (!payload || payload.event !== event) return badRequest();
101
- if (!Object.hasOwn(EVENT_HANDLER_NAMES, payload.event)) return ok();
102
- const handler = eventHandlers[EVENT_HANDLER_NAMES[payload.event]];
103
- await handler?.(payload, createContext(deliveryId));
104
- return ok();
105
- }
106
- function parsePayload(body) {
107
- let payload;
108
- try {
109
- payload = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(body));
110
- } catch {
111
- return null;
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();
112
81
  }
113
- 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;
114
- return payload;
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]];
88
+ if (!handler) return ok();
89
+ const toArgument = EVENT_ARGUMENTS[event.type];
90
+ await handler(toArgument(event), context);
91
+ return ok();
115
92
  }
116
93
  function ok() {
117
94
  return new Response("OK", { status: 200 });
@@ -119,5 +96,8 @@ function ok() {
119
96
  function badRequest() {
120
97
  return new Response("Bad Request", { status: 400 });
121
98
  }
99
+ function unauthorized() {
100
+ return new Response("Unauthorized", { status: 401 });
101
+ }
122
102
  //#endregion
123
103
  export { handleWebhookRequest as t };
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { a as AvailableVideoModel, c as VideoResolutionTier, i as AvailableModel, n as AVAILABLE_MODELS, o as ModelCapability, r as AVAILABLE_VIDEO_MODELS, s as VideoInputRole, t as MynthSDKTypes } from "./types.js";
1
+ import { _ as AvailableVideoModel, a as ImageRemoveBackgroundResult, b as VideoResolutionTier, c as MynthGeneratedImage, d as MynthCompletedTask, f as MynthTaskFailure, g as AvailableModel, h as AVAILABLE_VIDEO_MODELS, i as ImageReviewResult, l as MynthOutputImage, m as AVAILABLE_MODELS, n as MynthOutputVideo, o as ImageRateResult, p as MynthSDKTypes, r as ImageUpscaleResult, s as ImageGenerationResult, t as VideoGenerationResult, u as ImageAltResult, v as ModelCapability, y as VideoInputRole } from "./video-generation-result.js";
2
2
  //#region src/client.d.ts
3
3
  /**
4
4
  * Error thrown when an API request fails.
@@ -6,11 +6,11 @@ import { a as AvailableVideoModel, c as VideoResolutionTier, i as AvailableModel
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
16
  constructor(message: string, status: number, code?: string, issues?: ReadonlyArray<MynthAPIErrorIssue>);
@@ -48,179 +48,6 @@ declare class MynthClient {
48
48
  getOrThrow<DataType>(path: string, options?: MynthClientRequestOptions): Promise<DataType>;
49
49
  }
50
50
  //#endregion
51
- //#region src/image-alt-result.d.ts
52
- /**
53
- * Represents the result of a completed image alt text task.
54
- */
55
- export declare class ImageAltResult {
56
- /** The task ID created for this alt text request */
57
- readonly taskId: string;
58
- /** Cost charged for the completed task */
59
- readonly cost: string;
60
- /** Generated alt text */
61
- readonly alt: string;
62
- constructor(data: {
63
- taskId: string;
64
- cost: string;
65
- alt: string;
66
- });
67
- static fromTaskData(data: MynthSDKTypes.ImageAltTaskData): ImageAltResult;
68
- }
69
- //#endregion
70
- //#region src/image-generation-result.d.ts
71
- type TypedImageResultImageSuccess<RatingT> = Omit<MynthSDKTypes.ImageResultImageSuccess, "rating"> & {
72
- rating?: RatingT;
73
- };
74
- type TypedImageResultImageFailure = MynthSDKTypes.ImageResultImageFailure;
75
- type TypedImageResultImage<RatingT> = TypedImageResultImageSuccess<RatingT> | TypedImageResultImageFailure;
76
- type TypedImageResult<RatingT> = Omit<MynthSDKTypes.ImageResult, "images"> & {
77
- images: TypedImageResultImage<RatingT>[];
78
- };
79
- /**
80
- * Represents a completed image generation task.
81
- *
82
- * @template MetadataT - Type of the metadata attached to the request
83
- * @template RatingT - Type of the rating response
84
- */
85
- export declare class ImageGenerationResult<MetadataT = Record<string, unknown> | undefined, RatingT = MynthSDKTypes.ImageResultRating | undefined> {
86
- /** Raw task data from the API */
87
- readonly data: MynthSDKTypes.ImageGenerationTaskData;
88
- constructor(data: MynthSDKTypes.ImageGenerationTaskData);
89
- /** Unique identifier for this task */
90
- get id(): string;
91
- /** Current status of the task */
92
- get status(): MynthSDKTypes.TaskStatus;
93
- /**
94
- * The generation result: images, the format each one was delivered in, and the model.
95
- * Returns `null` if the task hasn't completed yet.
96
- */
97
- get result(): TypedImageResult<RatingT> | null;
98
- /** Whether the task completed successfully */
99
- get isCompleted(): boolean;
100
- /** Whether the task failed */
101
- get isFailed(): boolean;
102
- /**
103
- * Get all successfully generated image URLs.
104
- * Convenience method that extracts just the URLs from successful images.
105
- * Images delivered only to a user destination may have a `null` url and are omitted here;
106
- * use `getImages()` and read `mynth_url` to access the CDN URL directly.
107
- */
108
- get urls(): string[];
109
- /**
110
- * Get generated images from the task result.
111
- *
112
- * @param options.includeFailed - If true, includes failed image results
113
- * @returns Array of image results
114
- */
115
- getImages(options: {
116
- includeFailed: true;
117
- }): TypedImageResultImage<RatingT>[];
118
- getImages(options?: {
119
- includeFailed?: false;
120
- }): TypedImageResultImageSuccess<RatingT>[];
121
- /**
122
- * Get the metadata that was attached to the generation request.
123
- */
124
- getMetadata(): MetadataT;
125
- }
126
- //#endregion
127
- //#region src/image-rate-result.d.ts
128
- /**
129
- * Represents the result of a completed image content rating task.
130
- *
131
- * @template LevelT - Union of possible rating level strings (e.g. `"sfw" | "nsfw"`)
132
- */
133
- export declare class ImageRateResult<LevelT extends string = "sfw" | "nsfw"> {
134
- /** The task ID created for this rating request */
135
- readonly taskId: string;
136
- /** Cost charged for the completed task */
137
- readonly cost: string;
138
- /** Assigned rating level */
139
- readonly level: LevelT;
140
- constructor(data: {
141
- taskId: string;
142
- cost: string;
143
- level: LevelT;
144
- });
145
- static fromTaskData<LevelT extends string = "sfw" | "nsfw">(data: MynthSDKTypes.ImageRateTaskData): ImageRateResult<LevelT>;
146
- }
147
- //#endregion
148
- //#region src/image-remove-background-result.d.ts
149
- /**
150
- * Represents the result of a completed image background removal task.
151
- *
152
- * @template MetadataT - Type of the metadata attached to the request
153
- */
154
- export declare class ImageRemoveBackgroundResult<MetadataT = Record<string, unknown> | undefined> {
155
- /** The task ID created for this request */
156
- readonly taskId: string;
157
- /** Cost charged for the completed task */
158
- readonly cost: string;
159
- /** The image with its background removed */
160
- readonly image: MynthSDKTypes.ImageRemoveBackgroundResultImage;
161
- /** Metadata attached to the request */
162
- readonly metadata: MetadataT;
163
- constructor(data: {
164
- taskId: string;
165
- cost: string;
166
- image: MynthSDKTypes.ImageRemoveBackgroundResultImage;
167
- metadata: MetadataT;
168
- });
169
- static fromTaskData<MetadataT = Record<string, unknown> | undefined>(data: MynthSDKTypes.ImageRemoveBackgroundTaskData): ImageRemoveBackgroundResult<MetadataT>;
170
- }
171
- //#endregion
172
- //#region src/image-review-result.d.ts
173
- /**
174
- * Represents the result of a completed image quality review task.
175
- */
176
- export declare class ImageReviewResult {
177
- /** The task ID created for this review request */
178
- readonly taskId: string;
179
- /** Cost charged for the completed task */
180
- readonly cost: string;
181
- /** Median reviewer score from 1 to 4. Higher is better. */
182
- readonly score: number;
183
- /** Review summary */
184
- readonly summary: string;
185
- /** Defects found by the reviewer panel */
186
- readonly findings: MynthSDKTypes.ImageReviewFinding[];
187
- /** Strengths identified by the reviewer panel */
188
- readonly strengths: MynthSDKTypes.ImageReviewStrength[];
189
- constructor(data: {
190
- taskId: string;
191
- cost: string;
192
- score: number;
193
- summary: string;
194
- findings: MynthSDKTypes.ImageReviewFinding[];
195
- strengths: MynthSDKTypes.ImageReviewStrength[];
196
- });
197
- static fromTaskData(data: MynthSDKTypes.ImageReviewTaskData): ImageReviewResult;
198
- }
199
- //#endregion
200
- //#region src/image-upscale-result.d.ts
201
- /**
202
- * Represents the result of a completed image upscale task.
203
- *
204
- * @template MetadataT - Type of the metadata attached to the request
205
- */
206
- export declare class ImageUpscaleResult<MetadataT = Record<string, unknown> | undefined> {
207
- /** The task ID created for this request */
208
- readonly taskId: string;
209
- /** Cost charged for the completed task */
210
- readonly cost: string;
211
- /** The upscaled image */
212
- readonly image: MynthSDKTypes.ImageUpscaleResultImage;
213
- /** Metadata attached to the request */
214
- readonly metadata: MetadataT;
215
- constructor(data: {
216
- taskId: string;
217
- cost: string;
218
- image: MynthSDKTypes.ImageUpscaleResultImage;
219
- metadata: MetadataT;
220
- });
221
- static fromTaskData<MetadataT = Record<string, unknown> | undefined>(data: MynthSDKTypes.ImageUpscaleTaskData): ImageUpscaleResult<MetadataT>;
222
- }
223
- //#endregion
224
51
  //#region src/task-async.d.ts
225
52
  /**
226
53
  * Polling cadence overrides. Anything omitted keeps the image-task default.
@@ -329,51 +156,52 @@ export declare class TaskAsync<ResultT> {
329
156
  private sleep;
330
157
  }
331
158
  //#endregion
332
- //#region src/video-generation-result.d.ts
159
+ //#region src/webhooks/utils.d.ts
160
+ /** The headers of a webhook request, from a `Headers` or a Node-style header object. */
161
+ type WebhookHeaders = Headers | Record<string, string | string[] | undefined>;
162
+ //#endregion
163
+ //#region src/webhooks/verify.d.ts
164
+ /** A webhook request failed verification: unsigned, wrongly signed, stale, or not an event. */
165
+ export declare class MynthWebhookVerificationError extends Error {
166
+ constructor(message: string);
167
+ }
168
+ /** A webhook request as it arrived. */
169
+ type MynthWebhookRequest = {
170
+ /**
171
+ * The raw body, exactly as received. Parsing and serializing the JSON again
172
+ * can change the bytes, and the signature covers the bytes.
173
+ */
174
+ body: string | Uint8Array | ArrayBuffer;
175
+ /** A `Headers` object, or a Node-style header record such as `req.headers`. */
176
+ headers: WebhookHeaders;
177
+ };
333
178
  /**
334
- * Represents a completed video generation task.
179
+ * Verify a signed Mynth webhook and return its event.
335
180
  *
336
- * @template MetadataT - Type of the metadata attached to the request
181
+ * Checks the Standard Webhooks signature over `webhook-id`, `webhook-timestamp`
182
+ * and the raw body, rejects a timestamp more than five minutes off, and checks
183
+ * that the body's `id` is the `webhook-id`. Deduplicate on `event.id`: every
184
+ * delivery of the event repeats it.
185
+ *
186
+ * An event type newer than this SDK is returned as is, so keep a `default`
187
+ * branch when you switch on `event.type`.
188
+ *
189
+ * @param secret - The webhook's `whsec_` secret. Defaults to MYNTH_WEBHOOK_SECRET.
190
+ * @throws {MynthWebhookVerificationError} If the request is not a valid, signed event
191
+ * @throws {Error} If there is no secret, or it is not a `whsec_` secret
192
+ *
193
+ * @example
194
+ * ```typescript
195
+ * const event = await verifyWebhook({ body: await request.text(), headers: request.headers });
196
+ *
197
+ * switch (event.type) {
198
+ * case "task.image.generate.completed":
199
+ * console.log(event.data.result.images);
200
+ * break;
201
+ * }
202
+ * ```
337
203
  */
338
- export declare class VideoGenerationResult<MetadataT = Record<string, unknown> | undefined> {
339
- /** Raw task data from the API */
340
- readonly data: MynthSDKTypes.VideoGenerationTaskData;
341
- constructor(data: MynthSDKTypes.VideoGenerationTaskData);
342
- /** Unique identifier for this task */
343
- get id(): string;
344
- /** Current status of the task */
345
- get status(): MynthSDKTypes.TaskStatus;
346
- /**
347
- * The generation result containing videos and model info.
348
- * Returns `null` if the task hasn't completed yet.
349
- */
350
- get result(): MynthSDKTypes.VideoResult | null;
351
- /** Whether the task completed successfully */
352
- get isCompleted(): boolean;
353
- /** Whether the task failed */
354
- get isFailed(): boolean;
355
- /**
356
- * Get all successfully generated video URLs.
357
- * Convenience method that extracts just the URLs from successful videos.
358
- */
359
- get urls(): string[];
360
- /**
361
- * Get generated videos from the task result.
362
- *
363
- * @param options.includeFailed - If true, includes failed video results
364
- * @returns Array of video results
365
- */
366
- getVideos(options: {
367
- includeFailed: true;
368
- }): MynthSDKTypes.VideoResultVideo[];
369
- getVideos(options?: {
370
- includeFailed?: false;
371
- }): MynthSDKTypes.VideoResultVideoSuccess[];
372
- /**
373
- * Get the metadata that was attached to the generation request.
374
- */
375
- getMetadata(): MetadataT;
376
- }
204
+ export declare function verifyWebhook(request: MynthWebhookRequest, secret?: string | undefined): Promise<MynthSDKTypes.WebhookEvent>;
377
205
  //#endregion
378
206
  //#region src/index.d.ts
379
207
  /**
@@ -516,6 +344,7 @@ declare class MynthImage {
516
344
  * ```typescript
517
345
  * const taskAsync = await image.generateAsync({
518
346
  * prompt: "A futuristic cityscape",
347
+ * generate_public_access_token: true,
519
348
  * });
520
349
  *
521
350
  * return { id: taskAsync.id, access: taskAsync.access };
@@ -646,7 +475,10 @@ declare class MynthImage {
646
475
  *
647
476
  * @example
648
477
  * ```typescript
649
- * const taskAsync = await image.removeBackgroundAsync({ url: "https://..." });
478
+ * const taskAsync = await image.removeBackgroundAsync({
479
+ * url: "https://...",
480
+ * generate_public_access_token: true,
481
+ * });
650
482
  *
651
483
  * return { id: taskAsync.id, access: taskAsync.access };
652
484
  * ```
@@ -658,7 +490,7 @@ declare class MynthImage {
658
490
  *
659
491
  * Mynth picks the model. `effort` sets the price, so it has no default. The
660
492
  * upscaled image can be at most 4096x4096 pixels; a larger request fails
661
- * with `OUTPUT_TOO_LARGE` and is not charged.
493
+ * with `output_too_large` and is not charged.
662
494
  *
663
495
  * @param request - Image URL or local file, size, and effort, plus optional output, destination, webhook, and metadata
664
496
  * @returns An ImageUpscaleResult with the enlarged image
@@ -678,7 +510,12 @@ declare class MynthImage {
678
510
  *
679
511
  * @example
680
512
  * ```typescript
681
- * const taskAsync = await image.upscaleAsync({ url: "https://...", size: "2x", effort: "low" });
513
+ * const taskAsync = await image.upscaleAsync({
514
+ * url: "https://...",
515
+ * size: "2x",
516
+ * effort: "low",
517
+ * generate_public_access_token: true,
518
+ * });
682
519
  *
683
520
  * return { id: taskAsync.id, access: taskAsync.access };
684
521
  * ```
@@ -742,7 +579,8 @@ declare class MynthVideo {
742
579
  * Start video generation without waiting for completion.
743
580
  *
744
581
  * The preferred entry point for server code: hand `taskAsync.id` and
745
- * `taskAsync.access.publicAccessToken` to the browser, or register a webhook,
582
+ * `taskAsync.access.publicAccessToken` to the browser (pass
583
+ * `generate_public_access_token: true` to get one), or register a webhook,
746
584
  * instead of holding a connection open for the length of a render.
747
585
  *
748
586
  * @param request - Video generation request parameters
@@ -753,6 +591,7 @@ declare class MynthVideo {
753
591
  * const taskAsync = await video.generateAsync({
754
592
  * model: "prunaai/p-video",
755
593
  * prompt: "A neon city street in the rain",
594
+ * generate_public_access_token: true,
756
595
  * });
757
596
  *
758
597
  * return { id: taskAsync.id, access: taskAsync.access };
@@ -779,11 +618,11 @@ declare class MynthVideo {
779
618
  * video pins a concrete model, the returned estimate is exact.
780
619
  *
781
620
  * @param request - The same request you would pass to `generate()`
782
- * @returns The estimated cost in USD
621
+ * @returns The estimated cost in USD, as the API returns it
783
622
  *
784
623
  * @example
785
624
  * ```typescript
786
- * const { estimatedCost } = await video.estimate({
625
+ * const { estimated_cost } = await video.estimate({
787
626
  * model: "google/gemini-omni-flash-1.1",
788
627
  * prompt: "A timelapse of clouds over a canyon",
789
628
  * duration: 10,
@@ -855,4 +694,4 @@ declare class Mynth {
855
694
  get video(): MynthVideo;
856
695
  }
857
696
  //#endregion
858
- export { AVAILABLE_MODELS, AVAILABLE_VIDEO_MODELS, type AvailableModel, type AvailableVideoModel, type ModelCapability, Mynth, Mynth as default, type MynthAPIErrorIssue, MynthImage, type MynthModel, type MynthModelPricing, MynthModels, type MynthOptions, type MynthRequestOptions, type MynthSDKTypes, MynthVideo, type TaskAsyncAccess, type TaskAsyncWaitOptions, type VideoInputRole, type VideoResolutionTier };
697
+ 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 };