@mynthio/sdk 0.0.48 → 0.0.49

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -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.id);
46
+ console.log(task.taskId);
47
47
  console.log(task.urls);
48
- console.log(task.result?.model);
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.status); // "completed"
79
+ console.log(task.images[0]?.width); // 1024
80
80
  console.log(task.urls);
81
81
  ```
82
82
 
@@ -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
- console.log(task.getImages()[0]?.rating?.level); // "sfw" | "nsfw"
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
- console.log(task.getImages()[0]?.rating?.level); // "general" | "teen" | "adult"
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`):
@@ -485,7 +493,7 @@ const result = await mynth.image.upscale({
485
493
  });
486
494
 
487
495
  console.log(result.image.url); // upscaled image
488
- console.log(result.image.size); // e.g. "2048x1536"
496
+ console.log(result.image.width, result.image.height); // e.g. 2048 1536
489
497
  ```
490
498
 
491
499
  `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.
@@ -520,7 +528,7 @@ return { id: taskAsync.id, access: taskAsync.access };
520
528
 
521
529
  ## Working With Image Results
522
530
 
523
- Completed generation tasks expose a few helpful accessors:
531
+ `generate()`, `removeBackground()`, and `upscale()` all hand back the same image shape, `MynthOutputImage`:
524
532
 
525
533
  ```ts
526
534
  const task = await mynth.image.generate({
@@ -528,17 +536,53 @@ const task = await mynth.image.generate({
528
536
  metadata: { source: "readme-example" },
529
537
  });
530
538
 
531
- console.log(task.id);
532
- console.log(task.status);
533
- console.log(task.isCompleted);
534
- console.log(task.urls);
535
- console.log(task.getImages());
536
- console.log(task.getImages({ includeFailed: true }));
537
- console.log(task.getMetadata());
538
- console.log(task.result?.magic_prompt);
539
+ console.log(task.taskId);
540
+ console.log(task.cost); // "0.04"
541
+ console.log(task.model); // resolved model, also when you asked for "auto"
542
+ console.log(task.metadata); // { source: "readme-example" }, typed from the request
543
+ console.log(task.magicPrompt); // the rewritten prompt, with magic_prompt: true
544
+ console.log(task.urls); // `url` of each image, skipping `null`
545
+
546
+ for (const image of task.images) {
547
+ image.id;
548
+ image.url; // your destination's URL, or the Mynth URL without a destination; null if delivery failed
549
+ image.mynthUrl; // always set, served for 7 days
550
+ image.width; // 1024
551
+ image.height; // 768
552
+ image.size; // "1024x768"
553
+ image.format; // "png" | "jpg" | "webp"
554
+ image.mimeType; // "image/png" | "image/jpeg" | "image/webp"
555
+ image.destination; // delivery status when the request named a destination
556
+ image.rating; // generate() only, typed from the request's rating levels
557
+ }
558
+ ```
559
+
560
+ `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:
561
+
562
+ ```ts
563
+ const src = image.url ?? image.mynthUrl;
564
+ ```
565
+
566
+ `task.images` holds the successful images only. A completed task can also hold failed ones; `task.failures` lists why:
567
+
568
+ ```ts
569
+ if (task.failures.length > 0) {
570
+ console.warn(task.failures); // [{ code: "PROVIDER_ERROR", message: "..." }]
571
+ }
539
572
  ```
540
573
 
541
- `task.urls` and `task.getImages()` return only successful images by default. `task.result?.images` may also include failed image entries.
574
+ Results are plain objects, so they pass as they are to client components, server functions, Convex mutations, and `JSON.stringify`.
575
+
576
+ To download an image, fetch `mynthUrl`. It is set with or without a destination:
577
+
578
+ ```ts
579
+ import { writeFile } from "node:fs/promises";
580
+
581
+ const response = await fetch(image.mynthUrl);
582
+ await writeFile(`cat.${image.format}`, new Uint8Array(await response.arrayBuffer()));
583
+ ```
584
+
585
+ 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
586
 
543
587
  ## Available Models
544
588
 
@@ -651,7 +695,7 @@ const task = await mynth.video.generate({
651
695
  });
652
696
 
653
697
  console.log(task.urls);
654
- console.log(task.getVideos()[0]?.duration);
698
+ console.log(task.videos[0]?.duration);
655
699
  ```
656
700
 
657
701
  Video generation always runs on a pinned model: unlike images, there is no `auto`, so `model` is required.
