@sogni-ai/sogni-client 5.80.1 → 5.82.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.
Files changed (215) hide show
  1. package/AGENTS.md +2 -1
  2. package/CHANGELOG.md +25 -0
  3. package/README.md +192 -2
  4. package/dist/Account/TwoFactorRequiredError.d.ts +8 -0
  5. package/dist/Account/TwoFactorRequiredError.js +14 -0
  6. package/dist/Account/TwoFactorRequiredError.js.map +1 -0
  7. package/dist/Account/index.d.ts +43 -0
  8. package/dist/Account/index.js +97 -13
  9. package/dist/Account/index.js.map +1 -1
  10. package/dist/ApiClient/WebSocketClient/BrowserWebSocketClient/ChannelCoordinator.js +6 -5
  11. package/dist/ApiClient/WebSocketClient/BrowserWebSocketClient/ChannelCoordinator.js.map +1 -1
  12. package/dist/ApiClient/WebSocketClient/BrowserWebSocketClient/index.d.ts +11 -0
  13. package/dist/ApiClient/WebSocketClient/BrowserWebSocketClient/index.js +43 -5
  14. package/dist/ApiClient/WebSocketClient/BrowserWebSocketClient/index.js.map +1 -1
  15. package/dist/ApiClient/WebSocketClient/events.d.ts +27 -0
  16. package/dist/ApiClient/WebSocketClient/index.d.ts +13 -0
  17. package/dist/ApiClient/WebSocketClient/index.js +33 -1
  18. package/dist/ApiClient/WebSocketClient/index.js.map +1 -1
  19. package/dist/ApiClient/WebSocketClient/messages.d.ts +8 -0
  20. package/dist/ApiClient/WebSocketClient/types.d.ts +4 -0
  21. package/dist/ApiClient/index.d.ts +19 -1
  22. package/dist/ApiClient/index.js +23 -1
  23. package/dist/ApiClient/index.js.map +1 -1
  24. package/dist/Chat/modelRouting.d.ts +1 -0
  25. package/dist/Chat/modelRouting.js +7 -1
  26. package/dist/Chat/modelRouting.js.map +1 -1
  27. package/dist/MediaEncryption/index.d.ts +153 -0
  28. package/dist/MediaEncryption/index.js +434 -0
  29. package/dist/MediaEncryption/index.js.map +1 -0
  30. package/dist/Projects/Job.d.ts +27 -1
  31. package/dist/Projects/Job.js +51 -4
  32. package/dist/Projects/Job.js.map +1 -1
  33. package/dist/Projects/Project.d.ts +29 -0
  34. package/dist/Projects/Project.js +43 -2
  35. package/dist/Projects/Project.js.map +1 -1
  36. package/dist/Projects/createJobRequestMessage.js +16 -0
  37. package/dist/Projects/createJobRequestMessage.js.map +1 -1
  38. package/dist/Projects/index.d.ts +63 -2
  39. package/dist/Projects/index.js +391 -71
  40. package/dist/Projects/index.js.map +1 -1
  41. package/dist/Projects/recovery.js +4 -0
  42. package/dist/Projects/recovery.js.map +1 -1
  43. package/dist/Projects/types/JobProvenance.d.ts +2 -0
  44. package/dist/Projects/types/PayAsYouGo.d.ts +88 -0
  45. package/dist/Projects/types/PayAsYouGo.js +60 -0
  46. package/dist/Projects/types/PayAsYouGo.js.map +1 -0
  47. package/dist/Projects/types/RawProject.d.ts +2 -0
  48. package/dist/Projects/types/events.d.ts +9 -1
  49. package/dist/Projects/types/index.d.ts +143 -1
  50. package/dist/Projects/types/index.js.map +1 -1
  51. package/dist/Projects/utils/imageLayers.d.ts +7 -0
  52. package/dist/Projects/utils/imageLayers.js +123 -0
  53. package/dist/Projects/utils/imageLayers.js.map +1 -0
  54. package/dist/browser/mediaEncryptionPlayback/encryptedMediaResponse.d.ts +11 -0
  55. package/dist/browser/mediaEncryptionPlayback/encryptedMediaResponse.js +97 -0
  56. package/dist/browser/mediaEncryptionPlayback/encryptedMediaResponse.js.map +1 -0
  57. package/dist/browser/mediaEncryptionPlayback/encryptedMediaWorker.d.ts +5 -0
  58. package/dist/browser/mediaEncryptionPlayback/encryptedMediaWorker.js +109 -0
  59. package/dist/browser/mediaEncryptionPlayback/encryptedMediaWorker.js.map +1 -0
  60. package/dist/browser/mediaEncryptionPlayback/encryptedPlayback.d.ts +12 -0
  61. package/dist/browser/mediaEncryptionPlayback/encryptedPlayback.js +169 -0
  62. package/dist/browser/mediaEncryptionPlayback/encryptedPlayback.js.map +1 -0
  63. package/dist/browser/mediaEncryptionPlayback/index.d.ts +3 -0
  64. package/dist/browser/mediaEncryptionPlayback/index.js +20 -0
  65. package/dist/browser/mediaEncryptionPlayback/index.js.map +1 -0
  66. package/dist/index.d.ts +47 -6
  67. package/dist/index.js +24 -8
  68. package/dist/index.js.map +1 -1
  69. package/dist/lib/RestClient.d.ts +6 -0
  70. package/dist/lib/RestClient.js +12 -0
  71. package/dist/lib/RestClient.js.map +1 -1
  72. package/dist/lib/mediaEncryption/capability.d.ts +16 -0
  73. package/dist/lib/mediaEncryption/capability.js +12 -0
  74. package/dist/lib/mediaEncryption/capability.js.map +1 -0
  75. package/dist/lib/mediaEncryption/crypto.d.ts +36 -0
  76. package/dist/lib/mediaEncryption/crypto.js +169 -0
  77. package/dist/lib/mediaEncryption/crypto.js.map +1 -0
  78. package/dist/lib/mediaEncryption/format.d.ts +62 -0
  79. package/dist/lib/mediaEncryption/format.js +167 -0
  80. package/dist/lib/mediaEncryption/format.js.map +1 -0
  81. package/dist/lib/mediaEncryption/index.d.ts +12 -0
  82. package/dist/lib/mediaEncryption/index.js +46 -0
  83. package/dist/lib/mediaEncryption/index.js.map +1 -0
  84. package/dist/lib/mediaEncryption/inputKeys.d.ts +24 -0
  85. package/dist/lib/mediaEncryption/inputKeys.js +102 -0
  86. package/dist/lib/mediaEncryption/inputKeys.js.map +1 -0
  87. package/dist/lib/mediaEncryption/networks.d.ts +14 -0
  88. package/dist/lib/mediaEncryption/networks.js +22 -0
  89. package/dist/lib/mediaEncryption/networks.js.map +1 -0
  90. package/dist/lib/mediaEncryption/recipient.d.ts +17 -0
  91. package/dist/lib/mediaEncryption/recipient.js +106 -0
  92. package/dist/lib/mediaEncryption/recipient.js.map +1 -0
  93. package/dist/lib/mediaEncryption/redact.d.ts +5 -0
  94. package/dist/lib/mediaEncryption/redact.js +34 -0
  95. package/dist/lib/mediaEncryption/redact.js.map +1 -0
  96. package/dist/lib/mediaEncryption/remote.d.ts +18 -0
  97. package/dist/lib/mediaEncryption/remote.js +243 -0
  98. package/dist/lib/mediaEncryption/remote.js.map +1 -0
  99. package/dist/lib/validation.d.ts +12 -2
  100. package/dist/lib/validation.js +100 -10
  101. package/dist/lib/validation.js.map +1 -1
  102. package/dist/types/ErrorData.d.ts +15 -0
  103. package/dist/types/ErrorData.js +15 -1
  104. package/dist/types/ErrorData.js.map +1 -1
  105. package/dist/version.d.ts +1 -1
  106. package/dist/version.js +1 -1
  107. package/dist-esm/Account/TwoFactorRequiredError.js +11 -0
  108. package/dist-esm/Account/TwoFactorRequiredError.js.map +1 -0
  109. package/dist-esm/Account/index.js +97 -13
  110. package/dist-esm/Account/index.js.map +1 -1
  111. package/dist-esm/ApiClient/WebSocketClient/BrowserWebSocketClient/ChannelCoordinator.js +6 -5
  112. package/dist-esm/ApiClient/WebSocketClient/BrowserWebSocketClient/ChannelCoordinator.js.map +1 -1
  113. package/dist-esm/ApiClient/WebSocketClient/BrowserWebSocketClient/index.js +43 -5
  114. package/dist-esm/ApiClient/WebSocketClient/BrowserWebSocketClient/index.js.map +1 -1
  115. package/dist-esm/ApiClient/WebSocketClient/index.js +33 -1
  116. package/dist-esm/ApiClient/WebSocketClient/index.js.map +1 -1
  117. package/dist-esm/ApiClient/index.js +23 -1
  118. package/dist-esm/ApiClient/index.js.map +1 -1
  119. package/dist-esm/Chat/modelRouting.js +8 -2
  120. package/dist-esm/Chat/modelRouting.js.map +1 -1
  121. package/dist-esm/MediaEncryption/index.js +429 -0
  122. package/dist-esm/MediaEncryption/index.js.map +1 -0
  123. package/dist-esm/Projects/Job.js +51 -4
  124. package/dist-esm/Projects/Job.js.map +1 -1
  125. package/dist-esm/Projects/Project.js +43 -2
  126. package/dist-esm/Projects/Project.js.map +1 -1
  127. package/dist-esm/Projects/createJobRequestMessage.js +16 -0
  128. package/dist-esm/Projects/createJobRequestMessage.js.map +1 -1
  129. package/dist-esm/Projects/index.js +351 -31
  130. package/dist-esm/Projects/index.js.map +1 -1
  131. package/dist-esm/Projects/recovery.js +4 -0
  132. package/dist-esm/Projects/recovery.js.map +1 -1
  133. package/dist-esm/Projects/types/PayAsYouGo.js +55 -0
  134. package/dist-esm/Projects/types/PayAsYouGo.js.map +1 -0
  135. package/dist-esm/Projects/types/index.js.map +1 -1
  136. package/dist-esm/Projects/utils/imageLayers.js +120 -0
  137. package/dist-esm/Projects/utils/imageLayers.js.map +1 -0
  138. package/dist-esm/browser/mediaEncryptionPlayback/encryptedMediaResponse.js +93 -0
  139. package/dist-esm/browser/mediaEncryptionPlayback/encryptedMediaResponse.js.map +1 -0
  140. package/dist-esm/browser/mediaEncryptionPlayback/encryptedMediaWorker.js +106 -0
  141. package/dist-esm/browser/mediaEncryptionPlayback/encryptedMediaWorker.js.map +1 -0
  142. package/dist-esm/browser/mediaEncryptionPlayback/encryptedPlayback.js +166 -0
  143. package/dist-esm/browser/mediaEncryptionPlayback/encryptedPlayback.js.map +1 -0
  144. package/dist-esm/browser/mediaEncryptionPlayback/index.js +4 -0
  145. package/dist-esm/browser/mediaEncryptionPlayback/index.js.map +1 -0
  146. package/dist-esm/index.js +16 -5
  147. package/dist-esm/index.js.map +1 -1
  148. package/dist-esm/lib/RestClient.js +12 -0
  149. package/dist-esm/lib/RestClient.js.map +1 -1
  150. package/dist-esm/lib/mediaEncryption/capability.js +9 -0
  151. package/dist-esm/lib/mediaEncryption/capability.js.map +1 -0
  152. package/dist-esm/lib/mediaEncryption/crypto.js +157 -0
  153. package/dist-esm/lib/mediaEncryption/crypto.js.map +1 -0
  154. package/dist-esm/lib/mediaEncryption/format.js +157 -0
  155. package/dist-esm/lib/mediaEncryption/format.js.map +1 -0
  156. package/dist-esm/lib/mediaEncryption/index.js +17 -0
  157. package/dist-esm/lib/mediaEncryption/index.js.map +1 -0
  158. package/dist-esm/lib/mediaEncryption/inputKeys.js +94 -0
  159. package/dist-esm/lib/mediaEncryption/inputKeys.js.map +1 -0
  160. package/dist-esm/lib/mediaEncryption/networks.js +17 -0
  161. package/dist-esm/lib/mediaEncryption/networks.js.map +1 -0
  162. package/dist-esm/lib/mediaEncryption/recipient.js +100 -0
  163. package/dist-esm/lib/mediaEncryption/recipient.js.map +1 -0
  164. package/dist-esm/lib/mediaEncryption/redact.js +31 -0
  165. package/dist-esm/lib/mediaEncryption/redact.js.map +1 -0
  166. package/dist-esm/lib/mediaEncryption/remote.js +240 -0
  167. package/dist-esm/lib/mediaEncryption/remote.js.map +1 -0
  168. package/dist-esm/lib/validation.js +99 -9
  169. package/dist-esm/lib/validation.js.map +1 -1
  170. package/dist-esm/types/ErrorData.js +14 -0
  171. package/dist-esm/types/ErrorData.js.map +1 -1
  172. package/dist-esm/version.js +1 -1
  173. package/llms-full.txt +73 -0
  174. package/llms.txt +7 -2
  175. package/package.json +15 -3
  176. package/src/Account/TwoFactorRequiredError.ts +12 -0
  177. package/src/Account/index.ts +183 -3
  178. package/src/ApiClient/WebSocketClient/BrowserWebSocketClient/ChannelCoordinator.ts +9 -5
  179. package/src/ApiClient/WebSocketClient/BrowserWebSocketClient/index.ts +42 -4
  180. package/src/ApiClient/WebSocketClient/events.ts +27 -0
  181. package/src/ApiClient/WebSocketClient/index.ts +32 -1
  182. package/src/ApiClient/WebSocketClient/messages.ts +4 -0
  183. package/src/ApiClient/WebSocketClient/types.ts +4 -0
  184. package/src/ApiClient/index.ts +31 -1
  185. package/src/Chat/modelRouting.ts +9 -2
  186. package/src/MediaEncryption/index.ts +500 -0
  187. package/src/Projects/Job.ts +57 -4
  188. package/src/Projects/Project.ts +56 -2
  189. package/src/Projects/createJobRequestMessage.ts +16 -0
  190. package/src/Projects/index.ts +383 -31
  191. package/src/Projects/recovery.ts +4 -0
  192. package/src/Projects/types/JobProvenance.ts +2 -0
  193. package/src/Projects/types/PayAsYouGo.ts +162 -0
  194. package/src/Projects/types/RawProject.ts +2 -0
  195. package/src/Projects/types/events.ts +9 -1
  196. package/src/Projects/types/index.ts +143 -1
  197. package/src/Projects/utils/imageLayers.ts +131 -0
  198. package/src/browser/mediaEncryptionPlayback/encryptedMediaResponse.ts +88 -0
  199. package/src/browser/mediaEncryptionPlayback/encryptedMediaWorker.ts +103 -0
  200. package/src/browser/mediaEncryptionPlayback/encryptedPlayback.ts +166 -0
  201. package/src/browser/mediaEncryptionPlayback/index.ts +3 -0
  202. package/src/index.ts +91 -4
  203. package/src/lib/RestClient.ts +13 -0
  204. package/src/lib/mediaEncryption/capability.ts +17 -0
  205. package/src/lib/mediaEncryption/crypto.ts +217 -0
  206. package/src/lib/mediaEncryption/format.ts +209 -0
  207. package/src/lib/mediaEncryption/index.ts +43 -0
  208. package/src/lib/mediaEncryption/inputKeys.ts +130 -0
  209. package/src/lib/mediaEncryption/networks.ts +31 -0
  210. package/src/lib/mediaEncryption/recipient.ts +118 -0
  211. package/src/lib/mediaEncryption/redact.ts +30 -0
  212. package/src/lib/mediaEncryption/remote.ts +259 -0
  213. package/src/lib/validation.ts +106 -9
  214. package/src/types/ErrorData.ts +18 -0
  215. package/src/version.ts +1 -1
