@mynthio/sdk 0.0.43 → 0.0.45

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
@@ -855,7 +855,7 @@ Set `MYNTH_WEBHOOK_SECRET` in your environment, or pass `webhookSecret` explicit
855
855
 
856
856
  `upload()`, `generate()`, `generateAsync()`, `rate()`, `rateAsync()`, `alt()`, `altAsync()`, `review()`, `reviewAsync()`, `removeBackground()`, `removeBackgroundAsync()`, `models.list()`, and the `video` equivalents (`video.generate()`, `video.generateAsync()`, `video.upload()`, `video.estimate()`) may throw `MynthAPIError` if the request fails. Polling can also throw task-specific errors:
857
857
 
858
- While polling, transient failures (404, 5xx, dropped connections) are retried: a created task is owed an answer, so a cold cache or a brief outage does not lose you the result. Polling gives up after 20 consecutive failures (~100s) with `TaskAsyncFetchError` or `TaskAsyncTaskFetchError`, and immediately on a 401 or 403 with `TaskAsyncUnauthorizedError`. Image waits time out after 30 minutes, video waits after an hour.
858
+ While polling, transient failures (404, 5xx, dropped connections) are retried: a created task is owed an answer, so a cold cache or a brief outage does not lose you the result. A 429 slows polling down, doubling the interval up to 30 seconds, and only the timeout ends it. Polling gives up after 20 consecutive failures (~100s) with `TaskAsyncFetchError` or `TaskAsyncTaskFetchError`, immediately on a 401 or 403 with `TaskAsyncUnauthorizedError`, and immediately on any other 4xx with `TaskAsyncFetchError` or `TaskAsyncTaskFetchError`. Image waits time out after 30 minutes, video waits after an hour.
859
859
 
