@mynthio/sdk 0.0.40 → 0.0.42
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 +20 -4
- package/dist/convex/index.d.ts +39 -100
- package/dist/convex/index.js +41 -2
- package/dist/handler.d.ts +28 -0
- package/dist/handler.js +121 -0
- package/dist/index.d.ts +701 -360
- package/dist/index.js +1514 -2
- package/dist/next/index.d.ts +14 -24
- package/dist/next/index.js +25 -2
- package/dist/tanstack-start/index.d.ts +18 -23
- package/dist/tanstack-start/index.js +11 -2
- package/dist/types.d.ts +609 -660
- package/package.json +16 -21
- package/dist/client.d.ts +0 -41
- package/dist/client.d.ts.map +0 -1
- package/dist/constants.d.ts +0 -95
- package/dist/constants.d.ts.map +0 -1
- package/dist/convex/index.d.ts.map +0 -1
- package/dist/convex/utils.d.ts +0 -2
- package/dist/convex/utils.d.ts.map +0 -1
- package/dist/image-alt-result.d.ts +0 -19
- package/dist/image-alt-result.d.ts.map +0 -1
- package/dist/image-generation-result.d.ts +0 -58
- package/dist/image-generation-result.d.ts.map +0 -1
- package/dist/image-rate-result.d.ts +0 -21
- package/dist/image-rate-result.d.ts.map +0 -1
- package/dist/image-remove-background-result.d.ts +0 -24
- package/dist/image-remove-background-result.d.ts.map +0 -1
- package/dist/image-review-result.d.ts +0 -28
- package/dist/image-review-result.d.ts.map +0 -1
- package/dist/index-apss16tr.js +0 -3
- package/dist/index-ty295921.js +0 -3
- package/dist/index.d.ts.map +0 -1
- package/dist/next/index.d.ts.map +0 -1
- package/dist/tanstack-start/index.d.ts.map +0 -1
- package/dist/task-async.d.ts +0 -95
- package/dist/task-async.d.ts.map +0 -1
- package/dist/types.d.ts.map +0 -1
- package/dist/uploads.d.ts +0 -31
- package/dist/uploads.d.ts.map +0 -1
- package/dist/video-generation-result.d.ts +0 -46
- package/dist/video-generation-result.d.ts.map +0 -1
- package/dist/webhooks/utils.d.ts +0 -5
- package/dist/webhooks/utils.d.ts.map +0 -1
package/README.md
CHANGED
|
@@ -136,6 +136,22 @@ if (status.status === "completed") {
|
|
|
136
136
|
}
|
|
137
137
|
```
|
|
138
138
|
|
|
139
|
+
### Cancelling
|
|
140
|
+
|
|
141
|
+
Pass an `AbortSignal` to stop waiting, for example when the incoming request disconnects:
|
|
142
|
+
|
|
143
|
+
```ts
|
|
144
|
+
const task = await mynth.image.generate(
|
|
145
|
+
{ prompt: "A lighthouse in a storm" },
|
|
146
|
+
{ signal: AbortSignal.timeout(60_000) },
|
|
147
|
+
);
|
|
148
|
+
|
|
149
|
+
// Or on an async task:
|
|
150
|
+
const completedTask = await taskAsync.wait({ signal: request.signal });
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
An abort cancels pending uploads and API requests and stops polling, and the call rejects with the signal's reason. A task that was already created keeps running on Mynth. For `generateAsync()`, the signal covers the upload and the create request; pass one to `wait()` to abort the wait. When several `wait()` calls share a task, polling stops only after every one of them has aborted.
|
|
154
|
+
|
|
139
155
|
## Request Shape
|
|
140
156
|
|
|
141
157
|
`generate()` accepts a typed `ImageGenerationRequest`. The simplest request is just a prompt:
|
|
@@ -525,7 +541,7 @@ console.log(model);
|
|
|
525
541
|
// {
|
|
526
542
|
// id: "google/gemini-3.1-flash-image",
|
|
527
543
|
// label: "Nano Banana 2",
|
|
528
|
-
// capabilities: ["inputs", "4k"
|
|
544
|
+
// capabilities: ["inputs", "4k"]
|
|
529
545
|
// }
|
|
530
546
|
```
|
|
531
547
|
|
|
@@ -742,9 +758,9 @@ export const POST = mynthWebhookHandler({
|
|
|
742
758
|
});
|
|
743
759
|
```
|
|
744
760
|
|
|
745
|
-
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
|
|
761
|
+
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.
|
|
746
762
|
|
|
747
|
-
The route must be publicly reachable, so exclude it from authentication middleware. Make callback side effects idempotent
|
|
763
|
+
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.
|
|
748
764
|
|
|
749
765
|
Pass `{ webhookSecret: "wbs_..." }` as the second argument only when the application does not use `MYNTH_WEBHOOK_SECRET`. This helper accepts signed, registered webhooks; per-request custom webhooks are not signed.
|
|
750
766
|
|
|
@@ -775,7 +791,7 @@ export const Route = createFileRoute("/api/webhooks/mynth")({
|
|
|
775
791
|
});
|
|
776
792
|
```
|
|
777
793
|
|
|
778
|
-
Set `MYNTH_WEBHOOK_SECRET` in the server environment, or pass `webhookSecret` as the second argument. Event callbacks receive the original request, route params,
|
|
794
|
+
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 `deliveryId`.
|
|
779
795
|
|
|
780
796
|
## Convex Integration
|
|
781
797
|
|
package/dist/convex/index.d.ts
CHANGED
|
@@ -1,115 +1,54 @@
|
|
|
1
|
-
import
|
|
2
|
-
import
|
|
1
|
+
import { n as WebhookHandlerOptions, t as WebhookEventHandlers } from "../handler.js";
|
|
2
|
+
import { GenericActionCtx, PublicHttpAction } from "convex/server";
|
|
3
|
+
//#region src/convex/index.d.ts
|
|
4
|
+
type AnyActionCtx = GenericActionCtx<any>;
|
|
5
|
+
export type MynthWebhookActionContext<T extends AnyActionCtx = AnyActionCtx> = {
|
|
6
|
+
/** The Convex action context, for `runQuery`, `runMutation`, and `scheduler`. */
|
|
7
|
+
context: T;
|
|
8
|
+
/** The request received by the Convex HTTP action. Its body has already been read. */
|
|
9
|
+
request: Request;
|
|
10
|
+
/**
|
|
11
|
+
* The `X-Mynth-Delivery` ID. Every retry of a delivery repeats it, so store
|
|
12
|
+
* it and skip IDs you have already handled.
|
|
13
|
+
*/
|
|
14
|
+
deliveryId: string;
|
|
15
|
+
};
|
|
3
16
|
/**
|
|
4
17
|
* Event handlers for Mynth webhook events.
|
|
5
18
|
*/
|
|
6
|
-
export type EventHandlers<T extends
|
|
7
|
-
/** Called when an image generation task completes successfully */
|
|
8
|
-
imageTaskCompleted?: (payload: MynthSDKTypes.WebhookTaskImageCompletedPayload, context: {
|
|
9
|
-
context: T;
|
|
10
|
-
request: Request;
|
|
11
|
-
}) => Promise<void>;
|
|
12
|
-
/** Called when an image generation task fails */
|
|
13
|
-
imageTaskFailed?: (payload: MynthSDKTypes.WebhookTaskImageFailedPayload, context: {
|
|
14
|
-
context: T;
|
|
15
|
-
request: Request;
|
|
16
|
-
}) => Promise<void>;
|
|
17
|
-
/** Called when an image rating task completes successfully */
|
|
18
|
-
imageRateTaskCompleted?: (payload: MynthSDKTypes.WebhookTaskImageRateCompletedPayload, context: {
|
|
19
|
-
context: T;
|
|
20
|
-
request: Request;
|
|
21
|
-
}) => Promise<void>;
|
|
22
|
-
/** Called when an image rating task fails */
|
|
23
|
-
imageRateTaskFailed?: (payload: MynthSDKTypes.WebhookTaskImageRateFailedPayload, context: {
|
|
24
|
-
context: T;
|
|
25
|
-
request: Request;
|
|
26
|
-
}) => Promise<void>;
|
|
27
|
-
/** Called when an image alt text task completes successfully */
|
|
28
|
-
imageAltTaskCompleted?: (payload: MynthSDKTypes.WebhookTaskImageAltCompletedPayload, context: {
|
|
29
|
-
context: T;
|
|
30
|
-
request: Request;
|
|
31
|
-
}) => Promise<void>;
|
|
32
|
-
/** Called when an image alt text task fails */
|
|
33
|
-
imageAltTaskFailed?: (payload: MynthSDKTypes.WebhookTaskImageAltFailedPayload, context: {
|
|
34
|
-
context: T;
|
|
35
|
-
request: Request;
|
|
36
|
-
}) => Promise<void>;
|
|
37
|
-
/** Called when an image review task completes successfully */
|
|
38
|
-
imageReviewTaskCompleted?: (payload: MynthSDKTypes.WebhookTaskImageReviewCompletedPayload, context: {
|
|
39
|
-
context: T;
|
|
40
|
-
request: Request;
|
|
41
|
-
}) => Promise<void>;
|
|
42
|
-
/** Called when an image review task fails */
|
|
43
|
-
imageReviewTaskFailed?: (payload: MynthSDKTypes.WebhookTaskImageReviewFailedPayload, context: {
|
|
44
|
-
context: T;
|
|
45
|
-
request: Request;
|
|
46
|
-
}) => Promise<void>;
|
|
47
|
-
/** Called when an image remove background task completes successfully */
|
|
48
|
-
imageRemoveBackgroundTaskCompleted?: (payload: MynthSDKTypes.WebhookTaskImageRemoveBackgroundCompletedPayload, context: {
|
|
49
|
-
context: T;
|
|
50
|
-
request: Request;
|
|
51
|
-
}) => Promise<void>;
|
|
52
|
-
/** Called when an image remove background task fails */
|
|
53
|
-
imageRemoveBackgroundTaskFailed?: (payload: MynthSDKTypes.WebhookTaskImageRemoveBackgroundFailedPayload, context: {
|
|
54
|
-
context: T;
|
|
55
|
-
request: Request;
|
|
56
|
-
}) => Promise<void>;
|
|
57
|
-
/** Called when a video generation task completes successfully */
|
|
58
|
-
videoTaskCompleted?: (payload: MynthSDKTypes.WebhookTaskVideoCompletedPayload, context: {
|
|
59
|
-
context: T;
|
|
60
|
-
request: Request;
|
|
61
|
-
}) => Promise<void>;
|
|
62
|
-
/** Called when a video generation task fails */
|
|
63
|
-
videoTaskFailed?: (payload: MynthSDKTypes.WebhookTaskVideoFailedPayload, context: {
|
|
64
|
-
context: T;
|
|
65
|
-
request: Request;
|
|
66
|
-
}) => Promise<void>;
|
|
67
|
-
};
|
|
19
|
+
export type EventHandlers<T extends AnyActionCtx = AnyActionCtx> = WebhookEventHandlers<MynthWebhookActionContext<T>>;
|
|
68
20
|
/**
|
|
69
21
|
* Options for configuring the webhook action.
|
|
70
22
|
*/
|
|
71
|
-
export type MynthWebhookActionOptions =
|
|
72
|
-
/** Webhook secret for signature verification. Defaults to MYNTH_WEBHOOK_SECRET env var. */
|
|
73
|
-
webhookSecret?: string;
|
|
74
|
-
};
|
|
23
|
+
export type MynthWebhookActionOptions = WebhookHandlerOptions;
|
|
75
24
|
/**
|
|
76
|
-
*
|
|
77
|
-
*
|
|
78
|
-
* @param eventHandlers - Handlers for different webhook events
|
|
79
|
-
* @param options - Configuration options
|
|
80
|
-
* @returns A Convex HTTP action handler
|
|
25
|
+
* Create a Convex HTTP action for signed Mynth webhooks.
|
|
81
26
|
*
|
|
82
27
|
* @example
|
|
83
28
|
* ```typescript
|
|
84
|
-
* //
|
|
29
|
+
* // convex/http.ts
|
|
30
|
+
* import { httpRouter } from "convex/server";
|
|
85
31
|
* import { mynthWebhookAction } from "@mynthio/sdk/convex";
|
|
86
32
|
*
|
|
87
|
-
*
|
|
88
|
-
*
|
|
89
|
-
*
|
|
90
|
-
*
|
|
91
|
-
*
|
|
92
|
-
*
|
|
93
|
-
*
|
|
94
|
-
*
|
|
95
|
-
*
|
|
96
|
-
*
|
|
97
|
-
*
|
|
98
|
-
*
|
|
99
|
-
*
|
|
100
|
-
*
|
|
101
|
-
*
|
|
102
|
-
* });
|
|
103
|
-
* },
|
|
104
|
-
* imageAltTaskCompleted: async (payload, { context }) => {
|
|
105
|
-
* await context.runMutation(internal.images.saveAltText, {
|
|
106
|
-
* taskId: payload.task.id,
|
|
107
|
-
* url: payload.result.url,
|
|
108
|
-
* alt: payload.result.alt,
|
|
109
|
-
* });
|
|
110
|
-
* },
|
|
33
|
+
* import { internal } from "./_generated/api";
|
|
34
|
+
*
|
|
35
|
+
* const http = httpRouter();
|
|
36
|
+
*
|
|
37
|
+
* http.route({
|
|
38
|
+
* path: "/mynth-webhook",
|
|
39
|
+
* method: "POST",
|
|
40
|
+
* handler: mynthWebhookAction({
|
|
41
|
+
* imageTaskCompleted: async (payload, { context }) => {
|
|
42
|
+
* await context.runMutation(internal.images.save, {
|
|
43
|
+
* taskId: payload.task.id,
|
|
44
|
+
* images: payload.result.images,
|
|
45
|
+
* });
|
|
46
|
+
* },
|
|
47
|
+
* }),
|
|
111
48
|
* });
|
|
49
|
+
*
|
|
50
|
+
* export default http;
|
|
112
51
|
* ```
|
|
113
52
|
*/
|
|
114
|
-
export declare
|
|
115
|
-
//#
|
|
53
|
+
export declare function mynthWebhookAction(eventHandlers: EventHandlers, options?: MynthWebhookActionOptions): PublicHttpAction;
|
|
54
|
+
//#endregion
|
package/dist/convex/index.js
CHANGED
|
@@ -1,2 +1,41 @@
|
|
|
1
|
-
|
|
2
|
-
import
|
|
1
|
+
import { t as handleWebhookRequest } from "../handler.js";
|
|
2
|
+
import { httpActionGeneric } from "convex/server";
|
|
3
|
+
//#region src/convex/index.ts
|
|
4
|
+
/**
|
|
5
|
+
* Create a Convex HTTP action for signed Mynth webhooks.
|
|
6
|
+
*
|
|
7
|
+
* @example
|
|
8
|
+
* ```typescript
|
|
9
|
+
* // convex/http.ts
|
|
10
|
+
* import { httpRouter } from "convex/server";
|
|
11
|
+
* import { mynthWebhookAction } from "@mynthio/sdk/convex";
|
|
12
|
+
*
|
|
13
|
+
* import { internal } from "./_generated/api";
|
|
14
|
+
*
|
|
15
|
+
* const http = httpRouter();
|
|
16
|
+
*
|
|
17
|
+
* http.route({
|
|
18
|
+
* path: "/mynth-webhook",
|
|
19
|
+
* method: "POST",
|
|
20
|
+
* handler: mynthWebhookAction({
|
|
21
|
+
* imageTaskCompleted: async (payload, { context }) => {
|
|
22
|
+
* await context.runMutation(internal.images.save, {
|
|
23
|
+
* taskId: payload.task.id,
|
|
24
|
+
* images: payload.result.images,
|
|
25
|
+
* });
|
|
26
|
+
* },
|
|
27
|
+
* }),
|
|
28
|
+
* });
|
|
29
|
+
*
|
|
30
|
+
* export default http;
|
|
31
|
+
* ```
|
|
32
|
+
*/
|
|
33
|
+
function mynthWebhookAction(eventHandlers, options = {}) {
|
|
34
|
+
return httpActionGeneric((context, request) => handleWebhookRequest(request, eventHandlers, (deliveryId) => ({
|
|
35
|
+
context,
|
|
36
|
+
request,
|
|
37
|
+
deliveryId
|
|
38
|
+
}), options));
|
|
39
|
+
}
|
|
40
|
+
//#endregion
|
|
41
|
+
export { mynthWebhookAction };
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { t as MynthSDKTypes } from "./types.js";
|
|
2
|
+
//#region src/webhooks/handler.d.ts
|
|
3
|
+
/** Maps every webhook event to the callback name the framework helpers accept. */
|
|
4
|
+
declare const EVENT_HANDLER_NAMES: {
|
|
5
|
+
readonly "task.image.generate.completed": "imageTaskCompleted";
|
|
6
|
+
readonly "task.image.generate.failed": "imageTaskFailed";
|
|
7
|
+
readonly "task.image.rate.completed": "imageRateTaskCompleted";
|
|
8
|
+
readonly "task.image.rate.failed": "imageRateTaskFailed";
|
|
9
|
+
readonly "task.image.alt.completed": "imageAltTaskCompleted";
|
|
10
|
+
readonly "task.image.alt.failed": "imageAltTaskFailed";
|
|
11
|
+
readonly "task.image.review.completed": "imageReviewTaskCompleted";
|
|
12
|
+
readonly "task.image.review.failed": "imageReviewTaskFailed";
|
|
13
|
+
readonly "task.image.remove_background.completed": "imageRemoveBackgroundTaskCompleted";
|
|
14
|
+
readonly "task.image.remove_background.failed": "imageRemoveBackgroundTaskFailed";
|
|
15
|
+
readonly "task.video.generate.completed": "videoTaskCompleted";
|
|
16
|
+
readonly "task.video.generate.failed": "videoTaskFailed";
|
|
17
|
+
};
|
|
18
|
+
type WebhookEvent = MynthSDKTypes.WebhookPayload["event"];
|
|
19
|
+
/** Event callbacks shared by every framework helper, keyed by handler name. */
|
|
20
|
+
type WebhookEventHandlers<TContext> = { [TEvent in WebhookEvent as (typeof EVENT_HANDLER_NAMES)[TEvent]]?: (payload: Extract<MynthSDKTypes.WebhookPayload, {
|
|
21
|
+
event: TEvent;
|
|
22
|
+
}>, context: TContext) => void | Promise<void>; };
|
|
23
|
+
type WebhookHandlerOptions = {
|
|
24
|
+
/** Defaults to MYNTH_WEBHOOK_SECRET, read when each request arrives. */
|
|
25
|
+
webhookSecret?: string;
|
|
26
|
+
};
|
|
27
|
+
//#endregion
|
|
28
|
+
export { WebhookHandlerOptions as n, WebhookEventHandlers as t };
|
package/dist/handler.js
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
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
|
|
60
|
+
//#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
|
+
/** Maps every webhook event to the callback name the framework helpers accept. */
|
|
65
|
+
const EVENT_HANDLER_NAMES = {
|
|
66
|
+
"task.image.generate.completed": "imageTaskCompleted",
|
|
67
|
+
"task.image.generate.failed": "imageTaskFailed",
|
|
68
|
+
"task.image.rate.completed": "imageRateTaskCompleted",
|
|
69
|
+
"task.image.rate.failed": "imageRateTaskFailed",
|
|
70
|
+
"task.image.alt.completed": "imageAltTaskCompleted",
|
|
71
|
+
"task.image.alt.failed": "imageAltTaskFailed",
|
|
72
|
+
"task.image.review.completed": "imageReviewTaskCompleted",
|
|
73
|
+
"task.image.review.failed": "imageReviewTaskFailed",
|
|
74
|
+
"task.image.remove_background.completed": "imageRemoveBackgroundTaskCompleted",
|
|
75
|
+
"task.image.remove_background.failed": "imageRemoveBackgroundTaskFailed",
|
|
76
|
+
"task.video.generate.completed": "videoTaskCompleted",
|
|
77
|
+
"task.video.generate.failed": "videoTaskFailed"
|
|
78
|
+
};
|
|
79
|
+
/**
|
|
80
|
+
* Verify a signed Mynth webhook request and dispatch it to the matching callback.
|
|
81
|
+
*
|
|
82
|
+
* Answers `400` for a missing delivery ID, a missing or invalid signature, a
|
|
83
|
+
* stale timestamp, a malformed body, or an `X-Mynth-Event` header that does
|
|
84
|
+
* not match the body.
|
|
85
|
+
* Answers `200` for signed events without a callback. Callback errors
|
|
86
|
+
* propagate, so the framework answers `5xx` and Mynth retries the delivery.
|
|
87
|
+
*/
|
|
88
|
+
async function handleWebhookRequest(request, eventHandlers, createContext, options) {
|
|
89
|
+
const webhookSecret = options.webhookSecret ?? getWebhookSecretFromEnv();
|
|
90
|
+
if (!webhookSecret) throw new Error("MYNTH_WEBHOOK_SECRET is required. Either pass it as an option or set the environment variable.");
|
|
91
|
+
const event = request.headers.get(WEBHOOK_EVENT_HEADER);
|
|
92
|
+
const deliveryId = request.headers.get(WEBHOOK_DELIVERY_HEADER);
|
|
93
|
+
const signature = request.headers.get(WEBHOOK_SIGNATURE_HEADER);
|
|
94
|
+
if (!event || !deliveryId || !signature) return badRequest();
|
|
95
|
+
const body = new Uint8Array(await request.arrayBuffer());
|
|
96
|
+
if (!await verifySignature(body, signature, webhookSecret)) return badRequest();
|
|
97
|
+
const payload = parsePayload(body);
|
|
98
|
+
if (!payload || payload.event !== event) return badRequest();
|
|
99
|
+
if (!Object.hasOwn(EVENT_HANDLER_NAMES, payload.event)) return ok();
|
|
100
|
+
const handler = eventHandlers[EVENT_HANDLER_NAMES[payload.event]];
|
|
101
|
+
await handler?.(payload, createContext(deliveryId));
|
|
102
|
+
return ok();
|
|
103
|
+
}
|
|
104
|
+
function parsePayload(body) {
|
|
105
|
+
let payload;
|
|
106
|
+
try {
|
|
107
|
+
payload = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(body));
|
|
108
|
+
} catch {
|
|
109
|
+
return null;
|
|
110
|
+
}
|
|
111
|
+
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;
|
|
112
|
+
return payload;
|
|
113
|
+
}
|
|
114
|
+
function ok() {
|
|
115
|
+
return new Response("OK", { status: 200 });
|
|
116
|
+
}
|
|
117
|
+
function badRequest() {
|
|
118
|
+
return new Response("Bad Request", { status: 400 });
|
|
119
|
+
}
|
|
120
|
+
//#endregion
|
|
121
|
+
export { handleWebhookRequest as t };
|