@@ -49,16 +49,22 @@ const ApiGroup_js_1 = __importDefault(require("../ApiGroup.js"));
49
49
  const requestDelivery_js_1 = require("../ApiClient/WebSocketClient/requestDelivery.js");
50
50
  const ReusableUploads_js_1 = __importDefault(require("./ReusableUploads.js"));
51
51
  const requestSession_js_1 = require("../lib/requestSession.js");
52
+ const index_js_1 = require("../lib/mediaEncryption/index.js");
53
+ const networks_js_1 = require("../lib/mediaEncryption/networks.js");
52
54
  const Project_js_1 = __importDefault(require("./Project.js"));
55
+ const PayAsYouGo_js_1 = require("./types/PayAsYouGo.js");
56
+ const PAY_AS_YOU_GO_SWITCH_TIMEOUT_MS = 45000;
53
57
  const recovery_js_1 = require("./recovery.js");
54
58
  const createJobRequestMessage_js_1 = __importStar(require("./createJobRequestMessage.js"));
55
- const index_js_1 = require("../ApiClient/index.js");
59
+ const index_js_2 = require("../ApiClient/index.js");
56
60
  const PersonalLoras_js_1 = __importDefault(require("./PersonalLoras.js"));
57
61
  const getUUID_js_1 = __importDefault(require("../lib/getUUID.js"));
62
+ const ErrorData_js_1 = require("../types/ErrorData.js");
58
63
  const Cache_js_1 = __importDefault(require("../lib/Cache.js"));
59
64
  const Job_js_1 = require("./Job.js");
60
- const index_js_2 = require("./utils/index.js");
65
+ const index_js_3 = require("./utils/index.js");
61
66
  const fileContentType_js_1 = require("./utils/fileContentType.js");
67
+ const imageLayers_js_1 = require("./utils/imageLayers.js");
62
68
  const validation_js_1 = require("../lib/validation.js");
63
69
  const ModelTiersRaw_js_1 = require("./types/ModelTiersRaw.js");
64
70
  const ModelOptions_js_1 = require("./types/ModelOptions.js");
