@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/dist/utils.js ADDED
@@ -0,0 +1,312 @@
1
+ //#region src/image-alt-result.ts
2
+ /** Map a completed image alt text task. */
3
+ function toImageAltResult(task) {
4
+ return {
5
+ taskId: task.taskId,
6
+ cost: task.cost,
7
+ alt: task.result.alt,
8
+ raw: {
9
+ request: task.request,
10
+ result: task.result
11
+ }
12
+ };
13
+ }
14
+ //#endregion
15
+ //#region src/output-image.ts
16
+ const IMAGE_MIME_TYPES = {
17
+ png: "image/png",
18
+ jpg: "image/jpeg",
19
+ webp: "image/webp"
20
+ };
21
+ const SIZE_PATTERN = /^(\d+)x(\d+)$/;
22
+ function parseSize(size) {
23
+ const match = SIZE_PATTERN.exec(size);
24
+ if (!match) throw new Error(`Unexpected image size "${size}", expected {width}x{height}`);
25
+ return {
26
+ width: Number(match[1]),
27
+ height: Number(match[2])
28
+ };
29
+ }
30
+ /**
31
+ * Map an image from the API wire format.
32
+ *
33
+ * @throws {Error} If `size` is not `{width}x{height}`
34
+ */
35
+ function toOutputImage(image) {
36
+ const { width, height } = parseSize(image.size);
37
+ return {
38
+ id: image.id,
39
+ url: image.url,
40
+ mynthUrl: image.mynth_url,
41
+ width,
42
+ height,
43
+ size: image.size,
44
+ format: image.format,
45
+ mimeType: IMAGE_MIME_TYPES[image.format],
46
+ destination: image.destination
47
+ };
48
+ }
49
+ //#endregion
50
+ //#region src/image-generation-result.ts
51
+ /** Map a completed image generation task. */
52
+ function toImageGenerationResult(task) {
53
+ const images = [];
54
+ const failures = [];
55
+ for (const image of task.result.images) if (image.status === "success") images.push({
56
+ ...toOutputImage(image),
57
+ rating: image.rating
58
+ });
59
+ else failures.push(image.error);
60
+ return {
61
+ taskId: task.taskId,
62
+ cost: task.cost,
63
+ model: task.result.model,
64
+ images,
65
+ failures,
66
+ urls: images.flatMap((image) => image.url === null ? [] : [image.url]),
67
+ magicPrompt: task.result.magic_prompt,
68
+ metadata: task.request.metadata,
69
+ raw: {
70
+ request: task.request,
71
+ result: task.result
72
+ }
73
+ };
74
+ }
75
+ //#endregion
76
+ //#region src/image-rate-result.ts
77
+ /** Map a completed image content rating task. */
78
+ function toImageRateResult(task) {
79
+ return {
80
+ taskId: task.taskId,
81
+ cost: task.cost,
82
+ level: task.result.level,
83
+ raw: {
84
+ request: task.request,
85
+ result: task.result
86
+ }
87
+ };
88
+ }
89
+ //#endregion
90
+ //#region src/image-remove-background-result.ts
91
+ /** Map a completed image background removal task. */
92
+ function toImageRemoveBackgroundResult(task) {
93
+ return {
94
+ taskId: task.taskId,
95
+ cost: task.cost,
96
+ image: toOutputImage(task.result.image),
97
+ metadata: task.request.metadata,
98
+ raw: {
99
+ request: task.request,
100
+ result: task.result
101
+ }
102
+ };
103
+ }
104
+ //#endregion
105
+ //#region src/image-review-result.ts
106
+ /** Map a completed image quality review task. */
107
+ function toImageReviewResult(task) {
108
+ return {
109
+ taskId: task.taskId,
110
+ cost: task.cost,
111
+ score: task.result.score,
112
+ summary: task.result.summary,
113
+ findings: task.result.findings,
114
+ strengths: task.result.strengths,
115
+ raw: {
116
+ request: task.request,
117
+ result: task.result
118
+ }
119
+ };
120
+ }
121
+ //#endregion
122
+ //#region src/image-upscale-result.ts
123
+ /** Map a completed image upscale task. */
124
+ function toImageUpscaleResult(task) {
125
+ return {
126
+ taskId: task.taskId,
127
+ cost: task.cost,
128
+ image: toOutputImage(task.result.image),
129
+ metadata: task.request.metadata,
130
+ raw: {
131
+ request: task.request,
132
+ result: task.result
133
+ }
134
+ };
135
+ }
136
+ //#endregion
137
+ //#region src/task-result.ts
138
+ /**
139
+ * Read a completed task from polled task data.
140
+ *
141
+ * @param label - Names the task in errors, e.g. `"Image upscale"`
142
+ * @throws {Error} If the task has not completed, or completed without a cost
143
+ */
144
+ function completedTaskFromData(data, label) {
145
+ if (data.status !== "completed" || data.result === null) throw new Error(`${label} task ${data.id} is not completed`);
146
+ if (data.cost === null) throw new Error(`${label} task ${data.id} is missing cost`);
147
+ return {
148
+ taskId: data.id,
149
+ cost: data.cost,
150
+ request: data.request,
151
+ result: data.result
152
+ };
153
+ }
154
+ /**
155
+ * Read a completed task from a `...completed` webhook event. Its `data` is
156
+ * the task as `GET /tasks/{id}` returns it.
157
+ *
158
+ * @throws {Error} If the event's task has not completed, or has no cost
159
+ */
160
+ function completedTaskFromWebhook(event) {
161
+ return completedTaskFromData(event.data, "Webhook");
162
+ }
163
+ /**
164
+ * Read a failed task from a `...failed` webhook event. Callers add
165
+ * `metadata` for task types whose request takes it.
166
+ */
167
+ function taskFailureFromWebhook(event) {
168
+ return {
169
+ taskId: event.data.id,
170
+ errors: event.data.errors,
171
+ raw: { request: event.data.request }
172
+ };
173
+ }
174
+ //#endregion
175
+ //#region src/output-video.ts
176
+ /** Map a successful video from the API wire format. */
177
+ function toOutputVideo(video) {
178
+ return {
179
+ id: video.id,
180
+ url: video.url,
181
+ mynthUrl: video.mynth_url,
182
+ cost: video.cost,
183
+ duration: video.duration,
184
+ resolution: video.resolution,
185
+ audio: video.audio
186
+ };
187
+ }
188
+ //#endregion
189
+ //#region src/video-generation-result.ts
190
+ /** Map a completed video generation task. */
191
+ function toVideoGenerationResult(task) {
192
+ const videos = [];
193
+ const failures = [];
194
+ for (const video of task.result.videos) if (video.status === "success") videos.push(toOutputVideo(video));
195
+ else failures.push(video.error);
196
+ return {
197
+ taskId: task.taskId,
198
+ cost: task.cost,
199
+ model: task.result.model,
200
+ videos,
201
+ failures,
202
+ urls: videos.flatMap((video) => video.url === null ? [] : [video.url]),
203
+ metadata: task.request.metadata,
204
+ raw: {
205
+ request: task.request,
206
+ result: task.result
207
+ }
208
+ };
209
+ }
210
+ //#endregion
211
+ //#region src/webhooks/utils.ts
212
+ /** Environment variable used when no webhook secret is passed explicitly. */
213
+ const WEBHOOK_SECRET_ENV_VAR = "MYNTH_WEBHOOK_SECRET";
214
+ /** Standard Webhooks headers (https://www.standardwebhooks.com). */
215
+ const WEBHOOK_ID_HEADER = "webhook-id";
216
+ const WEBHOOK_TIMESTAMP_HEADER = "webhook-timestamp";
217
+ const WEBHOOK_SIGNATURE_HEADER = "webhook-signature";
218
+ const SECRET_PREFIX = "whsec_";
219
+ const TIMESTAMP_PATTERN = /^\d{1,15}$/;
220
+ const BASE64_PATTERN = /^[A-Za-z0-9+/]+={0,2}$/;
221
+ const encoder = new TextEncoder();
222
+ /** Read the webhook secret without assuming a Node.js runtime. */
223
+ function getWebhookSecretFromEnv() {
224
+ if (typeof process !== "undefined" && process.env) return process.env[WEBHOOK_SECRET_ENV_VAR];
225
+ }
226
+ /** A header by name, ignoring case. A repeated header reads as its first value. */
227
+ function readHeader(headers, name) {
228
+ if (typeof Headers !== "undefined" && headers instanceof Headers) return headers.get(name) ?? void 0;
229
+ const record = headers;
230
+ const key = Object.keys(record).find((candidate) => candidate.toLowerCase() === name);
231
+ const value = key === void 0 ? void 0 : record[key];
232
+ return Array.isArray(value) ? value[0] : value;
233
+ }
234
+ /** The bytes a base64 string encodes, or `null` when it is not valid base64. */
235
+ function base64ToBytes(value) {
236
+ if (!BASE64_PATTERN.test(value)) return null;
237
+ let binary;
238
+ try {
239
+ binary = atob(value);
240
+ } catch {
241
+ return null;
242
+ }
243
+ const bytes = new Uint8Array(binary.length);
244
+ for (let index = 0; index < binary.length; index++) bytes[index] = binary.charCodeAt(index);
245
+ return bytes;
246
+ }
247
+ /**
248
+ * The HMAC key a `whsec_` secret stands for: the bytes it encodes.
249
+ *
250
+ * @throws {Error} If the secret is not one Mynth issued, which is a setup problem
251
+ */
252
+ function secretKeyBytes(secret) {
253
+ const bytes = base64ToBytes(secret.startsWith(SECRET_PREFIX) ? secret.slice(6) : secret);
254
+ if (!bytes) throw new Error(`The Mynth webhook secret is not valid. Copy it from the dashboard: it starts with "${SECRET_PREFIX}".`);
255
+ return bytes;
256
+ }
257
+ /** Every `v1` signature in a space-separated `webhook-signature` header. */
258
+ function v1Signatures(header) {
259
+ return header.split(" ").flatMap((entry) => {
260
+ const separator = entry.indexOf(",");
261
+ if (separator === -1 || entry.slice(0, separator) !== "v1") return [];
262
+ const signature = base64ToBytes(entry.slice(separator + 1));
263
+ return signature ? [signature] : [];
264
+ });
265
+ }
266
+ function concatBytes(...parts) {
267
+ const bytes = new Uint8Array(parts.reduce((length, part) => length + part.length, 0));
268
+ let offset = 0;
269
+ for (const part of parts) {
270
+ bytes.set(part, offset);
271
+ offset += part.length;
272
+ }
273
+ return bytes;
274
+ }
275
+ /**
276
+ * Verify a Standard Webhooks signature: HMAC-SHA256 over
277
+ * `<webhook-id>.<webhook-timestamp>.<body>`, keyed with the secret's bytes.
278
+ *
279
+ * Accepts any matching `v1` signature in the header, and rejects a timestamp
280
+ * more than five minutes from `now` to limit replays. The comparison runs
281
+ * inside Web Crypto, so it does not leak timing information.
282
+ *
283
+ * @throws {Error} If the secret is not a valid `whsec_` secret
284
+ */
285
+ async function verifySignature({ id, timestamp, signature, body, secret, now = Date.now() }) {
286
+ const key = await crypto.subtle.importKey("raw", secretKeyBytes(secret), {
287
+ name: "HMAC",
288
+ hash: "SHA-256"
289
+ }, false, ["verify"]);
290
+ if (!TIMESTAMP_PATTERN.test(timestamp)) return false;
291
+ const ageSeconds = Math.floor(now / 1e3) - Number(timestamp);
292
+ if (Math.abs(ageSeconds) > 300) return false;
293
+ const message = concatBytes(encoder.encode(`${id}.${timestamp}.`), body);
294
+ for (const candidate of v1Signatures(signature)) if (await crypto.subtle.verify("HMAC", key, candidate, message)) return true;
295
+ return false;
296
+ }
297
+ /**
298
+ * Read a webhook body as an event, or `null` when it is not one: not JSON, not
299
+ * shaped like an event, or with an `id` other than the `webhook-id` header.
300
+ */
301
+ function parseWebhookEvent(body, id) {
302
+ let event;
303
+ try {
304
+ event = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(body));
305
+ } catch {
306
+ return null;
307
+ }
308
+ if (typeof event !== "object" || event === null || !("id" in event) || event.id !== id || !("type" in event) || typeof event.type !== "string" || !("timestamp" in event) || typeof event.timestamp !== "string" || !("data" in event) || typeof event.data !== "object" || event.data === null || !("id" in event.data) || typeof event.data.id !== "string") return null;
309
+ return event;
310
+ }
311
+ //#endregion
312
+ export { toImageAltResult as _, parseWebhookEvent as a, toVideoGenerationResult as c, taskFailureFromWebhook as d, toImageUpscaleResult as f, toImageGenerationResult as g, toImageRateResult as h, getWebhookSecretFromEnv as i, completedTaskFromData as l, toImageRemoveBackgroundResult as m, WEBHOOK_SIGNATURE_HEADER as n, readHeader as o, toImageReviewResult as p, WEBHOOK_TIMESTAMP_HEADER as r, verifySignature as s, WEBHOOK_ID_HEADER as t, completedTaskFromWebhook as u };