@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.
- package/README.md +242 -107
- package/dist/convex/index.d.ts +8 -7
- package/dist/convex/index.js +6 -6
- package/dist/handler.d.ts +40 -6
- package/dist/handler.js +69 -89
- package/dist/index.d.ts +65 -226
- package/dist/index.js +100 -295
- package/dist/next/index.d.ts +7 -6
- package/dist/next/index.js +5 -5
- package/dist/tanstack-start/index.d.ts +6 -5
- package/dist/tanstack-start/index.js +3 -3
- package/dist/utils.js +312 -0
- package/dist/{types.d.ts → video-generation-result.d.ts} +349 -161
- package/package.json +2 -1
package/README.md
CHANGED
|
@@ -43,9 +43,9 @@ const task = await mynth.image.generate({
|
|
|
43
43
|
prompt: "A fox in a neon-lit city at night",
|
|
44
44
|
});
|
|
45
45
|
|
|
46
|
-
console.log(task.
|
|
46
|
+
console.log(task.taskId);
|
|
47
47
|
console.log(task.urls);
|
|
48
|
-
console.log(task.
|
|
48
|
+
console.log(task.model);
|
|
49
49
|
```
|
|
50
50
|
|
|
51
51
|
If you omit `model` and `size`, Mynth resolves them automatically. `generate()` waits for completion and returns a completed task.
|
|
@@ -76,7 +76,7 @@ const task = await mynth.image.generate({
|
|
|
76
76
|
model: "black-forest-labs/flux.2-dev",
|
|
77
77
|
});
|
|
78
78
|
|
|
79
|
-
console.log(task.
|
|
79
|
+
console.log(task.images[0]?.width); // 1024
|
|
80
80
|
console.log(task.urls);
|
|
81
81
|
```
|
|
82
82
|
|
|
@@ -88,6 +88,7 @@ Use `generateAsync()` when you want to trigger work now and fetch the final task
|
|
|
88
88
|
const taskAsync = await mynth.image.generateAsync({
|
|
89
89
|
prompt: "A cinematic fantasy castle on a cliff",
|
|
90
90
|
model: "google/gemini-3.1-flash-image",
|
|
91
|
+
generate_public_access_token: true,
|
|
91
92
|
});
|
|
92
93
|
|
|
93
94
|
console.log(taskAsync.id);
|
|
@@ -97,7 +98,7 @@ const completedTask = await taskAsync.wait();
|
|
|
97
98
|
console.log(completedTask.urls);
|
|
98
99
|
```
|
|
99
100
|
|
|
100
|
-
`taskAsync.access.publicAccessToken` is safe to send to the client
|
|
101
|
+
`taskAsync.access.publicAccessToken` is set when the request asks for it with `generate_public_access_token: true`. It is safe to send to the client: it is scoped to that single task, so you can poll task state from the browser without exposing your API key or building your own polling proxy.
|
|
101
102
|
|
|
102
103
|
You can use it as a Bearer token against:
|
|
103
104
|
|
|
@@ -110,6 +111,7 @@ Example:
|
|
|
110
111
|
const taskAsync = await mynth.image.generateAsync({
|
|
111
112
|
prompt: "A cinematic fantasy castle on a cliff",
|
|
112
113
|
model: "google/gemini-3.1-flash-image",
|
|
114
|
+
generate_public_access_token: true,
|
|
113
115
|
});
|
|
114
116
|
|
|
115
117
|
const taskId = taskAsync.id;
|
|
@@ -172,21 +174,17 @@ const task = await mynth.image.generate({
|
|
|
172
174
|
model: "google/gemini-3-pro-image-preview",
|
|
173
175
|
size: {
|
|
174
176
|
type: "aspect_ratio",
|
|
175
|
-
|
|
177
|
+
aspect_ratio: "4:5",
|
|
176
178
|
},
|
|
177
179
|
count: 2,
|
|
178
180
|
output: {
|
|
179
181
|
format: "webp",
|
|
180
182
|
},
|
|
181
183
|
webhook: {
|
|
182
|
-
|
|
183
|
-
custom: [{ url: "https://your-app.com/api/mynth-webhook" }],
|
|
184
|
-
},
|
|
185
|
-
access: {
|
|
186
|
-
pat: {
|
|
187
|
-
enabled: true,
|
|
188
|
-
},
|
|
184
|
+
registered: false,
|
|
185
|
+
custom: [{ url: "https://your-app.com/api/mynth-webhook?token=your-secret-token" }],
|
|
189
186
|
},
|
|
187
|
+
generate_public_access_token: true,
|
|
190
188
|
rating: {
|
|
191
189
|
mode: "custom",
|
|
192
190
|
levels: [
|
|
@@ -211,7 +209,9 @@ const task = await mynth.image.generate({
|
|
|
211
209
|
});
|
|
212
210
|
```
|
|
213
211
|
|
|
214
|
-
|
|
212
|
+
Request fields are the API's own, in snake_case, and the API rejects a field it does not know. `generate_public_access_token` asks for a short-lived Public Access Token for browser-side polling, as `taskAsync.access.publicAccessToken`. It defaults to `false`.
|
|
213
|
+
|
|
214
|
+
`webhook.registered: false` skips the webhooks registered on your account for this task. `webhook.custom` sends this task's events to other URLs, unsigned: use https and a public host, and put a secret token in the URL so your handler can check it (see [Unsigned custom webhooks](#unsigned-custom-webhooks)). Mynth only ever shows `scheme://host` of a custom URL back.
|
|
215
215
|
|
|
216
216
|
`output` is optional. Set `output.format` to `png`, `jpg`, or `webp`. When it is omitted, the result keeps the format the provider delivered.
|
|
217
217
|
|
|
@@ -280,8 +280,8 @@ Examples:
|
|
|
280
280
|
```ts
|
|
281
281
|
size: "landscape";
|
|
282
282
|
size: "auto";
|
|
283
|
-
size: { type: "aspect_ratio",
|
|
284
|
-
size: { type: "aspect_ratio",
|
|
283
|
+
size: { type: "aspect_ratio", aspect_ratio: "16:9" };
|
|
284
|
+
size: { type: "aspect_ratio", aspect_ratio: "4:5", scale: "4k" };
|
|
285
285
|
size: { type: "auto" };
|
|
286
286
|
```
|
|
287
287
|
|
|
@@ -330,7 +330,11 @@ const task = await mynth.image.generate({
|
|
|
330
330
|
rating: true, // same result levels as { mode: "nsfw_sfw" }
|
|
331
331
|
});
|
|
332
332
|
|
|
333
|
-
|
|
333
|
+
const rating = task.images[0]?.rating;
|
|
334
|
+
|
|
335
|
+
if (rating?.status === "success") {
|
|
336
|
+
console.log(rating.level); // "sfw" | "nsfw"
|
|
337
|
+
}
|
|
334
338
|
```
|
|
335
339
|
|
|
336
340
|
For custom labels, pass at least two and at most seven levels:
|
|
@@ -348,7 +352,11 @@ const task = await mynth.image.generate({
|
|
|
348
352
|
},
|
|
349
353
|
});
|
|
350
354
|
|
|
351
|
-
|
|
355
|
+
const rating = task.images[0]?.rating;
|
|
356
|
+
|
|
357
|
+
if (rating?.status === "success") {
|
|
358
|
+
console.log(rating.level); // "general" | "teen" | "adult"
|
|
359
|
+
}
|
|
352
360
|
```
|
|
353
361
|
|
|
354
362
|
You can also rate an existing image URL (mode defaults to `nsfw_sfw`):
|
|
@@ -463,11 +471,12 @@ const result = await mynth.image.removeBackground({
|
|
|
463
471
|
console.log(result.metadata.productId);
|
|
464
472
|
```
|
|
465
473
|
|
|
466
|
-
Use `removeBackgroundAsync()` to create the task without waiting.
|
|
474
|
+
Use `removeBackgroundAsync()` to create the task without waiting. Like `generateAsync()`, it returns a public access token when you ask for one:
|
|
467
475
|
|
|
468
476
|
```ts
|
|
469
477
|
const taskAsync = await mynth.image.removeBackgroundAsync({
|
|
470
478
|
url: "https://example.com/product.jpg",
|
|
479
|
+
generate_public_access_token: true,
|
|
471
480
|
});
|
|
472
481
|
|
|
473
482
|
return { id: taskAsync.id, access: taskAsync.access };
|
|
@@ -485,10 +494,10 @@ const result = await mynth.image.upscale({
|
|
|
485
494
|
});
|
|
486
495
|
|
|
487
496
|
console.log(result.image.url); // upscaled image
|
|
488
|
-
console.log(result.image.
|
|
497
|
+
console.log(result.image.width, result.image.height); // e.g. 2048 1536
|
|
489
498
|
```
|
|
490
499
|
|
|
491
|
-
`effort` sets the price: `low` is fast and sharp, `high` rebuilds fine detail such as small text and faces. `size` is `"2x"` or `"4x"`, or `{ type: "scale", factor: 2 | 4 }`. The upscaled image can be at most 4096x4096 pixels; a larger request fails with `
|
|
500
|
+
`effort` sets the price: `low` is fast and sharp, `high` rebuilds fine detail such as small text and faces. `size` is `"2x"` or `"4x"`, or `{ type: "scale", factor: 2 | 4 }`. The upscaled image can be at most 4096x4096 pixels; a larger request fails with `output_too_large` and is not charged.
|
|
492
501
|
|
|
493
502
|
The result keeps the format the provider returned. Set `output.format` to always get `png`, `jpg`, or `webp`.
|
|
494
503
|
`upscale()` also takes a local `file`, plus `destination`, `webhook`, and `metadata` like `generate()`:
|
|
@@ -506,13 +515,14 @@ const result = await mynth.image.upscale({
|
|
|
506
515
|
console.log(result.metadata.productId);
|
|
507
516
|
```
|
|
508
517
|
|
|
509
|
-
Use `upscaleAsync()` to create the task without waiting.
|
|
518
|
+
Use `upscaleAsync()` to create the task without waiting. Like `generateAsync()`, it returns a public access token when you ask for one:
|
|
510
519
|
|
|
511
520
|
```ts
|
|
512
521
|
const taskAsync = await mynth.image.upscaleAsync({
|
|
513
522
|
url: "https://example.com/product.jpg",
|
|
514
523
|
size: "2x",
|
|
515
524
|
effort: "low",
|
|
525
|
+
generate_public_access_token: true,
|
|
516
526
|
});
|
|
517
527
|
|
|
518
528
|
return { id: taskAsync.id, access: taskAsync.access };
|
|
@@ -520,7 +530,7 @@ return { id: taskAsync.id, access: taskAsync.access };
|
|
|
520
530
|
|
|
521
531
|
## Working With Image Results
|
|
522
532
|
|
|
523
|
-
|
|
533
|
+
`generate()`, `removeBackground()`, and `upscale()` all hand back the same image shape, `MynthOutputImage`:
|
|
524
534
|
|
|
525
535
|
```ts
|
|
526
536
|
const task = await mynth.image.generate({
|
|
@@ -528,17 +538,53 @@ const task = await mynth.image.generate({
|
|
|
528
538
|
metadata: { source: "readme-example" },
|
|
529
539
|
});
|
|
530
540
|
|
|
531
|
-
console.log(task.
|
|
532
|
-
console.log(task.
|
|
533
|
-
console.log(task.
|
|
534
|
-
console.log(task.
|
|
535
|
-
console.log(task.
|
|
536
|
-
console.log(task.
|
|
537
|
-
|
|
538
|
-
|
|
541
|
+
console.log(task.taskId);
|
|
542
|
+
console.log(task.cost); // "0.04"
|
|
543
|
+
console.log(task.model); // resolved model, also when you asked for "auto"
|
|
544
|
+
console.log(task.metadata); // { source: "readme-example" }, typed from the request
|
|
545
|
+
console.log(task.magicPrompt); // the rewritten prompt, with magic_prompt: true
|
|
546
|
+
console.log(task.urls); // `url` of each image, skipping `null`
|
|
547
|
+
|
|
548
|
+
for (const image of task.images) {
|
|
549
|
+
image.id;
|
|
550
|
+
image.url; // your destination's URL, or the Mynth URL without a destination; null if delivery failed
|
|
551
|
+
image.mynthUrl; // always set, served for 7 days
|
|
552
|
+
image.width; // 1024
|
|
553
|
+
image.height; // 768
|
|
554
|
+
image.size; // "1024x768"
|
|
555
|
+
image.format; // "png" | "jpg" | "webp"
|
|
556
|
+
image.mimeType; // "image/png" | "image/jpeg" | "image/webp"
|
|
557
|
+
image.destination; // delivery status when the request named a destination
|
|
558
|
+
image.rating; // generate() only, typed from the request's rating levels
|
|
559
|
+
}
|
|
539
560
|
```
|
|
540
561
|
|
|
541
|
-
`
|
|
562
|
+
`url` is exactly what the API reports. The SDK never swaps in the Mynth URL for you, so a `null` cannot hide behind a URL from another origin. Fall back explicitly where any URL will do:
|
|
563
|
+
|
|
564
|
+
```ts
|
|
565
|
+
const src = image.url ?? image.mynthUrl;
|
|
566
|
+
```
|
|
567
|
+
|
|
568
|
+
`task.images` holds the successful images only. A completed task can also hold failed ones; `task.failures` lists why:
|
|
569
|
+
|
|
570
|
+
```ts
|
|
571
|
+
if (task.failures.length > 0) {
|
|
572
|
+
console.warn(task.failures); // [{ code: "provider_error", message: "..." }]
|
|
573
|
+
}
|
|
574
|
+
```
|
|
575
|
+
|
|
576
|
+
Results are plain objects, so they pass as they are to client components, server functions, Convex mutations, and `JSON.stringify`.
|
|
577
|
+
|
|
578
|
+
To download an image, fetch `mynthUrl`. It is set with or without a destination:
|
|
579
|
+
|
|
580
|
+
```ts
|
|
581
|
+
import { writeFile } from "node:fs/promises";
|
|
582
|
+
|
|
583
|
+
const response = await fetch(image.mynthUrl);
|
|
584
|
+
await writeFile(`cat.${image.format}`, new Uint8Array(await response.arrayBuffer()));
|
|
585
|
+
```
|
|
586
|
+
|
|
587
|
+
Every result also keeps the request and result exactly as the API returned them, in `raw`, for fields the SDK does not map yet.
|
|
542
588
|
|
|
543
589
|
## Available Models
|
|
544
590
|
|
|
@@ -550,10 +596,10 @@ const models = await mynth.models.list();
|
|
|
550
596
|
console.log(models[0]);
|
|
551
597
|
// {
|
|
552
598
|
// id: "black-forest-labs/flux.2-pro",
|
|
553
|
-
//
|
|
599
|
+
// display_name: "FLUX.2 Pro",
|
|
554
600
|
// type: "image",
|
|
555
|
-
// modes: { "txt->img": {}, "img->img": { inputs: { rules: [...],
|
|
556
|
-
// pricing: {
|
|
601
|
+
// modes: { "txt->img": {}, "img->img": { inputs: { rules: [...], max_total: 4 } } },
|
|
602
|
+
// pricing: { per_image: { base: "0.05" } }
|
|
557
603
|
// }
|
|
558
604
|
```
|
|
559
605
|
|
|
@@ -564,9 +610,9 @@ price per second of output, keyed by resolution tier.
|
|
|
564
610
|
```ts
|
|
565
611
|
for (const model of models) {
|
|
566
612
|
if (model.type === "video") {
|
|
567
|
-
console.log(model.id, model.pricing?.
|
|
613
|
+
console.log(model.id, model.pricing?.per_second["720p"], Object.keys(model.modes));
|
|
568
614
|
} else {
|
|
569
|
-
console.log(model.id, model.pricing?.
|
|
615
|
+
console.log(model.id, model.pricing?.per_image.base, Object.keys(model.modes));
|
|
570
616
|
}
|
|
571
617
|
}
|
|
572
618
|
```
|
|
@@ -651,7 +697,7 @@ const task = await mynth.video.generate({
|
|
|
651
697
|
});
|
|
652
698
|
|
|
653
699
|
console.log(task.urls);
|
|
654
|
-
console.log(task.
|
|
700
|
+
console.log(task.videos[0]?.duration);
|
|
655
701
|
```
|
|
656
702
|
|
|
657
703
|
Video generation always runs on a pinned model: unlike images, there is no `auto`, so `model` is required.
|
|
@@ -666,12 +712,13 @@ Prefer `generateAsync()` on the server and let the browser (or a webhook) pick t
|
|
|
666
712
|
const taskAsync = await mynth.video.generateAsync({
|
|
667
713
|
model: "bytedance/seedance-2.0-mini",
|
|
668
714
|
prompt: "A neon city street in the rain",
|
|
715
|
+
generate_public_access_token: true,
|
|
669
716
|
});
|
|
670
717
|
|
|
671
718
|
return { id: taskAsync.id, access: taskAsync.access };
|
|
672
719
|
```
|
|
673
720
|
|
|
674
|
-
`taskAsync.access.publicAccessToken` works exactly as it does for images: scoped to that one task, safe to send to the client, and usable against `GET /tasks/:id/status` and `GET /tasks/:id/result`.
|
|
721
|
+
`taskAsync.access.publicAccessToken` works exactly as it does for images: requested with `generate_public_access_token: true`, scoped to that one task, safe to send to the client, and usable against `GET /tasks/:id/status` and `GET /tasks/:id/result`.
|
|
675
722
|
|
|
676
723
|
### Duration, Resolution and Audio
|
|
677
724
|
|
|
@@ -708,7 +755,7 @@ Local files are uploaded to temporary input storage before the request, in a sin
|
|
|
708
755
|
Video is priced per render, so you can price a request before running it. The endpoint validates the request the same way `generate()` does, which makes it a pre-flight check as well as a cost lookup:
|
|
709
756
|
|
|
710
757
|
```ts
|
|
711
|
-
const {
|
|
758
|
+
const { estimated_cost } = await mynth.video.estimate({
|
|
712
759
|
model: "google/gemini-omni-flash-1.1",
|
|
713
760
|
prompt: "A timelapse of clouds over a canyon",
|
|
714
761
|
duration: 10,
|
|
@@ -716,21 +763,24 @@ const { estimatedCost } = await mynth.video.estimate({
|
|
|
716
763
|
});
|
|
717
764
|
```
|
|
718
765
|
|
|
719
|
-
Because the model is always concrete, the estimate is exact.
|
|
766
|
+
`estimate()` returns the API's own response, so its fields are snake_case. Because the model is always concrete, the estimate is exact.
|
|
720
767
|
|
|
721
768
|
### Working With Video Results
|
|
722
769
|
|
|
770
|
+
Video results mirror image results:
|
|
771
|
+
|
|
723
772
|
```ts
|
|
724
|
-
console.log(task.
|
|
725
|
-
console.log(task.
|
|
726
|
-
console.log(task.
|
|
773
|
+
console.log(task.taskId);
|
|
774
|
+
console.log(task.cost); // failed videos are refunded
|
|
775
|
+
console.log(task.model);
|
|
727
776
|
console.log(task.urls);
|
|
728
|
-
console.log(task.
|
|
729
|
-
console.log(task.
|
|
730
|
-
console.log(task.
|
|
777
|
+
console.log(task.videos); // successful videos only
|
|
778
|
+
console.log(task.failures); // [{ code, message? }] for each failed video
|
|
779
|
+
console.log(task.metadata);
|
|
780
|
+
console.log(task.raw);
|
|
731
781
|
```
|
|
732
782
|
|
|
733
|
-
Each
|
|
783
|
+
Each video has `id`, `url`, `mynthUrl`, `cost`, `duration`, `resolution`, and `audio`. `url` is `null` when the video could not be delivered there; `mynthUrl` is always set.
|
|
734
784
|
|
|
735
785
|
### Video Models
|
|
736
786
|
|
|
@@ -767,7 +817,7 @@ Each of these supports generated audio.
|
|
|
767
817
|
|
|
768
818
|
## TypeScript Types
|
|
769
819
|
|
|
770
|
-
The SDK exports the request and
|
|
820
|
+
The SDK exports the request, task and webhook event types via `MynthSDKTypes`. They describe the API's own data, so their fields are snake_case; the SDK's own surface (methods, options, result objects such as `task.taskId`) is camelCase.
|
|
771
821
|
|
|
772
822
|
```ts
|
|
773
823
|
import type { MynthSDKTypes } from "@mynthio/sdk";
|
|
@@ -778,12 +828,64 @@ const request: MynthSDKTypes.ImageGenerationRequest = {
|
|
|
778
828
|
};
|
|
779
829
|
```
|
|
780
830
|
|
|
781
|
-
##
|
|
831
|
+
## Webhooks
|
|
832
|
+
|
|
833
|
+
Mynth delivers webhooks the [Standard Webhooks](https://www.standardwebhooks.com) way. Every delivery is a `POST` with an event body and these headers:
|
|
834
|
+
|
|
835
|
+
- `webhook-id`: the event ID, `evt_...`. The same for every delivery of the event, and the same as the body's `id`
|
|
836
|
+
- `webhook-timestamp`: when this attempt was sent, in Unix seconds
|
|
837
|
+
- `webhook-signature`: `v1,<base64>`, only on deliveries to a webhook registered in the dashboard or through the API
|
|
838
|
+
|
|
839
|
+
```json
|
|
840
|
+
{
|
|
841
|
+
"id": "evt_01KE7Y9M3R8T2QXN5BVC4WJ6HD",
|
|
842
|
+
"type": "task.image.generate.completed",
|
|
843
|
+
"timestamp": "2026-10-04T10:00:12.000Z",
|
|
844
|
+
"data": {
|
|
845
|
+
"id": "tsk_...",
|
|
846
|
+
"type": "image.generate",
|
|
847
|
+
"status": "completed",
|
|
848
|
+
"request": {},
|
|
849
|
+
"result": {}
|
|
850
|
+
}
|
|
851
|
+
}
|
|
852
|
+
```
|
|
853
|
+
|
|
854
|
+
`data` is the task exactly as `GET /tasks/{id}` returns it. Deliveries are retried for about 72 hours, so the same event can arrive more than once: store `event.id` and skip IDs you have already handled.
|
|
855
|
+
|
|
856
|
+
### Verify an event
|
|
857
|
+
|
|
858
|
+
`verifyWebhook()` checks the signature against the raw body, rejects a timestamp more than five minutes off, checks that the body's `id` is the `webhook-id`, and returns the typed event. It runs on Web Crypto, so it works in Node, edge runtimes and Workers.
|
|
859
|
+
|
|
860
|
+
```ts
|
|
861
|
+
import { verifyWebhook } from "@mynthio/sdk";
|
|
862
|
+
|
|
863
|
+
export async function POST(request: Request) {
|
|
864
|
+
const event = await verifyWebhook({ body: await request.text(), headers: request.headers });
|
|
865
|
+
|
|
866
|
+
switch (event.type) {
|
|
867
|
+
case "task.image.generate.completed":
|
|
868
|
+
await saveImages(event.data.id, event.data.result.images);
|
|
869
|
+
break;
|
|
870
|
+
case "task.image.generate.failed":
|
|
871
|
+
await markTaskFailed(event.data.id, event.data.errors);
|
|
872
|
+
break;
|
|
873
|
+
}
|
|
874
|
+
|
|
875
|
+
return new Response(null, { status: 204 });
|
|
876
|
+
}
|
|
877
|
+
```
|
|
878
|
+
|
|
879
|
+
The secret defaults to `MYNTH_WEBHOOK_SECRET`; pass it as the second argument otherwise. A failed check throws `MynthWebhookVerificationError`, which your handler should answer with a `400`. Keep a `default` branch: an event type newer than your SDK version is returned as is.
|
|
880
|
+
|
|
881
|
+
The framework helpers below do the same verification and hand each event to a typed callback.
|
|
882
|
+
|
|
883
|
+
### Next.js Integration
|
|
782
884
|
|
|
783
885
|
Use the App Router helper to verify and route registered Mynth webhooks. Add the signing secret shown when you create the webhook:
|
|
784
886
|
|
|
785
887
|
```env
|
|
786
|
-
MYNTH_WEBHOOK_SECRET=
|
|
888
|
+
MYNTH_WEBHOOK_SECRET=whsec_...
|
|
787
889
|
```
|
|
788
890
|
|
|
789
891
|
Create a Route Handler:
|
|
@@ -793,28 +895,47 @@ Create a Route Handler:
|
|
|
793
895
|
import { mynthWebhookHandler } from "@mynthio/sdk/next";
|
|
794
896
|
|
|
795
897
|
export const POST = mynthWebhookHandler({
|
|
796
|
-
imageTaskCompleted: async (
|
|
797
|
-
console.log("
|
|
798
|
-
console.log("Received at:", request.url);
|
|
898
|
+
imageTaskCompleted: async (result, { event, request }) => {
|
|
899
|
+
console.log("Event:", event.id, "received at:", request.url);
|
|
799
900
|
|
|
800
|
-
await saveImages(
|
|
901
|
+
await saveImages(result.taskId, result.images);
|
|
801
902
|
},
|
|
802
|
-
imageTaskFailed: async (
|
|
803
|
-
await markTaskFailed(
|
|
903
|
+
imageTaskFailed: async (failure) => {
|
|
904
|
+
await markTaskFailed(failure.taskId, failure.errors);
|
|
804
905
|
},
|
|
805
|
-
videoTaskCompleted: async (
|
|
806
|
-
await saveVideos(
|
|
906
|
+
videoTaskCompleted: async (result) => {
|
|
907
|
+
await saveVideos(result.taskId, result.videos);
|
|
807
908
|
},
|
|
808
909
|
});
|
|
809
910
|
```
|
|
810
911
|
|
|
811
|
-
The helper reads the raw body, verifies
|
|
912
|
+
The helper reads the raw body, verifies the signature, rejects a timestamp more than five minutes off, and checks the event before calling a typed callback. A completed callback receives the same result that `generate()`, `upscale()` and the other methods return, so `result.images`, `result.cost` and `result.metadata` work the same in both places. A failed callback receives `{ taskId, errors, metadata, raw }`; `metadata` is there for task types whose request takes it. The last argument holds the original `request` and the verified `event`.
|
|
913
|
+
|
|
914
|
+
`onEvent` receives every event, typed, before its callback runs, including event types newer than the SDK. Events without a callback are answered `200`, so Mynth does not retry them.
|
|
812
915
|
|
|
813
|
-
The route must be publicly reachable, so exclude it from authentication middleware. Make callback side effects idempotent by storing `
|
|
916
|
+
The route must be publicly reachable, so exclude it from authentication middleware. Make callback side effects idempotent by storing `event.id` and skipping IDs you have already handled, and enqueue slow work before returning. Callback errors are propagated so Mynth can retry the delivery.
|
|
814
917
|
|
|
815
|
-
Pass `{ webhookSecret: "
|
|
918
|
+
Pass `{ webhookSecret: "whsec_..." }` as the second argument only when the application does not use `MYNTH_WEBHOOK_SECRET`.
|
|
816
919
|
|
|
817
|
-
|
|
920
|
+
### Unsigned custom webhooks
|
|
921
|
+
|
|
922
|
+
A request can send its events to URLs of its own with `webhook.custom`. Those deliveries are not signed: put a secret token in the URL, and check it with the `unsigned` option. The helpers then skip signature verification and answer `401` when `verify` returns `false`. Without the option, an unsigned delivery is answered `400`.
|
|
923
|
+
|
|
924
|
+
```ts
|
|
925
|
+
export const POST = mynthWebhookHandler(
|
|
926
|
+
{ imageTaskCompleted: async (result, { event }) => saveImages(result.taskId, result.images) },
|
|
927
|
+
{
|
|
928
|
+
unsigned: {
|
|
929
|
+
verify: (request) =>
|
|
930
|
+
new URL(request.url).searchParams.get("token") === process.env.MY_WEBHOOK_TOKEN,
|
|
931
|
+
},
|
|
932
|
+
},
|
|
933
|
+
);
|
|
934
|
+
```
|
|
935
|
+
|
|
936
|
+
Compare the token in constant time if an attacker could time your endpoint. Mynth only ever shows `scheme://host` of a custom URL back, so a token in the path or query does not leak through the task.
|
|
937
|
+
|
|
938
|
+
### TanStack Start Integration
|
|
818
939
|
|
|
819
940
|
Mount the webhook helper directly on a TanStack Start server route:
|
|
820
941
|
|
|
@@ -827,13 +948,12 @@ export const Route = createFileRoute("/api/webhooks/mynth")({
|
|
|
827
948
|
server: {
|
|
828
949
|
handlers: {
|
|
829
950
|
POST: mynthWebhookHandler({
|
|
830
|
-
imageTaskCompleted: async (
|
|
831
|
-
console.log("
|
|
832
|
-
|
|
833
|
-
await saveImages(payload.task.id, payload.result.images);
|
|
951
|
+
imageTaskCompleted: async (result, { event, request, params, context }) => {
|
|
952
|
+
console.log("Event:", event.id, "received at:", request.url);
|
|
953
|
+
await saveImages(result.taskId, result.images);
|
|
834
954
|
},
|
|
835
|
-
imageTaskFailed: async (
|
|
836
|
-
await markTaskFailed(
|
|
955
|
+
imageTaskFailed: async (failure) => {
|
|
956
|
+
await markTaskFailed(failure.taskId, failure.errors);
|
|
837
957
|
},
|
|
838
958
|
}),
|
|
839
959
|
},
|
|
@@ -841,9 +961,9 @@ export const Route = createFileRoute("/api/webhooks/mynth")({
|
|
|
841
961
|
});
|
|
842
962
|
```
|
|
843
963
|
|
|
844
|
-
Set `MYNTH_WEBHOOK_SECRET` in the server environment, or pass `webhookSecret` as the second argument. Event callbacks receive the original request, route params, TanStack Start middleware context, and `
|
|
964
|
+
Set `MYNTH_WEBHOOK_SECRET` in the server environment, or pass `webhookSecret` as the second argument. Event callbacks receive the original request, route params, TanStack Start middleware context, and the verified `event`.
|
|
845
965
|
|
|
846
|
-
|
|
966
|
+
### Convex Integration
|
|
847
967
|
|
|
848
968
|
The package includes a Convex HTTP action helper for webhook verification and event routing.
|
|
849
969
|
|
|
@@ -851,59 +971,59 @@ The package includes a Convex HTTP action helper for webhook verification and ev
|
|
|
851
971
|
import { mynthWebhookAction } from "@mynthio/sdk/convex";
|
|
852
972
|
|
|
853
973
|
export const mynthWebhook = mynthWebhookAction({
|
|
854
|
-
imageTaskCompleted: async (
|
|
855
|
-
console.log("Completed task:",
|
|
856
|
-
console.log(
|
|
974
|
+
imageTaskCompleted: async (result, { context, event }) => {
|
|
975
|
+
console.log("Completed task:", result.taskId, "event:", event.id);
|
|
976
|
+
console.log(result.images);
|
|
857
977
|
},
|
|
858
|
-
imageTaskFailed: async (
|
|
859
|
-
console.error("Mynth task failed:",
|
|
978
|
+
imageTaskFailed: async (failure) => {
|
|
979
|
+
console.error("Mynth task failed:", failure.taskId);
|
|
860
980
|
},
|
|
861
|
-
imageRateTaskCompleted: async (
|
|
862
|
-
console.log("Completed rating task:",
|
|
863
|
-
console.log(
|
|
981
|
+
imageRateTaskCompleted: async (result) => {
|
|
982
|
+
console.log("Completed rating task:", result.taskId);
|
|
983
|
+
console.log(result.level);
|
|
864
984
|
},
|
|
865
|
-
imageRateTaskFailed: async (
|
|
866
|
-
console.error("Mynth rating task failed:",
|
|
985
|
+
imageRateTaskFailed: async (failure) => {
|
|
986
|
+
console.error("Mynth rating task failed:", failure.taskId);
|
|
867
987
|
},
|
|
868
|
-
imageAltTaskCompleted: async (
|
|
869
|
-
console.log("Completed alt text task:",
|
|
870
|
-
console.log(
|
|
988
|
+
imageAltTaskCompleted: async (result) => {
|
|
989
|
+
console.log("Completed alt text task:", result.taskId);
|
|
990
|
+
console.log(result.alt);
|
|
871
991
|
},
|
|
872
|
-
imageAltTaskFailed: async (
|
|
873
|
-
console.error("Mynth alt text task failed:",
|
|
992
|
+
imageAltTaskFailed: async (failure) => {
|
|
993
|
+
console.error("Mynth alt text task failed:", failure.taskId);
|
|
874
994
|
},
|
|
875
|
-
imageReviewTaskCompleted: async (
|
|
876
|
-
console.log("Completed review task:",
|
|
877
|
-
console.log(
|
|
995
|
+
imageReviewTaskCompleted: async (result) => {
|
|
996
|
+
console.log("Completed review task:", result.taskId);
|
|
997
|
+
console.log(result.summary);
|
|
878
998
|
},
|
|
879
|
-
imageReviewTaskFailed: async (
|
|
880
|
-
console.error("Mynth review task failed:",
|
|
999
|
+
imageReviewTaskFailed: async (failure) => {
|
|
1000
|
+
console.error("Mynth review task failed:", failure.taskId);
|
|
881
1001
|
},
|
|
882
|
-
imageRemoveBackgroundTaskCompleted: async (
|
|
883
|
-
console.log("Completed remove background task:",
|
|
884
|
-
console.log(
|
|
1002
|
+
imageRemoveBackgroundTaskCompleted: async (result) => {
|
|
1003
|
+
console.log("Completed remove background task:", result.taskId);
|
|
1004
|
+
console.log(result.image.url);
|
|
885
1005
|
},
|
|
886
|
-
imageRemoveBackgroundTaskFailed: async (
|
|
887
|
-
console.error("Mynth remove background task failed:",
|
|
1006
|
+
imageRemoveBackgroundTaskFailed: async (failure) => {
|
|
1007
|
+
console.error("Mynth remove background task failed:", failure.taskId);
|
|
888
1008
|
},
|
|
889
|
-
imageUpscaleTaskCompleted: async (
|
|
890
|
-
console.log("Completed upscale task:",
|
|
891
|
-
console.log(
|
|
1009
|
+
imageUpscaleTaskCompleted: async (result) => {
|
|
1010
|
+
console.log("Completed upscale task:", result.taskId);
|
|
1011
|
+
console.log(result.image.url);
|
|
892
1012
|
},
|
|
893
|
-
imageUpscaleTaskFailed: async (
|
|
894
|
-
console.error("Mynth upscale task failed:",
|
|
1013
|
+
imageUpscaleTaskFailed: async (failure) => {
|
|
1014
|
+
console.error("Mynth upscale task failed:", failure.taskId);
|
|
895
1015
|
},
|
|
896
|
-
videoTaskCompleted: async (
|
|
897
|
-
console.log("Completed video task:",
|
|
898
|
-
console.log(
|
|
1016
|
+
videoTaskCompleted: async (result) => {
|
|
1017
|
+
console.log("Completed video task:", result.taskId);
|
|
1018
|
+
console.log(result.videos);
|
|
899
1019
|
},
|
|
900
|
-
videoTaskFailed: async (
|
|
901
|
-
console.error("Mynth video task failed:",
|
|
1020
|
+
videoTaskFailed: async (failure) => {
|
|
1021
|
+
console.error("Mynth video task failed:", failure.taskId);
|
|
902
1022
|
},
|
|
903
1023
|
});
|
|
904
1024
|
```
|
|
905
1025
|
|
|
906
|
-
Set `MYNTH_WEBHOOK_SECRET` in your environment, or pass `webhookSecret` explicitly as the second argument to `mynthWebhookAction(...)`.
|
|
1026
|
+
Set `MYNTH_WEBHOOK_SECRET` in your environment, or pass `webhookSecret` explicitly as the second argument to `mynthWebhookAction(...)`. The `unsigned` option works the same as in the Next.js helper.
|
|
907
1027
|
|
|
908
1028
|
## Error Handling
|
|
909
1029
|
|
|
@@ -928,7 +1048,7 @@ try {
|
|
|
928
1048
|
console.log(task.urls);
|
|
929
1049
|
} catch (error) {
|
|
930
1050
|
if (error instanceof MynthAPIError) {
|
|
931
|
-
// `message` says what to fix. On a
|
|
1051
|
+
// `message` says what to fix. On a validation_error, `issues` lists each invalid field.
|
|
932
1052
|
console.error(error.status, error.code, error.message, error.issues);
|
|
933
1053
|
} else if (error instanceof TaskAsyncTimeoutError) {
|
|
934
1054
|
console.error("Task polling timed out");
|
|
@@ -944,6 +1064,21 @@ try {
|
|
|
944
1064
|
}
|
|
945
1065
|
```
|
|
946
1066
|
|
|
1067
|
+
## Migrating from 0.0.49
|
|
1068
|
+
|
|
1069
|
+
0.0.50 follows the stable API, which changed in one go. Nothing in it is backward compatible:
|
|
1070
|
+
|
|
1071
|
+
- Request fields are snake_case, and the API now rejects a field it does not know. `size.aspectRatio` is `size.aspect_ratio`.
|
|
1072
|
+
- `access: { pat: { enabled } }` is `generate_public_access_token: true`, and it now defaults to `false`: pass it to get `taskAsync.access.publicAccessToken` from `generateAsync()`, `removeBackgroundAsync()`, `upscaleAsync()` and `video.generateAsync()`.
|
|
1073
|
+
- `webhook.dashboard` is `webhook.registered`.
|
|
1074
|
+
- `MynthAPIError.code` and every task error code are lowercase: `validation_error`, `insufficient_balance`, `provider_error`.
|
|
1075
|
+
- API data the SDK returns as is is snake_case: `MynthSDKTypes.TaskData` (`user_id`, `api_key_id`, `created_at`, `updated_at`), the model catalog (`display_name`, `per_image`, `per_second`, `max_total`) and `video.estimate()` (`estimated_cost`, `estimate_kind`).
|
|
1076
|
+
- A video's `url` can be `null`, like an image's. `result.urls` skips it.
|
|
1077
|
+
- Webhooks follow Standard Webhooks. Every registered webhook got a new `whsec_...` signing secret: copy it from the dashboard into `MYNTH_WEBHOOK_SECRET`. `X-Mynth-Event`, `X-Mynth-Delivery` and `X-Mynth-Signature` are gone; deliveries carry `webhook-id`, `webhook-timestamp` and `webhook-signature`.
|
|
1078
|
+
- The webhook body is an event, `{ id, type, timestamp, data }`, with the task in `data`. `MynthSDKTypes.WebhookPayload` and its variants are replaced by `MynthSDKTypes.WebhookEvent`, and `verifyWebhook()` returns one.
|
|
1079
|
+
- Webhook callbacks get `{ event }` in their last argument instead of `deliveryId`. Deduplicate on `event.id`.
|
|
1080
|
+
- Unsigned deliveries to a custom URL are refused unless the helper gets the `unsigned` option.
|
|
1081
|
+
|
|
947
1082
|
## Documentation
|
|
948
1083
|
|
|
949
1084
|
For product documentation and API guides, visit [mynth.io/docs](https://mynth.io/docs).
|
package/dist/convex/index.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { p as MynthSDKTypes } from "../video-generation-result.js";
|
|
1
2
|
import { n as WebhookHandlerOptions, t as WebhookEventHandlers } from "../handler.js";
|
|
2
3
|
import { GenericActionCtx, PublicHttpAction } from "convex/server";
|
|
3
4
|
//#region src/convex/index.d.ts
|
|
@@ -8,10 +9,10 @@ export type MynthWebhookActionContext<T extends AnyActionCtx = AnyActionCtx> = {
|
|
|
8
9
|
/** The request received by the Convex HTTP action. Its body has already been read. */
|
|
9
10
|
request: Request;
|
|
10
11
|
/**
|
|
11
|
-
* The `
|
|
12
|
-
* it and skip IDs you have already handled.
|
|
12
|
+
* The verified event. `event.id` is the `webhook-id`: every delivery of the
|
|
13
|
+
* event repeats it, so store it and skip IDs you have already handled.
|
|
13
14
|
*/
|
|
14
|
-
|
|
15
|
+
event: MynthSDKTypes.WebhookEvent;
|
|
15
16
|
};
|
|
16
17
|
/**
|
|
17
18
|
* Event handlers for Mynth webhook events.
|
|
@@ -22,7 +23,7 @@ export type EventHandlers<T extends AnyActionCtx = AnyActionCtx> = WebhookEventH
|
|
|
22
23
|
*/
|
|
23
24
|
export type MynthWebhookActionOptions = WebhookHandlerOptions;
|
|
24
25
|
/**
|
|
25
|
-
* Create a Convex HTTP action for
|
|
26
|
+
* Create a Convex HTTP action for Mynth webhooks.
|
|
26
27
|
*
|
|
27
28
|
* @example
|
|
28
29
|
* ```typescript
|
|
@@ -38,10 +39,10 @@ export type MynthWebhookActionOptions = WebhookHandlerOptions;
|
|
|
38
39
|
* path: "/mynth-webhook",
|
|
39
40
|
* method: "POST",
|
|
40
41
|
* handler: mynthWebhookAction({
|
|
41
|
-
* imageTaskCompleted: async (
|
|
42
|
+
* imageTaskCompleted: async (result, { context }) => {
|
|
42
43
|
* await context.runMutation(internal.images.save, {
|
|
43
|
-
* taskId:
|
|
44
|
-
* images:
|
|
44
|
+
* taskId: result.taskId,
|
|
45
|
+
* images: result.images,
|
|
45
46
|
* });
|
|
46
47
|
* },
|
|
47
48
|
* }),
|