@@ -182,6 +188,43 @@ function jobProvenanceFromResult(data) {
182
188
  // confirm and refund the same cancellation.
183
189
  const CANCELLATION_CONFIRMATION_TIMEOUT = 120000;
184
190
  const MODELS_REFRESH_INTERVAL = 1000 * 60 * 60 * 24; // 24 hours
191
+ /** Every project param that can carry uploadable media. */
192
+ const ENCRYPTABLE_MEDIA_FIELDS = [
193
+ 'startingImage',
194
+ 'controlNet.image',
195
+ 'contextImages',
196
+ 'gptImageMask',
197
+ 'leftViewImage',
198
+ 'backViewImage',
199
+ 'rightViewImage',
200
+ 'referenceImage',
201
+ 'referenceImageEnd',
202
+ 'referenceMask',
203
+ 'referenceAudio',
204
+ 'referenceAudios',
205
+ 'referenceAudioIdentity',
206
+ 'referenceVideo',
207
+ 'referenceVideos'
208
+ ];
209
+ /**
210
+ * The first media field set to `true` ("uploaded outside the SDK"), which the
211
+ * SDK cannot encrypt, or `undefined` when every input is media it holds.
212
+ */
213
+ function mediaUploadedElsewhere(data) {
214
+ const mediaFields = data;
215
+ const field = ENCRYPTABLE_MEDIA_FIELDS.find((name) => {
216
+ var _a;
217
+ const value = name === 'controlNet.image'
218
+ ? data.type === 'image' && ((_a = data.controlNet) === null || _a === void 0 ? void 0 : _a.image)
219
+ : mediaFields[name];
220
+ return value === true || (Array.isArray(value) && value.includes(true));
221
+ });
222
+ if (field)
223
+ return field;
224
+ if (data.type === 'video' && (0, index_js_3.getMinimaxH3KeyframeSlots)(data).some(({ media }) => media === true))
225
+ return 'keyframes';
226
+ return undefined;
227
+ }
185
228
  /** Fallback for an API that does not advertise its LoRA-capable model set. */
186
229
  function deriveLoraCapableModelIds(loras) {
187
230
  var _a;
@@ -329,7 +372,7 @@ class ProjectsApi extends ApiGroup_js_1.default {
329
372
  if (media)
330
373
  return media === 'video';
331
374
  // The catalog is not loaded, does not list the model, or gives it no kind.
332
- return (0, index_js_2.isVideoModel)(modelId);
375
+ return (0, index_js_3.isVideoModel)(modelId);
333
376
  }
334
377
  /**
335
378
  * Check if a model produces audio output using the cached models list.
@@ -340,7 +383,7 @@ class ProjectsApi extends ApiGroup_js_1.default {
340
383
  const media = this._catalogMediaKind(modelId);
341
384
  if (media)
342
385
  return media === 'audio';
343
- return (0, index_js_2.isAudioModel)(modelId);
386
+ return (0, index_js_3.isAudioModel)(modelId);
344
387
  }
345
388
  /**
346
389
  * Check whether a model returns a 3D artifact through the media endpoint.
@@ -356,7 +399,7 @@ class ProjectsApi extends ApiGroup_js_1.default {
356
399
  * knowledge of, so a future `media: 'model'` family needs no SDK release.
357
400
  */
358
401
  isModelArtifactModelId(modelId) {
359
- if ((0, index_js_2.isModelArtifactModel)(modelId))
402
+ if ((0, index_js_3.isModelArtifactModel)(modelId))
360
403
  return true;
361
404
  return this._catalogMediaKind(modelId) === 'model';
362
405
  }
@@ -369,7 +412,7 @@ class ProjectsApi extends ApiGroup_js_1.default {
369
412
  _catalogMediaKind(modelId) {
370
413
  var _a;
371
414
  const model = (_a = this._supportedModels.data) === null || _a === void 0 ? void 0 : _a.find((m) => m.id === modelId);
372
- return (0, index_js_2.asResultMediaKind)(model === null || model === void 0 ? void 0 : model.media);
415
+ return (0, index_js_3.asResultMediaKind)(model === null || model === void 0 ? void 0 : model.media);
373
416
  }
374
417
  /**
375
418
  * What a finished job's result is, from the evidence this client holds,
@@ -384,19 +427,19 @@ class ProjectsApi extends ApiGroup_js_1.default {
384
427
  _resultMediaKind(evidence) {
385
428
  const { modelId } = evidence;
386
429
  if (modelId) {
387
- if ((0, index_js_2.isModelArtifactModel)(modelId))
430
+ if ((0, index_js_3.isModelArtifactModel)(modelId))
388
431
  return 'model';
389
432
  const catalog = this._catalogMediaKind(modelId);
390
433
  if (catalog)
391
434
  return catalog;
392
- if ((0, index_js_2.isVideoModel)(modelId))
435
+ if ((0, index_js_3.isVideoModel)(modelId))
393
436
  return 'video';
394
- if ((0, index_js_2.isAudioModel)(modelId))
437
+ if ((0, index_js_3.isAudioModel)(modelId))
395
438
  return 'audio';
396
439
  }
397
440
  if (evidence.result)
398
441
  return evidence.result.kind;
399
- return (0, index_js_2.asResultMediaKind)(evidence.projectType);
442
+ return (0, index_js_3.asResultMediaKind)(evidence.projectType);
400
443
  }
401
444
  /**
402
445
  * Mint a signed download URL for a finished job's result from the endpoint
@@ -438,14 +481,18 @@ class ProjectsApi extends ApiGroup_js_1.default {
438
481
  this._mediaResultIds.delete(oldest);
439
482
  }
440
483
  }
441
- constructor(config) {
484
+ constructor(config,
485
+ /** @internal */
486
+ _mediaEncryption) {
442
487
  var _a, _b, _c;
443
488
  super(config);
489
+ this._mediaEncryption = _mediaEncryption;
444
490
  this._availableModels = [];
445
491
  this._currentNetworkType = null;
446
492
  this.projects = [];
447
493
  this._preparingSessions = new Map();
448
494
  this.cancellationRequests = new Map();
495
+ this.payAsYouGoSwitchRequests = new Map();
449
496
  this.transportDisconnected = false;
450
497
  this._connectedAt = 0;
451
498
  this._authenticatedTimer = null;
@@ -504,6 +551,8 @@ class ProjectsApi extends ApiGroup_js_1.default {
504
551
  data: {},
505
552
  updatedAt: new Date(0)
506
553
  };
554
+ /** Encryption of projects still being prepared, by project id. */
555
+ this._projectEncryption = new Map();
507
556
  // Listen to server events and emit them as project and job events
508
557
  this.client.socket.on('changeNetwork', this.handleChangeNetwork.bind(this));
509
558
  this.client.socket.on('swarmModels', this.handleSwarmModels.bind(this));
@@ -551,6 +600,14 @@ class ProjectsApi extends ApiGroup_js_1.default {
551
600
  this._recoveredCompletedIds.clear();
552
601
  this._syncChain = Promise.resolve();
553
602
  this.cancellationRequests.clear();
603
+ // A pending switch may already have been charged: its state is unknown, never refused.
604
+ for (const pending of this.payAsYouGoSwitchRequests.values())
605
+ pending.settle({
606
+ projectId: pending.projectId,
607
+ status: 'unknown',
608
+ reason: 'session_changed'
609
+ });
610
+ this.payAsYouGoSwitchRequests.clear();
554
611
  this._clearAuthenticatedTimer();
555
612
  if (this._recheckTimer)
556
613
  clearTimeout(this._recheckTimer);
@@ -728,7 +785,7 @@ class ProjectsApi extends ApiGroup_js_1.default {
728
785
  let downloadUrl = data.resultUrl || data.videoUrl || data.videoFile || null; // Use result URL from event if provided
729
786
  // If no resultUrl provided and NSFW check passes, generate download URL
730
787
  if (!downloadUrl && passNSFWCheck && !data.userCanceled) {
731
- const result = (0, index_js_2.resultMediaEvidence)(data);
788
+ const result = (0, index_js_3.resultMediaEvidence)(data);
732
789
  const kind = this._resultMediaKind({
733
790
  modelId: project === null || project === void 0 ? void 0 : project.params.modelId,
734
791
  projectType: project === null || project === void 0 ? void 0 : project.params.type,
@@ -763,6 +820,7 @@ class ProjectsApi extends ApiGroup_js_1.default {
763
820
  let seed = data.lastSeed !== undefined ? Number(data.lastSeed) : undefined;
764
821
  const provenance = jobProvenanceFromResult(data);
765
822
  const seedanceDraftFields = (0, Job_js_1.seedanceDraftResultFields)(data);
823
+ const layers = (0, imageLayers_js_1.imageLayersFromResult)(data.layers);
766
824
  if (project) {
767
825
  const job = project.job(data.imgID);
768
826
  if (job) {
@@ -773,23 +831,28 @@ class ProjectsApi extends ApiGroup_js_1.default {
773
831
  ? job.stepCount
774
832
  : job.step;
775
833
  seed = typeof seed === 'number' && Number.isFinite(seed) ? seed : job.seed;
776
- job._update(Object.assign(Object.assign(Object.assign({ status: data.userCanceled ? 'canceled' : 'completed', step: performedStepCount, seed, resultUrl: downloadUrl, lastFrameUrl: data.lastFrameUrl, lastFrameKey: data.lastFrameKey, outputFormat: data.outputFormat }, seedanceDraftFields), {
834
+ job._update(Object.assign(Object.assign(Object.assign(Object.assign({ status: data.userCanceled ? 'canceled' : 'completed', step: performedStepCount, seed, resultUrl: downloadUrl, lastFrameUrl: data.lastFrameUrl, lastFrameKey: data.lastFrameKey, outputFormat: data.outputFormat }, seedanceDraftFields), {
777
835
  // Unchanged meaning: the server withheld the media. The label for
778
836
  // media that WAS delivered is `nsfwDetected`, deliberately kept out of
779
837
  // this flag so upgrading the SDK changes no existing app's behaviour.
780
838
  // Several apps disable the filter for their own utility renders
781
839
  // (transitions, thumbnails, restorations) and drop anything flagged;
782
840
  // folding the label in here would silently delete that output.
783
- isNSFW: Boolean(data.triggeredNSFWFilter), nsfwDetected: data.nsfwDetected === true, nsfwSources: Array.isArray(data.nsfwSources) ? [...data.nsfwSources] : [], userCanceled: Boolean(data.userCanceled) }), (provenance ? { provenance } : {})));
841
+ isNSFW: Boolean(data.triggeredNSFWFilter), nsfwDetected: data.nsfwDetected === true, nsfwSources: Array.isArray(data.nsfwSources) ? [...data.nsfwSources] : [], userCanceled: Boolean(data.userCanceled) }), (provenance ? { provenance } : {})), (layers ? { layers } : {})));
784
842
  }
785
843
  }
786
844
  // Emit job completion event with the generated download URL
787
- this.emit('job', Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({ type: 'completed', projectId: data.jobID, jobId: data.imgID }, (typeof performedStepCount === 'number' ? { steps: performedStepCount } : {})), (typeof seed === 'number' && Number.isFinite(seed) ? { seed } : {})), { resultUrl: downloadUrl, lastFrameUrl: data.lastFrameUrl, outputFormat: data.outputFormat }), seedanceDraftFields), (data.lastFrameKey ? { lastFrameKey: data.lastFrameKey } : {})), { isNSFW: Boolean(data.triggeredNSFWFilter), nsfwDetected: data.nsfwDetected === true, nsfwSources: Array.isArray(data.nsfwSources) ? [...data.nsfwSources] : [], userCanceled: Boolean(data.userCanceled) }), (provenance ? { provenance } : {})));
845
+ this.emit('job', Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({ type: 'completed', projectId: data.jobID, jobId: data.imgID }, (typeof performedStepCount === 'number' ? { steps: performedStepCount } : {})), (typeof seed === 'number' && Number.isFinite(seed) ? { seed } : {})), { resultUrl: downloadUrl, lastFrameUrl: data.lastFrameUrl, outputFormat: data.outputFormat }), seedanceDraftFields), (data.lastFrameKey ? { lastFrameKey: data.lastFrameKey } : {})), { isNSFW: Boolean(data.triggeredNSFWFilter), nsfwDetected: data.nsfwDetected === true, nsfwSources: Array.isArray(data.nsfwSources) ? [...data.nsfwSources] : [], userCanceled: Boolean(data.userCanceled) }), (provenance ? { provenance } : {})), (layers ? { layers } : {})));
788
846
  });