@@ -720,17 +764,20 @@ Because the model is always concrete, the estimate is exact.
720
764
 
721
765
  ### Working With Video Results
722
766
 
767
+ Video results mirror image results:
768
+
723
769
  ```ts
724
- console.log(task.id);
725
- console.log(task.status);
726
- console.log(task.isCompleted);
770
+ console.log(task.taskId);
771
+ console.log(task.cost); // failed videos are refunded
772
+ console.log(task.model);
727
773
  console.log(task.urls);
728
- console.log(task.getVideos());
729
- console.log(task.getVideos({ includeFailed: true }));
730
- console.log(task.getMetadata());
774
+ console.log(task.videos); // successful videos only
775
+ console.log(task.failures); // [{ code, message? }] for each failed video
776
+ console.log(task.metadata);
777
+ console.log(task.raw);
731
778
  ```
732
779
 
733
- Each successful video carries `url`, `mynth_url`, `cost`, `duration`, `resolution`, and `audio`.
780
+ Each video has `id`, `url`, `mynthUrl`, `cost`, `duration`, `resolution`, and `audio`.
734
781
 
735
782
  ### Video Models
736
783
 
@@ -793,22 +840,22 @@ Create a Route Handler:
793
840
  import { mynthWebhookHandler } from "@mynthio/sdk/next";
794
841
 
