@picsart/ai-sdk 5.40.0 → 6.1.0

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/index.js CHANGED
@@ -1,31 +1,6 @@
1
+ import { __commonJS, __toESM } from './chunk-4VNS5WPM.js';
1
2
  import { deflateSync, inflateSync } from 'fflate';
2
3
 
3
- var __create = Object.create;
4
- var __defProp = Object.defineProperty;
5
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
- var __getOwnPropNames = Object.getOwnPropertyNames;
7
- var __getProtoOf = Object.getPrototypeOf;
8
- var __hasOwnProp = Object.prototype.hasOwnProperty;
9
- var __commonJS = (cb, mod) => function __require() {
10
- return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
11
- };
12
- var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
- }
18
- return to;
19
- };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- __defProp(target, "default", { value: mod, enumerable: true }) ,
26
- mod
27
- ));
28
-
29
4
  // ../../node_modules/@picsart/pa-model-pricing-sdk/build/lib/errors/ModelPricingClientError.js
30
5
  var require_ModelPricingClientError = __commonJS({
31
6
  "../../node_modules/@picsart/pa-model-pricing-sdk/build/lib/errors/ModelPricingClientError.js"(exports) {
@@ -441,192 +416,6 @@ var require_build = __commonJS({
441
416
  }
442
417
  });
443
418
 
444
- // src/core/errors.ts
445
- var ApiError = class extends Error {
446
- /** HTTP status, or the synthesized equivalent for non-HTTP failures. */
447
- status;
448
- /** Platform `reason`, or an SDK-synthesized code. Always equal to {@link reason}. */
449
- code;
450
- /** Alias of {@link code}, named after the platform's own error field. */
451
- reason;
452
- constructor(message, init) {
453
- super(message);
454
- this.name = "ApiError";
455
- this.status = init.status;
456
- this.code = init.code;
457
- this.reason = init.code;
458
- }
459
- };
460
- var CODE_BY_STATUS = {
461
- 400: "bad_request",
462
- 401: "unauthorized",
463
- 402: "payment_required",
464
- 403: "forbidden",
465
- 404: "not_found",
466
- 408: "timeout",
467
- 409: "conflict",
468
- 413: "payload_too_large",
469
- 422: "unprocessable_entity",
470
- 429: "rate_limited",
471
- 500: "server_error",
472
- 502: "bad_gateway",
473
- 503: "service_unavailable",
474
- 504: "gateway_timeout"
475
- };
476
- function codeForStatus(status) {
477
- return CODE_BY_STATUS[status] ?? (status >= 500 ? "server_error" : `http_${status}`);
478
- }
479
- async function readErrorBody(res) {
480
- let text = "";
481
- try {
482
- text = await res.text();
483
- } catch {
484
- return { text: "" };
485
- }
486
- try {
487
- const parsed = JSON.parse(text);
488
- if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
489
- return { text, json: parsed };
490
- }
491
- } catch {
492
- }
493
- return { text };
494
- }
495
- function reasonFrom(json, status) {
496
- const raw = json?.reason ?? json?.code;
497
- return typeof raw === "string" && raw.length > 0 ? raw : codeForStatus(status);
498
- }
499
-
500
- // src/core/workflow.ts
501
- var DEFAULT_POLL_INTERVAL_MS = 2e3;
502
- var DEFAULT_MAX_ATTEMPTS = 300;
503
- var sleepDefault = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
504
- function getNested(raw, path) {
505
- let current = raw;
506
- for (const key of path) {
507
- if (!current || typeof current !== "object") return void 0;
508
- current = current[key];
509
- }
510
- return current;
511
- }
512
- function pickFirst(raw, paths) {
513
- for (const path of paths) {
514
- const value = getNested(raw, path);
515
- if (value !== void 0) return value;
516
- }
517
- return void 0;
518
- }
519
- function normalizeStatus(status) {
520
- if (typeof status !== "string") return "UNKNOWN";
521
- const s = status.toUpperCase();
522
- if (s === "ACCEPTED") return "ACCEPTED";
523
- if (s === "IN_PROGRESS" || s === "PENDING" || s === "RUNNING") return "IN_PROGRESS";
524
- if (s === "COMPLETED" || s === "SUCCESS") return "COMPLETED";
525
- if (s === "FAILED" || s === "ERROR") return "FAILED";
526
- if (s === "CANCELED" || s === "CANCELLED") return "CANCELED";
527
- return "UNKNOWN";
528
- }
529
- function parseWorkflowStatus(handle, raw) {
530
- const statusRaw = pickFirst(raw, [["response", "status"], ["status"]]);
531
- const status = normalizeStatus(statusRaw);
532
- const result = pickFirst(raw, [["response", "result"], ["result"]]);
533
- const usageRaw = pickFirst(raw, [["response", "usage"], ["usage"]]);
534
- const usage = usageRaw && typeof usageRaw === "object" && (typeof usageRaw.credits === "number" || Array.isArray(usageRaw.details)) ? usageRaw : void 0;
535
- const errorRaw = pickFirst(raw, [["response", "error"], ["response", "message"], ["error"], ["message"], ["reason"]]);
536
- const reasonRaw = pickFirst(raw, [["response", "reason"], ["reason"]]);
537
- const statusCodeRaw = pickFirst(raw, [["response", "statusCode"], ["statusCode"]]);
538
- const progressRaw = pickFirst(raw, [["response", "progress"], ["progress"]]);
539
- const progress = progressRaw && typeof progressRaw === "object" ? {
540
- percent: typeof progressRaw.percent === "number" ? progressRaw.percent : void 0,
541
- estimatedSecondsLeft: typeof progressRaw.estimatedSecondsLeft === "number" ? progressRaw.estimatedSecondsLeft : void 0
542
- } : void 0;
543
- return {
544
- handle,
545
- status,
546
- result,
547
- error: typeof errorRaw === "string" ? errorRaw : void 0,
548
- reason: typeof reasonRaw === "string" ? reasonRaw : void 0,
549
- statusCode: typeof statusCodeRaw === "number" ? statusCodeRaw : void 0,
550
- progress,
551
- usage,
552
- raw
553
- };
554
- }
555
- function isTerminal(status) {
556
- return status === "COMPLETED" || status === "FAILED" || status === "CANCELED";
557
- }
558
- function createWorkflowClient(transport, options = {}) {
559
- const parseStatus = options.parseStatus ?? parseWorkflowStatus;
560
- const sleep2 = options.sleep ?? sleepDefault;
561
- const defaultPollIntervalMs = options.pollingIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;
562
- const defaultMaxAttempts = options.maxAttempts ?? DEFAULT_MAX_ATTEMPTS;
563
- const submit = async (request) => {
564
- if (!transport.submit) {
565
- throw new ApiError("Transport does not support submit (execute-only transport)", {
566
- status: 400,
567
- code: "unsupported_transport"
568
- });
569
- }
570
- return transport.submit(request);
571
- };
572
- const status = async (handle, signal) => {
573
- if (!transport.status) {
574
- throw new ApiError("Transport does not support status (execute-only transport)", {
575
- status: 400,
576
- code: "unsupported_transport"
577
- });
578
- }
579
- const raw = await transport.status(handle, signal);
580
- return parseStatus(handle, raw);
581
- };
582
- const result = async (handle, pollOptions = {}) => {
583
- const intervalMs = pollOptions.intervalMs ?? defaultPollIntervalMs;
584
- const maxAttempts = pollOptions.maxAttempts ?? defaultMaxAttempts;
585
- for (let attempt = 0; attempt < maxAttempts; attempt++) {
586
- if (pollOptions.signal?.aborted) {
587
- throw new ApiError("Operation aborted", { status: 499, code: "aborted" });
588
- }
589
- const next = await status(handle, pollOptions.signal);
590
- if (isTerminal(next.status)) return next;
591
- await sleep2(intervalMs);
592
- }
593
- throw new ApiError(
594
- `Timed out waiting for workflow ${handle.workflow}:${handle.id}`,
595
- { status: 408, code: "timeout" }
596
- );
597
- };
598
- const run = async (request, runOptions = {}) => {
599
- const runMode = runOptions.mode;
600
- const useExecute = runMode === "sync" || runMode === void 0 && !transport.submit;
601
- if (useExecute) {
602
- const raw = await transport.execute(request);
603
- const syntheticHandle = { workflow: request.workflow, id: "sync" };
604
- const parsed = parseStatus(syntheticHandle, raw);
605
- return parsed.status === "UNKNOWN" ? { ...parsed, status: "COMPLETED" } : parsed;
606
- }
607
- const handle = await submit(request);
608
- return result(handle, runOptions);
609
- };
610
- const subscribe = async function* (handle, subscribeOptions = {}) {
611
- const intervalMs = subscribeOptions.intervalMs ?? defaultPollIntervalMs;
612
- const maxAttempts = subscribeOptions.maxAttempts ?? defaultMaxAttempts;
613
- for (let attempt = 0; attempt < maxAttempts; attempt++) {
614
- if (subscribeOptions.signal?.aborted) {
615
- throw new ApiError("Operation aborted", { status: 499, code: "aborted" });
616
- }
617
- const next = await status(handle, subscribeOptions.signal);
618
- yield next;
619
- if (isTerminal(next.status)) return next;
620
- await sleep2(intervalMs);
621
- }
622
- throw new ApiError(
623
- `Timed out waiting for workflow ${handle.workflow}:${handle.id}`,
624
- { status: 408, code: "timeout" }
625
- );
626
- };
627
- return { submit, status, result, run, subscribe };
628
- }
629
-
630
419
  // src/core/descriptors/utils.ts
631
420
  function extractDefaults(params2) {
632
421
  const defaults = {};
@@ -851,11 +640,47 @@ function transferValues(newParams, prev) {
851
640
  return ctx;
852
641
  }
853
642
 
643
+ // src/core/errors.ts
644
+ var ApiError = class extends Error {
645
+ /** HTTP status, or the synthesized equivalent for non-HTTP failures. */
646
+ status;
647
+ /** Platform `reason`, or an SDK-synthesized code. Always equal to {@link reason}. */
648
+ code;
649
+ /** Alias of {@link code}, named after the platform's own error field. */
650
+ reason;
651
+ constructor(message, init) {
652
+ super(message);
653
+ this.name = "ApiError";
654
+ this.status = init.status;
655
+ this.code = init.code;
656
+ this.reason = init.code;
657
+ }
658
+ };
659
+ var CODE_BY_STATUS = {
660
+ 400: "bad_request",
661
+ 401: "unauthorized",
662
+ 402: "payment_required",
663
+ 403: "forbidden",
664
+ 404: "not_found",
665
+ 408: "timeout",
666
+ 409: "conflict",
667
+ 413: "payload_too_large",
668
+ 422: "unprocessable_entity",
669
+ 429: "rate_limited",
670
+ 500: "server_error",
671
+ 502: "bad_gateway",
672
+ 503: "service_unavailable",
673
+ 504: "gateway_timeout"
674
+ };
675
+ function codeForStatus(status) {
676
+ return CODE_BY_STATUS[status] ?? (status >= 500 ? "server_error" : `http_${status}`);
677
+ }
678
+
854
679
  // src/core/visibility.ts
855
680
  var DEFAULT_VISIBLE_RELEASES = ["production", "general-availability"];
856
681
  var releaseOf = (m) => m.release ?? "production";
857
682
  function isVisibleForReleases(m, releases = DEFAULT_VISIBLE_RELEASES) {
858
- if (m.disabled || m.deprecated) return false;
683
+ if (m.deprecated) return false;
859
684
  return releases.includes(releaseOf(m));
860
685
  }
861
686
 
@@ -1290,7 +1115,6 @@ function defineModels(provider, configs) {
1290
1115
  if (c.pollOptions !== void 0) model.pollOptions = c.pollOptions;
1291
1116
  if (c.badge !== void 0) model.badge = c.badge;
1292
1117
  if (c.addedAt !== void 0) model.addedAt = c.addedAt;
1293
- if (c.disabled !== void 0) model.disabled = c.disabled;
1294
1118
  if (c.deprecated !== void 0) model.deprecated = c.deprecated;
1295
1119
  if (c.release !== void 0) model.release = c.release;
1296
1120
  if (c.modelId !== void 0) model.modelId = c.modelId;
@@ -1523,23 +1347,6 @@ var klingOmniAdvancedParams = {
1523
1347
  };
1524
1348
 
1525
1349
  // src/vendors/catalog/kling/index.ts
1526
- var KLING_DUAL_IMAGE_EFFECTS = /* @__PURE__ */ new Set([
1527
- "pet_skateboard",
1528
- "daily_ootd",
1529
- "toss_run",
1530
- "switch_to_silk",
1531
- "studio_look",
1532
- "french_elegance",
1533
- "finger_swipe",
1534
- "smooth_transition",
1535
- "kiss_pro",
1536
- "snow_night_kiss",
1537
- "eternal_kiss",
1538
- "cheers_2026",
1539
- "fight_pro",
1540
- "hug_pro",
1541
- "heart_gesture_pro"
1542
- ]);
1543
1350
  var V3_DURATIONS = [3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
1544
1351
  var V26_DURATIONS = [5, 10];
1545
1352
  var KLING_IMAGE_AR = ["16:9", "9:16", "1:1", "21:9", "4:3", "3:2", "2:3", "3:4"];
@@ -1893,7 +1700,7 @@ var { MODELS } = defineModels("kling", [
1893
1700
  id: "kling-elements",
1894
1701
  name: "Kling Elements",
1895
1702
  addedAt: "2026-05-11",
1896
- disabled: true,
1703
+ release: "preview",
1897
1704
  // pending backend toolId + pricing confirmation
1898
1705
  workflow: "kling-elements",
1899
1706
  estimatedTime: 30,
@@ -2232,10 +2039,27 @@ var buildKlingElementsPayload = (input) => {
2232
2039
  ...input.elementVoiceId ? { element_voice_id: input.elementVoiceId } : {}
2233
2040
  };
2234
2041
  };
2042
+ var DUAL_IMAGE_EFFECTS = /* @__PURE__ */ new Set([
2043
+ "pet_skateboard",
2044
+ "daily_ootd",
2045
+ "toss_run",
2046
+ "switch_to_silk",
2047
+ "studio_look",
2048
+ "french_elegance",
2049
+ "finger_swipe",
2050
+ "smooth_transition",
2051
+ "kiss_pro",
2052
+ "snow_night_kiss",
2053
+ "eternal_kiss",
2054
+ "cheers_2026",
2055
+ "fight_pro",
2056
+ "hug_pro",
2057
+ "heart_gesture_pro"
2058
+ ]);
2235
2059
  var buildKlingVideoEffectsPayload = (input) => {
2236
- const scene = input.templateId ?? input.style;
2060
+ const scene = input.templateId;
2237
2061
  const catalogItem = getHydratedCatalog({ workflow: "kling/v1/catalog/templates" })?.items.find((item) => item.id === scene);
2238
- const slots = typeof catalogItem?.meta?.imageSlots === "number" ? catalogItem.meta.imageSlots : scene && KLING_DUAL_IMAGE_EFFECTS.has(scene) ? 2 : 1;
2062
+ const slots = typeof catalogItem?.meta?.imageSlots === "number" ? catalogItem.meta.imageSlots : scene && DUAL_IMAGE_EFFECTS.has(scene) ? 2 : 1;
2239
2063
  const uploaded = input.imageUrls?.length ?? 0;
2240
2064
  if (uploaded < slots) {
2241
2065
  throw new ApiError(`Kling Video Effects: the "${scene}" effect requires ${slots} image${slots > 1 ? "s" : ""} (got ${uploaded}).`, { status: 400, code: "validation_error" });
@@ -4734,8 +4558,8 @@ var GEMINI_DEFAULT_VOICE_ID = "Kore";
4734
4558
  var DEFAULT_GROK_VOICE_ID = "eve";
4735
4559
  var ASYNC_DEFAULT_VOICE_ID = "cca0e076-b350-4966-b570-4c2fca50b525";
4736
4560
  var SEEDAUDIO_DEFAULT_VOICE_ID = "en_male_tim_uranus_bigtts";
4737
- function getVoiceById(id, extra) {
4738
- return [...extra ?? [], ...getHydratedVoices()].find((v) => v.id === id);
4561
+ function getVoiceById(id) {
4562
+ return getHydratedVoices().find((v) => v.id === id);
4739
4563
  }
4740
4564
 
4741
4565
  // src/vendors/catalog/seedaudio.ts
@@ -6566,7 +6390,7 @@ var { MODELS: MODELS23 } = defineModels("elevenlabs", [
6566
6390
  estimatedTime: 15,
6567
6391
  mode: "audio",
6568
6392
  inputType: "tts",
6569
- disabled: true,
6393
+ release: "preview",
6570
6394
  description: "Remix voice characteristics by describing the desired vocal style.",
6571
6395
  features: [feat("Voice Design", "characteristic"), feat("Remix", "characteristic")],
6572
6396
  paramConfig: {
@@ -6735,9 +6559,6 @@ var { MODELS: MODELS24 } = defineModels("heygen", [
6735
6559
  ]);
6736
6560
 
6737
6561
  // src/vendors/catalog/minimax.ts
6738
- var buildMinimaxTTSPayload = (ctx) => ({
6739
- text: ctx.prompt
6740
- });
6741
6562
  var buildMinimaxMusicPayload = (ctx) => ({
6742
6563
  prompt: ctx.prompt,
6743
6564
  ...ctx.lyricsPrompt ? { lyrics: ctx.lyricsPrompt } : {},
@@ -6788,25 +6609,9 @@ var h3MaxConstraints = [
6788
6609
  } }
6789
6610
  ];
6790
6611
  var { MODELS: MODELS25 } = defineModels("minimax", [
6791
- {
6792
- id: "minimax-02-hd",
6793
- name: "MiniMax 02 HD",
6794
- modelId: "minimax-02-hd",
6795
- addedAt: "2026-02-06",
6796
- workflow: "minimax-tts",
6797
- buildPayload: buildMinimaxTTSPayload,
6798
- estimatedTime: 15,
6799
- mode: "audio",
6800
- inputType: "tts",
6801
- disabled: true,
6802
- // Backend workflow not deployed
6803
- description: "HD voice synthesis with rich tonal depth and consistent delivery.",
6804
- features: [feat("Consistent", "characteristic"), feat("Cinematic", "characteristic")],
6805
- paramConfig: {
6806
- ...params.language(true),
6807
- ...params.prompt({ maxLength: 150 })
6808
- }
6809
- },
6612
+ // minimax-02-hd (minimax-tts) was removed in 6.0: its backend workflow was
6613
+ // never deployed anywhere, so no generation ever existed to resolve — nothing
6614
+ // to deprecate. Re-add as a fresh entry if MiniMax TTS ever ships.
6810
6615
  {
6811
6616
  id: "minimax-music-v2",
6812
6617
  name: "MiniMax Music v2",
@@ -9371,7 +9176,7 @@ var ALL_MODELS = [
9371
9176
  ...MODELS36,
9372
9177
  ...MODELS37
9373
9178
  ];
9374
- var getModelsByMode = (mode, includeDisabled = false) => ALL_MODELS.filter((m) => m.mode === mode && (includeDisabled || isVisibleForReleases(m)));
9179
+ var getModelsByMode = (mode, includeHidden = false) => ALL_MODELS.filter((m) => m.mode === mode && (includeHidden || isVisibleForReleases(m)));
9375
9180
 
9376
9181
  // src/core/contracts.ts
9377
9182
  function requireObject(value, message) {
@@ -9416,9 +9221,6 @@ function createModelContract(model) {
9416
9221
  output: buildOutputSchema(model)
9417
9222
  };
9418
9223
  }
9419
- function validateModelInput(model, input) {
9420
- return createModelContract(model).input.parse(input);
9421
- }
9422
9224
  var _contracts = null;
9423
9225
  function ensureContracts() {
9424
9226
  if (!_contracts) {
@@ -9457,10 +9259,7 @@ function throwIfErrorResult(result, modelName) {
9457
9259
  function extractSyncResult(raw) {
9458
9260
  if (!raw || typeof raw !== "object") return raw;
9459
9261
  const data = raw;
9460
- const syncResult = data.response?.result ?? data.result;
9461
- const sr = syncResult;
9462
- const imgs = sr && Array.isArray(sr.images) ? sr.images : null;
9463
- return imgs?.length ? imgs[0] : syncResult;
9262
+ return data.response?.result ?? data.result;
9464
9263
  }
9465
9264
  var extractUrl = (result) => {
9466
9265
  if (Array.isArray(result)) return extractUrl(result[0]);
@@ -9586,27 +9385,42 @@ var extractText = (result) => {
9586
9385
  }
9587
9386
  return void 0;
9588
9387
  };
9388
+ var RESULT_ARRAY_KEYS = ["items", "images", "imageUrls", "urls", "data", "previews"];
9589
9389
  var extractAllResults = (result) => {
9590
9390
  if (!result || typeof result !== "object") return void 0;
9591
9391
  const obj = result;
9592
- if (Array.isArray(obj.items) && obj.items.length > 1) {
9593
- const items = [];
9594
- for (const item of obj.items) {
9595
- if (item && typeof item === "object") {
9596
- const it = item;
9597
- const url = typeof it.url === "string" ? it.url : void 0;
9598
- if (url) {
9599
- items.push({
9600
- url,
9601
- exploreImageId: typeof it.image_id === "string" ? it.image_id : void 0
9602
- });
9603
- }
9604
- }
9392
+ let arr;
9393
+ for (const key of RESULT_ARRAY_KEYS) {
9394
+ const candidate = obj[key];
9395
+ if (Array.isArray(candidate) && candidate.length > 1) {
9396
+ arr = candidate;
9397
+ break;
9605
9398
  }
9606
- if (items.length > 0) return items;
9607
9399
  }
9608
- return void 0;
9400
+ if (!arr) return void 0;
9401
+ const items = [];
9402
+ for (const entry of arr) {
9403
+ if (typeof entry === "string") {
9404
+ items.push({ url: entry });
9405
+ continue;
9406
+ }
9407
+ if (entry && typeof entry === "object") {
9408
+ const it = entry;
9409
+ if (typeof it.url === "string") items.push({ url: it.url, source: it });
9410
+ }
9411
+ }
9412
+ return items.length > 0 ? items : void 0;
9609
9413
  };
9414
+ function buildItemMetadata(parsed, item, _index, provider) {
9415
+ const meta = {};
9416
+ const top = parsed && typeof parsed === "object" ? parsed : void 0;
9417
+ const it = item && typeof item === "object" && !Array.isArray(item) ? item : void 0;
9418
+ if (provider === "recraft" && typeof it?.image_id === "string") meta.exploreImageId = it.image_id;
9419
+ if (provider === "elevenlabs" && typeof it?.generated_voice_id === "string") meta.generatedVoiceId = it.generated_voice_id;
9420
+ const lastFrame = it?.last_frame_url ?? top?.last_frame_url;
9421
+ if (typeof lastFrame === "string") meta.lastFrameUrl = lastFrame;
9422
+ return Object.keys(meta).length > 0 ? meta : void 0;
9423
+ }
9610
9424
  function toCompletedStatus(handle, result, raw, usage) {
9611
9425
  return {
9612
9426
  handle,
@@ -9659,1132 +9473,1792 @@ function resolveModel(id) {
9659
9473
  return found;
9660
9474
  }
9661
9475
 
9662
- // src/client/transport.ts
9663
- var GATEWAY_HEADERS = {
9664
- "platform": "api",
9665
- "X-Touchpoint": "sdk"
9476
+ // ../../node_modules/@picsart/workflows-client/dist/index.mjs
9477
+ var logger_default = {
9478
+ error: (...args) => {
9479
+ console.error(...args);
9480
+ },
9481
+ warn: (...args) => {
9482
+ console.debug(...args);
9483
+ },
9484
+ info: (...args) => {
9485
+ console.info(...args);
9486
+ },
9487
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
9488
+ debug: (...args) => {
9489
+ console.debug(...args);
9490
+ }
9666
9491
  };
9667
- function resolveFetch(config) {
9668
- if (config.fetch) return config.fetch;
9669
- if (config.apiKey) {
9670
- const token = config.apiKey.replace(/^Bearer\s+/i, "");
9671
- return (url, init) => {
9672
- const headers = new Headers(init?.headers);
9673
- headers.set("Authorization", `Bearer ${token}`);
9674
- for (const [name, value] of Object.entries(GATEWAY_HEADERS)) {
9675
- if (!headers.has(name)) headers.set(name, value);
9492
+ var ExecutionMode = /* @__PURE__ */ ((ExecutionMode2) => {
9493
+ ExecutionMode2["ASYNC"] = "ASYNC";
9494
+ ExecutionMode2["SYNC"] = "SYNC";
9495
+ ExecutionMode2["STREAM"] = "STREAM";
9496
+ ExecutionMode2["SOCKET"] = "SOCKET";
9497
+ return ExecutionMode2;
9498
+ })(ExecutionMode || {});
9499
+ var STREAM_EVENT_NAME = "task.stream";
9500
+ var normalizeWorkflowName = (workflow) => (workflow || "").replace(/-/g, "_").toLowerCase();
9501
+ var taskChannel = (workflow, taskId) => `workflows:${normalizeWorkflowName(workflow)}:${taskId}`;
9502
+ var workflowChannel = (workflow) => `workflows:${normalizeWorkflowName(workflow)}:all`;
9503
+ var DEFAULT_REASON = "unknown_error";
9504
+ var DEFAULT_MESSAGE = "Unknown error";
9505
+ var NON_JSON_BODY_MESSAGE = "Non json response was returned from server";
9506
+ var asRecord = (value) => value && typeof value === "object" ? value : void 0;
9507
+ var asText = (value) => typeof value === "string" && value.length > 0 ? value : void 0;
9508
+ var asStatusCode = (value) => typeof value === "number" && Number.isFinite(value) ? value : void 0;
9509
+ var WorkflowsError = class _WorkflowsError extends Error {
9510
+ constructor(init) {
9511
+ super(init.message);
9512
+ this.name = this.constructor.name;
9513
+ this.reason = init.reason;
9514
+ this.httpStatusCode = init.httpStatusCode;
9515
+ }
9516
+ /**
9517
+ * Builds an error from an already-parsed error payload — a `FailedResult` off a stream/socket
9518
+ * event, or any body with `reason` / `message` / `statusCode`. Each field falls back to
9519
+ * `fallback` individually, so a payload that carries only a message still keeps the caller's
9520
+ * reason and status.
9521
+ */
9522
+ static fromBody(body, fallback) {
9523
+ const parsed = asRecord(body);
9524
+ return new _WorkflowsError({
9525
+ reason: asText(parsed?.reason) || fallback.reason,
9526
+ message: asText(parsed?.message) || fallback.message,
9527
+ httpStatusCode: asStatusCode(parsed?.statusCode) ?? fallback.httpStatusCode
9528
+ });
9529
+ }
9530
+ /**
9531
+ * Builds an error from a non-ok `Response`. The status always comes from the response itself;
9532
+ * `reason` and `message` come from the JSON body when it has them, otherwise from `fallback`
9533
+ * (a body that isn't JSON at all is reported as such rather than throwing a parse error).
9534
+ */
9535
+ static async fromResponse(response, fallback) {
9536
+ let body;
9537
+ try {
9538
+ body = await response.json();
9539
+ } catch {
9540
+ body = void 0;
9541
+ }
9542
+ const parsed = asRecord(body);
9543
+ return new _WorkflowsError({
9544
+ reason: asText(parsed?.reason) || fallback?.reason || DEFAULT_REASON,
9545
+ message: asText(parsed?.message) || fallback?.message || (parsed ? DEFAULT_MESSAGE : NON_JSON_BODY_MESSAGE),
9546
+ httpStatusCode: response.status
9547
+ });
9548
+ }
9549
+ /** Wraps an unexpected local throw (anything that isn't already a WorkflowsError). */
9550
+ static fromUnknown(error) {
9551
+ return new _WorkflowsError({
9552
+ reason: DEFAULT_REASON,
9553
+ message: (error instanceof Error ? error.message : asText(error)) || DEFAULT_MESSAGE
9554
+ });
9555
+ }
9556
+ };
9557
+ var WorkflowResultUpdateAware = class {
9558
+ constructor(onProgressFn, onPartialResultFn, onEventFn) {
9559
+ this.onProgressFn = onProgressFn;
9560
+ this.onPartialResultFn = onPartialResultFn;
9561
+ this.onEventFn = onEventFn;
9562
+ }
9563
+ async onUpdate(response) {
9564
+ if (!response.updated) return;
9565
+ await this.deliverEvents(response);
9566
+ if (response.status !== "IN_PROGRESS") return;
9567
+ const newUpdated = new Date(response.updated);
9568
+ if (newUpdated?.getTime() !== this.updated?.getTime()) {
9569
+ this.updated = newUpdated;
9570
+ await this.onPartialResultFn?.(response);
9571
+ if (response.progress) {
9572
+ await this.onProgressFn?.(response.progress);
9676
9573
  }
9677
- return globalThis.fetch(url, { ...init, headers });
9678
- };
9574
+ }
9679
9575
  }
9680
- throw new Error("createClient config requires either `fetch` or `apiKey`.");
9681
- }
9682
- function buildTransport(config) {
9683
- const apiUrl = config.apiUrl;
9684
- const f = resolveFetch(config);
9685
- const jsonPost = async (url, body, signal) => f(url, {
9686
- method: "POST",
9687
- headers: { "Content-Type": "application/json" },
9688
- body: JSON.stringify(body),
9689
- signal
9690
- });
9691
- return {
9692
- async submit(request) {
9693
- const res = await jsonPost(
9694
- `${apiUrl}/workflows/${request.workflow}/submit`,
9695
- { params: request.payload },
9696
- request.signal
9697
- );
9698
- const { text, json } = await readErrorBody(res);
9699
- if (!res.ok) {
9700
- const detail = json ? json.message ?? JSON.stringify(json) : text;
9701
- throw new ApiError(`Submit failed (${res.status}): ${detail}`, {
9702
- status: res.status,
9703
- code: reasonFrom(json, res.status)
9704
- });
9576
+ async deliverEvents(response) {
9577
+ if (!response.events?.length || !this.onEventFn) return;
9578
+ let startIdx = 0;
9579
+ if (this._lastEventId) {
9580
+ const lastSeenIdx = response.events.findIndex((e) => e.id === this._lastEventId);
9581
+ if (lastSeenIdx !== -1) {
9582
+ startIdx = lastSeenIdx + 1;
9705
9583
  }
9706
- const response = json?.response;
9707
- const id = response?.id ?? json?.id;
9708
- if (!id) {
9709
- throw new ApiError(`No task id in response: ${json ? JSON.stringify(json) : text}`, {
9710
- status: 502,
9711
- code: "invalid_response"
9712
- });
9713
- }
9714
- return { workflow: request.workflow, id: String(id) };
9715
- },
9716
- async status(handle, signal) {
9717
- const res = await f(`${apiUrl}/workflows/${handle.workflow}/${handle.id}/result`, { signal });
9718
- if (!res.ok) {
9719
- const { text, json } = await readErrorBody(res);
9720
- const detail = json ? json.message ?? text : text;
9721
- throw new ApiError(`Status check failed (${res.status}): ${detail}`, {
9722
- status: res.status,
9723
- code: reasonFrom(json, res.status)
9584
+ }
9585
+ const newEvents = response.events.slice(startIdx);
9586
+ for (const event of newEvents) {
9587
+ await this.onEventFn(event);
9588
+ }
9589
+ if (newEvents.length > 0) {
9590
+ this._lastEventId = newEvents[newEvents.length - 1].id;
9591
+ }
9592
+ }
9593
+ };
9594
+ var bearer = (token) => token.startsWith("Bearer ") ? token : `Bearer ${token}`;
9595
+ var WorkflowsSocket = class {
9596
+ constructor(config) {
9597
+ this.config = config;
9598
+ this.ownsSocket = false;
9599
+ this.channelRefs = /* @__PURE__ */ new WeakMap();
9600
+ }
9601
+ // Watch already-submitted work live, as an async iterable of the raw StreamSocketMessage the gateway
9602
+ // pushes. Iterate with `for await` and switch on `msg.type` (EventTypes.* or an `event.<custom>`
9603
+ // string), reading `msg.payload`. With a taskId, watch that one task and end after its COMPLETED /
9604
+ // FAILED; without, watch every task of the workflow until stopped. A lost socket session (or the
9605
+ // passed AbortSignal) is THROWN out of the loop; `break` also stops watching — the `finally` tears
9606
+ // everything down.
9607
+ async *subscribe(options) {
9608
+ if (!this.config.socket && !this.config.socketConnection) {
9609
+ throw new WorkflowsError({
9610
+ httpStatusCode: 400,
9611
+ reason: "invalid_state",
9612
+ message: "subscribe() requires either `socket` or `socketConnection` on the client."
9613
+ });
9614
+ }
9615
+ if (options.signal?.aborted) throw new DOMException("Aborted", "AbortError");
9616
+ const channel = options.taskId ? taskChannel(options.name, options.taskId) : workflowChannel(options.name);
9617
+ this.assertValidChannel(channel);
9618
+ const socket = await this.resolveSocket();
9619
+ if (!socket) return;
9620
+ if (options.signal?.aborted) throw new DOMException("Aborted", "AbortError");
9621
+ const workflow = normalizeWorkflowName(options.name);
9622
+ const queue = [];
9623
+ let wake;
9624
+ const push = (item) => {
9625
+ queue.push(item);
9626
+ const w = wake;
9627
+ wake = void 0;
9628
+ w?.();
9629
+ };
9630
+ const handler = (message) => {
9631
+ if (!message) return;
9632
+ const mine = options.taskId ? message.taskId === options.taskId : message.workflow === workflow;
9633
+ if (mine) push({ msg: message });
9634
+ };
9635
+ socket.on(STREAM_EVENT_NAME, handler);
9636
+ const streamEnded = (detail) => push({ error: new WorkflowsError({
9637
+ httpStatusCode: 503,
9638
+ reason: "socket_connection_lost",
9639
+ message: `Lost the socket connection (${detail}); the event stream ended.`
9640
+ }) });
9641
+ const detachReconnect = this.onSessionLost(socket, () => streamEnded("the session could not be recovered on reconnect"));
9642
+ const detachAbandoned = this.onConnectAbandoned(socket, (err) => streamEnded(
9643
+ `socket.io stopped reconnecting after "${err instanceof Error ? err.message : String(err)}"`
9644
+ ));
9645
+ const detachDisconnect = this.onDisconnected(socket, (reason) => streamEnded(`"${reason}"`));
9646
+ const onAbort = () => push({ error: new DOMException("Aborted", "AbortError") });
9647
+ options.signal?.addEventListener("abort", onAbort);
9648
+ this.joinChannel(socket, channel);
9649
+ try {
9650
+ while (true) {
9651
+ while (queue.length) {
9652
+ const item = queue.shift();
9653
+ if ("error" in item) throw item.error;
9654
+ yield item.msg;
9655
+ if (options.taskId && (item.msg.type === "task.completed" || item.msg.type === "task.failed")) return;
9656
+ }
9657
+ await new Promise((resolve) => {
9658
+ wake = resolve;
9724
9659
  });
9725
9660
  }
9726
- return res.json();
9727
- },
9728
- async execute(request) {
9729
- const res = await jsonPost(
9730
- `${apiUrl}/workflows/${request.workflow}/execute`,
9731
- { params: request.payload },
9732
- request.signal
9733
- );
9734
- if (!res.ok) {
9735
- const { text, json } = await readErrorBody(res);
9736
- const detail = json ? json.message ?? text : text;
9737
- throw new ApiError(`Execute failed (${res.status}): ${detail}`, {
9738
- status: res.status,
9739
- code: reasonFrom(json, res.status)
9740
- });
9661
+ } finally {
9662
+ options.signal?.removeEventListener("abort", onAbort);
9663
+ this.leaveChannel(socket, channel);
9664
+ socket.off(STREAM_EVENT_NAME, handler);
9665
+ detachReconnect();
9666
+ detachAbandoned();
9667
+ detachDisconnect();
9668
+ }
9669
+ }
9670
+ // Opens the socket (create + connect for socketConnection; return an injected one). Idempotent —
9671
+ // resolveSocket memoizes, so repeated calls reuse the same connection.
9672
+ connect() {
9673
+ return this.resolveSocket();
9674
+ }
9675
+ // Disconnects the socket ONLY if this class created it (socketConnection); an injected socket is
9676
+ // left for the caller to manage. Safe to call more than once.
9677
+ async disconnect() {
9678
+ if (!this.ownsSocket || !this.socketPromise) return;
9679
+ const socket = await this.socketPromise.catch(() => void 0);
9680
+ socket?.disconnect();
9681
+ this.socketPromise = void 0;
9682
+ this.ownsSocket = false;
9683
+ }
9684
+ // Backs run({ mode: ExecutionMode.SOCKET }). Joins the workflow channel and starts listening BEFORE
9685
+ // submitting, so no early event is missed — the per-task channel can't be joined until submit mints
9686
+ // the taskId. Events seen before we know our taskId are buffered, then matched once we have it (the
9687
+ // workflow room carries sibling tasks, so the taskId filter is load-bearing).
9688
+ // `markSeen` is fired with the taskId the moment a terminal (COMPLETED/FAILED) event is received — the
9689
+ // socket-mode equivalent of the polling client fetching /result, which is what disabled the task's
9690
+ // pending notification server-side. Fired for both terminal outcomes (matching the old poll, which
9691
+ // disabled on COMPLETED and FAILED alike) and ONLY on a real terminal event — never on a lost session,
9692
+ // abort, or connect error, so an unconsumed result still triggers the async fallback notification.
9693
+ // It's best-effort: runTask fires it without awaiting and swallows any rejection, since a failed disable
9694
+ // only costs a redundant fallback notification and must never fail the run.
9695
+ async runTask(workflowName, submit, executionOptions, markSeen) {
9696
+ const signal = executionOptions?.abortSignal;
9697
+ await this.ensureSocketReady(workflowName, signal);
9698
+ const { onProgress, onPartialResult, onEvent } = executionOptions ?? {};
9699
+ const ac = new AbortController();
9700
+ const forwardAbort = () => ac.abort();
9701
+ signal?.addEventListener("abort", forwardAbort);
9702
+ const iter = this.subscribe({ name: workflowName, signal: ac.signal })[Symbol.asyncIterator]();
9703
+ const firstPull = iter.next();
9704
+ firstPull.catch(() => {
9705
+ });
9706
+ try {
9707
+ const taskId = await submit();
9708
+ for (let pull = firstPull; ; pull = iter.next()) {
9709
+ const { value: message, done } = await pull;
9710
+ if (done) break;
9711
+ if (message.taskId !== taskId) continue;
9712
+ switch (message.type) {
9713
+ case "task.completed":
9714
+ void Promise.resolve(markSeen?.(taskId)).catch(() => void 0);
9715
+ return {
9716
+ result: message.payload?.result,
9717
+ usage: message.payload?.usage,
9718
+ status: "COMPLETED"
9719
+ /* COMPLETED */
9720
+ // a FAILED message throws below instead
9721
+ };
9722
+ case "task.failed":
9723
+ void Promise.resolve(markSeen?.(taskId)).catch(() => void 0);
9724
+ throw this.failureError(message.payload?.result ?? message.payload);
9725
+ case "task.metrics":
9726
+ await onProgress?.(message.payload);
9727
+ break;
9728
+ case "task.partial-result":
9729
+ await onPartialResult?.({ status: "IN_PROGRESS", result: message.payload });
9730
+ break;
9731
+ default:
9732
+ if (message.type.startsWith("event.")) {
9733
+ await onEvent?.({ ...message.payload, type: message.type.replace(/^event\./, "") });
9734
+ }
9735
+ }
9741
9736
  }
9742
- return res.json();
9743
- },
9744
- async options(workflow, payload) {
9737
+ throw new WorkflowsError({
9738
+ httpStatusCode: 500,
9739
+ reason: "socket_stream_ended",
9740
+ message: "Socket stream ended before the task completed."
9741
+ });
9742
+ } finally {
9743
+ signal?.removeEventListener("abort", forwardAbort);
9744
+ ac.abort();
9745
+ await iter.return?.();
9746
+ }
9747
+ }
9748
+ // Pre-submit gate for runTask: validate the channel and get the socket connected before any work is
9749
+ // submitted. The socket itself isn't returned — subscribe() re-resolves it — this only proves it's
9750
+ // reachable and honors an abort that fired before (or during) connecting, since addEventListener('abort')
9751
+ // never fires for an already-aborted signal.
9752
+ async ensureSocketReady(workflowName, signal) {
9753
+ if (signal?.aborted) throw new DOMException("Aborted", "AbortError");
9754
+ const channel = workflowChannel(workflowName);
9755
+ this.assertValidChannel(channel);
9756
+ const socket = await this.resolveSocket();
9757
+ if (!socket) {
9758
+ throw new WorkflowsError({
9759
+ httpStatusCode: 400,
9760
+ reason: "invalid_state",
9761
+ message: "ExecutionMode.SOCKET requires either `socket` or `socketConnection` on the client."
9762
+ });
9763
+ }
9764
+ if (signal?.aborted) throw new DOMException("Aborted", "AbortError");
9765
+ }
9766
+ // Fails a run/subscription when a reconnect couldn't be recovered. The gateway has Connection State
9767
+ // Recovery: a reconnect within its window restores our room and replays missed events, so there's
9768
+ // nothing to do; past the window `recovered` is false and the stream is gone — and we don't refetch
9769
+ // from the DB. We only wire this after the socket is connected, so any 'connect' here is a reconnect.
9770
+ // Returns a function to detach the listener on teardown.
9771
+ onSessionLost(socket, onLost) {
9772
+ const listener = () => {
9773
+ if (!socket.recovered) onLost();
9774
+ };
9775
+ socket.on("connect", listener);
9776
+ return () => socket.off("connect", listener);
9777
+ }
9778
+ // The other half of onSessionLost, for the case it can't see: a connect attempt that FAILS rather than
9779
+ // succeeding — typically a reconnect whose handshake the gateway rejects (an expired token). No
9780
+ // 'connect' event ever fires then, so onSessionLost stays silent and the watcher parks forever on a
9781
+ // socket that will never deliver again. `socket.active` says whether socket.io intends to keep trying:
9782
+ // still true while it retries a transient transport failure (a blip Connection State Recovery papers
9783
+ // over — ignore it, or we'd fail runs that were about to resume), false once it has given up. Only
9784
+ // that second case is terminal, and it covers BOTH a server-side rejection (never retried) and
9785
+ // reconnectionAttempts running out, which is why the caller reports the error rather than a cause.
9786
+ // Returns a detach function.
9787
+ onConnectAbandoned(socket, onAbandoned) {
9788
+ const listener = (err) => {
9789
+ if (socket.active === false) onAbandoned(err);
9790
+ };
9791
+ socket.on("connect_error", listener);
9792
+ return () => socket.off("connect_error", listener);
9793
+ }
9794
+ // The third and last way this socket can go quiet for good: it disconnects and nothing is coming back
9795
+ // — `client.disconnect()` called while a watch is live ('io client disconnect'), or the gateway closing
9796
+ // us out ('io server disconnect'). Neither produces a 'connect' or a 'connect_error', so without this
9797
+ // the watcher parks forever on a socket that is simply gone. `active` splits the cases here too, as
9798
+ // socket.io documents: still true for a transport close or ping timeout, which it retries and CSR
9799
+ // papers over; false once the connection was closed for good. Returns a detach function.
9800
+ onDisconnected(socket, onGone) {
9801
+ const listener = (reason) => {
9802
+ if (socket.active === false) onGone(reason);
9803
+ };
9804
+ socket.on("disconnect", listener);
9805
+ return () => socket.off("disconnect", listener);
9806
+ }
9807
+ resolveSocket() {
9808
+ if (this.socketPromise) return this.socketPromise;
9809
+ const { socket, socketConnection } = this.config;
9810
+ if (!socket && !socketConnection) return Promise.resolve(void 0);
9811
+ const promise = (async () => {
9812
+ const resolved = socket ?? await this.createSocket(socketConnection);
9813
+ this.ownsSocket = !socket;
9745
9814
  try {
9746
- const res = await jsonPost(`${apiUrl}/workflows/${workflow}/options`, { params: payload });
9747
- if (!res.ok) return null;
9748
- const data = await res.json();
9749
- const response = data.response;
9750
- const credits = response?.credits;
9751
- return typeof credits === "number" ? credits : null;
9752
- } catch {
9753
- return null;
9815
+ await this.whenConnected(resolved);
9816
+ } catch (err) {
9817
+ if (!socket) {
9818
+ resolved.disconnect();
9819
+ this.ownsSocket = false;
9820
+ }
9821
+ throw err;
9754
9822
  }
9823
+ return resolved;
9824
+ })();
9825
+ promise.catch(() => {
9826
+ if (this.socketPromise === promise) this.socketPromise = void 0;
9827
+ });
9828
+ this.socketPromise = promise;
9829
+ return promise;
9830
+ }
9831
+ // Resolves once the socket's transport is up; rejects if the connection fails (so callers surface an
9832
+ // error instead of hanging). connect() is idempotent, so driving it is safe whether the socket is
9833
+ // already connecting (autoConnect) or was created with autoConnect:false.
9834
+ whenConnected(socket) {
9835
+ if (socket.connected) return Promise.resolve();
9836
+ return new Promise((resolve, reject) => {
9837
+ const cleanup = () => {
9838
+ socket.off("connect", onConnect);
9839
+ socket.off("connect_error", onError);
9840
+ };
9841
+ const onConnect = () => {
9842
+ cleanup();
9843
+ resolve();
9844
+ };
9845
+ const onError = (err) => {
9846
+ cleanup();
9847
+ reject(err instanceof Error ? err : new Error(`socket connection failed: ${String(err)}`));
9848
+ };
9849
+ socket.on("connect", onConnect);
9850
+ socket.on("connect_error", onError);
9851
+ socket.connect();
9852
+ });
9853
+ }
9854
+ // socket.io-client is an optional peer dependency, imported on demand so non-socket consumers
9855
+ // never load it (and SSR never connects).
9856
+ async createSocket(conn) {
9857
+ let io;
9858
+ try {
9859
+ ({ io } = await import('./esm-debug-3SQICTIF.js'));
9860
+ } catch {
9861
+ throw new WorkflowsError({
9862
+ httpStatusCode: 400,
9863
+ reason: "invalid_state",
9864
+ message: 'socketConnection requires the optional peer dependency "socket.io-client" to be installed.'
9865
+ });
9755
9866
  }
9756
- };
9757
- }
9758
- function isClientConfig(input) {
9759
- return "fetch" in input && typeof input.fetch === "function" || "apiKey" in input && typeof input.apiKey === "string";
9760
- }
9761
-
9762
- // src/client/prepare.ts
9763
- function resolvePayloadBuild(model, ctx) {
9764
- const hasImages = Array.isArray(ctx.imageUrls) && ctx.imageUrls.length > 0 || !!ctx.startFrame || !!ctx.endFrame;
9765
- return {
9766
- hasImages,
9767
- workflow: hasImages && model.editWorkflow ? model.editWorkflow : model.workflow,
9768
- buildPayload: hasImages && model.buildEditPayload ? model.buildEditPayload : model.buildPayload ?? ((ctx2) => ({ prompt: ctx2.prompt }))
9769
- };
9770
- }
9771
- function prepareRequest(model, params2) {
9772
- const ctx = { ...params2 };
9773
- const contract = getModelContract(model.id);
9774
- const validatedCtx = contract ? contract.input.parse(ctx) : ctx;
9775
- const resolved = resolvePayloadBuild(model, validatedCtx);
9776
- const payload = resolved.buildPayload(validatedCtx);
9777
- return { ctx, workflow: resolved.workflow, payload, contract };
9778
- }
9779
- function throwIfTerminalFailure(completed, model) {
9780
- if (completed.status === "FAILED") {
9781
- throw new ApiError(`${model.name} failed: ${completed.error ?? "unknown error"}`, {
9782
- status: completed.statusCode ?? 502,
9783
- code: completed.reason ?? "generation_failed"
9867
+ return io(conn.url, {
9868
+ path: conn.path ?? "/socket-gateway",
9869
+ transports: conn.transports ?? ["websocket"],
9870
+ auth: this.buildAuth(conn)
9784
9871
  });
9785
9872
  }
9786
- if (completed.status === "CANCELED") {
9787
- throw new ApiError(`${model.name} was canceled`, { status: 499, code: "canceled" });
9873
+ // The handshake auth payload, in socket.io's FUNCTION form — socket.io re-invokes it per (re)connect
9874
+ // attempt (Socket#onopen), which is the whole point: a plain object would be snapshotted once and
9875
+ // replayed on every reconnect, so it would go stale along with the token it captured.
9876
+ buildAuth(conn) {
9877
+ const { getToken } = conn;
9878
+ return (cb) => {
9879
+ void Promise.resolve().then(getToken).then((fresh) => cb({ token: bearer(fresh) })).catch((err) => {
9880
+ logger_default.error("workflows.socket - socketConnection.getToken failed; the handshake will be refused", err);
9881
+ cb({ token: "" });
9882
+ });
9883
+ };
9788
9884
  }
9789
- }
9790
- function parseResult(completed, model, contract) {
9791
- throwIfTerminalFailure(completed, model);
9792
- throwIfErrorResult(completed.result, model.name);
9793
- const parsed = contract?.output ? contract.output.parse(completed.result) : completed.result;
9794
- const multiItems = extractAllResults(parsed);
9795
- if (multiItems?.length) {
9796
- const results = multiItems.map((item) => ({
9797
- url: item.url,
9798
- metadata: item.exploreImageId ? { exploreImageId: item.exploreImageId } : void 0
9799
- }));
9800
- return { url: results[0].url, results, model: model.id, handle: completed.handle, raw: parsed, usage: completed.usage };
9885
+ // The gateway only accepts channels shaped `workflows:SEG:SEG` (SEG = letters, digits, _, - or /). We build
9886
+ // the channel from `name`/`taskId`, so validate it here to fail fast on a bad name instead of
9887
+ // silently never joining a room. Task names are slash-delimited paths (e.g. /v1/videos/text-to-video),
9888
+ // so `/` is allowed. (A channel that passes this but the gateway still refuses is left to hang — expected.)
9889
+ assertValidChannel(channel) {
9890
+ if (!/^workflows:[a-zA-Z0-9_/-]+:[a-zA-Z0-9_/-]+$/.test(channel)) {
9891
+ throw new WorkflowsError({
9892
+ httpStatusCode: 400,
9893
+ reason: "invalid_channel",
9894
+ message: `Invalid channel "${channel}" \u2014 name and taskId may only contain letters, digits, "_", "-" or "/".`
9895
+ });
9896
+ }
9801
9897
  }
9802
- const url = extractUrl(parsed);
9803
- if (!url) {
9804
- throw new ApiError(`${model.name}: unexpected response \u2014 no result URL`, {
9805
- status: 502,
9806
- code: "invalid_response"
9807
- });
9898
+ // Room membership. Every joiner emits its OWN `subscribe` (idempotent at the gateway); the ref-count
9899
+ // is used solely to emit `unsubscribe` ONCE, when the last watcher leaves, so one watcher's teardown
9900
+ // never drops a room a sibling still needs. Fire-and-forget: we validate the channel locally, so
9901
+ // there's no ack to act on.
9902
+ joinChannel(socket, channel) {
9903
+ let refs = this.channelRefs.get(socket);
9904
+ if (!refs) {
9905
+ refs = /* @__PURE__ */ new Map();
9906
+ this.channelRefs.set(socket, refs);
9907
+ }
9908
+ refs.set(channel, (refs.get(channel) ?? 0) + 1);
9909
+ socket.emit("subscribe", { channels: [channel] });
9910
+ }
9911
+ leaveChannel(socket, channel) {
9912
+ const refs = this.channelRefs.get(socket);
9913
+ if (!refs) return;
9914
+ const count = (refs.get(channel) ?? 0) - 1;
9915
+ if (count <= 0) {
9916
+ refs.delete(channel);
9917
+ socket.emit("unsubscribe", { channels: [channel] });
9918
+ } else {
9919
+ refs.set(channel, count);
9920
+ }
9808
9921
  }
9809
- return { url, results: [{ url }], model: model.id, handle: completed.handle, raw: parsed, usage: completed.usage };
9810
- }
9811
- function parseTextResult(completed, model) {
9812
- throwIfTerminalFailure(completed, model);
9813
- throwIfErrorResult(completed.result, model.name);
9814
- throwIfErrorResult(completed.raw, model.name);
9815
- const text = extractText(completed.result) ?? extractText(completed.raw);
9816
- if (text == null) {
9817
- throw new ApiError(`${model.name}: unexpected response \u2014 no text`, {
9818
- status: 502,
9819
- code: "invalid_response"
9922
+ // The Error a task failure maps to: the gateway's own reason/message/statusCode when it sent them,
9923
+ // otherwise a generic 500 failure.
9924
+ failureError(failure) {
9925
+ return WorkflowsError.fromBody(failure, {
9926
+ httpStatusCode: 500,
9927
+ reason: "workflow_failed",
9928
+ message: "Workflow failed"
9820
9929
  });
9821
9930
  }
9822
- return { text, model: model.id, handle: completed.handle, raw: completed.raw ?? completed.result, usage: completed.usage };
9823
- }
9824
-
9825
- // src/core/limits.ts
9826
- var MAX_DRIVE_PROMPT_LENGTH = 18e3;
9827
-
9828
- // src/client/drive.ts
9829
- var USER_REACTION_ATTR = "userReaction";
9830
- function inferResourceType(mode) {
9831
- if (mode === "video") return "VIDEO";
9832
- if (mode === "audio") return "AUDIO";
9833
- return "PHOTO";
9834
- }
9835
- function buildFilename(prompt, mode) {
9836
- const shortId = String(Date.now()).slice(-6);
9837
- const ext = mode === "video" ? "mp4" : mode === "audio" ? "mp3" : "png";
9838
- if (!prompt) return `ai-generation-${shortId}.${ext}`;
9839
- const slug = prompt.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 50);
9840
- return `${slug}-${shortId}.${ext}`;
9841
- }
9842
- function inferMediaType(file) {
9843
- const name = String(file.name || "");
9844
- if (/\.(mp3|wav|ogg|aac|flac|m4a)$/i.test(name)) return "audio";
9845
- if (/\.(mp4|webm|mov|avi|mkv|m4v|wmv)$/i.test(name)) return "video";
9846
- const contentType = file.contentType ?? file.content;
9847
- const resourceType = String(contentType?.resourceType || "").toUpperCase();
9848
- if (resourceType === "VIDEO") return "video";
9849
- if (resourceType === "AUDIO") return "audio";
9850
- return "image";
9851
- }
9852
- function contentResourceTypes(type) {
9853
- if (type === "image") return "PHOTO";
9854
- if (type === "video") return "VIDEO";
9855
- if (type === "audio") return "AUDIO";
9856
- return "PHOTO,VIDEO,AUDIO";
9857
- }
9858
- function normalizeUrl(raw) {
9859
- if (typeof raw !== "string") return void 0;
9860
- return raw.trim() || void 0;
9861
- }
9862
- function parseAttributes(raw) {
9863
- const map = {};
9864
- if (!raw || typeof raw !== "object") return map;
9865
- if (Array.isArray(raw)) {
9866
- for (const a of raw) {
9867
- map[a.property] = String(a.value);
9868
- }
9869
- } else {
9870
- for (const [k, v] of Object.entries(raw)) {
9871
- map[k] = String(v);
9931
+ };
9932
+ async function* decodeSSE(stream) {
9933
+ for await (const chunk of readSSE(stream)) {
9934
+ const lines = chunk.split("\n");
9935
+ const sseData = {};
9936
+ for (const line of lines) {
9937
+ if (line.startsWith("data:")) {
9938
+ const data = line.replace(/^data:\s*/, "");
9939
+ if (data === "[DONE]") {
9940
+ return;
9941
+ }
9942
+ try {
9943
+ sseData.data = JSON.parse(data);
9944
+ } catch (err) {
9945
+ logger_default.warn(
9946
+ `Failed to parse data JSON from OpenAI event stream: - ${data}, err=${JSON.stringify(err)}`
9947
+ );
9948
+ }
9949
+ }
9872
9950
  }
9951
+ yield sseData;
9873
9952
  }
9874
- return map;
9875
- }
9876
- function parseReaction(value) {
9877
- return value === "like" || value === "dislike" ? value : void 0;
9878
9953
  }
9879
- function parseJsonAttr(raw) {
9880
- if (!raw) return void 0;
9954
+ async function* readSSE(stream) {
9955
+ const reader = stream.getReader();
9956
+ let buffer = new Uint8Array();
9957
+ const decoder = new TextDecoder("utf-8");
9881
9958
  try {
9882
- const value = JSON.parse(raw);
9883
- return value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
9884
- } catch {
9885
- return void 0;
9959
+ while (true) {
9960
+ const { value, done } = await reader.read();
9961
+ if (done) break;
9962
+ const tmp = new Uint8Array(buffer.length + value.length);
9963
+ tmp.set(buffer);
9964
+ tmp.set(value, buffer.length);
9965
+ buffer = tmp;
9966
+ let index;
9967
+ while ((index = findDoubleNewlineIndex(buffer)) !== -1) {
9968
+ const slice = buffer.subarray(0, index);
9969
+ yield decoder.decode(slice);
9970
+ buffer = buffer.subarray(index);
9971
+ }
9972
+ }
9973
+ if (buffer.length > 0) {
9974
+ yield decoder.decode(buffer);
9975
+ }
9976
+ } finally {
9977
+ reader.releaseLock();
9886
9978
  }
9887
9979
  }
9888
- var asString = (v) => typeof v === "string" && v.trim() ? v : void 0;
9889
- var asStringArray = (v) => Array.isArray(v) && v.length && v.every((x) => typeof x === "string") ? v : void 0;
9890
- function toSdkPayload(params2) {
9891
- const p2 = { prompt: String(params2.prompt ?? "").slice(0, MAX_DRIVE_PROMPT_LENGTH) };
9892
- for (const [key, value] of Object.entries(params2)) {
9893
- if (key === "prompt") continue;
9894
- if (value === void 0 || value === null || value === "") continue;
9895
- p2[key] = value;
9980
+ function findDoubleNewlineIndex(buffer) {
9981
+ const newline = 10;
9982
+ const carriage = 13;
9983
+ for (let i = 0; i < buffer.length - 1; i++) {
9984
+ if (buffer[i] === newline && buffer[i + 1] === newline) {
9985
+ return i + 2;
9986
+ }
9987
+ if (buffer[i] === carriage && buffer[i + 1] === carriage) {
9988
+ return i + 2;
9989
+ }
9990
+ if (buffer[i] === carriage && buffer[i + 1] === newline && i + 3 < buffer.length && buffer[i + 2] === carriage && buffer[i + 3] === newline) {
9991
+ return i + 4;
9992
+ }
9896
9993
  }
9897
- return p2;
9994
+ return -1;
9898
9995
  }
9899
- function buildGenerationAttributes(input) {
9900
- const attrs = {
9901
- model: input.modelId,
9902
- aiSDKPayload: JSON.stringify(toSdkPayload(input.params))
9903
- };
9904
- if (input.app) {
9905
- attrs.appId = input.app.id;
9906
- attrs.appType = input.app.type;
9996
+ var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
9997
+ var DEFAULT_POLLING_INTERVAL = 300;
9998
+ var DEFAULT_RETRIES_COUNT = 1e3;
9999
+ var NETWORK_RETRIES_COUNT = 10;
10000
+ var MAX_POLLING_BACKOFF = 5e3;
10001
+ var WorkflowsClient = class {
10002
+ constructor(options) {
10003
+ this.defaultHeaders = {
10004
+ Accept: "application/json",
10005
+ "Content-Type": "application/json"
10006
+ };
10007
+ this.terminalStatuses = [
10008
+ "COMPLETED",
10009
+ "FAILED"
10010
+ /* FAILED */
10011
+ ];
10012
+ this.clientOptions = options || {};
10013
+ this.clientOptions.baseUrl = this.clientOptions.baseUrl || "https://api.picsart.com/";
10014
+ if (!this.clientOptions.baseUrl.endsWith("/")) this.clientOptions.baseUrl += "/";
10015
+ if (this.clientOptions.apiKey) {
10016
+ this.clientOptions.apiKey = this.clientOptions.apiKey.replace("Bearer ", "");
10017
+ }
10018
+ if (this.clientOptions.identityToken) {
10019
+ this.clientOptions.identityToken = this.clientOptions.identityToken.replace("Bearer ", "");
10020
+ }
10021
+ this.workflowsApiBaseUrl = `${this.clientOptions.baseUrl}workflows`;
10022
+ this.sockets = new WorkflowsSocket({
10023
+ socket: this.clientOptions.socket,
10024
+ socketConnection: this.clientOptions.socketConnection && {
10025
+ ...this.clientOptions.socketConnection,
10026
+ url: this.clientOptions.socketConnection.url || this.clientOptions.baseUrl
10027
+ }
10028
+ });
10029
+ if (this.clientOptions.socket || this.clientOptions.socketConnection) {
10030
+ void Promise.resolve().then(() => this.sockets.connect()).catch(() => void 0);
10031
+ }
9907
10032
  }
9908
- return attrs;
9909
- }
9910
- function toMediaItem(file) {
9911
- const url = normalizeUrl(file.sourceUrl);
9912
- if (!url || String(file.name || "").startsWith("__")) return null;
9913
- const preview = file.preview;
9914
- return {
9915
- uid: String(file.uid ?? ""),
9916
- url,
9917
- name: String(file.name || ""),
9918
- type: inferMediaType(file),
9919
- previewUrl: normalizeUrl(preview?.url),
9920
- timestamp: Number(file.updatedAt ?? file.createdAt ?? 0)
9921
- };
9922
- }
9923
- function toDetailedItem(file) {
9924
- const base2 = toMediaItem(file);
9925
- if (!base2) return null;
9926
- const attrs = parseAttributes(file.attributes);
9927
- let extras = {};
9928
- if (attrs.textScript) {
10033
+ /**
10034
+ * Runs a workflow end-to-end and resolves with its result.
10035
+ *
10036
+ * A workflow that has an entry in `WorkflowTypes` (from `@picsart/workflows-types`) is
10037
+ * type-checked against it: `params` must match the workflow's input and the result comes back
10038
+ * typed, with no type argument to pass. Every other workflow is left unconstrained — declare
10039
+ * the result yourself with `run<MyResult>(name, params)`.
10040
+ *
10041
+ * The execution mode is taken from remote settings when available, otherwise from
10042
+ * `executionOptions.mode`, defaulting to async (submit + polling). Supported modes:
10043
+ * sync (single HTTP call), stream (SSE, requires `onEvent`), socket (result pushed
10044
+ * over the socket), and async (submit + polling).
10045
+ *
10046
+ * @typeParam R - Shape of the result, for a workflow that has no `WorkflowTypes` entry.
10047
+ * Passing it explicitly also opts a mapped workflow out of its types.
10048
+ * @param name - Workflow name.
10049
+ * @param params - Workflow input, typed per the workflow definition when there is one.
10050
+ * @param executionOptions - Mode, callbacks (`onAccepted`, `onProgress`, `onPartialResult`,
10051
+ * `onEvent`), polling tuning, headers, and abort signal.
10052
+ * @returns The workflow result and usage info.
10053
+ * @throws {WorkflowsError} On a failed request (`httpStatusCode` carries the HTTP status),
10054
+ * invalid arguments, or an unexpected failure.
10055
+ */
10056
+ async run(name, params2, executionOptions) {
9929
10057
  try {
9930
- extras = JSON.parse(attrs.textScript);
9931
- } catch {
10058
+ const remoteSettings = await this.getApiSettings(
10059
+ name,
10060
+ executionOptions?.remoteSettingName
10061
+ );
10062
+ const executionMode = remoteSettings.executionMode || executionOptions?.mode || "ASYNC";
10063
+ if (executionMode === "SYNC") {
10064
+ return this.executeTaskSync(name, params2, executionOptions);
10065
+ }
10066
+ if (executionMode === "STREAM") {
10067
+ return this.executeTaskStream(name, params2, executionOptions);
10068
+ }
10069
+ if (executionMode === "SOCKET") {
10070
+ const submit = async () => {
10071
+ try {
10072
+ const id = await this.postTask(name, params2, executionOptions);
10073
+ await executionOptions?.onAccepted?.(id);
10074
+ return id;
10075
+ } catch (err) {
10076
+ throw this.wrapError(name, err);
10077
+ }
10078
+ };
10079
+ return this.sockets.runTask(
10080
+ name,
10081
+ submit,
10082
+ executionOptions,
10083
+ (taskId2) => this.disableNotification(taskId2, { headers: executionOptions?.headers })
10084
+ );
10085
+ }
10086
+ const taskId = await this.postTask(name, params2, executionOptions);
10087
+ await executionOptions?.onAccepted?.(taskId);
10088
+ return this.runPolling(name, taskId, executionOptions);
10089
+ } catch (err) {
10090
+ throw this.wrapError(name, err);
9932
10091
  }
9933
10092
  }
9934
- return {
9935
- ...base2,
9936
- createdAt: file.createdAt,
9937
- model: attrs.model,
9938
- prompt: attrs.prompt || void 0,
9939
- service: attrs.service,
9940
- subType: attrs.subType,
9941
- duration: attrs.duration,
9942
- userReaction: parseReaction(attrs[USER_REACTION_ATTR]),
9943
- referenceImageUrls: extras.referenceImageUrls,
9944
- referenceVideoUrl: extras.referenceVideoUrl,
9945
- referenceAudioUrl: extras.referenceAudioUrl,
9946
- aspectRatio: extras.aspectRatio,
9947
- resolution: extras.resolution,
9948
- quality: extras.quality
9949
- };
9950
- }
9951
- var LEGACY_TOOL_APP = {
9952
- "ai-playground": { appId: "com.picsart.ai-playground", appType: "miniapp" }
9953
- };
9954
- function adaptLegacyGeneration(attrs) {
9955
- let extras = {};
9956
- if (attrs.textScript) {
10093
+ /**
10094
+ * Submits a task WITHOUT waiting for its result — the standalone counterpart of {@link run}.
10095
+ * Consume the result later with {@link runPolling} or {@link subscribe} (`{ name, taskId }`).
10096
+ *
10097
+ * Only the submission-related execution options apply here (`headers`, `notificationConfig`,
10098
+ * `remoteSettingName`); result-consumption options (mode, callbacks, polling) belong to the consumer.
10099
+ *
10100
+ * @param name - Workflow name.
10101
+ * @param params - Workflow input parameters.
10102
+ * @param executionOptions - Submission-related options only.
10103
+ * @returns The taskId of the submitted task.
10104
+ * @throws {WorkflowsError} On a failed request (`httpStatusCode` carries the HTTP status)
10105
+ * or an unexpected failure.
10106
+ */
10107
+ async submit(name, params2, executionOptions) {
9957
10108
  try {
9958
- extras = JSON.parse(attrs.textScript);
9959
- } catch {
10109
+ return await this.postTask(name, params2, executionOptions);
10110
+ } catch (err) {
10111
+ throw this.wrapError(name, err);
9960
10112
  }
9961
10113
  }
9962
- const aiSDKPayload = { prompt: attrs.prompt || "" };
9963
- const aspectRatio = asString(extras.aspectRatio);
9964
- if (aspectRatio) aiSDKPayload.aspectRatio = aspectRatio;
9965
- const resolution = asString(extras.resolution);
9966
- if (resolution) aiSDKPayload.resolution = resolution;
9967
- const duration = extras.duration ?? attrs.duration;
9968
- if (duration != null && duration !== "") aiSDKPayload.duration = Number(duration);
9969
- const imageUrls = asStringArray(extras.referenceImageUrls);
9970
- if (imageUrls) aiSDKPayload.imageUrls = imageUrls;
9971
- const videoUrl = asString(extras.referenceVideoUrl);
9972
- if (videoUrl) aiSDKPayload.videoUrl = videoUrl;
9973
- const audioUrl = asString(extras.referenceAudioUrl);
9974
- if (audioUrl) aiSDKPayload.audioUrl = audioUrl;
9975
- const startFrame = asString(extras.startFrame);
9976
- if (startFrame) aiSDKPayload.startFrame = startFrame;
9977
- const endFrame = asString(extras.endFrame);
9978
- if (endFrame) aiSDKPayload.endFrame = endFrame;
9979
- const quality = asString(extras.quality);
9980
- if (quality) aiSDKPayload.quality = quality;
9981
- const style = asString(extras.style);
9982
- if (style) aiSDKPayload.style = style;
9983
- const iterateModel = asString(extras.iterateModel);
9984
- if (iterateModel) aiSDKPayload.iterateModel = iterateModel;
9985
- const exploreImageId = asString(extras.exploreImageId);
9986
- if (exploreImageId) aiSDKPayload.exploreImageId = exploreImageId;
9987
- const app = attrs.tool ? LEGACY_TOOL_APP[attrs.tool] : void 0;
9988
- return {
9989
- appId: app?.appId,
9990
- appType: app?.appType,
9991
- model: attrs.model || void 0,
9992
- aiSDKPayload,
9993
- userReaction: parseReaction(attrs[USER_REACTION_ATTR])
9994
- };
9995
- }
9996
- function parseGeneration(file) {
9997
- const attrs = parseAttributes(file.attributes);
9998
- if (!attrs.aiSDKPayload) {
9999
- return adaptLegacyGeneration(attrs);
10000
- }
10001
- return {
10002
- appId: attrs.appId || void 0,
10003
- appType: attrs.appType === "native" || attrs.appType === "miniapp" ? attrs.appType : void 0,
10004
- model: attrs.model || void 0,
10005
- aiSDKPayload: parseJsonAttr(attrs.aiSDKPayload),
10006
- userReaction: parseReaction(attrs[USER_REACTION_ATTR])
10007
- };
10008
- }
10009
- function createDriveClient(f, apiUrl, rootFolderName) {
10010
- let cachedRootUid = null;
10011
- let rootPromise = null;
10012
- const jsonPost = async (path, body) => f(`${apiUrl}${path}`, {
10013
- method: "POST",
10014
- headers: { "Content-Type": "application/json" },
10015
- body: JSON.stringify(body)
10016
- });
10017
- const jsonGet = async (path) => f(`${apiUrl}${path}`);
10018
- async function findFolderByPath(name) {
10114
+ /**
10115
+ * Fetches the options a workflow offers for the given input — what the adapter resolves for THIS
10116
+ * caller (subscription tier, country, the `x-config-id` CMS card), which is why it is read at call
10117
+ * time rather than described by the workflow's types.
10118
+ *
10119
+ * @param name - Workflow name, including the version when the workflow has one (`pipelineName/v1`).
10120
+ * @param params - Workflow input to resolve the options for; defaults to `{}` for the common case
10121
+ * of asking before anything is chosen.
10122
+ * @param requestOptions - `remoteSettingName` to resolve the `x-config-id` under a name other
10123
+ * than the workflow's own.
10124
+ * @returns The options payload — the envelope's `response`, unwrapped.
10125
+ * @throws {WorkflowsError} On a failed request; `httpStatusCode` carries the HTTP status.
10126
+ */
10127
+ async options(name, params2 = {}, requestOptions) {
10019
10128
  try {
10020
- const res = await jsonGet(`/cloud-storage/v1/me/files-by-path?path=${encodeURIComponent(name)}`);
10021
- if (!res.ok) return null;
10022
- const data = await res.json();
10023
- if (data.status !== "success") return null;
10024
- const response = data.response;
10025
- const file = Array.isArray(response) ? response[0] : response;
10026
- return file?.uid ?? null;
10027
- } catch {
10028
- return null;
10129
+ const remoteSettings = await this.getApiSettings(name, requestOptions?.remoteSettingName);
10130
+ const response = await this._fetch(`${this.workflowsApiBaseUrl}/${name}/options`, {
10131
+ method: "POST",
10132
+ headers: this.requestHeaders(remoteSettings.configId),
10133
+ body: JSON.stringify({ params: params2 })
10134
+ });
10135
+ const json = await this.toSuccessResponse(response);
10136
+ return json.response;
10137
+ } catch (err) {
10138
+ throw this.wrapError(name, err);
10029
10139
  }
10030
10140
  }
10031
- async function findFolderInList(name, parentUid) {
10032
- try {
10033
- const params2 = parentUid ? `parentFolderUid=${parentUid}&fileTypes=FOLDER&limit=100` : `fileTypes=FOLDER&limit=100`;
10034
- const res = await jsonGet(`/cloud-storage/v1/me/files?${params2}`);
10035
- if (!res.ok) return null;
10036
- const data = await res.json();
10037
- const response = data.response;
10038
- const files = Array.isArray(response) ? response : [];
10039
- const match = files.find((f2) => String(f2.name || "").toLowerCase() === name.toLowerCase());
10040
- return match?.uid ?? null;
10041
- } catch {
10042
- return null;
10141
+ async postTask(taskName, command, executionOptions) {
10142
+ const remoteSettings = await this.getApiSettings(taskName, executionOptions?.remoteSettingName);
10143
+ const response = await this._fetch(`${this.workflowsApiBaseUrl}/${taskName}/submit`, {
10144
+ method: "POST",
10145
+ headers: this.requestHeaders(remoteSettings.configId, executionOptions?.headers),
10146
+ body: JSON.stringify({
10147
+ params: command,
10148
+ notification: executionOptions?.notificationConfig
10149
+ })
10150
+ });
10151
+ const json = await this.toSuccessResponse(response);
10152
+ return json.response.id;
10153
+ }
10154
+ /**
10155
+ * Polls an already-submitted task until it reaches a terminal status (COMPLETED/FAILED)
10156
+ * and resolves with its result. Progress and partial-result callbacks from
10157
+ * `executionOptions` are invoked on each update.
10158
+ *
10159
+ * A poll that never reaches the server (dropped wifi, DNS failure, a reset connection) does not
10160
+ * end the run — the task keeps going server-side, so polling backs off and retries, giving up
10161
+ * only once the drops outlast the retry budget. Anything the server did answer, and any abort,
10162
+ * still fails immediately.
10163
+ *
10164
+ * @typeParam R - Shape of the workflow result.
10165
+ * @param taskName - Workflow name.
10166
+ * @param taskId - Task id returned by {@link submit} (or `onAccepted`).
10167
+ * @param executionOptions - `pollingInterval` (default 300ms), `retriesCount` (default 1000),
10168
+ * callbacks and abort signal.
10169
+ * @returns The workflow result and usage info.
10170
+ * @throws {WorkflowsError} With `httpStatusCode` 408 when the retry budget is exhausted
10171
+ * before the task completes, or the connection error when the connection never came back.
10172
+ */
10173
+ async runPolling(taskName, taskId, executionOptions) {
10174
+ const pollingInterval = executionOptions?.pollingInterval || DEFAULT_POLLING_INTERVAL;
10175
+ let retriesCounter = executionOptions?.retriesCount || DEFAULT_RETRIES_COUNT;
10176
+ let pollingResponse;
10177
+ let networkFailures = 0;
10178
+ let lastNetworkError;
10179
+ const progressAware = new WorkflowResultUpdateAware(
10180
+ executionOptions?.onProgress,
10181
+ executionOptions?.onPartialResult,
10182
+ executionOptions?.onEvent
10183
+ );
10184
+ do {
10185
+ if (executionOptions?.abortSignal?.aborted) throw new DOMException("Aborted", "AbortError");
10186
+ await sleep(this.pollingDelay(pollingInterval, networkFailures));
10187
+ retriesCounter--;
10188
+ try {
10189
+ pollingResponse = await this.getResult(taskName, taskId);
10190
+ networkFailures = 0;
10191
+ lastNetworkError = void 0;
10192
+ } catch (err) {
10193
+ if (!this.isConnectionError(err)) throw err;
10194
+ if (++networkFailures > NETWORK_RETRIES_COUNT) throw this.connectionError(err);
10195
+ lastNetworkError = err;
10196
+ logger_default.warn(
10197
+ `workflows.runPolling - poll ${networkFailures}/${NETWORK_RETRIES_COUNT} of ${taskName}/${taskId} did not reach the server, retrying`,
10198
+ err
10199
+ );
10200
+ continue;
10201
+ }
10202
+ await progressAware.onUpdate(pollingResponse.response);
10203
+ } while (retriesCounter > 0 && !this.isTerminal(pollingResponse));
10204
+ if (lastNetworkError) throw this.connectionError(lastNetworkError);
10205
+ if (!this.isTerminal(pollingResponse) || !pollingResponse?.response.result) {
10206
+ throw new WorkflowsError({
10207
+ httpStatusCode: 408,
10208
+ reason: "client_timeout",
10209
+ message: "Polling timeout reached. Consider increasing polling interval or retries count from execution options."
10210
+ });
10043
10211
  }
10212
+ return pollingResponse.response;
10044
10213
  }
10045
- async function createFolder(name, parentUid) {
10214
+ // Raw transport rejections (a TypeError from fetch) become the client's own error on the way out,
10215
+ // keeping what fetch said but labelling it for callers. No httpStatusCode: the server never answered.
10216
+ connectionError(error) {
10217
+ return new WorkflowsError({
10218
+ reason: "connection_error",
10219
+ message: error?.message || "The request did not reach the server"
10220
+ });
10221
+ }
10222
+ isTerminal(response) {
10223
+ return !!response && this.terminalStatuses.includes(response.response.status);
10224
+ }
10225
+ /**
10226
+ * Whether a failed poll never got an answer from the server — the connection dropped, DNS failed,
10227
+ * the request was reset. Classified by what the failure is NOT, so it holds in a browser
10228
+ * (`TypeError: Failed to fetch`) and in Node (`TypeError: fetch failed`) alike: anything the
10229
+ * server answered carries an `httpStatusCode`, and an abort is the caller's own doing.
10230
+ */
10231
+ isConnectionError(error) {
10232
+ const name = error?.name;
10233
+ if (name === "AbortError" || name === "TimeoutError") return false;
10234
+ if (error instanceof WorkflowsError) return error.httpStatusCode === void 0;
10235
+ return true;
10236
+ }
10237
+ // Back off while the connection is down instead of hammering a dead radio — never below the
10238
+ // caller's own interval, never above MAX_POLLING_BACKOFF.
10239
+ pollingDelay(interval, consecutiveFailures) {
10240
+ if (consecutiveFailures === 0) return interval;
10241
+ return Math.min(interval * 2 ** consecutiveFailures, Math.max(interval, MAX_POLLING_BACKOFF));
10242
+ }
10243
+ /**
10244
+ * Fetches the CURRENT state of an already-submitted task with a single request — no polling, no
10245
+ * waiting. Returns the task as it stands, so read `status` (and `progress`) to know what you got:
10246
+ * `result` may still be empty or partial while the task is not COMPLETED. Use {@link runPolling}
10247
+ * or {@link subscribe} to wait for a terminal status instead.
10248
+ *
10249
+ * @typeParam R - Shape of the workflow result.
10250
+ * @param taskName - Workflow name.
10251
+ * @param taskId - Task id returned by {@link submit} (or `onAccepted`).
10252
+ * @returns The task record as it stands at the moment of the call.
10253
+ * @throws {WorkflowsError} On a failed request (`httpStatusCode` carries the HTTP status)
10254
+ * or an unexpected failure.
10255
+ */
10256
+ async result(taskName, taskId) {
10046
10257
  try {
10047
- const body = { name };
10048
- if (parentUid) body.parentFolderUid = parentUid;
10049
- const res = await jsonPost("/cloud-storage/v1/me/folders", body);
10050
- if (!res.ok) return null;
10051
- const data = await res.json();
10052
- const response = data.response;
10053
- return response?.uid ?? null;
10054
- } catch {
10055
- return null;
10258
+ const response = await this.getResult(taskName, taskId);
10259
+ return response.response;
10260
+ } catch (err) {
10261
+ throw this.wrapError(taskName, err);
10056
10262
  }
10057
10263
  }
10058
- async function resolveRootFolder() {
10059
- const byPath = await findFolderByPath(rootFolderName);
10060
- if (byPath) return byPath;
10061
- const inList = await findFolderInList(rootFolderName);
10062
- if (inList) return inList;
10063
- const recheck = await findFolderByPath(rootFolderName);
10064
- if (recheck) return recheck;
10065
- return createFolder(rootFolderName);
10066
- }
10067
- async function ensureRootFolder() {
10068
- if (cachedRootUid) return cachedRootUid;
10069
- if (!rootPromise) {
10070
- rootPromise = resolveRootFolder().then((uid) => {
10071
- cachedRootUid = uid;
10072
- rootPromise = null;
10073
- return uid;
10074
- }).catch((err) => {
10075
- setTimeout(() => {
10076
- rootPromise = null;
10077
- }, 1e4);
10078
- throw err;
10264
+ /**
10265
+ * Watches already-submitted work LIVE over the socket (no re-submit), as an async iterable
10266
+ * of the raw `StreamSocketMessage` the gateway pushes — iterate with `for await` and switch
10267
+ * on `msg.type`. With a `taskId` it watches that task (ending after its COMPLETED/FAILED);
10268
+ * without it, it watches EVERY task of the workflow until stopped. A lost session throws out
10269
+ * of the loop; `break` (or an AbortSignal in options) stops watching.
10270
+ *
10271
+ * @param options - Subscription target: `name` (required), optional `taskId` and abort signal.
10272
+ * @returns Async iterable of socket messages for the subscribed workflow/task.
10273
+ * @throws {WorkflowsError} If `options.name` is missing.
10274
+ */
10275
+ subscribe(options) {
10276
+ if (!options.name) {
10277
+ throw new WorkflowsError({
10278
+ httpStatusCode: 400,
10279
+ reason: "INVALID_ARGUMENTS",
10280
+ message: "subscribe() requires `name`."
10079
10281
  });
10080
10282
  }
10081
- return rootPromise;
10283
+ return this.sockets.subscribe(options);
10082
10284
  }
10083
- async function fetchFolders(parentUid) {
10285
+ /**
10286
+ * Closes the socket the client created from `socketConnection`. No-op for an injected
10287
+ * `socket` (the caller owns that one). Safe to call more than once.
10288
+ */
10289
+ async disconnect() {
10290
+ return this.sockets.disconnect();
10291
+ }
10292
+ /**
10293
+ * Marks a task's notification as seen so it is no longer surfaced to the user.
10294
+ * Called automatically after socket-mode runs; call it manually when consuming
10295
+ * results yourself (e.g. after {@link submit} + {@link subscribe}).
10296
+ *
10297
+ * @param taskId - Task id whose notification should be dismissed.
10298
+ * @param options - Optional extra request headers.
10299
+ * @throws {WorkflowsError} On a failed request; `httpStatusCode` carries the HTTP status.
10300
+ */
10301
+ async disableNotification(taskId, options) {
10084
10302
  try {
10085
- const params2 = parentUid ? `parentFolderUid=${parentUid}&fileTypes=FOLDER&limit=100` : `fileTypes=FOLDER&limit=100`;
10086
- const res = await jsonGet(`/cloud-storage/v1/me/files?${params2}`);
10087
- if (!res.ok) return [];
10088
- const data = await res.json();
10089
- const files = Array.isArray(data.response) ? data.response : [];
10090
- return files.filter((f2) => f2.uid && f2.name).map((f2) => ({ name: String(f2.name), uid: String(f2.uid) }));
10091
- } catch {
10092
- return [];
10303
+ const url = `${this.clientOptions.baseUrl}workflow-notifications/${taskId}/seen-status`;
10304
+ const response = await this._fetch(url, { method: "PATCH", headers: options?.headers });
10305
+ await this.throwIfError(response);
10306
+ } catch (err) {
10307
+ throw this.wrapError("disableNotification", err);
10093
10308
  }
10094
10309
  }
10095
- async function fetchMedia(opts) {
10096
- try {
10097
- const endpoint = opts.folderUid ? "/cloud-storage/v1/me/files" : "/cloud-storage/v1/me/flattened-files";
10098
- const params2 = [
10099
- opts.folderUid ? `parentFolderUid=${opts.folderUid}` : "",
10100
- "limit=100",
10101
- "sortType=UPDATED",
10102
- "sortOrder=DESC",
10103
- "fileTypes=FILE",
10104
- `contentResourceTypes=${contentResourceTypes(opts.type)}`
10105
- ].filter(Boolean).join("&");
10106
- const res = await jsonGet(`${endpoint}?${params2}`);
10107
- if (!res.ok) return [];
10108
- const data = await res.json();
10109
- return Array.isArray(data.response) ? data.response : [];
10110
- } catch {
10111
- return [];
10310
+ async executeTaskSync(taskName, command, executionOptions) {
10311
+ const remoteSettings = await this.getApiSettings(taskName, executionOptions?.remoteSettingName);
10312
+ const response = await this._fetch(
10313
+ `${this.workflowsApiBaseUrl}/${taskName}/execute`,
10314
+ {
10315
+ signal: executionOptions?.abortSignal,
10316
+ method: "POST",
10317
+ headers: this.requestHeaders(remoteSettings.configId, executionOptions?.headers),
10318
+ body: JSON.stringify({ params: command })
10319
+ }
10320
+ );
10321
+ const successResponse = await this.toSuccessResponse(response);
10322
+ return successResponse.response;
10323
+ }
10324
+ async getResult(taskName, taskId) {
10325
+ const response = await this._fetch(`${this.workflowsApiBaseUrl}/${taskName}/${taskId}/result`, {
10326
+ method: "GET"
10327
+ });
10328
+ return this.toSuccessResponse(response);
10329
+ }
10330
+ async executeTaskStream(taskName, command, executionOptions) {
10331
+ const remoteSettings = await this.getApiSettings(taskName, executionOptions?.remoteSettingName);
10332
+ const onEvent = executionOptions?.onEvent;
10333
+ if (!onEvent) {
10334
+ throw new WorkflowsError({
10335
+ httpStatusCode: 400,
10336
+ reason: "INVALID_ARGUMENTS",
10337
+ message: "onEvent is required for streaming"
10338
+ });
10339
+ }
10340
+ const streamHeaders = this.requestHeaders(remoteSettings.configId, executionOptions?.headers);
10341
+ streamHeaders.set("Accept", "text/event-stream");
10342
+ const response = await this._fetch(`${this.workflowsApiBaseUrl}/${taskName}/stream`, {
10343
+ signal: executionOptions?.abortSignal,
10344
+ method: "POST",
10345
+ headers: streamHeaders,
10346
+ body: JSON.stringify({ params: command })
10347
+ });
10348
+ await this.throwIfError(response);
10349
+ if (!response.body) {
10350
+ throw new WorkflowsError({
10351
+ httpStatusCode: 500,
10352
+ reason: "invalid_response",
10353
+ message: "No response body"
10354
+ });
10355
+ }
10356
+ let completedEvent = {};
10357
+ for await (const event of decodeSSE(response.body)) {
10358
+ if (executionOptions?.abortSignal?.aborted) break;
10359
+ const data = event.data;
10360
+ if (data.type.startsWith("event.")) {
10361
+ await onEvent({
10362
+ ...data,
10363
+ type: data.type.replace(/^event\.\s*/, "")
10364
+ });
10365
+ }
10366
+ if (data.type === "task.partial-result") {
10367
+ await executionOptions.onPartialResult?.({
10368
+ status: "IN_PROGRESS",
10369
+ result: data.result
10370
+ });
10371
+ }
10372
+ if (data.type === "task.failed") {
10373
+ throw WorkflowsError.fromBody(data.result, {
10374
+ httpStatusCode: 500,
10375
+ reason: "workflow_failed",
10376
+ message: "Workflow failed"
10377
+ });
10378
+ }
10379
+ if (data.type === "task.completed") {
10380
+ completedEvent = data;
10381
+ }
10112
10382
  }
10383
+ return {
10384
+ result: completedEvent.result,
10385
+ usage: completedEvent.usage,
10386
+ status: "COMPLETED"
10387
+ /* COMPLETED */
10388
+ // the loop only leaves the FAILED branch by throwing
10389
+ };
10113
10390
  }
10114
- async function fetchFileByUid(fileUid) {
10391
+ /**
10392
+ * Fetches the execution history of a workflow, paginated.
10393
+ *
10394
+ * @typeParam R - Shape of each execution's result in the history entries.
10395
+ * @param taskName - Workflow name to fetch history for.
10396
+ * @param offset - Pagination offset (default 0).
10397
+ * @param limit - Page size (default 10).
10398
+ * @param isGrouped - When true, fetches the grouped history endpoint.
10399
+ * @returns The history page for the workflow.
10400
+ * @throws {WorkflowsError} On a failed request (`httpStatusCode` carries the HTTP status)
10401
+ * or an unexpected failure.
10402
+ */
10403
+ async executionsHistory(taskName, offset = 0, limit = 10, isGrouped = false) {
10115
10404
  try {
10116
- const res = await jsonGet(`/drive/v1/files/${fileUid}`);
10117
- if (!res.ok) return null;
10118
- const data = await res.json();
10119
- const file = data.response;
10120
- return file && typeof file === "object" && !Array.isArray(file) ? file : null;
10405
+ const grouped = isGrouped ? "/grouped" : "";
10406
+ const url = `${this.clientOptions.baseUrl}workflows-history${grouped}?name=${taskName}&limit=${limit}&offset=${offset}`;
10407
+ const res = await this._fetch(url);
10408
+ return this.toSuccessResponse(res);
10409
+ } catch (err) {
10410
+ throw this.wrapError("requestHistory", err);
10411
+ }
10412
+ }
10413
+ async toSuccessResponse(response) {
10414
+ await this.throwIfError(response);
10415
+ const body = await response.text();
10416
+ try {
10417
+ return JSON.parse(body);
10121
10418
  } catch {
10122
- return null;
10419
+ throw new WorkflowsError({
10420
+ httpStatusCode: response.status,
10421
+ reason: "invalid_response",
10422
+ message: "Non json response was returned from server"
10423
+ });
10123
10424
  }
10124
10425
  }
10125
- async function setReaction(fileUid, reaction) {
10426
+ async throwIfError(response) {
10427
+ if (response.ok) return;
10428
+ throw await WorkflowsError.fromResponse(response, { reason: "request_failed" });
10429
+ }
10430
+ async getApiSettings(name, remoteSettingName) {
10431
+ if (!this.clientOptions.getRemoteSettings) return {};
10432
+ const settingName = remoteSettingName || `${name.replace(/-/g, "_").toLowerCase()}_api`;
10126
10433
  try {
10127
- const res = await f(`${apiUrl}/drive/v1/files/${fileUid}`, {
10128
- method: "PATCH",
10129
- headers: { "Content-Type": "application/json" },
10130
- body: JSON.stringify({ attributes: { [USER_REACTION_ATTR]: reaction } })
10434
+ const apiSetting = await this.clientOptions.getRemoteSettings(
10435
+ settingName,
10436
+ "miniapp"
10437
+ );
10438
+ return {
10439
+ configId: apiSetting?.configId || "",
10440
+ executionMode: apiSetting?.executionMode
10441
+ };
10442
+ } catch (err) {
10443
+ logger_default.error(
10444
+ `workflows.getConfigId - failed when fetching remoteSettings: settingName=${settingName}`,
10445
+ err
10446
+ );
10447
+ return {};
10448
+ }
10449
+ }
10450
+ wrapError(actionName, error) {
10451
+ if (error instanceof WorkflowsError || error instanceof DOMException) {
10452
+ return error;
10453
+ }
10454
+ logger_default.error(`WorkflowsError - ${actionName} failed`, error);
10455
+ return WorkflowsError.fromUnknown(error);
10456
+ }
10457
+ // Per-call headers plus the resolved config id, with the call's own value winning — again via
10458
+ // Headers, so every HeadersInit shape survives.
10459
+ requestHeaders(configId, headers) {
10460
+ const merged = new Headers(headers);
10461
+ if (!merged.has("x-config-id")) merged.set("x-config-id", configId || "");
10462
+ return merged;
10463
+ }
10464
+ buildRequestHeaders(initHeaders) {
10465
+ const headers = new Headers(initHeaders);
10466
+ const optionHeaders = new Headers(this.defaultHeaders);
10467
+ for (const [key, value] of new Headers(this.clientOptions.headers).entries()) {
10468
+ optionHeaders.set(key, value);
10469
+ }
10470
+ for (const [key, value] of optionHeaders.entries()) {
10471
+ if (!headers.has(key)) {
10472
+ headers.set(key, value);
10473
+ }
10474
+ }
10475
+ if (this.clientOptions.apiKey) {
10476
+ headers.set("Authorization", `Bearer ${this.clientOptions.apiKey}`);
10477
+ }
10478
+ if (this.clientOptions.identityToken) {
10479
+ headers.set("x-app-authorization", `Bearer ${this.clientOptions.identityToken}`);
10480
+ }
10481
+ return headers;
10482
+ }
10483
+ async _fetch(input, init) {
10484
+ const headers = this.buildRequestHeaders(init?.headers);
10485
+ const requestInit = {
10486
+ ...init,
10487
+ headers
10488
+ };
10489
+ if (this.clientOptions.fetch) {
10490
+ return this.clientOptions.fetch(input, {
10491
+ ...requestInit,
10492
+ // return headers as a plain object for easier handling in custom fetch
10493
+ headers: Object.fromEntries(headers.entries())
10494
+ });
10495
+ }
10496
+ if (!headers.has("Authorization") && !headers.has("x-app-authorization")) {
10497
+ throw new WorkflowsError({
10498
+ httpStatusCode: 400,
10499
+ reason: "invalid_state",
10500
+ message: "apiKey is not provided"
10501
+ });
10502
+ }
10503
+ return fetch(input, requestInit);
10504
+ }
10505
+ };
10506
+ var WorkflowsClient_default = WorkflowsClient;
10507
+
10508
+ // src/client/workflows-error.ts
10509
+ var GENERIC_REASONS = /* @__PURE__ */ new Set(["request_failed", "unknown_error"]);
10510
+ function isWorkflowsError(err) {
10511
+ if (err instanceof WorkflowsError) return true;
10512
+ const e = err;
10513
+ return err instanceof Error && typeof e.reason === "string" && /WorkflowsError$/.test(e.name ?? "");
10514
+ }
10515
+ function toApiError(err, workflow, id) {
10516
+ if (err instanceof ApiError) return err;
10517
+ if (err instanceof DOMException && err.name === "AbortError") return err;
10518
+ const e = err;
10519
+ if (isWorkflowsError(err)) {
10520
+ if (e.reason === "client_timeout") {
10521
+ return new ApiError(`Timed out waiting for workflow ${workflow}${id ? `:${id}` : ""}`, {
10522
+ status: 408,
10523
+ code: "timeout"
10131
10524
  });
10132
- return res.ok;
10133
- } catch {
10134
- return false;
10135
10525
  }
10526
+ const status = e.httpStatusCode ?? 502;
10527
+ return new ApiError(e.message ?? "Request failed", {
10528
+ status,
10529
+ code: e.reason && !GENERIC_REASONS.has(e.reason) ? e.reason : codeForStatus(status)
10530
+ });
10531
+ }
10532
+ return new ApiError(err instanceof Error ? err.message : String(err), {
10533
+ status: 502,
10534
+ code: "generation_failed"
10535
+ });
10536
+ }
10537
+
10538
+ // src/client/transport.ts
10539
+ var GATEWAY_HEADERS = {
10540
+ "platform": "api",
10541
+ "X-Touchpoint": "sdk"
10542
+ };
10543
+ function maybeFetch(config) {
10544
+ if (config.fetch) return config.fetch;
10545
+ if (config.apiKey) {
10546
+ const token = config.apiKey.replace(/^Bearer\s+/i, "");
10547
+ return (url, init) => {
10548
+ const headers = new Headers(init?.headers);
10549
+ headers.set("Authorization", `Bearer ${token}`);
10550
+ for (const [name, value] of Object.entries(GATEWAY_HEADERS)) {
10551
+ if (!headers.has(name)) headers.set(name, value);
10552
+ }
10553
+ return globalThis.fetch(url, { ...init, headers });
10554
+ };
10136
10555
  }
10556
+ return null;
10557
+ }
10558
+ function createWorkflowsClient(apiUrl, authedFetch) {
10559
+ return new WorkflowsClient_default({
10560
+ baseUrl: apiUrl,
10561
+ // AuthenticatedFetch takes a string url; the client's fetch type accepts
10562
+ // URL/Request inputs too. Normalize without losing the Request's own url,
10563
+ // method, headers, or body (the client passes plain string urls today,
10564
+ // but the contract allows more).
10565
+ fetch: (input, init) => {
10566
+ if (input instanceof Request) {
10567
+ return authedFetch(input.url, init ?? {
10568
+ method: input.method,
10569
+ headers: input.headers,
10570
+ body: input.body,
10571
+ signal: input.signal
10572
+ });
10573
+ }
10574
+ return authedFetch(typeof input === "string" ? input : input.toString(), init);
10575
+ }
10576
+ });
10577
+ }
10578
+ function buildTransport(wc) {
10579
+ const asResult = (res) => ({
10580
+ result: res.result,
10581
+ usage: res.usage,
10582
+ raw: res.result
10583
+ });
10137
10584
  return {
10138
- /**
10139
- * Ensure a subfolder exists inside the root folder.
10140
- * Creates both root and subfolder if needed. Returns the folder reference.
10141
- * Call with no argument to just ensure the root folder exists.
10142
- */
10143
- async ensureFolder(subfolder) {
10144
- const rootUid = await ensureRootFolder();
10145
- if (!rootUid) return null;
10146
- if (!subfolder) {
10147
- return { name: rootFolderName, uid: rootUid };
10585
+ async execute(request) {
10586
+ try {
10587
+ const res = await wc.run(request.workflow, request.payload, {
10588
+ mode: ExecutionMode.SYNC,
10589
+ abortSignal: request.signal
10590
+ });
10591
+ return asResult(res);
10592
+ } catch (err) {
10593
+ throw toApiError(err, request.workflow);
10148
10594
  }
10149
- const existingUid = await findFolderInList(subfolder, rootUid);
10150
- if (existingUid) return { name: subfolder, uid: existingUid };
10151
- const newUid = await createFolder(subfolder, rootUid);
10152
- if (!newUid) return null;
10153
- return { name: subfolder, uid: newUid };
10154
- },
10155
- /** List subfolders inside the root folder (boards). */
10156
- async folders() {
10157
- const rootUid = await ensureRootFolder();
10158
- if (!rootUid) return [];
10159
- return fetchFolders(rootUid);
10160
10595
  },
10161
- /** List top-level Drive folders + root subfolders, deduplicated. */
10162
- async allFolders() {
10163
- const rootUid = await ensureRootFolder();
10164
- const [rootLevel, subfolders] = await Promise.all([
10165
- fetchFolders(),
10166
- rootUid ? fetchFolders(rootUid) : Promise.resolve([])
10167
- ]);
10168
- const seen = /* @__PURE__ */ new Set();
10169
- const merged = [];
10170
- for (const folder of [...rootLevel, ...subfolders]) {
10171
- if (seen.has(folder.uid)) continue;
10172
- seen.add(folder.uid);
10173
- merged.push(folder);
10596
+ async submit(request) {
10597
+ try {
10598
+ const id = await wc.submit(request.workflow, request.payload, { abortSignal: request.signal });
10599
+ if (!id) {
10600
+ throw new ApiError("No task id in response", { status: 502, code: "invalid_response" });
10601
+ }
10602
+ return id;
10603
+ } catch (err) {
10604
+ throw toApiError(err, request.workflow);
10174
10605
  }
10175
- return merged;
10176
10606
  },
10177
- /** Find a folder by name (case-insensitive) across root and subfolders. */
10178
- async findFolder(name) {
10179
- if (name.toLowerCase() === rootFolderName.toLowerCase()) {
10180
- const uid = await ensureRootFolder();
10181
- return uid ? { name: rootFolderName, uid } : null;
10607
+ async poll(handle, options) {
10608
+ try {
10609
+ const res = await wc.runPolling(handle.workflow, handle.id, {
10610
+ pollingInterval: options?.intervalMs,
10611
+ retriesCount: options?.maxAttempts,
10612
+ abortSignal: options?.signal,
10613
+ onProgress: options?.onProgress
10614
+ });
10615
+ return asResult(res);
10616
+ } catch (err) {
10617
+ throw toApiError(err, handle.workflow, handle.id);
10182
10618
  }
10183
- const rootUid = await ensureRootFolder();
10184
- const [rootLevel, subfolders] = await Promise.all([
10185
- fetchFolders(),
10186
- rootUid ? fetchFolders(rootUid) : Promise.resolve([])
10187
- ]);
10188
- const lowerName = name.toLowerCase();
10189
- return [...rootLevel, ...subfolders].find((f2) => f2.name.toLowerCase() === lowerName) ?? null;
10190
10619
  },
10191
- /**
10192
- * List media items. When no folder is given, lists across all folders (flattened).
10193
- * Optionally filter by media type (sent to backend, not client-side).
10194
- */
10195
- async list(options) {
10196
- const folderUid = options?.folder?.uid ?? void 0;
10197
- const files = await fetchMedia({ folderUid, type: options?.type });
10198
- const items = [];
10199
- for (const file of files) {
10200
- const item = toMediaItem(file);
10201
- if (item) items.push(item);
10620
+ async status(handle, signal) {
10621
+ if (signal?.aborted) {
10622
+ throw new ApiError("Operation aborted", { status: 499, code: "aborted" });
10202
10623
  }
10203
- return items;
10204
- },
10205
- /**
10206
- * List media items with full generation metadata (model, prompt, params, etc.).
10207
- * Same options as list() — folder and type filter.
10208
- */
10209
- async listDetailed(options) {
10210
- const folderUid = options?.folder?.uid ?? void 0;
10211
- const files = await fetchMedia({ folderUid, type: options?.type });
10212
- const items = [];
10213
- for (const file of files) {
10214
- const item = toDetailedItem(file);
10215
- if (item) items.push(item);
10624
+ try {
10625
+ return asResult(await wc.result(handle.workflow, handle.id));
10626
+ } catch (err) {
10627
+ throw toApiError(err, handle.workflow, handle.id);
10216
10628
  }
10217
- return items;
10218
10629
  },
10219
- async getGeneration(fileUid) {
10220
- const file = await fetchFileByUid(fileUid);
10221
- return file ? parseGeneration(file) : null;
10222
- },
10223
- /** Save a file to Drive. Returns save result or null on failure. */
10224
- async save(params2, folder) {
10225
- const targetUid = folder?.uid ?? await ensureRootFolder();
10226
- if (!targetUid) return null;
10227
- const targetFolder = folder ?? { name: rootFolderName, uid: targetUid };
10228
- const body = {
10229
- name: params2.name,
10230
- sourceUrl: params2.url,
10231
- parentFolderUid: targetUid,
10232
- content: {
10233
- type: "STANDALONE",
10234
- resourceType: params2.resourceType,
10235
- sourcePlatform: "WEB"
10236
- },
10237
- preview: {
10238
- url: params2.previewUrl || params2.url,
10239
- width: 1024,
10240
- height: 1024
10241
- },
10242
- attributes: Object.entries(params2.attributes ?? {}).map(([property, value]) => ({
10243
- property,
10244
- value
10245
- }))
10246
- };
10630
+ async options(workflow, payload) {
10247
10631
  try {
10248
- let res = await jsonPost("/cloud-storage/v1/me/files", body);
10249
- if (res.status === 400) {
10250
- const text = await res.text();
10251
- if (text.includes("restricted_keywords")) {
10252
- const ext = params2.name.split(".").pop() || "png";
10253
- body.name = `ai-generation-${Date.now()}.${ext}`;
10254
- res = await jsonPost("/cloud-storage/v1/me/files", body);
10255
- } else {
10256
- return null;
10257
- }
10258
- }
10259
- if (!res.ok) return null;
10260
- const data = await res.json();
10261
- const file = data.response;
10262
- const uid = file?.uid;
10263
- if (!uid) return null;
10264
- return { uid, folder: targetFolder };
10632
+ const res = await wc.options(workflow, payload);
10633
+ return typeof res?.credits === "number" ? res.credits : null;
10265
10634
  } catch {
10266
10635
  return null;
10267
10636
  }
10268
- },
10269
- /** Build standard save params from a generation result. */
10270
- buildSaveParams(url, modelId, modelName, mode, prompt) {
10271
- return {
10272
- url,
10273
- name: buildFilename(prompt, mode),
10274
- resourceType: inferResourceType(mode),
10275
- attributes: {
10276
- tool: "ai-sdk",
10277
- model: modelId,
10278
- prompt: prompt || "",
10279
- service: modelName
10280
- }
10281
- };
10282
- },
10283
- async addReaction(fileUid, reaction) {
10284
- return setReaction(fileUid, reaction);
10285
- },
10286
- async removeReaction(fileUid) {
10287
- return setReaction(fileUid, null);
10288
10637
  }
10289
10638
  };
10290
10639
  }
10291
10640
 
10292
- // ../../node_modules/@picsart/workflows-client/dist/index.mjs
10293
- var logger_default = {
10294
- error: (...args) => {
10295
- console.error(...args);
10296
- },
10297
- warn: (...args) => {
10298
- console.debug(...args);
10299
- },
10300
- info: (...args) => {
10301
- console.info(...args);
10302
- },
10303
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
10304
- debug: (...args) => {
10305
- console.debug(...args);
10306
- }
10307
- };
10308
- var ExecutionMode = /* @__PURE__ */ ((ExecutionMode2) => {
10309
- ExecutionMode2["ASYNC"] = "ASYNC";
10310
- ExecutionMode2["SYNC"] = "SYNC";
10311
- ExecutionMode2["STREAM"] = "STREAM";
10312
- return ExecutionMode2;
10313
- })(ExecutionMode || {});
10314
- var WorkflowsServerError = class extends Error {
10315
- constructor(message) {
10316
- super(`WorkflowsServerError: ${message}`);
10317
- this.name = this.constructor.name;
10318
- }
10319
- };
10320
- var WorkflowsClientError = class extends Error {
10321
- constructor(action, status, responseBody) {
10322
- super(
10323
- `WorkflowsClientError: [${status}] ${action} failed: ${responseBody.reason} - ${responseBody.message}`
10324
- );
10325
- this.name = this.constructor.name;
10326
- this.status = status;
10327
- this.details = responseBody;
10328
- }
10329
- };
10330
- var WorkflowsUnknownError = class extends Error {
10331
- constructor(message) {
10332
- super(`WorkflowsUnknownError: ${message}`);
10333
- this.name = this.constructor.name;
10641
+ // src/client/prepare.ts
10642
+ function resolvePayloadBuild(model, ctx) {
10643
+ const hasImages = Array.isArray(ctx.imageUrls) && ctx.imageUrls.length > 0 || !!ctx.startFrame || !!ctx.endFrame;
10644
+ return {
10645
+ hasImages,
10646
+ workflow: hasImages && model.editWorkflow ? model.editWorkflow : model.workflow,
10647
+ buildPayload: hasImages && model.buildEditPayload ? model.buildEditPayload : model.buildPayload ?? ((ctx2) => ({ prompt: ctx2.prompt }))
10648
+ };
10649
+ }
10650
+ function prepareRequest(model, params2) {
10651
+ const ctx = { ...params2 };
10652
+ const contract = getModelContract(model.id);
10653
+ const validatedCtx = contract ? contract.input.parse(ctx) : ctx;
10654
+ const resolved = resolvePayloadBuild(model, validatedCtx);
10655
+ const payload = resolved.buildPayload(validatedCtx);
10656
+ return { ctx, workflow: resolved.workflow, payload, contract };
10657
+ }
10658
+ function parseResult(completed, model, contract) {
10659
+ throwIfErrorResult(completed.result, model.name);
10660
+ const parsed = contract?.output ? contract.output.parse(completed.result) : completed.result;
10661
+ const multiItems = extractAllResults(parsed);
10662
+ if (multiItems?.length) {
10663
+ const items2 = multiItems.map((item, i) => ({
10664
+ url: item.url,
10665
+ metadata: buildItemMetadata(parsed, item.source, i, model.provider)
10666
+ }));
10667
+ return {
10668
+ url: items2[0].url,
10669
+ items: items2,
10670
+ results: items2,
10671
+ // Sync executions have no job id (nothing to poll) — omit rather than ''.
10672
+ ...completed.handle.id ? { generationId: completed.handle.id } : {},
10673
+ usage: completed.usage
10674
+ };
10334
10675
  }
10335
- };
10336
- var WorkflowResultUpdateAware = class {
10337
- constructor(onProgressFn, onPartialResultFn, onEventFn) {
10338
- this.onProgressFn = onProgressFn;
10339
- this.onPartialResultFn = onPartialResultFn;
10340
- this.onEventFn = onEventFn;
10676
+ const url = extractUrl(parsed);
10677
+ if (!url) {
10678
+ throw new ApiError(`${model.name}: unexpected response \u2014 no result URL`, {
10679
+ status: 502,
10680
+ code: "invalid_response"
10681
+ });
10341
10682
  }
10342
- async onUpdate(response) {
10343
- if (!response.updated) return;
10344
- await this.deliverEvents(response);
10345
- if (response.status !== "IN_PROGRESS") return;
10346
- const newUpdated = new Date(response.updated);
10347
- if (newUpdated?.getTime() !== this.updated?.getTime()) {
10348
- this.updated = newUpdated;
10349
- await this.onPartialResultFn?.(response);
10350
- if (response.progress) {
10351
- await this.onProgressFn?.(response.progress);
10352
- }
10683
+ const obj = parsed && typeof parsed === "object" ? parsed : void 0;
10684
+ let source = parsed;
10685
+ for (const key of ["images", "items", "imageUrls", "data", "previews"]) {
10686
+ const arr = obj?.[key];
10687
+ if (Array.isArray(arr) && arr.length > 0) {
10688
+ source = arr[0];
10689
+ break;
10353
10690
  }
10354
10691
  }
10355
- async deliverEvents(response) {
10356
- if (!response.events?.length || !this.onEventFn) return;
10357
- let startIdx = 0;
10358
- if (this._lastEventId) {
10359
- const lastSeenIdx = response.events.findIndex((e) => e.id === this._lastEventId);
10360
- if (lastSeenIdx !== -1) {
10361
- startIdx = lastSeenIdx + 1;
10362
- }
10363
- }
10364
- const newEvents = response.events.slice(startIdx);
10365
- for (const event of newEvents) {
10366
- await this.onEventFn(event);
10367
- }
10368
- if (newEvents.length > 0) {
10369
- this._lastEventId = newEvents[newEvents.length - 1].id;
10370
- }
10692
+ const items = [{ url, metadata: buildItemMetadata(parsed, source, 0, model.provider) }];
10693
+ return {
10694
+ url,
10695
+ items,
10696
+ results: items,
10697
+ // Sync executions have no job id (nothing to poll) — omit rather than ''.
10698
+ ...completed.handle.id ? { generationId: completed.handle.id } : {},
10699
+ usage: completed.usage
10700
+ };
10701
+ }
10702
+ function parseTextResult(completed, model) {
10703
+ throwIfErrorResult(completed.result, model.name);
10704
+ throwIfErrorResult(completed.raw, model.name);
10705
+ const text = extractText(completed.result) ?? extractText(completed.raw);
10706
+ if (text == null) {
10707
+ throw new ApiError(`${model.name}: unexpected response \u2014 no text`, {
10708
+ status: 502,
10709
+ code: "invalid_response"
10710
+ });
10371
10711
  }
10372
- };
10373
- async function* decodeSSE(stream) {
10374
- for await (const chunk of readSSE(stream)) {
10375
- const lines = chunk.split("\n");
10376
- const sseData = {};
10377
- for (const line of lines) {
10378
- if (line.startsWith("data:")) {
10379
- const data = line.replace(/^data:\s*/, "");
10380
- if (data === "[DONE]") {
10381
- return;
10382
- }
10383
- try {
10384
- sseData.data = JSON.parse(data);
10385
- } catch (err) {
10386
- logger_default.warn(
10387
- `Failed to parse data JSON from OpenAI event stream: - ${data}, err=${JSON.stringify(err)}`
10388
- );
10389
- }
10390
- }
10712
+ return { text, model: model.id, raw: completed.raw ?? completed.result, usage: completed.usage };
10713
+ }
10714
+
10715
+ // src/core/limits.ts
10716
+ var MAX_DRIVE_PROMPT_LENGTH = 18e3;
10717
+
10718
+ // src/client/drive.ts
10719
+ var USER_REACTION_ATTR = "userReaction";
10720
+ function inferResourceType(mode) {
10721
+ if (mode === "video") return "VIDEO";
10722
+ if (mode === "audio") return "AUDIO";
10723
+ return "PHOTO";
10724
+ }
10725
+ function buildFilename(prompt, mode) {
10726
+ const shortId = String(Date.now()).slice(-6);
10727
+ const ext = mode === "video" ? "mp4" : mode === "audio" ? "mp3" : "png";
10728
+ if (!prompt) return `ai-generation-${shortId}.${ext}`;
10729
+ const slug = prompt.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 50);
10730
+ return `${slug}-${shortId}.${ext}`;
10731
+ }
10732
+ function inferMediaType(file) {
10733
+ const name = String(file.name || "");
10734
+ if (/\.(mp3|wav|ogg|aac|flac|m4a)$/i.test(name)) return "audio";
10735
+ if (/\.(mp4|webm|mov|avi|mkv|m4v|wmv)$/i.test(name)) return "video";
10736
+ const contentType = file.contentType ?? file.content;
10737
+ const resourceType = String(contentType?.resourceType || "").toUpperCase();
10738
+ if (resourceType === "VIDEO") return "video";
10739
+ if (resourceType === "AUDIO") return "audio";
10740
+ return "image";
10741
+ }
10742
+ function contentResourceTypes(type) {
10743
+ if (type === "image") return "PHOTO";
10744
+ if (type === "video") return "VIDEO";
10745
+ if (type === "audio") return "AUDIO";
10746
+ return "PHOTO,VIDEO,AUDIO";
10747
+ }
10748
+ function normalizeUrl(raw) {
10749
+ if (typeof raw !== "string") return void 0;
10750
+ return raw.trim() || void 0;
10751
+ }
10752
+ function parseAttributes(raw) {
10753
+ const map = {};
10754
+ if (!raw || typeof raw !== "object") return map;
10755
+ if (Array.isArray(raw)) {
10756
+ for (const a of raw) {
10757
+ map[a.property] = String(a.value);
10758
+ }
10759
+ } else {
10760
+ for (const [k, v] of Object.entries(raw)) {
10761
+ map[k] = String(v);
10391
10762
  }
10392
- yield sseData;
10393
10763
  }
10764
+ return map;
10394
10765
  }
10395
- async function* readSSE(stream) {
10396
- const reader = stream.getReader();
10397
- let buffer = new Uint8Array();
10398
- const decoder = new TextDecoder("utf-8");
10766
+ function parseReaction(value) {
10767
+ return value === "like" || value === "dislike" ? value : void 0;
10768
+ }
10769
+ function parseJsonAttr(raw) {
10770
+ if (!raw) return void 0;
10399
10771
  try {
10400
- while (true) {
10401
- const { value, done } = await reader.read();
10402
- if (done) break;
10403
- const tmp = new Uint8Array(buffer.length + value.length);
10404
- tmp.set(buffer);
10405
- tmp.set(value, buffer.length);
10406
- buffer = tmp;
10407
- let index;
10408
- while ((index = findDoubleNewlineIndex(buffer)) !== -1) {
10409
- const slice = buffer.subarray(0, index);
10410
- yield decoder.decode(slice);
10411
- buffer = buffer.subarray(index);
10412
- }
10413
- }
10414
- if (buffer.length > 0) {
10415
- yield decoder.decode(buffer);
10416
- }
10417
- } finally {
10418
- reader.releaseLock();
10772
+ const value = JSON.parse(raw);
10773
+ return value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
10774
+ } catch {
10775
+ return void 0;
10419
10776
  }
10420
10777
  }
10421
- function findDoubleNewlineIndex(buffer) {
10422
- const newline = 10;
10423
- const carriage = 13;
10424
- for (let i = 0; i < buffer.length - 1; i++) {
10425
- if (buffer[i] === newline && buffer[i + 1] === newline) {
10426
- return i + 2;
10427
- }
10428
- if (buffer[i] === carriage && buffer[i + 1] === carriage) {
10429
- return i + 2;
10430
- }
10431
- if (buffer[i] === carriage && buffer[i + 1] === newline && i + 3 < buffer.length && buffer[i + 2] === carriage && buffer[i + 3] === newline) {
10432
- return i + 4;
10433
- }
10778
+ var asString = (v) => typeof v === "string" && v.trim() ? v : void 0;
10779
+ var asStringArray = (v) => Array.isArray(v) && v.length && v.every((x) => typeof x === "string") ? v : void 0;
10780
+ function toSdkPayload(params2) {
10781
+ const p2 = { prompt: String(params2.prompt ?? "").slice(0, MAX_DRIVE_PROMPT_LENGTH) };
10782
+ for (const [key, value] of Object.entries(params2)) {
10783
+ if (key === "prompt") continue;
10784
+ if (value === void 0 || value === null || value === "") continue;
10785
+ p2[key] = value;
10434
10786
  }
10435
- return -1;
10787
+ return p2;
10436
10788
  }
10437
- var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
10438
- var DEFAULT_POLLING_INTERVAL = 300;
10439
- var DEFAULT_RETRIES_COUNT = 1e3;
10440
- var WorkflowsClient = class {
10441
- constructor(options) {
10442
- this.defaultHeaders = {
10443
- Accept: "application/json",
10444
- "Content-Type": "application/json"
10445
- };
10446
- this.terminalStatuses = [
10447
- "COMPLETED",
10448
- "FAILED"
10449
- /* FAILED */
10450
- ];
10451
- this.options = options || {};
10452
- this.options.baseUrl = this.options.baseUrl || "https://api.picsart.com/";
10453
- if (!this.options.baseUrl.endsWith("/")) this.options.baseUrl += "/";
10454
- if (this.options.apiKey) {
10455
- this.options.apiKey = this.options.apiKey.replace("Bearer ", "");
10456
- }
10457
- if (this.options.identityToken) {
10458
- this.options.identityToken = this.options.identityToken.replace("Bearer ", "");
10459
- }
10460
- this.workflowsApiBaseUrl = `${this.options.baseUrl}workflows`;
10789
+ function buildGenerationAttributes(input) {
10790
+ const attrs = {
10791
+ model: input.modelId,
10792
+ aiSDKPayload: JSON.stringify(toSdkPayload(input.params))
10793
+ };
10794
+ if (input.app) {
10795
+ attrs.appId = input.app.id;
10796
+ attrs.appType = input.app.type;
10461
10797
  }
10462
- async run(name, params2, executionOptions) {
10798
+ return attrs;
10799
+ }
10800
+ function toMediaItem(file) {
10801
+ const url = normalizeUrl(file.sourceUrl);
10802
+ if (!url || String(file.name || "").startsWith("__")) return null;
10803
+ const preview = file.preview;
10804
+ return {
10805
+ uid: String(file.uid ?? ""),
10806
+ url,
10807
+ name: String(file.name || ""),
10808
+ type: inferMediaType(file),
10809
+ previewUrl: normalizeUrl(preview?.url),
10810
+ timestamp: Number(file.updatedAt ?? file.createdAt ?? 0)
10811
+ };
10812
+ }
10813
+ function toDetailedItem(file) {
10814
+ const base2 = toMediaItem(file);
10815
+ if (!base2) return null;
10816
+ const attrs = parseAttributes(file.attributes);
10817
+ let extras = {};
10818
+ if (attrs.textScript) {
10463
10819
  try {
10464
- const remoteSettings = await this.getApiSettings(
10465
- name,
10466
- executionOptions?.remoteSettingName
10467
- );
10468
- const executionMode = remoteSettings.executionMode || executionOptions?.mode || "ASYNC";
10469
- if (executionMode === "SYNC") {
10470
- return this.executeTaskSync(name, params2, executionOptions);
10471
- }
10472
- if (executionMode === "STREAM") {
10473
- return this.executeTaskStream(name, params2, executionOptions);
10474
- }
10475
- const taskId = await this.postTask(name, params2, executionOptions);
10476
- await executionOptions?.onAccepted?.(taskId);
10477
- return this.runPolling(name, taskId, executionOptions);
10478
- } catch (err) {
10479
- throw this.wrapError(name, err);
10820
+ extras = JSON.parse(attrs.textScript);
10821
+ } catch {
10480
10822
  }
10481
10823
  }
10482
- async runTypeSafe(name, params2, executionOptions) {
10483
- return this.run(name, params2, executionOptions);
10824
+ return {
10825
+ ...base2,
10826
+ createdAt: file.createdAt,
10827
+ model: attrs.model,
10828
+ prompt: attrs.prompt || void 0,
10829
+ service: attrs.service,
10830
+ subType: attrs.subType,
10831
+ duration: attrs.duration,
10832
+ userReaction: parseReaction(attrs[USER_REACTION_ATTR]),
10833
+ referenceImageUrls: extras.referenceImageUrls,
10834
+ referenceVideoUrl: extras.referenceVideoUrl,
10835
+ referenceAudioUrl: extras.referenceAudioUrl,
10836
+ aspectRatio: extras.aspectRatio,
10837
+ resolution: extras.resolution,
10838
+ quality: extras.quality
10839
+ };
10840
+ }
10841
+ var LEGACY_TOOL_APP = {
10842
+ "ai-playground": { appId: "com.picsart.ai-playground", appType: "miniapp" }
10843
+ };
10844
+ function adaptLegacyGeneration(attrs) {
10845
+ let extras = {};
10846
+ if (attrs.textScript) {
10847
+ try {
10848
+ extras = JSON.parse(attrs.textScript);
10849
+ } catch {
10850
+ }
10484
10851
  }
10485
- async postTask(taskName, command, executionOptions) {
10486
- const remoteSettings = await this.getApiSettings(taskName, executionOptions?.remoteSettingName);
10487
- const response = await this._fetch(`${this.workflowsApiBaseUrl}/${taskName}/submit`, {
10488
- method: "POST",
10489
- headers: {
10490
- "x-config-id": remoteSettings.configId || "",
10491
- ...executionOptions?.headers
10492
- },
10493
- body: JSON.stringify({
10494
- params: command,
10495
- notification: executionOptions?.notificationConfig
10496
- })
10497
- });
10498
- const json = await this.toSuccessResponse(response, taskName);
10499
- return json.response.id;
10852
+ const aiSDKPayload = { prompt: attrs.prompt || "" };
10853
+ const aspectRatio = asString(extras.aspectRatio);
10854
+ if (aspectRatio) aiSDKPayload.aspectRatio = aspectRatio;
10855
+ const resolution = asString(extras.resolution);
10856
+ if (resolution) aiSDKPayload.resolution = resolution;
10857
+ const duration = extras.duration ?? attrs.duration;
10858
+ if (duration != null && duration !== "") aiSDKPayload.duration = Number(duration);
10859
+ const imageUrls = asStringArray(extras.referenceImageUrls);
10860
+ if (imageUrls) aiSDKPayload.imageUrls = imageUrls;
10861
+ const videoUrl = asString(extras.referenceVideoUrl);
10862
+ if (videoUrl) aiSDKPayload.videoUrl = videoUrl;
10863
+ const audioUrl = asString(extras.referenceAudioUrl);
10864
+ if (audioUrl) aiSDKPayload.audioUrl = audioUrl;
10865
+ const startFrame = asString(extras.startFrame);
10866
+ if (startFrame) aiSDKPayload.startFrame = startFrame;
10867
+ const endFrame = asString(extras.endFrame);
10868
+ if (endFrame) aiSDKPayload.endFrame = endFrame;
10869
+ const quality = asString(extras.quality);
10870
+ if (quality) aiSDKPayload.quality = quality;
10871
+ const style = asString(extras.style);
10872
+ if (style) aiSDKPayload.style = style;
10873
+ const iterateModel = asString(extras.iterateModel);
10874
+ if (iterateModel) aiSDKPayload.iterateModel = iterateModel;
10875
+ const exploreImageId = asString(extras.exploreImageId);
10876
+ if (exploreImageId) aiSDKPayload.exploreImageId = exploreImageId;
10877
+ const app = attrs.tool ? LEGACY_TOOL_APP[attrs.tool] : void 0;
10878
+ return {
10879
+ appId: app?.appId,
10880
+ appType: app?.appType,
10881
+ model: attrs.model || void 0,
10882
+ aiSDKPayload,
10883
+ userReaction: parseReaction(attrs[USER_REACTION_ATTR])
10884
+ };
10885
+ }
10886
+ function parseGeneration(file) {
10887
+ const attrs = parseAttributes(file.attributes);
10888
+ if (!attrs.aiSDKPayload) {
10889
+ return adaptLegacyGeneration(attrs);
10500
10890
  }
10501
- async runPolling(taskName, taskId, executionOptions) {
10502
- let retriesCounter = executionOptions?.retriesCount || DEFAULT_RETRIES_COUNT;
10503
- let pollingResponse;
10504
- const progressAware = new WorkflowResultUpdateAware(
10505
- executionOptions?.onProgress,
10506
- executionOptions?.onPartialResult,
10507
- executionOptions?.onEvent
10508
- );
10509
- do {
10510
- await sleep(executionOptions?.pollingInterval || DEFAULT_POLLING_INTERVAL);
10511
- pollingResponse = await this.getResult(taskName, taskId, executionOptions?.abortSignal, executionOptions?.headers);
10512
- await progressAware.onUpdate(pollingResponse.response);
10513
- retriesCounter--;
10514
- } while (retriesCounter > 0 && !this.terminalStatuses.includes(pollingResponse.response.status));
10515
- if (!this.terminalStatuses.includes(pollingResponse.response.status) || !pollingResponse.response.result) {
10516
- throw new WorkflowsClientError(taskName, 408, {
10517
- status: "error",
10518
- reason: "client_timeout",
10519
- message: "Polling timeout reached. Consider increasing polling interval or retries count from execution options. "
10520
- });
10891
+ return {
10892
+ appId: attrs.appId || void 0,
10893
+ appType: attrs.appType === "native" || attrs.appType === "miniapp" ? attrs.appType : void 0,
10894
+ model: attrs.model || void 0,
10895
+ aiSDKPayload: parseJsonAttr(attrs.aiSDKPayload),
10896
+ userReaction: parseReaction(attrs[USER_REACTION_ATTR])
10897
+ };
10898
+ }
10899
+ function createDriveClient(f, apiUrl, rootFolderName) {
10900
+ let cachedRootUid = null;
10901
+ let rootPromise = null;
10902
+ const jsonPost = async (path, body) => f(`${apiUrl}${path}`, {
10903
+ method: "POST",
10904
+ headers: { "Content-Type": "application/json" },
10905
+ body: JSON.stringify(body)
10906
+ });
10907
+ const jsonGet = async (path) => f(`${apiUrl}${path}`);
10908
+ async function findFolderByPath(name) {
10909
+ try {
10910
+ const res = await jsonGet(`/cloud-storage/v1/me/files-by-path?path=${encodeURIComponent(name)}`);
10911
+ if (!res.ok) return null;
10912
+ const data = await res.json();
10913
+ if (data.status !== "success") return null;
10914
+ const response = data.response;
10915
+ const file = Array.isArray(response) ? response[0] : response;
10916
+ return file?.uid ?? null;
10917
+ } catch {
10918
+ return null;
10521
10919
  }
10522
- return {
10523
- result: pollingResponse.response.result,
10524
- usage: pollingResponse.response.usage
10525
- };
10526
10920
  }
10527
- async executeTaskSync(taskName, command, executionOptions) {
10528
- const remoteSettings = await this.getApiSettings(taskName, executionOptions?.remoteSettingName);
10529
- const response = await this._fetch(
10530
- `${this.workflowsApiBaseUrl}/${taskName}/execute`,
10531
- {
10532
- signal: executionOptions?.abortSignal,
10533
- method: "POST",
10534
- headers: {
10535
- "x-config-id": remoteSettings.configId || "",
10536
- ...executionOptions?.headers
10537
- },
10538
- body: JSON.stringify({ params: command })
10539
- }
10540
- );
10541
- const successResponse = await this.toSuccessResponse(
10542
- response,
10543
- taskName
10544
- );
10545
- return {
10546
- result: successResponse.response.result,
10547
- usage: successResponse.response.usage
10548
- };
10921
+ async function findFolderInList(name, parentUid) {
10922
+ try {
10923
+ const params2 = parentUid ? `parentFolderUid=${parentUid}&fileTypes=FOLDER&limit=100` : `fileTypes=FOLDER&limit=100`;
10924
+ const res = await jsonGet(`/cloud-storage/v1/me/files?${params2}`);
10925
+ if (!res.ok) return null;
10926
+ const data = await res.json();
10927
+ const response = data.response;
10928
+ const files = Array.isArray(response) ? response : [];
10929
+ const match = files.find((f2) => String(f2.name || "").toLowerCase() === name.toLowerCase());
10930
+ return match?.uid ?? null;
10931
+ } catch {
10932
+ return null;
10933
+ }
10549
10934
  }
10550
- async getResult(taskName, taskId, abortSignal, headers) {
10551
- const response = await this._fetch(
10552
- `${this.workflowsApiBaseUrl}/${taskName}/${taskId}/result`,
10553
- {
10554
- method: "GET",
10555
- headers: {
10556
- ...headers
10557
- },
10558
- signal: abortSignal
10559
- }
10560
- );
10561
- return this.toSuccessResponse(response, taskName);
10562
- }
10563
- async executeTaskStream(taskName, command, executionOptions) {
10564
- const remoteSettings = await this.getApiSettings(taskName, executionOptions?.remoteSettingName);
10565
- const onEvent = executionOptions?.onEvent;
10566
- const actionName = `Executing ${taskName} task in stream mode`;
10567
- if (!onEvent) {
10568
- throw new WorkflowsClientError(actionName, 400, {
10569
- message: "onEvent is required for streaming",
10570
- status: "error",
10571
- reason: "INVALID_ARGUMENTS"
10572
- });
10573
- }
10574
- const response = await this._fetch(`${this.workflowsApiBaseUrl}/${taskName}/stream`, {
10575
- signal: executionOptions?.abortSignal,
10576
- method: "POST",
10577
- headers: {
10578
- "x-config-id": remoteSettings.configId || "",
10579
- ...executionOptions?.headers,
10580
- Accept: "text/event-stream"
10581
- },
10582
- body: JSON.stringify({ params: command })
10583
- });
10584
- await this.throwIfError(response, actionName);
10585
- if (!response.body) throw new WorkflowsServerError("No response body");
10586
- let completedEvent = {};
10587
- for await (const event of decodeSSE(response.body)) {
10588
- if (executionOptions?.abortSignal?.aborted) break;
10589
- const data = event.data;
10590
- if (data.type.startsWith("event.")) {
10591
- await onEvent({
10592
- ...data,
10593
- type: data.type.replace(/^event\.\s*/, "")
10594
- });
10595
- }
10596
- if (data.type === "task.partial-result") {
10597
- await executionOptions.onPartialResult?.({
10598
- status: "IN_PROGRESS",
10599
- result: data.result
10600
- });
10601
- }
10602
- if (data.type === "task.failed") {
10603
- const failedResult = data.result;
10604
- const statusCode = failedResult.statusCode;
10605
- if (statusCode >= 500) {
10606
- throw new WorkflowsServerError(`[${statusCode}] - ${actionName} failed with message ${failedResult.message}.`);
10607
- }
10608
- if (statusCode >= 400) {
10609
- throw new WorkflowsClientError(actionName, statusCode, failedResult);
10610
- }
10611
- throw new WorkflowsUnknownError(failedResult.message || failedResult.reason);
10612
- }
10613
- if (data.type === "task.completed") {
10614
- completedEvent = data;
10615
- }
10616
- }
10617
- return {
10618
- result: completedEvent.result,
10619
- usage: completedEvent.usage
10620
- };
10621
- }
10622
- async executionsHistory(taskName, offset = 0, limit = 10, isGrouped = false) {
10935
+ async function createFolder(name, parentUid) {
10623
10936
  try {
10624
- const grouped = isGrouped ? "/grouped" : "";
10625
- const url = `${this.options.baseUrl}workflows-history${grouped}?name=${taskName}&limit=${limit}&offset=${offset}`;
10626
- const res = await this._fetch(url);
10627
- return this.toSuccessResponse(res, "requestHistory");
10628
- } catch (err) {
10629
- throw this.wrapError("requestHistory", err);
10937
+ const body = { name };
10938
+ if (parentUid) body.parentFolderUid = parentUid;
10939
+ const res = await jsonPost("/cloud-storage/v1/me/folders", body);
10940
+ if (!res.ok) return null;
10941
+ const data = await res.json();
10942
+ const response = data.response;
10943
+ return response?.uid ?? null;
10944
+ } catch {
10945
+ return null;
10630
10946
  }
10631
10947
  }
10632
- async toSuccessResponse(response, actionName) {
10633
- await this.throwIfError(response, actionName);
10634
- return await response.json();
10948
+ async function resolveRootFolder() {
10949
+ const byPath = await findFolderByPath(rootFolderName);
10950
+ if (byPath) return byPath;
10951
+ const inList = await findFolderInList(rootFolderName);
10952
+ if (inList) return inList;
10953
+ const recheck = await findFolderByPath(rootFolderName);
10954
+ if (recheck) return recheck;
10955
+ return createFolder(rootFolderName);
10635
10956
  }
10636
- async throwIfError(response, actionName) {
10637
- if (response.status >= 500) {
10638
- let message;
10639
- try {
10640
- const errorResponse = await response.json();
10641
- message = errorResponse.message || errorResponse.reason || "Unknown error";
10642
- } catch (err) {
10643
- message = "Non json response was returned from server";
10644
- }
10645
- throw new WorkflowsServerError(`[${response.status}] - ${actionName} failed with message: ${message}.`);
10646
- }
10647
- if (!response.ok) {
10648
- throw new WorkflowsClientError(actionName, response.status, await response.json());
10957
+ async function ensureRootFolder() {
10958
+ if (cachedRootUid) return cachedRootUid;
10959
+ if (!rootPromise) {
10960
+ rootPromise = resolveRootFolder().then((uid) => {
10961
+ cachedRootUid = uid;
10962
+ rootPromise = null;
10963
+ return uid;
10964
+ }).catch((err) => {
10965
+ setTimeout(() => {
10966
+ rootPromise = null;
10967
+ }, 1e4);
10968
+ throw err;
10969
+ });
10649
10970
  }
10971
+ return rootPromise;
10650
10972
  }
10651
- async getApiSettings(name, remoteSettingName) {
10652
- if (!this.options.getRemoteSettings) return {};
10653
- const settingName = remoteSettingName || `${name.replace(/-/g, "_").toLowerCase()}_api`;
10973
+ async function fetchFolders(parentUid) {
10654
10974
  try {
10655
- const apiSetting = await this.options.getRemoteSettings(
10656
- settingName,
10657
- "miniapp"
10658
- );
10659
- return {
10660
- configId: apiSetting?.configId || "",
10661
- executionMode: apiSetting?.executionMode
10662
- };
10663
- } catch (err) {
10664
- logger_default.error(
10665
- `workflows.getConfigId - failed when fetching remoteSettings: settingName=${settingName}`,
10666
- err
10667
- );
10668
- return {};
10975
+ const params2 = parentUid ? `parentFolderUid=${parentUid}&fileTypes=FOLDER&limit=100` : `fileTypes=FOLDER&limit=100`;
10976
+ const res = await jsonGet(`/cloud-storage/v1/me/files?${params2}`);
10977
+ if (!res.ok) return [];
10978
+ const data = await res.json();
10979
+ const files = Array.isArray(data.response) ? data.response : [];
10980
+ return files.filter((f2) => f2.uid && f2.name).map((f2) => ({ name: String(f2.name), uid: String(f2.uid) }));
10981
+ } catch {
10982
+ return [];
10669
10983
  }
10670
10984
  }
10671
- wrapError(actionName, error) {
10672
- if (error instanceof WorkflowsClientError || error instanceof WorkflowsServerError || error instanceof DOMException) {
10673
- return error;
10985
+ async function fetchMedia(opts) {
10986
+ try {
10987
+ const endpoint = opts.folderUid ? "/cloud-storage/v1/me/files" : "/cloud-storage/v1/me/flattened-files";
10988
+ const params2 = [
10989
+ opts.folderUid ? `parentFolderUid=${opts.folderUid}` : "",
10990
+ "limit=100",
10991
+ "sortType=UPDATED",
10992
+ "sortOrder=DESC",
10993
+ "fileTypes=FILE",
10994
+ `contentResourceTypes=${contentResourceTypes(opts.type)}`
10995
+ ].filter(Boolean).join("&");
10996
+ const res = await jsonGet(`${endpoint}?${params2}`);
10997
+ if (!res.ok) return [];
10998
+ const data = await res.json();
10999
+ return Array.isArray(data.response) ? data.response : [];
11000
+ } catch {
11001
+ return [];
10674
11002
  }
10675
- logger_default.error(`PluggableAPIUnknownError - ${actionName} failed`, error);
10676
- return new WorkflowsUnknownError(
10677
- `workflows.${actionName} failed - ${error.message}`
10678
- );
10679
11003
  }
10680
- buildRequestHeaders(initHeaders) {
10681
- const headers = new Headers(initHeaders);
10682
- const optionHeaders = new Headers({
10683
- ...this.defaultHeaders,
10684
- ...this.options.headers
10685
- });
10686
- for (const [key, value] of optionHeaders.entries()) {
10687
- if (!headers.has(key)) {
10688
- headers.set(key, value);
10689
- }
10690
- }
10691
- if (this.options.apiKey) {
10692
- headers.set("Authorization", `Bearer ${this.options.apiKey}`);
10693
- }
10694
- if (this.options.identityToken) {
10695
- headers.set("x-app-authorization", `Bearer ${this.options.identityToken}`);
11004
+ async function fetchFileByUid(fileUid) {
11005
+ try {
11006
+ const res = await jsonGet(`/drive/v1/files/${fileUid}`);
11007
+ if (!res.ok) return null;
11008
+ const data = await res.json();
11009
+ const file = data.response;
11010
+ return file && typeof file === "object" && !Array.isArray(file) ? file : null;
11011
+ } catch {
11012
+ return null;
10696
11013
  }
10697
- return headers;
10698
11014
  }
10699
- async _fetch(input, init) {
10700
- const headers = this.buildRequestHeaders(init?.headers);
10701
- const requestInit = {
10702
- ...init,
10703
- headers
10704
- };
10705
- if (this.options.fetch) {
10706
- return this.options.fetch(input, {
10707
- ...requestInit,
10708
- // return headers as a plain object for easier handling in custom fetch
10709
- headers: Object.fromEntries(headers.entries())
11015
+ async function setReaction(fileUid, reaction) {
11016
+ try {
11017
+ const res = await f(`${apiUrl}/drive/v1/files/${fileUid}`, {
11018
+ method: "PATCH",
11019
+ headers: { "Content-Type": "application/json" },
11020
+ body: JSON.stringify({ attributes: { [USER_REACTION_ATTR]: reaction } })
10710
11021
  });
11022
+ return res.ok;
11023
+ } catch {
11024
+ return false;
10711
11025
  }
10712
- if (!headers.has("Authorization") && !headers.has("x-app-authorization")) {
10713
- throw new Error("apiKey is not provided");
10714
- }
10715
- return fetch(input, requestInit);
10716
11026
  }
10717
- };
10718
- var WorkflowsClient_default = WorkflowsClient;
10719
-
10720
- // src/client/apis.ts
10721
- function createApis(config) {
10722
- const f = config ? resolveFetch(config) : null;
10723
- const client = config && f ? new WorkflowsClient_default({
10724
- baseUrl: config.apiUrl,
10725
- fetch: (input, init) => f(typeof input === "string" ? input : input.toString(), init)
10726
- }) : null;
10727
11027
  return {
10728
- async run(api, payload, options) {
10729
- if (!client) {
10730
- throw new Error("ai.apis requires a client created with a ClientConfig (authenticated fetch).");
11028
+ /**
11029
+ * Ensure a subfolder exists inside the root folder.
11030
+ * Creates both root and subfolder if needed. Returns the folder reference.
11031
+ * Call with no argument to just ensure the root folder exists.
11032
+ */
11033
+ async ensureFolder(subfolder) {
11034
+ const rootUid = await ensureRootFolder();
11035
+ if (!rootUid) return null;
11036
+ if (!subfolder) {
11037
+ return { name: rootFolderName, uid: rootUid };
10731
11038
  }
10732
- const forwarded = { ...options ?? {} };
10733
- delete forwarded.remoteSettingName;
10734
- delete forwarded.onPartialResult;
10735
- delete forwarded.notificationConfig;
10736
- return client.run(api, payload, forwarded);
10737
- }
10738
- // The public conditional-typed signature lives on ApisClient; the runtime
10739
- // impl is uniform, so we assert the shape here.
10740
- };
10741
- }
10742
-
10743
- // src/client/catalogs.ts
10744
- var DEFAULT_LIMIT = 100;
10745
- var MIN_TTL_SECONDS = 60;
10746
- var copyPage = (page) => ({
10747
- items: [...page.items],
10748
- nextCursor: page.nextCursor
10749
- });
10750
- var abortError = (signal) => signal.reason ?? new DOMException("The catalog load was aborted.", "AbortError");
10751
- function abortable(promise, signal) {
10752
- if (!signal) return promise;
10753
- if (signal.aborted) return Promise.reject(abortError(signal));
10754
- return new Promise((resolve, reject) => {
10755
- const onAbort = () => reject(abortError(signal));
10756
- signal.addEventListener("abort", onAbort, { once: true });
10757
- const settle = () => signal.removeEventListener("abort", onAbort);
10758
- promise.then(
10759
- (value) => {
10760
- settle();
10761
- resolve(value);
10762
- },
10763
- (err) => {
10764
- settle();
10765
- reject(err);
11039
+ const existingUid = await findFolderInList(subfolder, rootUid);
11040
+ if (existingUid) return { name: subfolder, uid: existingUid };
11041
+ const newUid = await createFolder(subfolder, rootUid);
11042
+ if (!newUid) return null;
11043
+ return { name: subfolder, uid: newUid };
11044
+ },
11045
+ /** List subfolders inside the root folder (boards). */
11046
+ async folders() {
11047
+ const rootUid = await ensureRootFolder();
11048
+ if (!rootUid) return [];
11049
+ return fetchFolders(rootUid);
11050
+ },
11051
+ /** List top-level Drive folders + root subfolders, deduplicated. */
11052
+ async allFolders() {
11053
+ const rootUid = await ensureRootFolder();
11054
+ const [rootLevel, subfolders] = await Promise.all([
11055
+ fetchFolders(),
11056
+ rootUid ? fetchFolders(rootUid) : Promise.resolve([])
11057
+ ]);
11058
+ const seen = /* @__PURE__ */ new Set();
11059
+ const merged = [];
11060
+ for (const folder of [...rootLevel, ...subfolders]) {
11061
+ if (seen.has(folder.uid)) continue;
11062
+ seen.add(folder.uid);
11063
+ merged.push(folder);
10766
11064
  }
10767
- );
10768
- });
10769
- }
10770
- function createCatalogs(transport, options) {
10771
- const stores = /* @__PURE__ */ new Map();
10772
- const inflight = /* @__PURE__ */ new Map();
10773
- const keyOf2 = (s) => `${s.workflow} ${s.modelId ?? ""}`;
10774
- async function fetchPage(workflow, query) {
10775
- const payload = {};
10776
- if (query.modelId) payload.modelId = query.modelId;
10777
- if (query.cursor) payload.cursor = query.cursor;
10778
- if (query.limit) payload.limit = query.limit;
10779
- const raw = await transport.execute({ workflow, payload });
10780
- const container = raw?.response ?? raw;
10781
- if (raw?.status === "error" || container?.status === "FAILED") {
10782
- const message = container?.message ?? container?.error ?? raw?.message;
10783
- throw new Error(`${workflow} failed${message ? `: ${String(message)}` : ""}`);
10784
- }
10785
- const result = container?.result;
11065
+ return merged;
11066
+ },
11067
+ /** Find a folder by name (case-insensitive) across root and subfolders. */
11068
+ async findFolder(name) {
11069
+ if (name.toLowerCase() === rootFolderName.toLowerCase()) {
11070
+ const uid = await ensureRootFolder();
11071
+ return uid ? { name: rootFolderName, uid } : null;
11072
+ }
11073
+ const rootUid = await ensureRootFolder();
11074
+ const [rootLevel, subfolders] = await Promise.all([
11075
+ fetchFolders(),
11076
+ rootUid ? fetchFolders(rootUid) : Promise.resolve([])
11077
+ ]);
11078
+ const lowerName = name.toLowerCase();
11079
+ return [...rootLevel, ...subfolders].find((f2) => f2.name.toLowerCase() === lowerName) ?? null;
11080
+ },
11081
+ /**
11082
+ * List media items. When no folder is given, lists across all folders (flattened).
11083
+ * Optionally filter by media type (sent to backend, not client-side).
11084
+ */
11085
+ async list(options) {
11086
+ const folderUid = options?.folder?.uid ?? void 0;
11087
+ const files = await fetchMedia({ folderUid, type: options?.type });
11088
+ const items = [];
11089
+ for (const file of files) {
11090
+ const item = toMediaItem(file);
11091
+ if (item) items.push(item);
11092
+ }
11093
+ return items;
11094
+ },
11095
+ /**
11096
+ * List media items with full generation metadata (model, prompt, params, etc.).
11097
+ * Same options as list() — folder and type filter.
11098
+ */
11099
+ async listDetailed(options) {
11100
+ const folderUid = options?.folder?.uid ?? void 0;
11101
+ const files = await fetchMedia({ folderUid, type: options?.type });
11102
+ const items = [];
11103
+ for (const file of files) {
11104
+ const item = toDetailedItem(file);
11105
+ if (item) items.push(item);
11106
+ }
11107
+ return items;
11108
+ },
11109
+ async getGeneration(fileUid) {
11110
+ const file = await fetchFileByUid(fileUid);
11111
+ return file ? parseGeneration(file) : null;
11112
+ },
11113
+ /** Save a file to Drive. Returns save result or null on failure. */
11114
+ async save(params2, folder) {
11115
+ const targetUid = folder?.uid ?? await ensureRootFolder();
11116
+ if (!targetUid) return null;
11117
+ const targetFolder = folder ?? { name: rootFolderName, uid: targetUid };
11118
+ const body = {
11119
+ name: params2.name,
11120
+ sourceUrl: params2.url,
11121
+ parentFolderUid: targetUid,
11122
+ content: {
11123
+ type: "STANDALONE",
11124
+ resourceType: params2.resourceType,
11125
+ sourcePlatform: "WEB"
11126
+ },
11127
+ preview: {
11128
+ url: params2.previewUrl || params2.url,
11129
+ width: 1024,
11130
+ height: 1024
11131
+ },
11132
+ attributes: Object.entries(params2.attributes ?? {}).map(([property, value]) => ({
11133
+ property,
11134
+ value
11135
+ }))
11136
+ };
11137
+ try {
11138
+ let res = await jsonPost("/cloud-storage/v1/me/files", body);
11139
+ if (res.status === 400) {
11140
+ const text = await res.text();
11141
+ if (text.includes("restricted_keywords")) {
11142
+ const ext = params2.name.split(".").pop() || "png";
11143
+ body.name = `ai-generation-${Date.now()}.${ext}`;
11144
+ res = await jsonPost("/cloud-storage/v1/me/files", body);
11145
+ } else {
11146
+ return null;
11147
+ }
11148
+ }
11149
+ if (!res.ok) return null;
11150
+ const data = await res.json();
11151
+ const file = data.response;
11152
+ const uid = file?.uid;
11153
+ if (!uid) return null;
11154
+ return { uid, folder: targetFolder };
11155
+ } catch {
11156
+ return null;
11157
+ }
11158
+ },
11159
+ /** Build standard save params from a generation result. */
11160
+ buildSaveParams(url, modelId, modelName, mode, prompt) {
11161
+ return {
11162
+ url,
11163
+ name: buildFilename(prompt, mode),
11164
+ resourceType: inferResourceType(mode),
11165
+ attributes: {
11166
+ tool: "ai-sdk",
11167
+ model: modelId,
11168
+ prompt: prompt || "",
11169
+ service: modelName
11170
+ }
11171
+ };
11172
+ },
11173
+ async addReaction(fileUid, reaction) {
11174
+ return setReaction(fileUid, reaction);
11175
+ },
11176
+ async removeReaction(fileUid) {
11177
+ return setReaction(fileUid, null);
11178
+ }
11179
+ };
11180
+ }
11181
+
11182
+ // src/client/apis.ts
11183
+ function createApis(client) {
11184
+ return {
11185
+ async run(api, payload, options) {
11186
+ if (!client) {
11187
+ throw new ApiError(
11188
+ "`ai.apis` requires `apiUrl` plus `fetch` or `apiKey` on createClient \u2014 the workflows APIs are not served by a custom transport.",
11189
+ { status: 400, code: "unsupported_transport" }
11190
+ );
11191
+ }
11192
+ const forwarded = { ...options ?? {} };
11193
+ delete forwarded.remoteSettingName;
11194
+ delete forwarded.onPartialResult;
11195
+ delete forwarded.notificationConfig;
11196
+ try {
11197
+ return await client.run(api, payload, forwarded);
11198
+ } catch (err) {
11199
+ throw toApiError(err, api);
11200
+ }
11201
+ }
11202
+ // The public conditional-typed signature lives on ApisClient; the runtime
11203
+ // impl is uniform, so we assert the shape here.
11204
+ };
11205
+ }
11206
+
11207
+ // src/client/catalogs.ts
11208
+ var DEFAULT_LIMIT = 100;
11209
+ var MIN_TTL_SECONDS = 60;
11210
+ var copyPage = (page) => ({
11211
+ items: [...page.items],
11212
+ nextCursor: page.nextCursor
11213
+ });
11214
+ var abortError = (signal) => signal.reason ?? new DOMException("The catalog load was aborted.", "AbortError");
11215
+ function abortable(promise, signal) {
11216
+ if (!signal) return promise;
11217
+ if (signal.aborted) return Promise.reject(abortError(signal));
11218
+ return new Promise((resolve, reject) => {
11219
+ const onAbort = () => reject(abortError(signal));
11220
+ signal.addEventListener("abort", onAbort, { once: true });
11221
+ const settle = () => signal.removeEventListener("abort", onAbort);
11222
+ promise.then(
11223
+ (value) => {
11224
+ settle();
11225
+ resolve(value);
11226
+ },
11227
+ (err) => {
11228
+ settle();
11229
+ reject(err);
11230
+ }
11231
+ );
11232
+ });
11233
+ }
11234
+ function createCatalogs(transport, options) {
11235
+ const stores = /* @__PURE__ */ new Map();
11236
+ const inflight = /* @__PURE__ */ new Map();
11237
+ const keyOf2 = (s) => `${s.workflow} ${s.modelId ?? ""}`;
11238
+ async function fetchPage(workflow, query) {
11239
+ const payload = {};
11240
+ if (query.modelId) payload.modelId = query.modelId;
11241
+ if (query.cursor) payload.cursor = query.cursor;
11242
+ if (query.limit) payload.limit = query.limit;
11243
+ let res;
11244
+ try {
11245
+ res = await transport.execute({ workflow, payload });
11246
+ } catch (err) {
11247
+ if (err instanceof ApiError || err instanceof DOMException && err.name === "AbortError") throw err;
11248
+ throw new ApiError(`${workflow} failed: ${err instanceof Error ? err.message : String(err)}`, {
11249
+ status: 502,
11250
+ code: "bad_gateway"
11251
+ });
11252
+ }
11253
+ const body = res.result ?? res.raw;
11254
+ const container = body?.response ?? body;
11255
+ const result = container?.result ?? container;
11256
+ throwIfErrorResult(result, workflow);
10786
11257
  if (!result || !Array.isArray(result.items)) {
10787
- throw new Error(`${workflow} returned no catalog result`);
11258
+ throw new ApiError(`${workflow} returned no catalog result`, {
11259
+ status: 502,
11260
+ code: "invalid_response"
11261
+ });
10788
11262
  }
10789
11263
  return { ...result, nextCursor: result.nextCursor ?? null };
10790
11264
  }
@@ -10876,6 +11350,13 @@ function createCatalogs(transport, options) {
10876
11350
  return client;
10877
11351
  }
10878
11352
 
11353
+ // src/client/types.ts
11354
+ var GenerationEventType = {
11355
+ Progress: "generation.progress",
11356
+ Completed: "generation.completed",
11357
+ Failed: "generation.failed"
11358
+ };
11359
+
10879
11360
  // src/client/index.ts
10880
11361
  var MODE_POLL_DEFAULTS = {
10881
11362
  video: { intervalMs: 2e3, maxAttempts: 1800 },
@@ -10895,30 +11376,90 @@ function resolvePollOptions(model, overrides) {
10895
11376
  return resolved;
10896
11377
  }
10897
11378
  function createClient(config) {
10898
- const isConfig = isClientConfig(config);
10899
- const transport = isConfig ? buildTransport(config) : config;
10900
- const client = createWorkflowClient(transport, { pollingIntervalMs: 2e3 });
10901
- const supportsSubmit = typeof transport.submit === "function";
10902
- const apis = createApis(isConfig ? config : null);
10903
- const catalogs = createCatalogs(transport, isConfig ? config.catalogs : void 0);
10904
- const inputsTransformationConfig = isConfig ? config.inputsTransformation : void 0;
10905
- const driveConfig = isConfig ? config.drive : void 0;
10906
- const driveClient = isConfig && driveConfig ? createDriveClient(resolveFetch(config), config.apiUrl, driveConfig.folder) : null;
11379
+ const authedFetch = maybeFetch(config);
11380
+ const wc = config.apiUrl && authedFetch ? createWorkflowsClient(config.apiUrl, authedFetch) : null;
11381
+ function buildDefaultTransport() {
11382
+ if (wc) return buildTransport(wc);
11383
+ throw new Error(config.apiUrl ? "createClient config requires either `fetch` or `apiKey` (or a custom `transport`)." : "createClient config requires `apiUrl` (or a custom `transport`).");
11384
+ }
11385
+ const transport = config.transport ?? buildDefaultTransport();
11386
+ const supportsAsync = typeof transport.submit === "function" && typeof transport.poll === "function";
11387
+ const apis = createApis(wc);
11388
+ const inputsTransformationConfig = config.inputsTransformation;
11389
+ const catalogs = createCatalogs(transport, config.catalogs);
11390
+ const driveConfig = config.drive;
11391
+ const driveApiUrl = config.apiUrl;
11392
+ if (driveConfig && !(authedFetch && driveApiUrl)) {
11393
+ throw new Error("createClient `drive` requires `apiUrl` plus `fetch` or `apiKey` \u2014 Drive is a REST surface, not served by a custom transport.");
11394
+ }
11395
+ const driveClient = driveConfig && authedFetch && driveApiUrl ? createDriveClient(authedFetch, driveApiUrl, driveConfig.folder) : null;
11396
+ function toApiError2(err, signal) {
11397
+ if (err instanceof ApiError) return err;
11398
+ if (err instanceof DOMException && err.name === "AbortError") {
11399
+ if (signal?.aborted) {
11400
+ return new ApiError("Operation aborted", { status: 499, code: "aborted" });
11401
+ }
11402
+ throw err;
11403
+ }
11404
+ return new ApiError(err instanceof Error ? err.message : String(err), {
11405
+ status: 502,
11406
+ code: "generation_failed"
11407
+ });
11408
+ }
11409
+ function unsupportedTransport(capability) {
11410
+ return new ApiError(`Transport does not support ${capability} (execute-only transport)`, {
11411
+ status: 400,
11412
+ code: "unsupported_transport"
11413
+ });
11414
+ }
11415
+ function asCompleted(handle, res) {
11416
+ return toCompletedStatus(handle, res.result, res.raw ?? res.result, res.usage);
11417
+ }
11418
+ function pollJob(handle, poll, onProgress) {
11419
+ if (!transport.poll) return Promise.reject(unsupportedTransport("polling"));
11420
+ return transport.poll(handle, { ...poll, onProgress });
11421
+ }
11422
+ function assertAsyncLifecycle() {
11423
+ if (!transport.submit) throw unsupportedTransport("submit");
11424
+ if (!transport.poll) throw unsupportedTransport("polling");
11425
+ }
11426
+ function assertMediaModel(model) {
11427
+ if (model.mode === "text") {
11428
+ throw new ApiError(`${model.name} is a text model \u2014 use generateText() instead.`, {
11429
+ status: 400,
11430
+ code: "wrong_model_mode"
11431
+ });
11432
+ }
11433
+ }
11434
+ async function submitJob(workflow, payload, signal) {
11435
+ if (signal?.aborted) {
11436
+ throw new ApiError("Operation aborted", { status: 499, code: "aborted" });
11437
+ }
11438
+ if (!transport.submit) throw unsupportedTransport("submit");
11439
+ const id = await transport.submit({ workflow, payload, signal });
11440
+ if (!id) {
11441
+ throw new ApiError("No task id in response", { status: 502, code: "invalid_response" });
11442
+ }
11443
+ return id;
11444
+ }
10907
11445
  async function executeModel(model, workflow, payload, options) {
10908
11446
  const signal = options?.signal;
10909
- if (model.syncExecute || !supportsSubmit) {
10910
- const syncResponse = await client.run(
10911
- { workflow, payload, signal },
10912
- { mode: "sync" }
10913
- );
10914
- return toCompletedStatus(
10915
- syncResponse.handle,
10916
- extractSyncResult(syncResponse.raw),
10917
- syncResponse.raw,
10918
- syncResponse.usage
10919
- );
11447
+ try {
11448
+ if (model.syncExecute || !supportsAsync) {
11449
+ const res2 = await transport.execute({ workflow, payload, signal });
11450
+ return toCompletedStatus(
11451
+ { workflow, id: "" },
11452
+ extractSyncResult(res2.result) ?? res2.result,
11453
+ res2.raw ?? res2.result,
11454
+ res2.usage
11455
+ );
11456
+ }
11457
+ const id = await submitJob(workflow, payload, signal);
11458
+ const res = await pollJob({ workflow, id }, resolvePollOptions(model, options));
11459
+ return asCompleted({ workflow, id }, res);
11460
+ } catch (err) {
11461
+ throw toApiError2(err, signal);
10920
11462
  }
10921
- return client.run({ workflow, payload, signal }, resolvePollOptions(model, options));
10922
11463
  }
10923
11464
  function buildDrivePayloadOptions(model, params2, options) {
10924
11465
  const explicit = options?.drive;
@@ -10950,24 +11491,33 @@ function createClient(config) {
10950
11491
  }
10951
11492
  };
10952
11493
  }
11494
+ async function resolveJobHandle(model, generationId, signal) {
11495
+ const primary = { workflow: model.workflow, id: generationId };
11496
+ if (!model.editWorkflow || !transport.status) return primary;
11497
+ try {
11498
+ await transport.status(primary, signal);
11499
+ return primary;
11500
+ } catch (err) {
11501
+ if (err instanceof ApiError && err.status === 404) {
11502
+ return { workflow: model.editWorkflow, id: generationId };
11503
+ }
11504
+ throw err;
11505
+ }
11506
+ }
10953
11507
  return {
10954
11508
  // ── Simple path ──────────────────────────────────────────────────
10955
11509
  /**
10956
11510
  * Generate content using a model.
10957
11511
  *
10958
11512
  * Validates input, builds the vendor payload, picks the right workflow,
10959
- * submits the job, polls to completion, and returns the result URL.
11513
+ * submits the job, polls to completion, and returns the parsed result
11514
+ * (`items[]` with per-item URLs and promoted vendor metadata).
10960
11515
  * If drive options are provided (or DriveConfig is set), the backend
10961
11516
  * saves the result to Picsart Drive.
10962
11517
  */
10963
11518
  async generate(model, params2, options) {
10964
11519
  const resolved = resolveModel(model);
10965
- if (resolved.mode === "text") {
10966
- throw new ApiError(`${resolved.name} is a text model \u2014 use generateText() instead.`, {
10967
- status: 400,
10968
- code: "wrong_model_mode"
10969
- });
10970
- }
11520
+ assertMediaModel(resolved);
10971
11521
  const { workflow, payload, contract } = prepareRequest(resolved, params2);
10972
11522
  const drive = buildDrivePayloadOptions(resolved, params2, options);
10973
11523
  const finalPayload = injectPayloadOptions(payload, drive, options?.inputsTransformation);
@@ -10994,13 +11544,6 @@ function createClient(config) {
10994
11544
  const completed = await executeModel(resolved, workflow, payload, options);
10995
11545
  return parseTextResult(completed, resolved);
10996
11546
  },
10997
- /** @deprecated Use `getCredits()` instead. */
10998
- async estimate(model, params2) {
10999
- if (!transport.options) return null;
11000
- const resolved = resolveModel(model);
11001
- const { workflow, payload } = prepareRequest(resolved, params2);
11002
- return await transport.options(workflow, payload) ?? null;
11003
- },
11004
11547
  /**
11005
11548
  * Get exact credit cost for a model with specific parameters.
11006
11549
  * Calls the backend /options endpoint for real-time pricing.
@@ -11019,61 +11562,114 @@ function createClient(config) {
11019
11562
  return payload;
11020
11563
  },
11021
11564
  // ── Advanced lifecycle ────────────────────────────────────────────
11022
- /** Submit a generation job and get a handle back. */
11565
+ /** Submit a generation job and get its generation id back. Media models
11566
+ * only — text models have no async lifecycle (`result()`/`subscribe()`
11567
+ * reject them). Pass the id to `result(model, id)` / `subscribe(model, id)`. */
11023
11568
  async submit(model, params2, options) {
11024
11569
  const resolved = resolveModel(model);
11570
+ assertMediaModel(resolved);
11571
+ assertAsyncLifecycle();
11025
11572
  const { workflow, payload } = prepareRequest(resolved, params2);
11026
11573
  const drive = buildDrivePayloadOptions(resolved, params2, options);
11027
11574
  const finalPayload = injectPayloadOptions(payload, drive, options?.inputsTransformation);
11028
- return client.submit({ workflow, payload: finalPayload, signal: options?.signal });
11029
- },
11030
- /** Check the current status of a submitted job. */
11031
- async status(handle, signal) {
11032
- return client.status(handle, signal);
11575
+ try {
11576
+ return await submitJob(workflow, finalPayload, options?.signal);
11577
+ } catch (err) {
11578
+ throw toApiError2(err, options?.signal);
11579
+ }
11033
11580
  },
11034
11581
  /** Poll a submitted job until it completes and return the parsed result. */
11035
- async result(handle, model, options) {
11582
+ async result(model, generationId, options) {
11036
11583
  const resolved = resolveModel(model);
11584
+ assertMediaModel(resolved);
11037
11585
  const contract = getModelContract(resolved.id);
11038
- const completed = await client.result(handle, resolvePollOptions(resolved, options));
11586
+ assertAsyncLifecycle();
11587
+ const handle = await resolveJobHandle(resolved, generationId, options?.signal);
11588
+ let completed;
11589
+ try {
11590
+ completed = asCompleted(handle, await pollJob(handle, resolvePollOptions(resolved, options)));
11591
+ } catch (err) {
11592
+ throw toApiError2(err, options?.signal);
11593
+ }
11039
11594
  return parseResult(completed, resolved, contract);
11040
11595
  },
11041
11596
  /**
11042
- * Subscribe to live status updates for a submitted job.
11597
+ * Subscribe to live updates for a submitted job. Yields one
11598
+ * {@link GenerationEvent} per poll: `generation.progress` while running,
11599
+ * then a single terminal `generation.completed` (with the parsed result)
11600
+ * or `generation.failed` (with the {@link ApiError} `result()` would have
11601
+ * thrown). Failures arrive as events, not exceptions.
11043
11602
  *
11044
11603
  * ```ts
11045
- * const handle = await ai.submit(Models.Flux2Pro, { prompt: 'a cat' });
11046
- * for await (const update of ai.subscribe(handle)) {
11047
- * console.log(update.status, update.progress);
11604
+ * const id = await ai.submit(Models.Flux2Pro, { prompt: 'a cat' });
11605
+ * for await (const e of ai.subscribe(Models.Flux2Pro, id)) {
11606
+ * if (e.type === 'generation.progress') console.log(e.progress?.percent);
11607
+ * if (e.type === 'generation.completed') console.log(e.result.url);
11608
+ * if (e.type === 'generation.failed') console.error(e.error.message);
11048
11609
  * }
11049
11610
  * ```
11050
11611
  */
11051
- subscribe(handle, options) {
11052
- return client.subscribe(handle, options);
11053
- },
11054
- // ── Raw workflow access ──────────────────────────────────────────
11055
- /**
11056
- * Run a raw workflow (not tied to a model).
11057
- * @deprecated Use `apis.run()` instead.
11058
- */
11059
- async runWorkflow(workflow, payload, options) {
11060
- const done = await client.run(
11061
- { workflow, payload, signal: options?.signal },
11062
- options
11063
- );
11064
- if (done.status === "FAILED" || done.status === "CANCELED") {
11065
- throw new ApiError(done.error ?? `${workflow} failed with status ${done.status}`, {
11066
- status: done.statusCode ?? (done.status === "CANCELED" ? 499 : 502),
11067
- code: done.reason ?? (done.status === "CANCELED" ? "canceled" : "generation_failed")
11068
- });
11069
- }
11070
- if (done.result === void 0) {
11071
- throw new ApiError(`${workflow} completed but returned no result`, {
11072
- status: 502,
11073
- code: "invalid_response"
11612
+ subscribe(model, generationId, options) {
11613
+ const resolved = resolveModel(model);
11614
+ assertMediaModel(resolved);
11615
+ assertAsyncLifecycle();
11616
+ const contract = getModelContract(resolved.id);
11617
+ return (async function* () {
11618
+ let handle;
11619
+ try {
11620
+ handle = await resolveJobHandle(resolved, generationId, options?.signal);
11621
+ } catch (err) {
11622
+ yield { type: "generation.failed", error: toApiError2(err, options?.signal) };
11623
+ return;
11624
+ }
11625
+ const poll = new AbortController();
11626
+ if (options?.signal) {
11627
+ if (options.signal.aborted) poll.abort();
11628
+ else options.signal.addEventListener("abort", () => poll.abort(), { once: true });
11629
+ }
11630
+ const queue = [];
11631
+ let wake;
11632
+ let waker = new Promise((resolve) => {
11633
+ wake = () => resolve(null);
11074
11634
  });
11075
- }
11076
- return done.result;
11635
+ const done = pollJob(
11636
+ handle,
11637
+ { ...resolvePollOptions(resolved, options), signal: poll.signal },
11638
+ (p2) => {
11639
+ queue.push(p2);
11640
+ wake();
11641
+ }
11642
+ ).then(
11643
+ (res) => ({ ok: true, res }),
11644
+ (err) => ({ ok: false, err })
11645
+ );
11646
+ try {
11647
+ for (; ; ) {
11648
+ while (queue.length) yield { type: "generation.progress", progress: queue.shift() };
11649
+ const raced = await Promise.race([done, waker]);
11650
+ if (raced === null) {
11651
+ waker = new Promise((resolve) => {
11652
+ wake = () => resolve(null);
11653
+ });
11654
+ continue;
11655
+ }
11656
+ while (queue.length) yield { type: "generation.progress", progress: queue.shift() };
11657
+ if (!raced.ok) {
11658
+ yield { type: "generation.failed", error: toApiError2(raced.err, options?.signal) };
11659
+ return;
11660
+ }
11661
+ const completed = asCompleted(handle, raced.res);
11662
+ try {
11663
+ yield { type: "generation.completed", result: parseResult(completed, resolved, contract) };
11664
+ } catch (err) {
11665
+ yield { type: "generation.failed", error: toApiError2(err, options?.signal) };
11666
+ }
11667
+ return;
11668
+ }
11669
+ } finally {
11670
+ poll.abort();
11671
+ }
11672
+ })();
11077
11673
  },
11078
11674
  // ── apis (direct, low-level API access) ───────────────────────────
11079
11675
  /** Direct, low-level access to the Picsart model APIs. See `./apis.ts`. */
@@ -11087,446 +11683,6 @@ function createClient(config) {
11087
11683
  };
11088
11684
  }
11089
11685
 
11090
- // src/core/constraints.ts
11091
- function normalize(r) {
11092
- if ("disabled" in r) return { kind: "disabled", reason: r.reason };
11093
- return { kind: "allowed", allowed: r.allowed, reason: r.reason };
11094
- }
11095
- function matchOperator(op, actual) {
11096
- if ("exists" in op) {
11097
- const has = actual != null && (!Array.isArray(actual) || actual.length > 0) && (typeof actual !== "string" || actual.length > 0);
11098
- return op.exists ? has : !has;
11099
- }
11100
- if ("is" in op) return actual === op.is;
11101
- return false;
11102
- }
11103
- function matchCondition(when, values) {
11104
- return Object.entries(when).every(
11105
- ([key, op]) => matchOperator(op, values[key])
11106
- );
11107
- }
11108
- function merge(prev, next) {
11109
- if (!prev) return next;
11110
- if (prev.kind === "disabled" || next.kind === "disabled") {
11111
- return { kind: "disabled", reason: next.kind === "disabled" ? next.reason : prev.kind === "disabled" ? prev.reason : void 0 };
11112
- }
11113
- const allowed = new Set(next.allowed.map(String));
11114
- return {
11115
- kind: "allowed",
11116
- allowed: prev.allowed.filter((o) => allowed.has(String(o))),
11117
- reason: next.reason ?? prev.reason
11118
- };
11119
- }
11120
- function evaluateConstraints(constraints, values) {
11121
- const effects = /* @__PURE__ */ new Map();
11122
- if (!constraints?.length) return effects;
11123
- for (const rule of constraints) {
11124
- if (!matchCondition(rule.when, values)) continue;
11125
- for (const [key, restriction] of Object.entries(rule.then)) {
11126
- effects.set(key, merge(effects.get(key), normalize(restriction)));
11127
- }
11128
- }
11129
- return effects;
11130
- }
11131
-
11132
- // src/core/descriptors/pricing.ts
11133
- var import_pa_model_pricing_sdk = __toESM(require_build());
11134
- var _client = null;
11135
- var _byModel = null;
11136
- var _loadPromise = null;
11137
- function configurePricing(options) {
11138
- _client = new import_pa_model_pricing_sdk.ModelPricingClient(options);
11139
- _byModel = null;
11140
- _loadPromise = null;
11141
- }
11142
- function loadPricing() {
11143
- if (_byModel) return Promise.resolve();
11144
- if (!_client) {
11145
- return Promise.reject(new Error(
11146
- "loadPricing(): not configured. Call catalog.pricing.configure({ baseUrl, fetch }) first."
11147
- ));
11148
- }
11149
- if (!_loadPromise) {
11150
- const client = _client;
11151
- _loadPromise = client.init().then(() => {
11152
- const byModel = /* @__PURE__ */ new Map();
11153
- for (const entry of client.getModelPricing()) {
11154
- const id = entry.metadata.modelId;
11155
- const list = byModel.get(id);
11156
- if (list) list.push(entry);
11157
- else byModel.set(id, [entry]);
11158
- }
11159
- _byModel = byModel;
11160
- }).catch((err) => {
11161
- _loadPromise = null;
11162
- throw err;
11163
- });
11164
- }
11165
- return _loadPromise;
11166
- }
11167
- function isPricingLoaded() {
11168
- return _byModel !== null;
11169
- }
11170
- function getCreditsForModel(modelId, ctx) {
11171
- if (!_byModel) return null;
11172
- let entries = _byModel.get(modelId);
11173
- if (!entries || entries.length === 0) return null;
11174
- if (ctx) {
11175
- entries = entries.filter((e) => {
11176
- if (ctx.generateAudio !== void 0 && e.metadata.audio !== ctx.generateAudio) return false;
11177
- if (ctx.resolution !== void 0 && e.metadata.quality !== ctx.resolution) return false;
11178
- return true;
11179
- });
11180
- if (entries.length === 0) return null;
11181
- }
11182
- let min = Infinity;
11183
- let max = -Infinity;
11184
- let unit = entries[0].unit;
11185
- for (const e of entries) {
11186
- if (e.credits < min) min = e.credits;
11187
- if (e.credits > max) max = e.credits;
11188
- if (e.unit !== unit) unit = void 0;
11189
- }
11190
- const tiers = entries.map((e) => ({
11191
- credits: e.credits,
11192
- unit: e.unit,
11193
- quality: e.metadata.quality || void 0,
11194
- audio: e.metadata.audio,
11195
- useCase: e.metadata.useCase
11196
- }));
11197
- return unit ? { min, max, unit, tiers } : { min, max, tiers };
11198
- }
11199
-
11200
- // src/core/descriptors/model-accessor.ts
11201
- function withHydration(entry, flat) {
11202
- if (entry.descriptor.kind !== "catalog") return flat;
11203
- const hydrated = getHydratedCatalog(entry.descriptor.source);
11204
- if (!hydrated) return flat;
11205
- return { ...flat, catalogOptions: hydrated.catalogOptions };
11206
- }
11207
- var ModelParamsAccessorImpl = class {
11208
- def;
11209
- constructor(def) {
11210
- this.def = def;
11211
- }
11212
- param(key) {
11213
- const entry = this.def.paramConfig[key];
11214
- if (!entry) return void 0;
11215
- const { descriptor, ...meta } = entry;
11216
- return withHydration(entry, { ...meta, ...descriptor });
11217
- }
11218
- hasParam(key) {
11219
- return key in this.def.paramConfig;
11220
- }
11221
- all() {
11222
- return Object.entries(this.def.paramConfig).map(
11223
- ([key, entry]) => {
11224
- const { descriptor, ...meta } = entry;
11225
- return withHydration(entry, { key, ...meta, ...descriptor });
11226
- }
11227
- );
11228
- }
11229
- // Kind-narrowed accessors
11230
- enum(key) {
11231
- return this.narrow(key, "enum");
11232
- }
11233
- catalog(key) {
11234
- return this.narrow(key, "catalog");
11235
- }
11236
- range(key) {
11237
- return this.narrow(key, "range");
11238
- }
11239
- boolean(key) {
11240
- return this.narrow(key, "boolean");
11241
- }
11242
- text(key) {
11243
- return this.narrow(key, "text");
11244
- }
11245
- file(key) {
11246
- return this.narrow(key, "file");
11247
- }
11248
- // Well-known shorthands
11249
- prompt() {
11250
- return this.narrow("prompt", "text");
11251
- }
11252
- aspectRatio() {
11253
- return this.narrow("aspectRatio", "enum");
11254
- }
11255
- /** Enum on fixed-option models, range where the vendor accepts every value
11256
- * in a span — callers narrow on `.kind`. */
11257
- duration() {
11258
- const entry = this.param("duration");
11259
- if (!entry || entry.kind !== "enum" && entry.kind !== "range") return void 0;
11260
- return entry;
11261
- }
11262
- resolution() {
11263
- return this.narrow("resolution", "enum");
11264
- }
11265
- generateAudio() {
11266
- return this.narrow("generateAudio", "boolean");
11267
- }
11268
- startFrame() {
11269
- return this.narrow("startFrame", "file");
11270
- }
11271
- endFrame() {
11272
- return this.narrow("endFrame", "file");
11273
- }
11274
- // Absorbed from Models namespace
11275
- hasFileInput() {
11276
- return Object.values(this.def.paramConfig).some((e) => e.descriptor.kind === "file");
11277
- }
11278
- getDefault(key) {
11279
- const entry = this.def.paramConfig[key];
11280
- if (!entry) return void 0;
11281
- const d = entry.descriptor;
11282
- return "default" in d ? d.default : void 0;
11283
- }
11284
- getDefaults() {
11285
- return extractDefaults(this.def.paramConfig);
11286
- }
11287
- /** @deprecated Use `enum(key)` instead. */
11288
- getEnumOptions(key) {
11289
- const entry = this.def.paramConfig[key];
11290
- if (!entry || entry.descriptor.kind !== "enum") return null;
11291
- return entry.descriptor.options.map((o) => o.id);
11292
- }
11293
- toSchema() {
11294
- return descriptorsToSchema(this.def.paramConfig);
11295
- }
11296
- transferValues(prev) {
11297
- return transferValues(this.def.paramConfig, prev);
11298
- }
11299
- narrow(key, kind) {
11300
- const entry = this.param(key);
11301
- if (!entry || entry.kind !== kind) return void 0;
11302
- return entry;
11303
- }
11304
- };
11305
- var ConstrainedParamsAccessor = class {
11306
- inner;
11307
- effects;
11308
- constructor(inner, effects) {
11309
- this.inner = inner;
11310
- this.effects = effects;
11311
- }
11312
- // ── Decorated accessors ──────────────────────────────────────────
11313
- enum(key) {
11314
- return this.applyEnum(key, this.inner.enum(key));
11315
- }
11316
- catalog(key) {
11317
- return this.applyEntry(key, this.inner.catalog(key));
11318
- }
11319
- range(key) {
11320
- return this.applyEntry(key, this.inner.range(key));
11321
- }
11322
- boolean(key) {
11323
- return this.applyEntry(key, this.inner.boolean(key));
11324
- }
11325
- text(key) {
11326
- return this.applyEntry(key, this.inner.text(key));
11327
- }
11328
- file(key) {
11329
- return this.applyEntry(key, this.inner.file(key));
11330
- }
11331
- prompt() {
11332
- return this.applyEntry("prompt", this.inner.prompt());
11333
- }
11334
- aspectRatio() {
11335
- return this.applyEnum("aspectRatio", this.inner.aspectRatio());
11336
- }
11337
- duration() {
11338
- const entry = this.inner.duration();
11339
- return entry?.kind === "enum" ? this.applyEnum("duration", entry) : this.applyEntry("duration", entry);
11340
- }
11341
- resolution() {
11342
- return this.applyEnum("resolution", this.inner.resolution());
11343
- }
11344
- generateAudio() {
11345
- return this.applyEntry("generateAudio", this.inner.generateAudio());
11346
- }
11347
- startFrame() {
11348
- return this.applyEntry("startFrame", this.inner.startFrame());
11349
- }
11350
- endFrame() {
11351
- return this.applyEntry("endFrame", this.inner.endFrame());
11352
- }
11353
- all() {
11354
- return this.inner.all().map((e) => {
11355
- const r = this.effects.get(e.key);
11356
- if (!r) return e;
11357
- if (e.kind === "enum") return this.decorateEnumFlat(e, r);
11358
- if (r.kind === "disabled") return { ...e, disabled: true, disabledReason: r.reason };
11359
- return e;
11360
- });
11361
- }
11362
- // ── Pass-through delegates ───────────────────────────────────────
11363
- param(key) {
11364
- return this.inner.param(key);
11365
- }
11366
- hasParam(key) {
11367
- return this.inner.hasParam(key);
11368
- }
11369
- hasFileInput() {
11370
- return this.inner.hasFileInput();
11371
- }
11372
- getDefault(key) {
11373
- return this.inner.getDefault(key);
11374
- }
11375
- getDefaults() {
11376
- return this.inner.getDefaults();
11377
- }
11378
- getEnumOptions(key) {
11379
- return this.inner.getEnumOptions(key);
11380
- }
11381
- toSchema() {
11382
- return this.inner.toSchema();
11383
- }
11384
- transferValues(prev) {
11385
- return this.inner.transferValues(prev);
11386
- }
11387
- // ── Private helpers ──────────────────────────────────────────────
11388
- applyEntry(key, entry) {
11389
- if (!entry) return void 0;
11390
- const r = this.effects.get(key);
11391
- if (!r) return entry;
11392
- if (r.kind === "disabled") return { ...entry, disabled: true, disabledReason: r.reason };
11393
- return entry;
11394
- }
11395
- applyEnum(key, entry) {
11396
- if (!entry) return void 0;
11397
- const r = this.effects.get(key);
11398
- if (!r) return entry;
11399
- if (r.kind === "disabled") {
11400
- const options2 = entry.options.map((opt) => ({ ...opt, disabled: true, disabledReason: r.reason }));
11401
- return { ...entry, options: options2, disabled: true, disabledReason: r.reason };
11402
- }
11403
- const allowed = new Set(r.allowed.map(String));
11404
- const options = entry.options.map(
11405
- (opt) => allowed.has(String(opt.id)) ? opt : { ...opt, disabled: true, disabledReason: r.reason }
11406
- );
11407
- return { ...entry, options };
11408
- }
11409
- decorateEnumFlat(entry, r) {
11410
- if (entry.kind !== "enum") return entry;
11411
- if (r.kind === "disabled") {
11412
- const options2 = entry.options.map((opt) => ({
11413
- ...opt,
11414
- disabled: true,
11415
- disabledReason: r.reason
11416
- }));
11417
- return { ...entry, options: options2, disabled: true, disabledReason: r.reason };
11418
- }
11419
- const allowed = new Set(r.allowed.map(String));
11420
- const options = entry.options.map(
11421
- (opt) => allowed.has(String(opt.id)) ? opt : { ...opt, disabled: true, disabledReason: r.reason }
11422
- );
11423
- return { ...entry, options };
11424
- }
11425
- };
11426
- var ModelMetaImpl = class {
11427
- mode;
11428
- inputType;
11429
- description;
11430
- features;
11431
- badges;
11432
- provider;
11433
- addedAt;
11434
- release;
11435
- constructor(def) {
11436
- this.mode = def.mode;
11437
- this.inputType = def.inputType;
11438
- this.description = def.description;
11439
- this.features = def.features;
11440
- this.badges = def.badge ?? [];
11441
- this.release = def.release ?? "production";
11442
- this.provider = {
11443
- id: def.provider,
11444
- name: def.providerName,
11445
- color: def.providerColor,
11446
- label: def.providerLabel
11447
- };
11448
- this.addedAt = def.addedAt ?? null;
11449
- }
11450
- };
11451
- var ModelDescriptorImpl = class {
11452
- id;
11453
- name;
11454
- api;
11455
- def;
11456
- _params;
11457
- _meta;
11458
- constructor(def) {
11459
- this.id = def.id;
11460
- this.name = def.name;
11461
- this.api = { workflow: def.workflow, editWorkflow: def.editWorkflow };
11462
- this.def = def;
11463
- }
11464
- params() {
11465
- return this._params ??= new ModelParamsAccessorImpl(this.def);
11466
- }
11467
- paramsFor(values) {
11468
- const inner = this.params();
11469
- const effects = evaluateConstraints(this.def.constraints, values);
11470
- if (!effects.size) return inner;
11471
- return new ConstrainedParamsAccessor(inner, effects);
11472
- }
11473
- validate(input) {
11474
- if (!input || typeof input !== "object" || Array.isArray(input)) {
11475
- return { valid: false, errors: [`Invalid input for model "${this.def.id}"`] };
11476
- }
11477
- try {
11478
- validateAll(this.def.paramConfig, input);
11479
- return { valid: true };
11480
- } catch (err) {
11481
- return { valid: false, errors: [err instanceof Error ? err.message : String(err)] };
11482
- }
11483
- }
11484
- meta() {
11485
- return this._meta ??= new ModelMetaImpl(this.def);
11486
- }
11487
- getCreditsInfo(ctx) {
11488
- if (this.def.modelId) {
11489
- const byModelId = getCreditsForModel(this.def.modelId, ctx);
11490
- if (byModelId) return byModelId;
11491
- }
11492
- return getCreditsForModel(this.def.id, ctx);
11493
- }
11494
- };
11495
- function _model(id) {
11496
- return new ModelDescriptorImpl(resolveModel(id));
11497
- }
11498
- function _all(filter = {}) {
11499
- const releases = filter.release ?? DEFAULT_VISIBLE_RELEASES;
11500
- return ALL_MODELS.filter((m) => isVisibleForReleases(m, releases)).map((m) => new ModelDescriptorImpl(m));
11501
- }
11502
- function _find(filter) {
11503
- const releases = filter.release ?? DEFAULT_VISIBLE_RELEASES;
11504
- return ALL_MODELS.filter((m) => {
11505
- if (!isVisibleForReleases(m, releases)) return false;
11506
- if (filter.output && m.mode !== filter.output) return false;
11507
- if (filter.provider && m.provider !== filter.provider) return false;
11508
- return true;
11509
- }).map((m) => new ModelDescriptorImpl(m));
11510
- }
11511
- function _search(query, filter = {}) {
11512
- const releases = filter.release ?? DEFAULT_VISIBLE_RELEASES;
11513
- const q = query.toLowerCase();
11514
- return ALL_MODELS.filter(
11515
- (m) => isVisibleForReleases(m, releases) && (m.id.toLowerCase().includes(q) || m.name.toLowerCase().includes(q) || m.provider.toLowerCase().includes(q))
11516
- ).map((m) => new ModelDescriptorImpl(m));
11517
- }
11518
- var Model = _model;
11519
- var catalog = {
11520
- all: _all,
11521
- find: _find,
11522
- search: _search,
11523
- pricing: {
11524
- configure: configurePricing,
11525
- load: loadPricing,
11526
- isLoaded: isPricingLoaded
11527
- }
11528
- };
11529
-
11530
11686
  // src/generated/model-constants.ts
11531
11687
  var AsyncFlashV1 = "async-flash-v1";
11532
11688
  var BytedanceOmnihumanV15 = "bytedance-omnihuman-v1.5";
@@ -11643,7 +11799,6 @@ var LumaUni1Max = "luma-uni-1-max";
11643
11799
  var Lyria3Clip = "lyria-3-clip";
11644
11800
  var Lyria3Pro = "lyria-3-pro";
11645
11801
  var Lyria35 = "lyria-3.5";
11646
- var Minimax02Hd = "minimax-02-hd";
11647
11802
  var MinimaxH3 = "minimax-h3";
11648
11803
  var MinimaxH3Max = "minimax-h3-max";
11649
11804
  var MinimaxH3MaxCameraControls = "minimax-h3-max-camera-controls";
@@ -11869,7 +12024,6 @@ var Models = {
11869
12024
  Lyria3Clip,
11870
12025
  Lyria3Pro,
11871
12026
  Lyria35,
11872
- Minimax02Hd,
11873
12027
  MinimaxH3,
11874
12028
  MinimaxH3Max,
11875
12029
  MinimaxH3MaxCameraControls,
@@ -11978,39 +12132,437 @@ var Models = {
11978
12132
  Wan27T2v,
11979
12133
  Wan27VideoEdit,
11980
12134
  Wan30Video,
11981
- Wan30VideoPrime,
11982
- /** @deprecated Use the `catalog` accessor (`catalog.all()` / `catalog.find({ output, provider })`) instead. */
11983
- list(filter) {
11984
- if (!filter) return [...ALL_MODELS];
11985
- return ALL_MODELS.filter((m) => {
11986
- if (filter.mode && m.mode !== filter.mode) return false;
11987
- if (filter.provider && m.provider !== filter.provider) return false;
12135
+ Wan30VideoPrime
12136
+ };
12137
+
12138
+ // src/core/constraints.ts
12139
+ function normalize(r) {
12140
+ if ("disabled" in r) return { kind: "disabled", reason: r.reason };
12141
+ return { kind: "allowed", allowed: r.allowed, reason: r.reason };
12142
+ }
12143
+ function matchOperator(op, actual) {
12144
+ if ("exists" in op) {
12145
+ const has = actual != null && (!Array.isArray(actual) || actual.length > 0) && (typeof actual !== "string" || actual.length > 0);
12146
+ return op.exists ? has : !has;
12147
+ }
12148
+ if ("is" in op) return actual === op.is;
12149
+ return false;
12150
+ }
12151
+ function matchCondition(when, values) {
12152
+ return Object.entries(when).every(
12153
+ ([key, op]) => matchOperator(op, values[key])
12154
+ );
12155
+ }
12156
+ function merge(prev, next) {
12157
+ if (!prev) return next;
12158
+ if (prev.kind === "disabled" || next.kind === "disabled") {
12159
+ return { kind: "disabled", reason: next.kind === "disabled" ? next.reason : prev.kind === "disabled" ? prev.reason : void 0 };
12160
+ }
12161
+ const allowed = new Set(next.allowed.map(String));
12162
+ return {
12163
+ kind: "allowed",
12164
+ allowed: prev.allowed.filter((o) => allowed.has(String(o))),
12165
+ reason: next.reason ?? prev.reason
12166
+ };
12167
+ }
12168
+ function evaluateConstraints(constraints, values) {
12169
+ const effects = /* @__PURE__ */ new Map();
12170
+ if (!constraints?.length) return effects;
12171
+ for (const rule of constraints) {
12172
+ if (!matchCondition(rule.when, values)) continue;
12173
+ for (const [key, restriction] of Object.entries(rule.then)) {
12174
+ effects.set(key, merge(effects.get(key), normalize(restriction)));
12175
+ }
12176
+ }
12177
+ return effects;
12178
+ }
12179
+
12180
+ // src/core/descriptors/pricing.ts
12181
+ var import_pa_model_pricing_sdk = __toESM(require_build(), 1);
12182
+ var _client = null;
12183
+ var _byModel = null;
12184
+ var _loadPromise = null;
12185
+ function configurePricing(options) {
12186
+ _client = new import_pa_model_pricing_sdk.ModelPricingClient(options);
12187
+ _byModel = null;
12188
+ _loadPromise = null;
12189
+ }
12190
+ function loadPricing() {
12191
+ if (_byModel) return Promise.resolve();
12192
+ if (!_client) {
12193
+ return Promise.reject(new Error(
12194
+ "loadPricing(): not configured. Call catalog.pricing.configure({ baseUrl, fetch }) first."
12195
+ ));
12196
+ }
12197
+ if (!_loadPromise) {
12198
+ const client = _client;
12199
+ _loadPromise = client.init().then(() => {
12200
+ const byModel = /* @__PURE__ */ new Map();
12201
+ for (const entry of client.getModelPricing()) {
12202
+ const id = entry.metadata.modelId;
12203
+ const list = byModel.get(id);
12204
+ if (list) list.push(entry);
12205
+ else byModel.set(id, [entry]);
12206
+ }
12207
+ _byModel = byModel;
12208
+ }).catch((err) => {
12209
+ _loadPromise = null;
12210
+ throw err;
12211
+ });
12212
+ }
12213
+ return _loadPromise;
12214
+ }
12215
+ function isPricingLoaded() {
12216
+ return _byModel !== null;
12217
+ }
12218
+ function getCreditsForModel(modelId, ctx) {
12219
+ if (!_byModel) return null;
12220
+ let entries = _byModel.get(modelId);
12221
+ if (!entries || entries.length === 0) return null;
12222
+ if (ctx) {
12223
+ entries = entries.filter((e) => {
12224
+ if (ctx.generateAudio !== void 0 && e.metadata.audio !== ctx.generateAudio) return false;
12225
+ if (ctx.resolution !== void 0 && e.metadata.quality !== ctx.resolution) return false;
11988
12226
  return true;
11989
12227
  });
11990
- },
11991
- /** @deprecated Use `Model(id).validate(input)` instead. */
11992
- validate(model, input) {
12228
+ if (entries.length === 0) return null;
12229
+ }
12230
+ let min = Infinity;
12231
+ let max = -Infinity;
12232
+ let unit = entries[0].unit;
12233
+ for (const e of entries) {
12234
+ if (e.credits < min) min = e.credits;
12235
+ if (e.credits > max) max = e.credits;
12236
+ if (e.unit !== unit) unit = void 0;
12237
+ }
12238
+ const tiers = entries.map((e) => ({
12239
+ credits: e.credits,
12240
+ unit: e.unit,
12241
+ quality: e.metadata.quality || void 0,
12242
+ audio: e.metadata.audio,
12243
+ useCase: e.metadata.useCase
12244
+ }));
12245
+ return unit ? { min, max, unit, tiers } : { min, max, tiers };
12246
+ }
12247
+
12248
+ // src/core/descriptors/model-accessor.ts
12249
+ function withHydration(entry, flat) {
12250
+ if (entry.descriptor.kind !== "catalog") return flat;
12251
+ const hydrated = getHydratedCatalog(entry.descriptor.source);
12252
+ if (!hydrated) return flat;
12253
+ return { ...flat, catalogOptions: hydrated.catalogOptions };
12254
+ }
12255
+ var ModelParamsAccessorImpl = class {
12256
+ def;
12257
+ constructor(def) {
12258
+ this.def = def;
12259
+ }
12260
+ param(key) {
12261
+ const entry = this.def.paramConfig[key];
12262
+ if (!entry) return void 0;
12263
+ const { descriptor, ...meta } = entry;
12264
+ return withHydration(entry, { ...meta, ...descriptor });
12265
+ }
12266
+ hasParam(key) {
12267
+ return key in this.def.paramConfig;
12268
+ }
12269
+ all() {
12270
+ return Object.entries(this.def.paramConfig).map(
12271
+ ([key, entry]) => {
12272
+ const { descriptor, ...meta } = entry;
12273
+ return withHydration(entry, { key, ...meta, ...descriptor });
12274
+ }
12275
+ );
12276
+ }
12277
+ // Kind-narrowed accessors
12278
+ enum(key) {
12279
+ return this.narrow(key, "enum");
12280
+ }
12281
+ catalog(key) {
12282
+ return this.narrow(key, "catalog");
12283
+ }
12284
+ range(key) {
12285
+ return this.narrow(key, "range");
12286
+ }
12287
+ boolean(key) {
12288
+ return this.narrow(key, "boolean");
12289
+ }
12290
+ text(key) {
12291
+ return this.narrow(key, "text");
12292
+ }
12293
+ file(key) {
12294
+ return this.narrow(key, "file");
12295
+ }
12296
+ // Well-known shorthands
12297
+ prompt() {
12298
+ return this.narrow("prompt", "text");
12299
+ }
12300
+ aspectRatio() {
12301
+ return this.narrow("aspectRatio", "enum");
12302
+ }
12303
+ /** Enum on fixed-option models, range where the vendor accepts every value
12304
+ * in a span — callers narrow on `.kind`. */
12305
+ duration() {
12306
+ const entry = this.param("duration");
12307
+ if (!entry || entry.kind !== "enum" && entry.kind !== "range") return void 0;
12308
+ return entry;
12309
+ }
12310
+ resolution() {
12311
+ return this.narrow("resolution", "enum");
12312
+ }
12313
+ generateAudio() {
12314
+ return this.narrow("generateAudio", "boolean");
12315
+ }
12316
+ startFrame() {
12317
+ return this.narrow("startFrame", "file");
12318
+ }
12319
+ endFrame() {
12320
+ return this.narrow("endFrame", "file");
12321
+ }
12322
+ // Absorbed from Models namespace
12323
+ hasFileInput() {
12324
+ return Object.values(this.def.paramConfig).some((e) => e.descriptor.kind === "file");
12325
+ }
12326
+ getDefault(key) {
12327
+ const entry = this.def.paramConfig[key];
12328
+ if (!entry) return void 0;
12329
+ const d = entry.descriptor;
12330
+ return "default" in d ? d.default : void 0;
12331
+ }
12332
+ getDefaults() {
12333
+ return extractDefaults(this.def.paramConfig);
12334
+ }
12335
+ toSchema() {
12336
+ return descriptorsToSchema(this.def.paramConfig);
12337
+ }
12338
+ transferValues(prev) {
12339
+ return transferValues(this.def.paramConfig, prev);
12340
+ }
12341
+ narrow(key, kind) {
12342
+ const entry = this.param(key);
12343
+ if (!entry || entry.kind !== kind) return void 0;
12344
+ return entry;
12345
+ }
12346
+ };
12347
+ var ConstrainedParamsAccessor = class {
12348
+ inner;
12349
+ effects;
12350
+ constructor(inner, effects) {
12351
+ this.inner = inner;
12352
+ this.effects = effects;
12353
+ }
12354
+ // ── Decorated accessors ──────────────────────────────────────────
12355
+ enum(key) {
12356
+ return this.applyEnum(key, this.inner.enum(key));
12357
+ }
12358
+ catalog(key) {
12359
+ return this.applyEntry(key, this.inner.catalog(key));
12360
+ }
12361
+ range(key) {
12362
+ return this.applyEntry(key, this.inner.range(key));
12363
+ }
12364
+ boolean(key) {
12365
+ return this.applyEntry(key, this.inner.boolean(key));
12366
+ }
12367
+ text(key) {
12368
+ return this.applyEntry(key, this.inner.text(key));
12369
+ }
12370
+ file(key) {
12371
+ return this.applyEntry(key, this.inner.file(key));
12372
+ }
12373
+ prompt() {
12374
+ return this.applyEntry("prompt", this.inner.prompt());
12375
+ }
12376
+ aspectRatio() {
12377
+ return this.applyEnum("aspectRatio", this.inner.aspectRatio());
12378
+ }
12379
+ duration() {
12380
+ const entry = this.inner.duration();
12381
+ return entry?.kind === "enum" ? this.applyEnum("duration", entry) : this.applyEntry("duration", entry);
12382
+ }
12383
+ resolution() {
12384
+ return this.applyEnum("resolution", this.inner.resolution());
12385
+ }
12386
+ generateAudio() {
12387
+ return this.applyEntry("generateAudio", this.inner.generateAudio());
12388
+ }
12389
+ startFrame() {
12390
+ return this.applyEntry("startFrame", this.inner.startFrame());
12391
+ }
12392
+ endFrame() {
12393
+ return this.applyEntry("endFrame", this.inner.endFrame());
12394
+ }
12395
+ all() {
12396
+ return this.inner.all().map((e) => {
12397
+ const r = this.effects.get(e.key);
12398
+ if (!r) return e;
12399
+ if (e.kind === "enum") return this.decorateEnumFlat(e, r);
12400
+ if (r.kind === "disabled") return { ...e, disabled: true, disabledReason: r.reason };
12401
+ return e;
12402
+ });
12403
+ }
12404
+ // ── Pass-through delegates ───────────────────────────────────────
12405
+ param(key) {
12406
+ return this.inner.param(key);
12407
+ }
12408
+ hasParam(key) {
12409
+ return this.inner.hasParam(key);
12410
+ }
12411
+ hasFileInput() {
12412
+ return this.inner.hasFileInput();
12413
+ }
12414
+ getDefault(key) {
12415
+ return this.inner.getDefault(key);
12416
+ }
12417
+ getDefaults() {
12418
+ return this.inner.getDefaults();
12419
+ }
12420
+ toSchema() {
12421
+ return this.inner.toSchema();
12422
+ }
12423
+ transferValues(prev) {
12424
+ return this.inner.transferValues(prev);
12425
+ }
12426
+ // ── Private helpers ──────────────────────────────────────────────
12427
+ applyEntry(key, entry) {
12428
+ if (!entry) return void 0;
12429
+ const r = this.effects.get(key);
12430
+ if (!r) return entry;
12431
+ if (r.kind === "disabled") return { ...entry, disabled: true, disabledReason: r.reason };
12432
+ return entry;
12433
+ }
12434
+ applyEnum(key, entry) {
12435
+ if (!entry) return void 0;
12436
+ const r = this.effects.get(key);
12437
+ if (!r) return entry;
12438
+ if (r.kind === "disabled") {
12439
+ const options2 = entry.options.map((opt) => ({ ...opt, disabled: true, disabledReason: r.reason }));
12440
+ return { ...entry, options: options2, disabled: true, disabledReason: r.reason };
12441
+ }
12442
+ const allowed = new Set(r.allowed.map(String));
12443
+ const options = entry.options.map(
12444
+ (opt) => allowed.has(String(opt.id)) ? opt : { ...opt, disabled: true, disabledReason: r.reason }
12445
+ );
12446
+ return { ...entry, options };
12447
+ }
12448
+ decorateEnumFlat(entry, r) {
12449
+ if (entry.kind !== "enum") return entry;
12450
+ if (r.kind === "disabled") {
12451
+ const options2 = entry.options.map((opt) => ({
12452
+ ...opt,
12453
+ disabled: true,
12454
+ disabledReason: r.reason
12455
+ }));
12456
+ return { ...entry, options: options2, disabled: true, disabledReason: r.reason };
12457
+ }
12458
+ const allowed = new Set(r.allowed.map(String));
12459
+ const options = entry.options.map(
12460
+ (opt) => allowed.has(String(opt.id)) ? opt : { ...opt, disabled: true, disabledReason: r.reason }
12461
+ );
12462
+ return { ...entry, options };
12463
+ }
12464
+ };
12465
+ var ModelMetaImpl = class {
12466
+ mode;
12467
+ inputType;
12468
+ description;
12469
+ features;
12470
+ badges;
12471
+ provider;
12472
+ addedAt;
12473
+ release;
12474
+ constructor(def) {
12475
+ this.mode = def.mode;
12476
+ this.inputType = def.inputType;
12477
+ this.description = def.description;
12478
+ this.features = def.features;
12479
+ this.badges = def.badge ?? [];
12480
+ this.release = def.release ?? "production";
12481
+ this.provider = {
12482
+ id: def.provider,
12483
+ name: def.providerName,
12484
+ color: def.providerColor,
12485
+ label: def.providerLabel
12486
+ };
12487
+ this.addedAt = def.addedAt ?? null;
12488
+ }
12489
+ };
12490
+ var ModelDescriptorImpl = class {
12491
+ id;
12492
+ name;
12493
+ api;
12494
+ def;
12495
+ _params;
12496
+ _meta;
12497
+ constructor(def) {
12498
+ this.id = def.id;
12499
+ this.name = def.name;
12500
+ this.api = { workflow: def.workflow, editWorkflow: def.editWorkflow };
12501
+ this.def = def;
12502
+ }
12503
+ params() {
12504
+ return this._params ??= new ModelParamsAccessorImpl(this.def);
12505
+ }
12506
+ paramsFor(values) {
12507
+ const inner = this.params();
12508
+ const effects = evaluateConstraints(this.def.constraints, values);
12509
+ if (!effects.size) return inner;
12510
+ return new ConstrainedParamsAccessor(inner, effects);
12511
+ }
12512
+ validate(input) {
12513
+ if (!input || typeof input !== "object" || Array.isArray(input)) {
12514
+ return { valid: false, errors: [`Invalid input for model "${this.def.id}"`] };
12515
+ }
11993
12516
  try {
11994
- validateModelInput(resolveModel(model), input);
12517
+ validateAll(this.def.paramConfig, input);
11995
12518
  return { valid: true };
11996
12519
  } catch (err) {
11997
- const message = err instanceof Error ? err.message : String(err);
11998
- return { valid: false, errors: [message] };
12520
+ return { valid: false, errors: [err instanceof Error ? err.message : String(err)] };
11999
12521
  }
12000
- },
12001
- /** @deprecated Use `Model(id).params().toSchema()` instead. */
12002
- toSchema(id) {
12003
- return Model(id).params().toSchema();
12004
- },
12005
- /** @deprecated Use `Model(id).params().file(key)` instead. */
12006
- getFileParam(id, key) {
12007
- const f = Model(id).params().file(key);
12008
- if (!f) return null;
12009
- return { required: f.required ?? false, max: f.array?.max ?? 1, label: f.label, accept: f.accept };
12010
- },
12011
- /** @deprecated Use `Model(id).params().hasParam(key)` instead. */
12012
- hasParam(id, key) {
12013
- return Model(id).params().hasParam(key);
12522
+ }
12523
+ meta() {
12524
+ return this._meta ??= new ModelMetaImpl(this.def);
12525
+ }
12526
+ getCreditsInfo(ctx) {
12527
+ if (this.def.modelId) {
12528
+ const byModelId = getCreditsForModel(this.def.modelId, ctx);
12529
+ if (byModelId) return byModelId;
12530
+ }
12531
+ return getCreditsForModel(this.def.id, ctx);
12532
+ }
12533
+ };
12534
+ function _model(id) {
12535
+ return new ModelDescriptorImpl(resolveModel(id));
12536
+ }
12537
+ function _all(filter = {}) {
12538
+ const releases = filter.release ?? DEFAULT_VISIBLE_RELEASES;
12539
+ return ALL_MODELS.filter((m) => isVisibleForReleases(m, releases)).map((m) => new ModelDescriptorImpl(m));
12540
+ }
12541
+ function _find(filter) {
12542
+ const releases = filter.release ?? DEFAULT_VISIBLE_RELEASES;
12543
+ return ALL_MODELS.filter((m) => {
12544
+ if (!isVisibleForReleases(m, releases)) return false;
12545
+ if (filter.output && m.mode !== filter.output) return false;
12546
+ if (filter.provider && m.provider !== filter.provider) return false;
12547
+ return true;
12548
+ }).map((m) => new ModelDescriptorImpl(m));
12549
+ }
12550
+ function _search(query, filter = {}) {
12551
+ const releases = filter.release ?? DEFAULT_VISIBLE_RELEASES;
12552
+ const q = query.toLowerCase();
12553
+ return ALL_MODELS.filter(
12554
+ (m) => isVisibleForReleases(m, releases) && (m.id.toLowerCase().includes(q) || m.name.toLowerCase().includes(q) || m.provider.toLowerCase().includes(q))
12555
+ ).map((m) => new ModelDescriptorImpl(m));
12556
+ }
12557
+ var Model = _model;
12558
+ var catalog = {
12559
+ all: _all,
12560
+ find: _find,
12561
+ search: _search,
12562
+ pricing: {
12563
+ configure: configurePricing,
12564
+ load: loadPricing,
12565
+ isLoaded: isPricingLoaded
12014
12566
  }
12015
12567
  };
12016
12568
  function toBase64Url(bytes) {
@@ -12194,4 +12746,4 @@ function decodeDeepLinkPayload(encoded) {
12194
12746
  return deserializePayload(encoded);
12195
12747
  }
12196
12748
 
12197
- export { ALL_MODELS, ApiError, ExecutionMode as ApiRunMode, DEFAULT_VISIBLE_RELEASES, KLING_DUAL_IMAGE_EFFECTS, Model, Models, buildFilename, buildGenerationAttributes, catalog, createClient, decodeDeepLinkPayload, encodeDeepLinkPayload, findModel, getModel, getModelsByMode, getVoiceById, inferResourceType, isVisibleForReleases, parseGeneration, releaseOf, toAvatarOption, toVoiceOption };
12749
+ export { ALL_MODELS, ApiError, ExecutionMode as ApiRunMode, DEFAULT_VISIBLE_RELEASES, GenerationEventType, Model, Models, buildFilename, buildGenerationAttributes, catalog, createClient, decodeDeepLinkPayload, encodeDeepLinkPayload, findModel, getModel, getModelsByMode, getVoiceById, inferResourceType, isVisibleForReleases, parseGeneration, releaseOf, toAvatarOption, toVoiceOption };