860
860
  ```ts
861
861
  import {
@@ -874,7 +874,8 @@ try {
874
874
  console.log(task.urls);
875
875
  } catch (error) {
876
876
  if (error instanceof MynthAPIError) {
877
- console.error(error.status, error.code, error.message);
877
+ // `message` says what to fix. On a VALIDATION_ERROR, `issues` lists each invalid field.
878
+ console.error(error.status, error.code, error.message, error.issues);
878
879
  } else if (error instanceof TaskAsyncTimeoutError) {
879
880
  console.error("Task polling timed out");
880
881
  } else if (error instanceof TaskAsyncUnauthorizedError) {
package/dist/index.d.ts CHANGED
@@ -8,8 +8,18 @@ export declare class MynthAPIError extends Error {
8
8
  readonly status: number;
9
9
  /** Error code from the API response, if available */
10
10
  readonly code?: string | undefined;
11
- constructor(message: string, status: number, code?: string);
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.
14
+ */
15
+ readonly issues?: ReadonlyArray<MynthAPIErrorIssue> | undefined;
16
+ constructor(message: string, status: number, code?: string, issues?: ReadonlyArray<MynthAPIErrorIssue>);
12
17
  }
18
+ type MynthAPIErrorIssue = {
19
+ /** Where the problem is, e.g. `["size", "scale"]`. Empty for the body as a whole. */
20
+ path: ReadonlyArray<string | number>;
21
+ message: string;
22
+ };
13
23
  type MynthClientRequestOptions = {
14
24
  headers?: Record<string, string>;
15
25
  accessToken?: string | undefined;
@@ -214,10 +224,11 @@ export declare class TaskAsyncUnauthorizedError extends Error {
214
224
  constructor(taskId: string);
215
225
  }
216
226
  /**
217
- * Error thrown when fetching task status fails after multiple retries.
227
+ * Error thrown when fetching task status fails after multiple retries, or at
228
+ * once on a response that a retry cannot change (a 400, say).
218
229
  */
219
230
  export declare class TaskAsyncFetchError extends Error {
220
- constructor(taskId: string, cause?: Error);
231
+ constructor(taskId: string, cause?: Error, status?: number);
221
232
  }
222
233
  /**
223
234
  * Error thrown when fetching full task data fails.
@@ -282,7 +293,7 @@ export declare class TaskAsync<ResultT> {
282
293
  * @param options.signal - Stops this wait when aborted (see {@link TaskAsyncWaitOptions})
283
294
  * @throws {TaskAsyncTimeoutError} If polling exceeds the timeout
284
295
  * @throws {TaskAsyncUnauthorizedError} If access is denied
285
- * @throws {TaskAsyncFetchError} If fetching status fails repeatedly
296
+ * @throws {TaskAsyncFetchError} If fetching status fails repeatedly, or with a non-retryable 4xx
286
297
  * @throws {TaskAsyncTaskFetchError} If fetching the completed task fails
287
298
  * @throws {TaskAsyncTaskFailedError} If the task fails before completion
288
299
  */
@@ -787,4 +798,4 @@ declare class Mynth {
787
798
  get video(): MynthVideo;
788
799
  }
789
800
  //#endregion
790
- export { AVAILABLE_MODELS, AVAILABLE_VIDEO_MODELS, type AvailableModel, type AvailableVideoModel, type ModelCapability, Mynth, Mynth as default, MynthImage, type MynthModel, type MynthModelPricing, MynthModels, type MynthOptions, type MynthRequestOptions, type MynthSDKTypes, MynthVideo, type TaskAsyncAccess, type TaskAsyncWaitOptions, type VideoInputRole, type VideoResolutionTier };
801
+ 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 };
package/dist/index.js CHANGED
@@ -390,16 +390,30 @@ var MynthAPIError = class extends Error {
390
390
  status;
391
391
  /** Error code from the API response, if available */
392
392
  code;
393
- constructor(message, status, code) {
393
+ /**
394
+ * One entry per invalid field when `code` is `VALIDATION_ERROR` and the
395
+ * request failed its schema. `message` already states all of them.
396
+ */
397
+ issues;
398
+ constructor(message, status, code, issues) {
394
399
  super(message);
395
400
  this.name = "MynthAPIError";
396
401
  this.status = status;
397
402
  this.code = code;
403
+ this.issues = issues;
398
404
  }
399
405
  };
400
406
  function createApiError(data, status) {
401
- const errorResponse = data;
402
- return new MynthAPIError(errorResponse.error || errorResponse.message || `Request failed with status ${status}`, status, errorResponse.code);
407
+ const errorResponse = typeof data === "object" && data !== null ? data : {};
408
+ return new MynthAPIError(typeof errorResponse.message === "string" && errorResponse.message || typeof errorResponse.error === "string" && errorResponse.error || `Request failed with status ${status}`, status, typeof errorResponse.code === "string" ? errorResponse.code : void 0, Array.isArray(errorResponse.issues) ? errorResponse.issues : void 0);
409
+ }
410
+ /** An error body that is not JSON (a proxy's HTML page, say) still yields an API error. */
411
+ async function readErrorBody(response) {
412
+ try {
413
+ return await response.json();
414
+ } catch {
415
+ return;
416
+ }
403
417
  }
404
418
  /**
405
419
  * Internal HTTP client for making API requests.
@@ -431,9 +445,8 @@ var MynthClient = class {
431
445
  body: isFormData ? data : JSON.stringify(data),
432
446
  ...signal ? { signal } : {}
433
447
  });
434
- const json = await response.json();
435
- if (!response.ok) throw createApiError(json, response.status);
436
- return json;
448
+ if (!response.ok) throw createApiError(await readErrorBody(response), response.status);
449
+ return await response.json();
437
450
  }
438
451
  async get(path, { headers, accessToken, auth, signal } = {}) {
439
452
  const response = await fetch(this.getUrl(path), {
@@ -647,6 +660,7 @@ const FAST_POLLING_DURATION_MS = 12e3;
647
660
  const FAST_POLLING_INTERVAL_MS = 2500;
648
661
  const SLOW_POLLING_INTERVAL_MS = 5e3;
649
662
  const MAX_RETRY_COUNT = 20;
663
+ const MAX_RATE_LIMITED_INTERVAL_MS = 3e4;
650
664
  /**
651
665
  * Error thrown when task polling exceeds the maximum timeout duration.
652
666
  */
@@ -666,11 +680,12 @@ var TaskAsyncUnauthorizedError = class extends Error {
666
680
  }
667
681
  };
668
682
  /**
669
- * Error thrown when fetching task status fails after multiple retries.
683
+ * Error thrown when fetching task status fails after multiple retries, or at
684
+ * once on a response that a retry cannot change (a 400, say).
670
685
  */
671
686
  var TaskAsyncFetchError = class extends Error {
672
- constructor(taskId, cause) {
673
- super(`Failed to fetch status for task ${taskId} after multiple retries`);
687
+ constructor(taskId, cause, status) {
688
+ super(status ? `Failed to fetch status for task ${taskId} (status ${status})` : `Failed to fetch status for task ${taskId} after multiple retries`);
674
689
  this.name = "TaskAsyncFetchError";
675
690
  this.cause = cause;
676
691
  }
@@ -738,7 +753,7 @@ var TaskAsync = class {
738
753
  * @param options.signal - Stops this wait when aborted (see {@link TaskAsyncWaitOptions})
739
754
  * @throws {TaskAsyncTimeoutError} If polling exceeds the timeout
740
755
  * @throws {TaskAsyncUnauthorizedError} If access is denied
741
- * @throws {TaskAsyncFetchError} If fetching status fails repeatedly
756
+ * @throws {TaskAsyncFetchError} If fetching status fails repeatedly, or with a non-retryable 4xx
742
757
  * @throws {TaskAsyncTaskFetchError} If fetching the completed task fails
743
758
  * @throws {TaskAsyncTaskFailedError} If the task fails before completion
744
759
  */
@@ -784,19 +799,24 @@ var TaskAsync = class {
784
799
  const { timeoutMs, fastDurationMs, fastIntervalMs, intervalMs } = this.polling;
785
800
  const startTime = Date.now();
786
801
  let retryCount = 0;
802
+ let rateLimitedCount = 0;
787
803
  let useApiKeyFallback = false;
788
804
  let lastError;
789
805
  while (true) {
790
806
  const elapsed = Date.now() - startTime;
791
807
  if (elapsed >= timeoutMs) throw new TaskAsyncTimeoutError(this.id, timeoutMs);
792
808
  const result = await this.fetchStatus(useApiKeyFallback, signal);
809
+ let rateLimited = false;
793
810
  if (result.ok) {
794
811
  if (result.status === "completed") {
795
812
  const fetched = await this.fetchTask(signal);
796
813
  if (fetched.ok) return this.resultFactory(fetched.data);
797
814
  if (fetched.unauthorized) throw new TaskAsyncUnauthorizedError(this.id);
798
- retryCount++;
799
- if (!fetched.retryable || retryCount >= MAX_RETRY_COUNT) throw new TaskAsyncTaskFetchError(this.id, fetched.status, fetched.error);
815
+ if (fetched.rateLimited) rateLimited = true;
816
+ else {
817
+ retryCount++;
818
+ if (!fetched.retryable || retryCount >= MAX_RETRY_COUNT) throw new TaskAsyncTaskFetchError(this.id, fetched.status, fetched.error);
819
+ }
800
820
  } else if (result.status === "failed") throw new TaskAsyncTaskFailedError(this.id);
801
821
  else retryCount = 0;
802
822
  } else {
@@ -805,13 +825,17 @@ var TaskAsync = class {
805
825
  continue;
806
826
  }
807
827
  if (result.unauthorized) throw new TaskAsyncUnauthorizedError(this.id);
808
- if (result.retryable) {
828
+ if (!result.retryable) throw new TaskAsyncFetchError(this.id, result.error, result.status);
829
+ if (result.rateLimited) rateLimited = true;
830
+ else {
809
831
  retryCount++;
810
832
  lastError = result.error;
811
833
  if (retryCount >= MAX_RETRY_COUNT) throw new TaskAsyncFetchError(this.id, lastError);
812
834
  }
813
835
  }
814
- const interval = (elapsed < fastDurationMs ? fastIntervalMs : intervalMs) + Math.random() * 500;
836
+ rateLimitedCount = rateLimited ? rateLimitedCount + 1 : 0;
837
+ const baseInterval = elapsed < fastDurationMs ? fastIntervalMs : intervalMs;
838
+ const interval = Math.min(baseInterval * 2 ** rateLimitedCount, Math.max(baseInterval, MAX_RATE_LIMITED_INTERVAL_MS)) + Math.random() * 500;
815
839
  const remainingTime = timeoutMs - elapsed;
816
840
  const waitTime = Math.min(interval, remainingTime);
817
841
  await this.sleep(waitTime, signal);
@@ -839,6 +863,12 @@ var TaskAsync = class {
839
863
  retryable: true,
840
864
  notFound: true
841
865
  };
866
+ if (response.status === 429) return {
867
+ ok: false,
868
+ unauthorized: false,
869
+ retryable: true,
870
+ rateLimited: true
871
+ };
842
872
  if (response.status >= 500) return {
843
873
  ok: false,
844
874
  unauthorized: false,
@@ -847,7 +877,8 @@ var TaskAsync = class {
847
877
  return {
848
878
  ok: false,
849
879
  unauthorized: false,
850
- retryable: false
880
+ retryable: false,
881
+ status: response.status
851
882
  };
852
883
  } catch (error) {
853
884
  signal.throwIfAborted();
@@ -871,6 +902,13 @@ var TaskAsync = class {
871
902
  unauthorized: true,
872
903
  retryable: false
873
904
  };
905
+ if (response.status === 429) return {
906
+ ok: false,
907
+ unauthorized: false,
908
+ retryable: true,
909
+ rateLimited: true,
910
+ status: response.status
911
+ };
874
912
  if (response.status === 404 || response.status >= 500) return {
875
913
  ok: false,
876
914
  unauthorized: false,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mynthio/sdk",
3
- "version": "0.0.43",
3
+ "version": "0.0.45",
4
4
  "description": "Official Mynth SDK for image generation and analysis",
5
5
  "keywords": [
6
6
  "ai",
@@ -45,11 +45,12 @@
45
45
  "devDependencies": {
46
46
  "@arethetypeswrong/core": "^0.18.5",
47
47
  "@types/node": "^22.20.4",
48
+ "@vitest/coverage-v8": "^5.0.2",
48
49
  "convex": "^1.46.0",
49
50
  "publint": "^0.3.24",
50
51
  "tsdown": "^0.23.0",
51
52
  "typescript": "7.0.2",
52
- "vitest": "^5.0.1"
53
+ "vitest": "^5.0.2"
53
54
  },
54
55
  "peerDependencies": {
55
56
  "convex": "^1.27.3"
@@ -62,6 +63,7 @@
62
63
  "scripts": {
63
64
  "build": "tsdown",
64
65
  "test": "vitest run",
66
+ "test:coverage": "vitest run --coverage",
65
67
  "test:watch": "vitest",
66
68
  "typecheck": "tsc"
67
69
  }