795
842
  export const POST = mynthWebhookHandler({
796
- imageTaskCompleted: async (payload, { request }) => {
797
- console.log("Completed task:", payload.task.id);
843
+ imageTaskCompleted: async (result, { request }) => {
844
+ console.log("Completed task:", result.taskId);
798
845
  console.log("Received at:", request.url);
799
846
 
800
- await saveImages(payload.task.id, payload.result.images);
847
+ await saveImages(result.taskId, result.images);
801
848
  },
802
- imageTaskFailed: async (payload) => {
803
- await markTaskFailed(payload.task.id, payload.errors);
849
+ imageTaskFailed: async (failure) => {
850
+ await markTaskFailed(failure.taskId, failure.errors);
804
851
  },
805
- videoTaskCompleted: async (payload) => {
806
- await saveVideos(payload.task.id, payload.result.videos);
852
+ videoTaskCompleted: async (result) => {
853
+ await saveVideos(result.taskId, result.videos);
807
854
  },
808
855
  });
809
856
  ```
810
857
 
811
- The helper reads the raw body, verifies `X-Mynth-Signature`, rejects signatures older than five minutes, and checks `X-Mynth-Event` before calling a typed handler. The last handler argument contains the original `request` and `deliveryId`, the `X-Mynth-Delivery` value that every retry repeats.
858
+ The helper reads the raw body, verifies `X-Mynth-Signature`, rejects signatures older than five minutes, and checks `X-Mynth-Event` before calling a typed handler. 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 handler argument contains the original `request` and `deliveryId`, the `X-Mynth-Delivery` value that every retry repeats.
812
859
 
813
860
  The route must be publicly reachable, so exclude it from authentication middleware. Make callback side effects idempotent by storing `deliveryId` and skipping IDs you have already handled, and enqueue slow work before returning. Callback errors are propagated so Mynth can retry the delivery.
814
861
 
@@ -827,13 +874,13 @@ export const Route = createFileRoute("/api/webhooks/mynth")({
827
874
  server: {
828
875
  handlers: {
829
876
  POST: mynthWebhookHandler({
830
- imageTaskCompleted: async (payload, { request, params, context }) => {
831
- console.log("Completed task:", payload.task.id);
877
+ imageTaskCompleted: async (result, { request, params, context }) => {
878
+ console.log("Completed task:", result.taskId);
832
879
  console.log("Received at:", request.url);
833
- await saveImages(payload.task.id, payload.result.images);
880
+ await saveImages(result.taskId, result.images);
834
881
  },
835
- imageTaskFailed: async (payload) => {
836
- await markTaskFailed(payload.task.id, payload.errors);
882
+ imageTaskFailed: async (failure) => {
883
+ await markTaskFailed(failure.taskId, failure.errors);
837
884
  },
838
885
  }),
839
886
  },
@@ -851,54 +898,54 @@ The package includes a Convex HTTP action helper for webhook verification and ev
851
898
  import { mynthWebhookAction } from "@mynthio/sdk/convex";
852
899
 
853
900
  export const mynthWebhook = mynthWebhookAction({
854
- imageTaskCompleted: async (payload, { context }) => {
855
- console.log("Completed task:", payload.task.id);
856
- console.log(payload.result.images);
901
+ imageTaskCompleted: async (result, { context }) => {
902
+ console.log("Completed task:", result.taskId);
903
+ console.log(result.images);
857
904
  },
858
- imageTaskFailed: async (payload) => {
859
- console.error("Mynth task failed:", payload.task.id);
905
+ imageTaskFailed: async (failure) => {
906
+ console.error("Mynth task failed:", failure.taskId);
860
907
  },
861
- imageRateTaskCompleted: async (payload) => {
862
- console.log("Completed rating task:", payload.task.id);
863
- console.log(payload.result.level);
908
+ imageRateTaskCompleted: async (result) => {
909
+ console.log("Completed rating task:", result.taskId);
910
+ console.log(result.level);
864
911
  },
865
- imageRateTaskFailed: async (payload) => {
866
- console.error("Mynth rating task failed:", payload.task.id);
912
+ imageRateTaskFailed: async (failure) => {
913
+ console.error("Mynth rating task failed:", failure.taskId);
867
914
  },
868
- imageAltTaskCompleted: async (payload) => {
869
- console.log("Completed alt text task:", payload.task.id);
870
- console.log(payload.result.alt);
915
+ imageAltTaskCompleted: async (result) => {
916
+ console.log("Completed alt text task:", result.taskId);
917
+ console.log(result.alt);
871
918
  },
872
- imageAltTaskFailed: async (payload) => {
873
- console.error("Mynth alt text task failed:", payload.task.id);
919
+ imageAltTaskFailed: async (failure) => {
920
+ console.error("Mynth alt text task failed:", failure.taskId);
874
921
  },
875
- imageReviewTaskCompleted: async (payload) => {
876
- console.log("Completed review task:", payload.task.id);
877
- console.log(payload.result.summary);
922
+ imageReviewTaskCompleted: async (result) => {
923
+ console.log("Completed review task:", result.taskId);
924
+ console.log(result.summary);
878
925
  },
879
- imageReviewTaskFailed: async (payload) => {
880
- console.error("Mynth review task failed:", payload.task.id);
926
+ imageReviewTaskFailed: async (failure) => {
927
+ console.error("Mynth review task failed:", failure.taskId);
881
928
  },
882
- imageRemoveBackgroundTaskCompleted: async (payload) => {
883
- console.log("Completed remove background task:", payload.task.id);
884
- console.log(payload.result.image.url);
929
+ imageRemoveBackgroundTaskCompleted: async (result) => {
930
+ console.log("Completed remove background task:", result.taskId);
931
+ console.log(result.image.url);
885
932
  },
886
- imageRemoveBackgroundTaskFailed: async (payload) => {
887
- console.error("Mynth remove background task failed:", payload.task.id);
933
+ imageRemoveBackgroundTaskFailed: async (failure) => {
934
+ console.error("Mynth remove background task failed:", failure.taskId);
888
935
  },
889
- imageUpscaleTaskCompleted: async (payload) => {
890
- console.log("Completed upscale task:", payload.task.id);
891
- console.log(payload.result.image.url);
936
+ imageUpscaleTaskCompleted: async (result) => {
937
+ console.log("Completed upscale task:", result.taskId);
938
+ console.log(result.image.url);
892
939
  },
893
- imageUpscaleTaskFailed: async (payload) => {
894
- console.error("Mynth upscale task failed:", payload.task.id);
940
+ imageUpscaleTaskFailed: async (failure) => {
941
+ console.error("Mynth upscale task failed:", failure.taskId);
895
942
  },
896
- videoTaskCompleted: async (payload) => {
897
- console.log("Completed video task:", payload.task.id);
898
- console.log(payload.result.videos);
943
+ videoTaskCompleted: async (result) => {
944
+ console.log("Completed video task:", result.taskId);
945
+ console.log(result.videos);
899
946
  },
900
- videoTaskFailed: async (payload) => {
901
- console.error("Mynth video task failed:", payload.task.id);
947
+ videoTaskFailed: async (failure) => {
948
+ console.error("Mynth video task failed:", failure.taskId);
902
949
  },
903
950
  });
904
951
  ```
@@ -38,10 +38,10 @@ export type MynthWebhookActionOptions = WebhookHandlerOptions;
38
38
  * path: "/mynth-webhook",
39
39
  * method: "POST",
40
40
  * handler: mynthWebhookAction({
41
- * imageTaskCompleted: async (payload, { context }) => {
41
+ * imageTaskCompleted: async (result, { context }) => {
42
42
  * await context.runMutation(internal.images.save, {
43
- * taskId: payload.task.id,
44
- * images: payload.result.images,
43
+ * taskId: result.taskId,
44
+ * images: result.images,
45
45
  * });
46
46
  * },
47
47
  * }),
@@ -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
  * }),
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: {
@@ -18,10 +18,28 @@ declare const EVENT_HANDLER_NAMES: {
18
18
  readonly "task.video.generate.failed": "videoTaskFailed";
19
19
  };
20
20
  type WebhookEvent = MynthSDKTypes.WebhookPayload["event"];
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
+ };
21
41
  /** 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>; };
42
+ type WebhookEventHandlers<TContext> = { [TEvent in WebhookEvent as (typeof EVENT_HANDLER_NAMES)[TEvent]]?: (argument: WebhookEventArguments[TEvent], context: TContext) => void | Promise<void>; };
25
43
  type WebhookHandlerOptions = {
26
44
  /** Defaults to MYNTH_WEBHOOK_SECRET, read when each request arrives. */
27
45
  webhookSecret?: string;
package/dist/handler.js CHANGED
@@ -1,3 +1,4 @@
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";
1
2
  //#region src/webhooks/utils.ts
2
3
  /** Environment variable used when no webhook secret is passed explicitly. */
3
4
  const WEBHOOK_SECRET_ENV_VAR = "MYNTH_WEBHOOK_SECRET";
@@ -78,14 +79,44 @@ const EVENT_HANDLER_NAMES = {
78
79
  "task.video.generate.completed": "videoTaskCompleted",
79
80
  "task.video.generate.failed": "videoTaskFailed"
80
81
  };
82
+ /** Builds each event's callback argument from its payload. */
83
+ 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
88
+ }),
89
+ "task.image.rate.completed": (payload) => toImageRateResult(completedTaskFromWebhook(payload)),
90
+ "task.image.rate.failed": taskFailureFromWebhook,
91
+ "task.image.alt.completed": (payload) => toImageAltResult(completedTaskFromWebhook(payload)),
92
+ "task.image.alt.failed": taskFailureFromWebhook,
93
+ "task.image.review.completed": (payload) => toImageReviewResult(completedTaskFromWebhook(payload)),
94
+ "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
99
+ }),
100
+ "task.image.upscale.completed": (payload) => toImageUpscaleResult(completedTaskFromWebhook(payload)),
101
+ "task.image.upscale.failed": (payload) => ({
102
+ ...taskFailureFromWebhook(payload),
103
+ metadata: payload.request.metadata
104
+ }),
105
+ "task.video.generate.completed": (payload) => toVideoGenerationResult(completedTaskFromWebhook(payload)),
106
+ "task.video.generate.failed": (payload) => ({
107
+ ...taskFailureFromWebhook(payload),
108
+ metadata: payload.request.metadata
109
+ })
110
+ };
81
111
  /**
82
112
  * Verify a signed Mynth webhook request and dispatch it to the matching callback.
83
113
  *
84
114
  * Answers `400` for a missing delivery ID, a missing or invalid signature, a
85
115
  * stale timestamp, a malformed body, or an `X-Mynth-Event` header that does
86
116
  * not match the body.
87
- * Answers `200` for signed events without a callback. Callback errors
88
- * propagate, so the framework answers `5xx` and Mynth retries the delivery.
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.
89
120
  */
90
121
  async function handleWebhookRequest(request, eventHandlers, createContext, options) {
91
122
  const webhookSecret = options.webhookSecret ?? getWebhookSecretFromEnv();
@@ -100,7 +131,9 @@ async function handleWebhookRequest(request, eventHandlers, createContext, optio
100
131
  if (!payload || payload.event !== event) return badRequest();
101
132
  if (!Object.hasOwn(EVENT_HANDLER_NAMES, payload.event)) return ok();
102
133
  const handler = eventHandlers[EVENT_HANDLER_NAMES[payload.event]];
103
- await handler?.(payload, createContext(deliveryId));
134
+ if (!handler) return ok();
135
+ const toArgument = EVENT_ARGUMENTS[payload.event];
136
+ await handler(toArgument(payload), createContext(deliveryId));
104
137
  return ok();
105
138
  }
106
139
  function parsePayload(body) {