789
847
  }
790
848
  handleJobError(data) {
791
849
  var _a;
792
850
  const errorCode = Number(data.error);
851
+ if (!data.imgID && errorCode === ErrorData_js_1.MEDIA_ENCRYPTION_ERROR_CODES.UNSUPPORTED) {
852
+ // The cached model list said this model could encrypt. Read it again on
853
+ // the next check rather than wait out the cache.
854
+ this._supportedModels = Object.assign(Object.assign({}, this._supportedModels), { updatedAt: new Date(0) });
855
+ }
793
856
  if (!data.imgID &&
794
857
  errorCode === SERVER_RESTARTING_ERROR_CODE &&
795
858
  this._resubmitAfterReconnect(data.jobID, data.error_message)) {
@@ -921,7 +984,11 @@ class ProjectsApi extends ApiGroup_js_1.default {
921
984
  if (!project || project.finished)
922
985
  return;
923
986
  project._queueRevision += 1;
924
- project._setQueueState(data.waitingReason, data.jobWaitingReasons);
987
+ // The offer first, so a queueChanged emitted by the queue state carries it.
988
+ const offerChanged = project._setPayAsYouGo(data.payAsYouGo);
989
+ const queueChanged = project._setQueueState(data.waitingReason, data.jobWaitingReasons);
990
+ if (offerChanged && !queueChanged)
991
+ this._emitQueueChanged(project);
925
992
  }
926
993
  /** @internal */
927
994
  _emitQueueChanged(project) {
@@ -929,7 +996,8 @@ class ProjectsApi extends ApiGroup_js_1.default {
929
996
  this.emit('queueChanged', {
930
997
  projectId: project.id,
931
998
  waitingReason: (_a = project.waitingReason) !== null && _a !== void 0 ? _a : null,
932
- jobWaitingReasons: project.jobWaitingReasons
999
+ jobWaitingReasons: project.jobWaitingReasons,
1000
+ payAsYouGo: project.payAsYouGo
933
1001
  });
934
1002
  }
935
1003
  clearJobQueueState(project, jobId, jobIndex) {
@@ -941,9 +1009,14 @@ class ProjectsApi extends ApiGroup_js_1.default {
941
1009
  return ((_a = row.imgID) === null || _a === void 0 ? void 0 : _a.toUpperCase()) !== jobId.toUpperCase() &&
942
1010
  (jobIndex === undefined || row.jobIndex !== jobIndex);
943
1011
  });
944
- if (remaining.length !== project.jobWaitingReasons.length ||
945
- ((_b = project.waitingReason) === null || _b === void 0 ? void 0 : _b.reason) === 'payment_pending')
946
- project._setQueueState((_d = (_c = remaining[0]) === null || _c === void 0 ? void 0 : _c.waitingReason) !== null && _d !== void 0 ? _d : null, remaining);
1012
+ // A started result ends any Premium Spark offer: the switch needs every result waiting.
1013
+ const offerChanged = project._setPayAsYouGo(null);
1014
+ const queueChanged = remaining.length !== project.jobWaitingReasons.length ||
1015
+ ((_b = project.waitingReason) === null || _b === void 0 ? void 0 : _b.reason) === 'payment_pending'
1016
+ ? project._setQueueState((_d = (_c = remaining[0]) === null || _c === void 0 ? void 0 : _c.waitingReason) !== null && _d !== void 0 ? _d : null, remaining)
1017
+ : false;
1018
+ if (offerChanged && !queueChanged)
1019
+ this._emitQueueChanged(project);
947
1020
  }
948
1021
  handleProjectEvent(event) {
949
1022
  let project = this.projects.find((p) => p.id === event.projectId);
@@ -1113,7 +1186,7 @@ class ProjectsApi extends ApiGroup_js_1.default {
1113
1186
  job._update({ previewUrl: event.url });
1114
1187
  break;
1115
1188
  case 'completed': {
1116
- const delta = Object.assign({ status: event.userCanceled ? 'canceled' : 'completed', resultUrl: event.resultUrl, isNSFW: event.isNSFW, nsfwDetected: Boolean(event.nsfwDetected), nsfwSources: Array.isArray(event.nsfwSources) ? [...event.nsfwSources] : [], userCanceled: event.userCanceled }, (event.provenance ? { provenance: event.provenance } : {}));
1189
+ const delta = Object.assign(Object.assign({ status: event.userCanceled ? 'canceled' : 'completed', resultUrl: event.resultUrl, isNSFW: event.isNSFW, nsfwDetected: Boolean(event.nsfwDetected), nsfwSources: Array.isArray(event.nsfwSources) ? [...event.nsfwSources] : [], userCanceled: event.userCanceled }, (event.provenance ? { provenance: event.provenance } : {})), (event.layers ? { layers: event.layers } : {}));
1117
1190
  if (typeof event.steps === 'number') {
1118
1191
  delta.step = event.steps;
1119
1192
  }
@@ -1156,7 +1229,11 @@ class ProjectsApi extends ApiGroup_js_1.default {
1156
1229
  this.projects.forEach((p) => {
1157
1230
  if (!p.finished) {
1158
1231
  p._queueRevision += 1;
1159
- p._setQueueState(null, []);
1232
+ // The offer first, so a queueChanged emitted by the queue state carries it.
1233
+ const offerChanged = p._setPayAsYouGo(null);
1234
+ const queueChanged = p._setQueueState(null, []);
1235
+ if (offerChanged && !queueChanged)
1236
+ this._emitQueueChanged(p);
1160
1237
  p._keepAlive();
1161
1238
  }
1162
1239
  });
@@ -1713,7 +1790,7 @@ class ProjectsApi extends ApiGroup_js_1.default {
1713
1790
  if (local === null || local === void 0 ? void 0 : local.finished)
1714
1791
  continue;
1715
1792
  this.clearJobQueueState(project, imgID, jobIndex);
1716
- const result = this.handleJobResult(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({ jobID: projectId, imgID }, (typeof job.performedSteps === 'number'
1793
+ const result = this.handleJobResult(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({ jobID: projectId, imgID }, (typeof job.performedSteps === 'number'
1717
1794
  ? { performedStepCount: job.performedSteps }
1718
1795
  : {})), (typeof job.seedUsed === 'number' ? { lastSeed: String(job.seedUsed) } : {})), { triggeredNSFWFilter: Boolean(job.triggeredNSFWFilter), userCanceled: job.reason === 'artistCanceled', lastFrameUrl: (typeof job.lastFrameUrl === 'string'
1719
1796
  ? job.lastFrameUrl
@@ -1723,6 +1800,8 @@ class ProjectsApi extends ApiGroup_js_1.default {
1723
1800
  ? { resultUrl: job.resultUrl }
1724
1801
  : {})), (job.result && typeof job.result === 'object'
1725
1802
  ? jobProvenanceFromResult(job.result)
1803
+ : {})), (job.result && typeof job.result === 'object'
1804
+ ? { layers: job.result.layers }
1726
1805
  : {})));
1727
1806
  replayRevision = project._queueRevision;
1728
1807
  yield result;
@@ -1893,13 +1972,13 @@ class ProjectsApi extends ApiGroup_js_1.default {
1893
1972
  // Segmentation is a one-source/one-mask utility workflow, SAM 3 and
1894
1973
  // BiRefNet alike. Normalize before Project construction so lifecycle
1895
1974
  // completion and result MIME use the same values as the serialized request.
1896
- let normalizedData = data.type === 'image' && (0, index_js_2.isSegmentationModel)(data.modelId)
1975
+ let normalizedData = data.type === 'image' && (0, index_js_3.isSegmentationModel)(data.modelId)
1897
1976
  ? Object.assign(Object.assign({}, data), { numberOfMedia: 1, numberOfPreviews: 0, outputFormat: 'png' })
1898
1977
  : data;
1899
1978
  // Pixal3D reconstructs a 3D artifact, so there are no intermediate images
1900
1979
  // to preview. Normalize here as well as on the wire so the Project's own
1901
1980
  // params agree with the request that was actually sent.
1902
- if (normalizedData.type === 'image' && (0, index_js_2.isModelArtifactModel)(normalizedData.modelId)) {
1981
+ if (normalizedData.type === 'image' && (0, index_js_3.isModelArtifactModel)(normalizedData.modelId)) {
1903
1982
  normalizedData = Object.assign(Object.assign({}, normalizedData), { numberOfPreviews: 0 });
1904
1983
  }
1905
1984
  if (normalizedData.type === 'image' &&
@@ -1932,6 +2011,17 @@ class ProjectsApi extends ApiGroup_js_1.default {
1932
2011
  assertSession();
1933
2012
  const requestParams = Object.assign(Object.assign({}, normalizedData), { appSource: normalizedData.appSource || this.client.appSource, attribution: this.resolveWorkloadAttribution(normalizedData.attribution, project.id) });
1934
2013
  const request = (0, createJobRequestMessage_js_1.default)(project.id, requestParams, modelOptions);
2014
+ // No extra wait at all for a project that is not encrypted.
2015
+ const startingEncryption = this._projectEncryptionFor(normalizedData);
2016
+ const projectEncryption = startingEncryption && (yield startingEncryption);
2017
+ const encryption = projectEncryption === null || projectEncryption === void 0 ? void 0 : projectEncryption.encryption;
2018
+ if (projectEncryption) {
2019
+ // Some models take their inputs as they are.
2020
+ if (projectEncryption.encryptInputs) {
2021
+ this._projectEncryption.set(project.id, projectEncryption.encryption);
2022
+ }
2023
+ project._markMediaEncrypted();
2024
+ }
1935
2025
  switch (normalizedData.type) {
1936
2026
  case 'image':
1937
2027
  yield this._processImageAssets(project, normalizedData);
@@ -1945,6 +2035,9 @@ class ProjectsApi extends ApiGroup_js_1.default {
1945
2035
  this._annotateAudioAssetContentTypes(request, normalizedData);
1946
2036
  break;
1947
2037
  }
2038
+ // After the uploads, which add to it.
2039
+ if (encryption)
2040
+ request.mediaEncryption = encryption.wire();
1948
2041
  // Recorded before sending: a refusal can arrive as soon as the frame lands.
1949
2042
  assertSession();
1950
2043
  this._unadmittedRequests.set(project.id, request);
@@ -1978,6 +2071,7 @@ class ProjectsApi extends ApiGroup_js_1.default {
1978
2071
  }
1979
2072
  finally {
1980
2073
  this._preparingSessions.delete(project.id);
2074
+ this._projectEncryption.delete(project.id);
1981
2075
  }
1982
2076
  });
1983
2077
  }
@@ -2002,6 +2096,96 @@ class ProjectsApi extends ApiGroup_js_1.default {
2002
2096
  project._dispose();
2003
2097
  return tracked;
2004
2098
  }
2099
+ /** Whether projects for this model can use `mediaEncryption`, from the server's model list. */
2100
+ supportsMediaEncryption(modelId) {
2101
+ return __awaiter(this, void 0, void 0, function* () {
2102
+ var _a;
2103
+ const models = yield this.getSupportedModels();
2104
+ return ((_a = models.find((model) => model.id === modelId)) === null || _a === void 0 ? void 0 : _a.supportsMediaEncryption) === true;
2105
+ });
2106
+ }
2107
+ /** Whether an encrypted project on this model has its inputs encrypted too. */
2108
+ _encryptsInputs(modelId) {
2109
+ return __awaiter(this, void 0, void 0, function* () {
2110
+ var _a;
2111
+ const models = yield this.getSupportedModels();
2112
+ return ((_a = models.find((model) => model.id === modelId)) === null || _a === void 0 ? void 0 : _a.mediaEncryptionInputs) !== false;
2113
+ });
2114
+ }
2115
+ /**
2116
+ * How this project's media is encrypted, or `null` when it is not: an
2117
+ * explicit `mediaEncryption: true` must be honoured, `false` never is, and
2118
+ * an unset value follows the client's `mediaEncryption` mode.
2119
+ */
2120
+ _projectEncryptionFor(data) {
2121
+ var _a;
2122
+ if (data.mediaEncryption === true)
2123
+ return this._requireProjectEncryption(data);
2124
+ if (data.mediaEncryption === undefined && ((_a = this._mediaEncryption) === null || _a === void 0 ? void 0 : _a.automatic)) {
2125
+ return this._automaticProjectEncryption(data);
2126
+ }
2127
+ return null;
2128
+ }
2129
+ /** The network this project's request goes to. */
2130
+ _projectNetwork(data) {
2131
+ var _a, _b;
2132
+ return (_b = (_a = data.network) !== null && _a !== void 0 ? _a : this._currentNetworkType) !== null && _b !== void 0 ? _b : this.client.socket.supernetType;
2133
+ }
2134
+ /** `mediaEncryption: true`: every reason it cannot be done is an error. */
2135
+ _requireProjectEncryption(data) {
2136
+ return __awaiter(this, void 0, void 0, function* () {
2137
+ if (!this._mediaEncryption) {
2138
+ throw new index_js_1.MediaEncryptionError('unsupported', 'Media encryption is not available on this client instance');
2139
+ }
2140
+ const network = this._projectNetwork(data);
2141
+ if (!(0, networks_js_1.networkServesMediaEncryption)(network)) {
2142
+ throw new index_js_1.MediaEncryptionError('unsupported', `Media encryption is not available on the ${network} network`);
2143
+ }
2144
+ if (!(yield this.supportsMediaEncryption(data.modelId))) {
2145
+ throw new index_js_1.MediaEncryptionError('unsupported', `Media encryption is not available for model "${data.modelId}"`);
2146
+ }
2147
+ const encryptInputs = yield this._encryptsInputs(data.modelId);
2148
+ const field = encryptInputs && mediaUploadedElsewhere(data);
2149
+ if (field) {
2150
+ throw new index_js_1.MediaEncryptionError('unsupported', `Media encryption needs the media itself: pass a File, Blob or Buffer for "${field}" instead of true`);
2151
+ }
2152
+ return { encryption: yield this._mediaEncryption._createProjectEncryption(), encryptInputs };
2153
+ });
2154
+ }
2155
+ /**
2156
+ * `mediaEncryption: 'auto'`: encrypt when the network, the account and the
2157
+ * model all support it. Anything else is sent exactly as without encryption.
2158
+ */
2159
+ _automaticProjectEncryption(data) {
2160
+ return __awaiter(this, void 0, void 0, function* () {
2161
+ if (!(0, networks_js_1.networkServesMediaEncryption)(this._projectNetwork(data)))
2162
+ return null;
2163
+ const mediaEncryption = this._mediaEncryption;
2164
+ if (!(yield mediaEncryption._canEncryptAutomatically()))
2165
+ return null;
2166
+ if (!(yield this.supportsMediaEncryption(data.modelId)))
2167
+ return null;
2168
+ const encryptInputs = yield this._encryptsInputs(data.modelId);
2169
+ if (encryptInputs && mediaUploadedElsewhere(data))
2170
+ return null;
2171
+ return { encryption: yield mediaEncryption._createProjectEncryption(), encryptInputs };
2172
+ });
2173
+ }
2174
+ /** Saved uploads work for encrypted projects too: the encrypted file is saved and reused. */
2175
+ _bindSavedUpload(file, contentType, target) {
2176
+ return __awaiter(this, void 0, void 0, function* () {
2177
+ const encryption = this._projectEncryption.get(target.projectId);
2178
+ if (!encryption)
2179
+ return this.assets.tryBindFile(file, contentType, target);
2180
+ return this.assets.tryBindFile(yield encryption.encrypt(file, contentType), contentType, target);
2181
+ });
2182
+ }
2183
+ _uploadBody(projectId, file, contentType) {
2184
+ return __awaiter(this, void 0, void 0, function* () {
2185
+ const encryption = this._projectEncryption.get(projectId);
2186
+ return encryption ? encryption.encrypt(file, contentType) : toFetchBody(file);
2187
+ });
2188
+ }
2005
2189
  _processImageAssets(project, data) {
2006
2190
  return __awaiter(this, void 0, void 0, function* () {
2007
2191
  var _a, _b;
@@ -2020,7 +2204,7 @@ class ProjectsApi extends ApiGroup_js_1.default {
2020
2204
  if ((_b = data.contextImages) === null || _b === void 0 ? void 0 : _b.length) {
2021
2205
  const maxContextImages = (0, validation_js_1.getMaxContextImages)(data.modelId);
2022
2206
  if (data.contextImages.length > maxContextImages) {
2023
- throw new index_js_1.ApiError(500, {
2207
+ throw new index_js_2.ApiError(500, {
2024
2208
  status: 'error',
2025
2209
  errorCode: 0,
2026
2210
  message: `Up to ${maxContextImages} context images are supported for this model`
@@ -2034,7 +2218,7 @@ class ProjectsApi extends ApiGroup_js_1.default {
2034
2218
  }
2035
2219
  // Pixal3D multi-view orbit views use fixed contextImage slots (left 1, back
2036
2220
  // 2, right 3); createJobRequestMessage has already refused them anywhere else.
2037
- yield Promise.all((0, index_js_2.getPixal3dOrbitViewSlots)(data).map(({ slot, media }) => media === true
2221
+ yield Promise.all((0, index_js_3.getPixal3dOrbitViewSlots)(data).map(({ slot, media }) => media === true
2038
2222
  ? undefined
2039
2223
  : this.uploadContextImage(project.id, (slot - 1), media)));
2040
2224
  });
@@ -2058,7 +2242,7 @@ class ProjectsApi extends ApiGroup_js_1.default {
2058
2242
  }
2059
2243
  _processVideoAssets(project, data) {
2060
2244
  return __awaiter(this, void 0, void 0, function* () {
2061
- const isMinimaxH3R2v = (0, index_js_2.isMinimaxH3ReferenceModel)(data.modelId);
2245
+ const isMinimaxH3R2v = (0, index_js_3.isMinimaxH3ReferenceModel)(data.modelId);
2062
2246
  if ((data === null || data === void 0 ? void 0 : data.referenceImage) && data.referenceImage !== true) {
2063
2247
  yield this.uploadReferenceImage(project.id, data.referenceImage);
2064
2248
  }
@@ -2067,14 +2251,14 @@ class ProjectsApi extends ApiGroup_js_1.default {
2067
2251
  // getVideoContextImageSlots offsets them past referenceImage so the two
2068
2252
  // never land on the same slot. createJobRequestMessage has already checked
2069
2253
  // the model, the entries, and the 9-image ceiling.
2070
- yield Promise.all((0, index_js_2.getVideoContextImageSlots)(data).map(({ slot, media }) => typeof media === 'boolean'
2254
+ yield Promise.all((0, index_js_3.getVideoContextImageSlots)(data).map(({ slot, media }) => typeof media === 'boolean'
2071
2255
  ? undefined
2072
2256
  : this.uploadContextImage(project.id, (slot - 1), media)));
2073
2257
  // MiniMax H3 intermediate keyframes, uploaded to their own keyframeImage1..N
2074
2258
  // slots in caller order, apart from the contextImage slots r2v references
2075
2259
  // use. createJobRequestMessage has already checked the model, the entries
2076
2260
  // and the frame indices.
2077
- yield Promise.all((0, index_js_2.getMinimaxH3KeyframeSlots)(data).map(({ slot, media }) => typeof media === 'boolean'
2261
+ yield Promise.all((0, index_js_3.getMinimaxH3KeyframeSlots)(data).map(({ slot, media }) => typeof media === 'boolean'
2078
2262
  ? undefined
2079
2263
  : this.uploadKeyframeImage(project.id, slot, media)));
2080
2264
  if ((data === null || data === void 0 ? void 0 : data.referenceImageEnd) && data.referenceImageEnd !== true) {
@@ -2091,15 +2275,15 @@ class ProjectsApi extends ApiGroup_js_1.default {
2091
2275
  }
2092
2276
  if (isMinimaxH3R2v) {
2093
2277
  yield Promise.all([
2094
- ...(0, index_js_2.getMinimaxH3ReferenceAudioSlots)(data).map(({ slot, media }) => typeof media === 'boolean'
2278
+ ...(0, index_js_3.getMinimaxH3ReferenceAudioSlots)(data).map(({ slot, media }) => typeof media === 'boolean'
2095
2279
  ? undefined
2096
2280
  : this.uploadReferenceAudio(project.id, media, `referenceAudio${slot}`)),
2097
- ...(0, index_js_2.getMinimaxH3ReferenceVideoSlots)(data).map(({ slot, media }) => typeof media === 'boolean'
2281
+ ...(0, index_js_3.getMinimaxH3ReferenceVideoSlots)(data).map(({ slot, media }) => typeof media === 'boolean'
2098
2282
  ? undefined
2099
2283
  : this.uploadReferenceVideo(project.id, media, `referenceVideo${slot}`))
2100
2284
  ]);
2101
2285
  }
2102
- if ((data === null || data === void 0 ? void 0 : data.referenceMask) && data.referenceMask !== true && (0, index_js_2.usesReferenceMask)(data)) {
2286
+ if ((data === null || data === void 0 ? void 0 : data.referenceMask) && data.referenceMask !== true && (0, index_js_3.usesReferenceMask)(data)) {
2103
2287
  yield this.uploadReferenceMask(project.id, data.referenceMask);
2104
2288
  }
2105
2289
  });
@@ -2115,7 +2299,7 @@ class ProjectsApi extends ApiGroup_js_1.default {
2115
2299
  if (data.referenceImageEnd && data.referenceImageEnd !== true) {
2116
2300
  keyFrame.referenceImageEndContentType = (0, fileContentType_js_1.getFileContentType)(data.referenceImageEnd);
2117
2301
  }
2118
- const isMinimaxH3R2v = (0, index_js_2.isMinimaxH3ReferenceModel)(data.modelId);
2302
+ const isMinimaxH3R2v = (0, index_js_3.isMinimaxH3ReferenceModel)(data.modelId);
2119
2303
  if (!isMinimaxH3R2v && data.referenceAudio && data.referenceAudio !== true) {
2120
2304
  keyFrame.referenceAudioContentType = (0, fileContentType_js_1.getFileContentType)(data.referenceAudio, 'audio');
2121
2305
  }
@@ -2128,18 +2312,18 @@ class ProjectsApi extends ApiGroup_js_1.default {
2128
2312
  keyFrame.referenceVideoContentType = (0, fileContentType_js_1.getFileContentType)(data.referenceVideo, 'video');
2129
2313
  }
2130
2314
  if (isMinimaxH3R2v) {
2131
- for (const { slot, media } of (0, index_js_2.getMinimaxH3ReferenceAudioSlots)(data)) {
2315
+ for (const { slot, media } of (0, index_js_3.getMinimaxH3ReferenceAudioSlots)(data)) {
2132
2316
  if (typeof media !== 'boolean') {
2133
2317
  keyFrame[`referenceAudio${slot}ContentType`] = (0, fileContentType_js_1.getFileContentType)(media, 'audio');
2134
2318
  }
2135
2319
  }
2136
- for (const { slot, media } of (0, index_js_2.getMinimaxH3ReferenceVideoSlots)(data)) {
2320
+ for (const { slot, media } of (0, index_js_3.getMinimaxH3ReferenceVideoSlots)(data)) {
2137
2321
  if (typeof media !== 'boolean') {
2138
2322
  keyFrame[`referenceVideo${slot}ContentType`] = (0, fileContentType_js_1.getFileContentType)(media, 'video');
2139
2323
  }
2140
2324
  }
2141
2325
  }
2142
- if (data.referenceMask && data.referenceMask !== true && (0, index_js_2.usesReferenceMask)(data)) {
2326
+ if (data.referenceMask && data.referenceMask !== true && (0, index_js_3.usesReferenceMask)(data)) {
2143
2327
  keyFrame.referenceMaskContentType = (0, fileContentType_js_1.getFileContentType)(data.referenceMask);
2144
2328
  }
2145
2329
  }
@@ -2248,7 +2432,7 @@ class ProjectsApi extends ApiGroup_js_1.default {
2248
2432
  entry.url = job.resultUrl;
2249
2433
  }
2250
2434
  else {
2251
- const result = (0, index_js_2.resultMediaEvidence)(Object.assign(Object.assign({}, (job.result || {})), { outputFormat: (_c = job.outputFormat) !== null && _c !== void 0 ? _c : (_d = job.result) === null || _d === void 0 ? void 0 : _d.outputFormat }));
2435
+ const result = (0, index_js_3.resultMediaEvidence)(Object.assign(Object.assign({}, (job.result || {})), { outputFormat: (_c = job.outputFormat) !== null && _c !== void 0 ? _c : (_d = job.result) === null || _d === void 0 ? void 0 : _d.outputFormat }));
2252
2436
  const kind = (_e = this._resultMediaKind({ modelId, projectType, result })) !== null && _e !== void 0 ? _e : options.kind;
2253
2437
  if (!kind) {
2254
2438
  entry.urlUnavailable = 'unknownMediaKind';
@@ -2373,6 +2557,136 @@ class ProjectsApi extends ApiGroup_js_1.default {
2373
2557
  }
2374
2558
  });
2375
2559
  }
2560
+ /**
2561
+ * Run one waiting Unlimited plan project on Premium Spark now, at its normal
2562
+ * price, when {@link Project.payAsYouGo} offers it. The server re-checks every
2563
+ * condition when asked. The result has one of three statuses:
2564
+ *
2565
+ * - `switched`: the project runs on Premium Spark; its price was charged once.
2566
+ * - `refused`: this request costs nothing; `reason` says why. A debit the server
2567
+ * had already started (after `payment_failed`, `no_idle_worker` or `started`)
2568
+ * is cancelled, and the balance can take a moment to show it. `started` and
2569
+ * `not_eligible` clear the offer at once. After any other refusal (for example
2570
+ * `insufficient_premium_spark`, where an app can offer a Spark purchase and ask
2571
+ * again) the server's next queue update decides whether the offer stays.
2572
+ * - `unknown` (`timeout`, `not_found`, `session_changed`, `unrecognized_reply`):
2573
+ * the server may have switched and charged the project. Treat the payment as
2574
+ * possibly made. Asking again is safe and never charges twice: it answers
2575
+ * `switched` if the earlier request switched, a refusal if it costs nothing,
2576
+ * or `unknown` again (including `not_found` once the creation has finished).
2577
+ * While it stays unknown, check the member's Spark history or the creation's
2578
+ * result rather than assuming either way.
2579
+ *
2580
+ * A repeated call while one is pending shares its result. If the connection
2581
+ * drops while the request is pending, the SDK sends it once more after
2582
+ * reconnecting, because the server replies only on the socket that asked.
2583
+ * `timeoutMs` (default 45 s) counts from when the request is sent, and restarts
2584
+ * after that one re-send.
2585
+ */
2586
+ switchToPremiumSpark(projectId_1) {
2587
+ return __awaiter(this, arguments, void 0, function* (projectId, options = {}) {
2588
+ const key = projectId.toUpperCase();
2589
+ const existing = this.payAsYouGoSwitchRequests.get(key);
2590
+ if (existing)
2591
+ return existing.promise;
2592
+ const requested = options.timeoutMs;
2593
+ const timeoutMs = typeof requested === 'number' && Number.isFinite(requested) && requested > 0
2594
+ ? requested
2595
+ : PAY_AS_YOU_GO_SWITCH_TIMEOUT_MS;
2596
+ const pending = this.startPremiumSparkSwitch(projectId, timeoutMs);
2597
+ this.payAsYouGoSwitchRequests.set(key, pending);
2598
+ try {
2599
+ return yield pending.promise;
2600
+ }
2601
+ finally {
2602
+ if (this.payAsYouGoSwitchRequests.get(key) === pending)
2603
+ this.payAsYouGoSwitchRequests.delete(key);
2604
+ }
2605
+ });
2606
+ }
2607
+ startPremiumSparkSwitch(projectId, timeoutMs) {
2608
+ const upperId = projectId.toUpperCase();
2609
+ let resolveOutcome;
2610
+ const outcome = new Promise((resolve) => {
2611
+ resolveOutcome = resolve;
2612
+ });
2613
+ let settled = false;
2614
+ let timeout;
2615
+ let removeConnectedListener = () => { };
2616
+ const removeReplyListener = this.client.socket.on('projectPaymentSwitch', (data) => {
2617
+ if (String((data === null || data === void 0 ? void 0 : data.jobID) || '').toUpperCase() !== upperId)
2618
+ return;
2619
+ finish((0, PayAsYouGo_js_1.normalizePayAsYouGoSwitchResult)(projectId, data));
2620
+ });
2621
+ const finish = (result) => {
2622
+ if (settled)
2623
+ return;
2624
+ settled = true;
2625
+ removeReplyListener();
2626
+ removeConnectedListener();
2627
+ if (timeout)
2628
+ clearTimeout(timeout);
2629
+ resolveOutcome(result);
2630
+ };
2631
+ const armTimer = () => {
2632
+ var _a;
2633
+ if (settled)
2634
+ return;
2635
+ if (timeout)
2636
+ clearTimeout(timeout);
2637
+ timeout = setTimeout(() => finish({
2638
+ projectId,
2639
+ status: 'unknown',
2640
+ reason: 'timeout',
2641
+ message: 'No reply arrived, so the payment state is unknown. Asking again is safe.'
2642
+ }), timeoutMs);
2643
+ (_a = timeout.unref) === null || _a === void 0 ? void 0 : _a.call(timeout);
2644
+ };
2645
+ // Resolves false only when the request certainly never left this client.
2646
+ const send = () => __awaiter(this, void 0, void 0, function* () {
2647
+ try {
2648
+ yield this.client.socket.send('switchProjectToPremiumSpark', { projectId });
2649
+ return true;
2650
+ }
2651
+ catch (error) {
2652
+ return error instanceof requestDelivery_js_1.MessageDeliveryUncertainError;
2653
+ }
2654
+ });
2655
+ void (() => __awaiter(this, void 0, void 0, function* () {
2656
+ const delivered = yield send();
2657
+ if (settled)
2658
+ return;
2659
+ if (!delivered) {
2660
+ finish({ projectId, status: 'refused', reason: 'not_sent' });
2661
+ return;
2662
+ }
2663
+ const sentGeneration = this._transportGeneration;
2664
+ // The server replies only on the socket that asked: after a reconnect,
2665
+ // ask once more from the new socket. Repeats never charge twice.
2666
+ removeConnectedListener = this.client.on('connected', () => {
2667
+ if (settled || this._transportGeneration === sentGeneration)
2668
+ return;
2669
+ removeConnectedListener();
2670
+ if (timeout)
2671
+ clearTimeout(timeout);
2672
+ void send().then(armTimer);
2673
+ });
2674
+ armTimer();
2675
+ }))();
2676
+ const promise = outcome.then((result) => {
2677
+ // Clear the offer only when the outcome ends it for good; the server's next
2678
+ // projectQueue update decides every other case.
2679
+ const clearsOffer = result.status === 'switched' ||
2680
+ (result.status === 'refused' && PayAsYouGo_js_1.PAY_AS_YOU_GO_REFUSALS_CLEARING_OFFER.has(result.reason));
2681
+ if (clearsOffer) {
2682
+ const project = this.projects.find((item) => item.id.toUpperCase() === upperId);
2683
+ if (project === null || project === void 0 ? void 0 : project._setPayAsYouGo(null))
2684
+ this._emitQueueChanged(project);
2685
+ }
2686
+ return result;
2687
+ });
2688
+ return { projectId, promise, settle: finish };
2689
+ }
2376
2690
  /**
2377
2691
  * Cancel a project by id after the server confirms that cancellation succeeded.
2378
2692
  *
@@ -2480,7 +2794,7 @@ class ProjectsApi extends ApiGroup_js_1.default {
2480
2794
  const assertSession = (_a = this._preparingSessions.get(projectId)) !== null && _a !== void 0 ? _a : (0, requestSession_js_1.captureRequestSession)(this.client.auth);
2481
2795
  assertSession();
2482
2796
  const contentType = (0, fileContentType_js_1.getFileContentType)(file);
2483
- if (yield this.assets.tryBindFile(file, contentType, { projectId, type: 'startingImage' }))
2797
+ if (yield this._bindSavedUpload(file, contentType, { projectId, type: 'startingImage' }))
2484
2798
  return imageId;
2485
2799
  assertSession();
2486
2800
  const presignedUrl = yield this.uploadUrl({
@@ -2495,12 +2809,12 @@ class ProjectsApi extends ApiGroup_js_1.default {
2495
2809
  assertSession();
2496
2810
  const res = yield fetch(presignedUrl, {
2497
2811
  method: 'PUT',
2498
- body: toFetchBody(file),
2812
+ body: yield this._uploadBody(projectId, file, contentType),
2499
2813
  headers
2500
2814
  });
2501
2815
  assertSession();
2502
2816
  if (!res.ok) {
2503
- throw new index_js_1.ApiError(res.status, {
2817
+ throw new index_js_2.ApiError(res.status, {
2504
2818
  status: 'error',
2505
2819
  errorCode: 0,
2506
2820
  message: 'Failed to upload guide image'
@@ -2516,7 +2830,7 @@ class ProjectsApi extends ApiGroup_js_1.default {
2516
2830
  const assertSession = (_a = this._preparingSessions.get(projectId)) !== null && _a !== void 0 ? _a : (0, requestSession_js_1.captureRequestSession)(this.client.auth);
2517
2831
  assertSession();
2518
2832
  const contentType = (0, fileContentType_js_1.getFileContentType)(file);
2519
- if (yield this.assets.tryBindFile(file, contentType, { projectId, type: 'cnImage' }))
2833
+ if (yield this._bindSavedUpload(file, contentType, { projectId, type: 'cnImage' }))
2520
2834
  return imageId;
2521
2835
  assertSession();
2522
2836
  const presignedUrl = yield this.uploadUrl({
@@ -2531,12 +2845,12 @@ class ProjectsApi extends ApiGroup_js_1.default {
2531
2845
  assertSession();
2532
2846
  const res = yield fetch(presignedUrl, {
2533
2847
  method: 'PUT',
2534
- body: toFetchBody(file),
2848
+ body: yield this._uploadBody(projectId, file, contentType),
2535
2849
  headers
2536
2850
  });
2537
2851
  assertSession();
2538
2852
  if (!res.ok) {
2539
- throw new index_js_1.ApiError(res.status, {
2853
+ throw new index_js_2.ApiError(res.status, {
2540
2854
  status: 'error',
2541
2855
  errorCode: 0,
2542
2856
  message: 'Failed to upload ControlNet image'
@@ -2553,7 +2867,7 @@ class ProjectsApi extends ApiGroup_js_1.default {
2553
2867
  const assertSession = (_a = this._preparingSessions.get(projectId)) !== null && _a !== void 0 ? _a : (0, requestSession_js_1.captureRequestSession)(this.client.auth);
2554
2868
  assertSession();
2555
2869
  const contentType = (0, fileContentType_js_1.getFileContentType)(file);
2556
- if (yield this.assets.tryBindFile(file, contentType, {
2870
+ if (yield this._bindSavedUpload(file, contentType, {
2557
2871
  projectId,
2558
2872
  type: `contextImage${imageIndex}`
2559
2873
  }))
@@ -2565,7 +2879,7 @@ class ProjectsApi extends ApiGroup_js_1.default {
2565
2879
  type: `contextImage${imageIndex}`,
2566
2880
  contentType
2567
2881
  });
2568
- const body = toFetchBody(file);
2882
+ const body = yield this._uploadBody(projectId, file, contentType);
2569
2883
  const headers = {};
2570
2884
  if (contentType)
2571
2885
  headers['Content-Type'] = contentType;
@@ -2577,7 +2891,7 @@ class ProjectsApi extends ApiGroup_js_1.default {
2577
2891
  });
2578
2892
  assertSession();
2579
2893
  if (!res.ok) {
2580
- throw new index_js_1.ApiError(res.status, {
2894
+ throw new index_js_2.ApiError(res.status, {
2581
2895
  status: 'error',
2582
2896
  errorCode: 0,
2583
2897
  message: `Failed to upload context image ${index}`
@@ -2599,7 +2913,7 @@ class ProjectsApi extends ApiGroup_js_1.default {
2599
2913
  const assertSession = (_a = this._preparingSessions.get(projectId)) !== null && _a !== void 0 ? _a : (0, requestSession_js_1.captureRequestSession)(this.client.auth);
2600
2914
  assertSession();
2601
2915
  const contentType = (0, fileContentType_js_1.getFileContentType)(file);
2602
- if (yield this.assets.tryBindFile(file, contentType, { projectId, type }))
2916
+ if (yield this._bindSavedUpload(file, contentType, { projectId, type }))
2603
2917
  return imageId;
2604
2918
  assertSession();
2605
2919
  const presignedUrl = yield this.uploadUrl({ imageId, jobId: projectId, type, contentType });
@@ -2609,12 +2923,12 @@ class ProjectsApi extends ApiGroup_js_1.default {
2609
2923
  assertSession();
2610
2924
  const res = yield fetch(presignedUrl, {
2611
2925
  method: 'PUT',
2612
- body: toFetchBody(file),
2926
+ body: yield this._uploadBody(projectId, file, contentType),
2613
2927
  headers
2614
2928
  });
2615
2929
  assertSession();
2616
2930
  if (!res.ok) {
2617
- throw new index_js_1.ApiError(res.status, {
2931
+ throw new index_js_2.ApiError(res.status, {
2618
2932
  status: 'error',
2619
2933
  errorCode: 0,
2620
2934
  message: `Failed to upload keyframe image ${slot}`
@@ -2637,7 +2951,7 @@ class ProjectsApi extends ApiGroup_js_1.default {
2637
2951
  const assertSession = (_a = this._preparingSessions.get(projectId)) !== null && _a !== void 0 ? _a : (0, requestSession_js_1.captureRequestSession)(this.client.auth);
2638
2952
  assertSession();
2639
2953
  const contentType = (0, fileContentType_js_1.getFileContentType)(file);
2640
- if (yield this.assets.tryBindFile(file, contentType, { projectId, type: 'referenceImage' }))
2954
+ if (yield this._bindSavedUpload(file, contentType, { projectId, type: 'referenceImage' }))
2641
2955
  return imageId;
2642
2956
  assertSession();
2643
2957
  const presignedUrl = yield this.uploadUrl({
@@ -2652,12 +2966,12 @@ class ProjectsApi extends ApiGroup_js_1.default {
2652
2966
  assertSession();
2653
2967
  const res = yield fetch(presignedUrl, {
2654
2968
  method: 'PUT',
2655
- body: toFetchBody(file),
2969
+ body: yield this._uploadBody(projectId, file, contentType),
2656
2970
  headers
2657
2971
  });
2658
2972
  assertSession();
2659
2973
  if (!res.ok) {
2660
- throw new index_js_1.ApiError(res.status, {
2974
+ throw new index_js_2.ApiError(res.status, {
2661
2975
  status: 'error',
2662
2976
  errorCode: 0,
2663
2977
  message: 'Failed to upload reference image'
@@ -2677,7 +2991,7 @@ class ProjectsApi extends ApiGroup_js_1.default {
2677
2991
  const assertSession = (_a = this._preparingSessions.get(projectId)) !== null && _a !== void 0 ? _a : (0, requestSession_js_1.captureRequestSession)(this.client.auth);
2678
2992
  assertSession();
2679
2993
  const contentType = (0, fileContentType_js_1.getFileContentType)(file);
2680
- if (yield this.assets.tryBindFile(file, contentType, { projectId, type: 'referenceMask' }))
2994
+ if (yield this._bindSavedUpload(file, contentType, { projectId, type: 'referenceMask' }))
2681
2995
  return imageId;
2682
2996
  assertSession();
2683
2997
  const presignedUrl = yield this.uploadUrl({
@@ -2692,12 +3006,12 @@ class ProjectsApi extends ApiGroup_js_1.default {
2692
3006
  assertSession();
2693
3007
  const res = yield fetch(presignedUrl, {
2694
3008
  method: 'PUT',
2695
- body: toFetchBody(file),
3009
+ body: yield this._uploadBody(projectId, file, contentType),
2696
3010
  headers
2697
3011
  });
2698
3012
  assertSession();
2699
3013
  if (!res.ok) {
2700
- throw new index_js_1.ApiError(res.status, {
3014
+ throw new index_js_2.ApiError(res.status, {
2701
3015
  status: 'error',
2702
3016
  errorCode: 0,
2703
3017
  message: 'Failed to upload reference mask'
@@ -2717,7 +3031,7 @@ class ProjectsApi extends ApiGroup_js_1.default {
2717
3031
  const assertSession = (_a = this._preparingSessions.get(projectId)) !== null && _a !== void 0 ? _a : (0, requestSession_js_1.captureRequestSession)(this.client.auth);
2718
3032
  assertSession();
2719
3033
  const contentType = (0, fileContentType_js_1.getFileContentType)(file);
2720
- if (yield this.assets.tryBindFile(file, contentType, { projectId, type: 'referenceImageEnd' }))
3034
+ if (yield this._bindSavedUpload(file, contentType, { projectId, type: 'referenceImageEnd' }))
2721
3035
  return imageId;
2722
3036
  assertSession();
2723
3037
  const presignedUrl = yield this.uploadUrl({
@@ -2732,12 +3046,12 @@ class ProjectsApi extends ApiGroup_js_1.default {
2732
3046
  assertSession();
2733
3047
  const res = yield fetch(presignedUrl, {
2734
3048
  method: 'PUT',
2735
- body: toFetchBody(file),
3049
+ body: yield this._uploadBody(projectId, file, contentType),
2736
3050
  headers
2737
3051
  });
2738
3052
  assertSession();
2739
3053
  if (!res.ok) {
2740
- throw new index_js_1.ApiError(res.status, {
3054
+ throw new index_js_2.ApiError(res.status, {
2741
3055
  status: 'error',
2742
3056
  errorCode: 0,
2743
3057
  message: 'Failed to upload reference image end'
@@ -2758,7 +3072,7 @@ class ProjectsApi extends ApiGroup_js_1.default {
2758
3072
  const assertSession = (_a = this._preparingSessions.get(projectId)) !== null && _a !== void 0 ? _a : (0, requestSession_js_1.captureRequestSession)(this.client.auth);
2759
3073
  assertSession();
2760
3074
  const contentType = (0, fileContentType_js_1.getFileContentType)(file, 'audio');
2761
- if (yield this.assets.tryBindFile(file, contentType, { projectId, type: 'referenceAudio', id }))
3075
+ if (yield this._bindSavedUpload(file, contentType, { projectId, type: 'referenceAudio', id }))
2762
3076
  return;
2763
3077
  assertSession();
2764
3078
  const presignedUrl = yield this.mediaUploadUrl({
@@ -2774,12 +3088,12 @@ class ProjectsApi extends ApiGroup_js_1.default {
2774
3088
  assertSession();
2775
3089
  const res = yield fetch(presignedUrl, {
2776
3090
  method: 'PUT',
2777
- body: toFetchBody(file),
3091
+ body: yield this._uploadBody(projectId, file, contentType),
2778
3092
  headers
2779
3093
  });
2780
3094
  assertSession();
2781
3095
  if (!res.ok) {
2782
- throw new index_js_1.ApiError(res.status, {
3096
+ throw new index_js_2.ApiError(res.status, {
2783
3097
  status: 'error',
2784
3098
  errorCode: 0,
2785
3099
  message: 'Failed to upload reference audio'
@@ -2798,7 +3112,7 @@ class ProjectsApi extends ApiGroup_js_1.default {
2798
3112
  const assertSession = (_a = this._preparingSessions.get(projectId)) !== null && _a !== void 0 ? _a : (0, requestSession_js_1.captureRequestSession)(this.client.auth);
2799
3113
  assertSession();
2800
3114
  const contentType = (0, fileContentType_js_1.getFileContentType)(file, 'video');
2801
- if (yield this.assets.tryBindFile(file, contentType, { projectId, type: 'referenceVideo', id }))
3115
+ if (yield this._bindSavedUpload(file, contentType, { projectId, type: 'referenceVideo', id }))
2802
3116
  return;
2803
3117
  assertSession();
2804
3118
  const presignedUrl = yield this.mediaUploadUrl({
@@ -2814,12 +3128,12 @@ class ProjectsApi extends ApiGroup_js_1.default {
2814
3128
  assertSession();
2815
3129
  const res = yield fetch(presignedUrl, {
2816
3130
  method: 'PUT',
2817
- body: toFetchBody(file),
3131
+ body: yield this._uploadBody(projectId, file, contentType),
2818
3132
  headers
2819
3133
  });
2820
3134
  assertSession();
2821
3135
  if (!res.ok) {
2822
- throw new index_js_1.ApiError(res.status, {
3136
+ throw new index_js_2.ApiError(res.status, {
2823
3137
  status: 'error',
2824
3138
  errorCode: 0,
2825
3139
  message: 'Failed to upload reference video'
@@ -2834,7 +3148,7 @@ class ProjectsApi extends ApiGroup_js_1.default {
2834
3148
  * Estimate image project cost
2835
3149
  */
2836
3150
  estimateCost(_a) {
2837
- return __awaiter(this, arguments, void 0, function* ({ network = 'fast', tokenType, model, imageCount, stepCount, previewCount, cnEnabled, startingImageStrength, width, height, sizePreset, guidance, sampler, contextImages, gptImageQuality, gptImageFrameCount, gptImageFrameDurationMs, gptImageComplexity, outputFormat, billingMode, priorityMode, includeMonthlyFairUse }) {
3151
+ return __awaiter(this, arguments, void 0, function* ({ network = 'fast', tokenType, model, imageCount, stepCount, previewCount, cnEnabled, startingImageStrength, width, height, sizePreset, guidance, sampler, contextImages, gptImageQuality, gptImageFrameCount, gptImageFrameDurationMs, gptImageComplexity, outputFormat, seedreamLayerDecomposition, seedreamLayerSize, seedreamLayerMaxImages, billingMode, priorityMode, includeMonthlyFairUse }) {
2838
3152
  var _b, _c, _d;
2839
3153
  let apiVersion = 2;
2840
3154
  const modelOptions = yield this.getModelOptions(model);
@@ -2885,6 +3199,12 @@ class ProjectsApi extends ApiGroup_js_1.default {
2885
3199
  queryParams.set('gptImageComplexity', gptImageComplexity);
2886
3200
  if (outputFormat)
2887
3201
  queryParams.set('outputFormat', outputFormat);
3202
+ if (seedreamLayerDecomposition)
3203
+ queryParams.set('seedreamLayerDecomposition', 'true');
3204
+ if (seedreamLayerSize)
3205
+ queryParams.set('seedreamLayerSize', seedreamLayerSize);
3206
+ if (seedreamLayerMaxImages !== undefined)
3207
+ queryParams.set('seedreamLayerMaxImages', String(seedreamLayerMaxImages));
2888
3208
  if (billingMode)
2889
3209
  queryParams.set('billingMode', billingMode);
2890
3210
  if (priorityMode !== undefined)
@@ -2906,7 +3226,7 @@ class ProjectsApi extends ApiGroup_js_1.default {
2906
3226
  return __awaiter(this, arguments, void 0, function* (strength, tokenType = 'spark', size) {
2907
3227
  return this.estimateCost(Object.assign({ network: Job_js_1.enhancementDefaults.network, tokenType, model: Job_js_1.enhancementDefaults.modelId, imageCount: 1, stepCount: Job_js_1.enhancementDefaults.steps, previewCount: 0, cnEnabled: false,
2908
3228
  // Guide influence, exactly as job.enhance() submits it: light keeps the most.
2909
- startingImageStrength: 1 - (0, index_js_2.getEnhacementStrength)(strength) }, (size ? { width: size.width, height: size.height } : {})));
3229
+ startingImageStrength: 1 - (0, index_js_3.getEnhacementStrength)(strength) }, (size ? { width: size.width, height: size.height } : {})));
2910
3230
  });
2911
3231
  }
2912
3232
  /**
@@ -2944,7 +3264,7 @@ class ProjectsApi extends ApiGroup_js_1.default {
2944
3264
  (0, createJobRequestMessage_js_1.validateSeedanceDraftFields)(params);
2945
3265
  const frames = params.frames
2946
3266
  ? params.frames
2947
- : (0, index_js_2.calculateVideoFrames)(params.model, params.duration, params.fps);
3267
+ : (0, index_js_3.calculateVideoFrames)(params.model, params.duration, params.fps);
2948
3268
  const numberOfMedia = (_a = params.numberOfMedia) !== null && _a !== void 0 ? _a : 1;
2949
3269
  const pathParams = [
2950
3270
  params.tokenType,
@@ -3263,13 +3583,13 @@ class ProjectsApi extends ApiGroup_js_1.default {
3263
3583
  getVideoAssetConfig(modelId) {
3264
3584
  return __awaiter(this, void 0, void 0, function* () {
3265
3585
  if (!this.isVideoModelId(modelId)) {
3266
- throw new index_js_1.ApiError(400, {
3586
+ throw new index_js_2.ApiError(400, {
3267
3587
  status: 'error',
3268
3588
  errorCode: 0,
3269
3589
  message: `Model ${modelId} is not a video model`
3270
3590
  });
3271
3591
  }
3272
- const workflow = (0, index_js_2.getVideoWorkflowType)(modelId);
3592
+ const workflow = (0, index_js_3.getVideoWorkflowType)(modelId);
3273
3593
  if (!workflow) {
3274
3594
  return {
3275
3595
  workflowType: null
@@ -3277,7 +3597,7 @@ class ProjectsApi extends ApiGroup_js_1.default {
3277
3597
  }
3278
3598
  return {
3279
3599
  workflowType: workflow,
3280
- assets: (0, index_js_2.getVideoAssetRequirements)(modelId)
3600
+ assets: (0, index_js_3.getVideoAssetRequirements)(modelId)
3281
3601
  };
3282
3602
  });
3283
3603
  }