@runware/sdk-js 1.2.5-beta.2 → 1.2.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.cts CHANGED
@@ -1,64 +1,3 @@
1
- /**
2
- * Runware SDK Telemetry Logger
3
- *
4
- * Beautiful colored console output for debugging SDK internals.
5
- * Only active when `enableLogging: true` is passed during instantiation.
6
- *
7
- * Usage:
8
- * const runware = new RunwareServer({ apiKey: "...", enableLogging: true });
9
- */
10
- declare enum LogLevel {
11
- CONNECTION = "CONNECTION",
12
- AUTH = "AUTH",
13
- HEARTBEAT = "HEARTBEAT",
14
- SEND = "SEND",
15
- RECEIVE = "RECEIVE",
16
- RETRY = "RETRY",
17
- REQUEST = "REQUEST",
18
- ERROR = "ERROR",
19
- WARN = "WARN",
20
- INFO = "INFO"
21
- }
22
- declare class RunwareLogger {
23
- private enabled;
24
- constructor(enabled?: boolean);
25
- private log;
26
- connecting(url: string): void;
27
- connected(sessionUUID: string): void;
28
- reconnecting(attempt: number): void;
29
- reconnectScheduled(delayMs: number): void;
30
- disconnected(reason?: string): void;
31
- connectionClosed(code?: number): void;
32
- connectionError(error?: any): void;
33
- ensureConnectionStart(): void;
34
- ensureConnectionSuccess(): void;
35
- ensureConnectionTimeout(): void;
36
- authenticating(hasSession: boolean): void;
37
- authenticated(sessionUUID: string): void;
38
- authError(error: any): void;
39
- heartbeatStarted(intervalMs: number): void;
40
- heartbeatPingSent(): void;
41
- heartbeatPongReceived(): void;
42
- heartbeatPongMissed(count: number, max: number): void;
43
- heartbeatStopped(): void;
44
- messageSent(taskType: string, taskUUID?: string): void;
45
- messageReceived(taskType?: string, taskUUID?: string): void;
46
- sendReconnecting(): void;
47
- sendFailed(error: string): void;
48
- requestStart(taskType: string, taskUUID: string): void;
49
- requestComplete(taskType: string, taskUUID: string, durationMs: number): void;
50
- requestTimeout(taskUUID: string, timeoutMs: number): void;
51
- requestError(taskUUID: string, error: any): void;
52
- retryAttempt(attempt: number, maxRetries: number, delayMs: number): void;
53
- retrySuccess(attempt: number): void;
54
- retryExhausted(maxRetries: number): void;
55
- retrySkippedApiError(code: string): void;
56
- info(message: string, data?: any): void;
57
- warn(message: string, data?: any): void;
58
- error(message: string, data?: any): void;
59
- }
60
- declare function createLogger(enabled: boolean): RunwareLogger;
61
-
62
1
  declare enum Environment {
63
2
  PRODUCTION = "PRODUCTION",
64
3
  DEVELOPMENT = "DEVELOPMENT",
@@ -95,8 +34,6 @@ type RunwareBaseType = {
95
34
  shouldReconnect?: boolean;
96
35
  globalMaxRetries?: number;
97
36
  timeoutDuration?: number;
98
- heartbeatInterval?: number;
99
- enableLogging?: boolean;
100
37
  };
101
38
  type IOutputType = "base64Data" | "dataURI" | "URL";
102
39
  type IOutputFormat = "JPG" | "PNG" | "WEBP";
@@ -502,7 +439,7 @@ interface IEnhancedPrompt extends IImageToText {
502
439
  }
503
440
  interface IUpscaleGan extends IAdditionalResponsePayload {
504
441
  inputImage?: File | string;
505
- upscaleFactor: number;
442
+ upscaleFactor?: number;
506
443
  outputType?: IOutputType;
507
444
  outputFormat?: IOutputFormat | "MP4" | "WEBM" | "MOV";
508
445
  includeCost?: boolean;
@@ -519,6 +456,7 @@ interface IUpscaleGan extends IAdditionalResponsePayload {
519
456
  retry?: number;
520
457
  skipResponse?: boolean;
521
458
  deliveryMethod?: string;
459
+ [key: string]: any;
522
460
  }
523
461
  type ReconnectingWebsocketProps = {
524
462
  addEventListener: (type: string, listener: EventListener, options: any) => void;
@@ -903,14 +841,8 @@ declare class RunwareBase {
903
841
  _shouldReconnect: boolean;
904
842
  _globalMaxRetries: number;
905
843
  _timeoutDuration: number;
906
- _heartbeatIntervalId: any;
907
- _pongTimeoutId: any;
908
- _heartbeatInterval: number;
909
- _missedPongCount: number;
910
- _maxMissedPongs: number;
911
844
  ensureConnectionUUID: string | null;
912
- _logger: RunwareLogger;
913
- constructor({ apiKey, url, shouldReconnect, globalMaxRetries, timeoutDuration, heartbeatInterval, enableLogging, }: RunwareBaseType);
845
+ constructor({ apiKey, url, shouldReconnect, globalMaxRetries, timeoutDuration, }: RunwareBaseType);
914
846
  private getUniqueUUID;
915
847
  /**
916
848
  * Shared polling logic for async results.
@@ -922,9 +854,6 @@ declare class RunwareBase {
922
854
  static initialize(props: RunwareBaseType): Promise<RunwareBase>;
923
855
  protected isWebsocketReadyState: () => boolean;
924
856
  protected isInvalidAPIKey: () => boolean;
925
- protected startHeartbeat(): void;
926
- protected stopHeartbeat(): void;
927
- protected handlePongMessage(data: any): boolean;
928
857
  protected addListener({ lis, groupKey, taskUUID, }: {
929
858
  lis: (v: any) => any;
930
859
  groupKey?: string;
@@ -933,7 +862,7 @@ declare class RunwareBase {
933
862
  destroy: () => void;
934
863
  };
935
864
  protected connect(): void;
936
- protected send: (msg: Object) => Promise<void>;
865
+ protected send: (msg: Object) => void;
937
866
  private destroy;
938
867
  private uploadImage;
939
868
  private listenToResponse;
@@ -971,7 +900,7 @@ declare class RunwareBase {
971
900
  * @since 1.2.0
972
901
  * @returns {Promise<IImage>} If called with `inputs.image` or `inputs.video`, returns an object with `mediaUUID` and `mediaURL`. If called with `inputImage`, returns an object with `imageUUID` and `imageURL` (not guaranteed).
973
902
  */
974
- upscaleGan: ({ inputImage, inputs, model, upscaleFactor, outputType, outputFormat, includeCost, outputQuality, customTaskUUID, taskUUID: _taskUUID, retry, includeGenerationTime, includePayload, skipResponse, deliveryMethod, }: IUpscaleGan) => Promise<IImage>;
903
+ upscaleGan: (payload: IUpscaleGan) => Promise<IImage>;
975
904
  upscale: (params: IUpscaleGan) => Promise<IImage>;
976
905
  enhancePrompt: ({ prompt, promptMaxLength, promptVersions, includeCost, customTaskUUID, taskUUID: _taskUUID, retry, includeGenerationTime, includePayload, }: IPromptEnhancer) => Promise<IEnhancedPrompt[]>;
977
906
  promptEnhance: (params: IPromptEnhancer) => Promise<IEnhancedPrompt[]>;
@@ -1009,14 +938,16 @@ declare class RunwareServer extends RunwareBase {
1009
938
  _instantiated: boolean;
1010
939
  _listeners: any[];
1011
940
  _reconnectingIntervalId: null | any;
1012
- private _connecting;
941
+ _pingTimeout: any;
942
+ _pongListener: any;
1013
943
  constructor(props: RunwareBaseType);
1014
944
  protected connect(): Promise<void>;
1015
- protected send: (msg: Object) => Promise<void>;
945
+ protected send: (msg: Object) => void;
1016
946
  protected handleClose(): void;
1017
947
  protected resetConnection: () => void;
948
+ protected heartBeat(): void;
1018
949
  }
1019
950
 
1020
951
  declare let Runware: typeof RunwareClient | typeof RunwareServer;
1021
952
 
1022
- export { EControlMode, EModelArchitecture, EModelConditioning, EModelFormat, EModelType, EOpenPosePreProcessor, EPhotoMakerEnum, EPreProcessor, EPreProcessorGroup, ETaskType, Environment, type GetWithPromiseAsyncCallBackType, type GetWithPromiseCallBackType, type IAddModelResponse, type IAdditionalResponsePayload, type IAsyncResults, type IAudio, type IAudioOutputFormat, type IBflProviderSettings, type IControlNet, type IControlNetGeneral, type IControlNetImage, type IControlNetPreprocess, type IControlNetWithUUID, type IEmbedding, type IEnhancedPrompt, type IError, type IErrorResponse, type IImage, type IImageToText, type IOutpaint, type IOutputFormat, type IOutputType, type IPromptEnhancer, type IProviderSettings, type IRefiner, type IRemoveImage, type IRemoveImageBackground, type IRequestAudio, type IRequestImage, type IRequestImageToText, type IRequestTextInference, type IRequestThreeD, type IRequestVideo, type ITextMessage, type ITextResponse, type ITextToImage, type IThreeDImage, type IThreeDOutputFormat, type IUpscaleGan, type IVideoOutputFormat, type IVideoToImage, type IipAdapter, type ListenerType, LogLevel, type MediaUUID, type ProviderSettings, type ReconnectingWebsocketProps, type RequireAtLeastOne, type RequireOnlyOne, Runware, type RunwareBaseType, RunwareClient, RunwareLogger, RunwareServer, SdkType, type TAcceleratorOptions, type TAddModel, type TAddModelBaseType, type TAddModelCheckPoint, type TAddModelControlNet, type TAddModelLora, type TImageMasking, type TImageMaskingResponse, type TImageUpload, type TImageUploadResponse, type TMediaStorage, type TMediaStorageResponse, type TModel, type TModelSearch, type TModelSearchResponse, type TPhotoMaker, type TPhotoMakerResponse, type TPromptWeighting, type TServerError, type TVectorize, type TVectorizeResponse, type UploadImageType, createLogger };
953
+ export { EControlMode, EModelArchitecture, EModelConditioning, EModelFormat, EModelType, EOpenPosePreProcessor, EPhotoMakerEnum, EPreProcessor, EPreProcessorGroup, ETaskType, Environment, type GetWithPromiseAsyncCallBackType, type GetWithPromiseCallBackType, type IAddModelResponse, type IAdditionalResponsePayload, type IAsyncResults, type IAudio, type IAudioOutputFormat, type IBflProviderSettings, type IControlNet, type IControlNetGeneral, type IControlNetImage, type IControlNetPreprocess, type IControlNetWithUUID, type IEmbedding, type IEnhancedPrompt, type IError, type IErrorResponse, type IImage, type IImageToText, type IOutpaint, type IOutputFormat, type IOutputType, type IPromptEnhancer, type IProviderSettings, type IRefiner, type IRemoveImage, type IRemoveImageBackground, type IRequestAudio, type IRequestImage, type IRequestImageToText, type IRequestTextInference, type IRequestThreeD, type IRequestVideo, type ITextMessage, type ITextResponse, type ITextToImage, type IThreeDImage, type IThreeDOutputFormat, type IUpscaleGan, type IVideoOutputFormat, type IVideoToImage, type IipAdapter, type ListenerType, type MediaUUID, type ProviderSettings, type ReconnectingWebsocketProps, type RequireAtLeastOne, type RequireOnlyOne, Runware, type RunwareBaseType, RunwareClient, RunwareServer, SdkType, type TAcceleratorOptions, type TAddModel, type TAddModelBaseType, type TAddModelCheckPoint, type TAddModelControlNet, type TAddModelLora, type TImageMasking, type TImageMaskingResponse, type TImageUpload, type TImageUploadResponse, type TMediaStorage, type TMediaStorageResponse, type TModel, type TModelSearch, type TModelSearchResponse, type TPhotoMaker, type TPhotoMakerResponse, type TPromptWeighting, type TServerError, type TVectorize, type TVectorizeResponse, type UploadImageType };
package/dist/index.d.ts CHANGED
@@ -1,64 +1,3 @@
1
- /**
2
- * Runware SDK Telemetry Logger
3
- *
4
- * Beautiful colored console output for debugging SDK internals.
5
- * Only active when `enableLogging: true` is passed during instantiation.
6
- *
7
- * Usage:
8
- * const runware = new RunwareServer({ apiKey: "...", enableLogging: true });
9
- */
10
- declare enum LogLevel {
11
- CONNECTION = "CONNECTION",
12
- AUTH = "AUTH",
13
- HEARTBEAT = "HEARTBEAT",
14
- SEND = "SEND",
15
- RECEIVE = "RECEIVE",
16
- RETRY = "RETRY",
17
- REQUEST = "REQUEST",
18
- ERROR = "ERROR",
19
- WARN = "WARN",
20
- INFO = "INFO"
21
- }
22
- declare class RunwareLogger {
23
- private enabled;
24
- constructor(enabled?: boolean);
25
- private log;
26
- connecting(url: string): void;
27
- connected(sessionUUID: string): void;
28
- reconnecting(attempt: number): void;
29
- reconnectScheduled(delayMs: number): void;
30
- disconnected(reason?: string): void;
31
- connectionClosed(code?: number): void;
32
- connectionError(error?: any): void;
33
- ensureConnectionStart(): void;
34
- ensureConnectionSuccess(): void;
35
- ensureConnectionTimeout(): void;
36
- authenticating(hasSession: boolean): void;
37
- authenticated(sessionUUID: string): void;
38
- authError(error: any): void;
39
- heartbeatStarted(intervalMs: number): void;
40
- heartbeatPingSent(): void;
41
- heartbeatPongReceived(): void;
42
- heartbeatPongMissed(count: number, max: number): void;
43
- heartbeatStopped(): void;
44
- messageSent(taskType: string, taskUUID?: string): void;
45
- messageReceived(taskType?: string, taskUUID?: string): void;
46
- sendReconnecting(): void;
47
- sendFailed(error: string): void;
48
- requestStart(taskType: string, taskUUID: string): void;
49
- requestComplete(taskType: string, taskUUID: string, durationMs: number): void;
50
- requestTimeout(taskUUID: string, timeoutMs: number): void;
51
- requestError(taskUUID: string, error: any): void;
52
- retryAttempt(attempt: number, maxRetries: number, delayMs: number): void;
53
- retrySuccess(attempt: number): void;
54
- retryExhausted(maxRetries: number): void;
55
- retrySkippedApiError(code: string): void;
56
- info(message: string, data?: any): void;
57
- warn(message: string, data?: any): void;
58
- error(message: string, data?: any): void;
59
- }
60
- declare function createLogger(enabled: boolean): RunwareLogger;
61
-
62
1
  declare enum Environment {
63
2
  PRODUCTION = "PRODUCTION",
64
3
  DEVELOPMENT = "DEVELOPMENT",
@@ -95,8 +34,6 @@ type RunwareBaseType = {
95
34
  shouldReconnect?: boolean;
96
35
  globalMaxRetries?: number;
97
36
  timeoutDuration?: number;
98
- heartbeatInterval?: number;
99
- enableLogging?: boolean;
100
37
  };
101
38
  type IOutputType = "base64Data" | "dataURI" | "URL";
102
39
  type IOutputFormat = "JPG" | "PNG" | "WEBP";
@@ -502,7 +439,7 @@ interface IEnhancedPrompt extends IImageToText {
502
439
  }
503
440
  interface IUpscaleGan extends IAdditionalResponsePayload {
504
441
  inputImage?: File | string;
505
- upscaleFactor: number;
442
+ upscaleFactor?: number;
506
443
  outputType?: IOutputType;
507
444
  outputFormat?: IOutputFormat | "MP4" | "WEBM" | "MOV";
508
445
  includeCost?: boolean;
@@ -519,6 +456,7 @@ interface IUpscaleGan extends IAdditionalResponsePayload {
519
456
  retry?: number;
520
457
  skipResponse?: boolean;
521
458
  deliveryMethod?: string;
459
+ [key: string]: any;
522
460
  }
523
461
  type ReconnectingWebsocketProps = {
524
462
  addEventListener: (type: string, listener: EventListener, options: any) => void;
@@ -903,14 +841,8 @@ declare class RunwareBase {
903
841
  _shouldReconnect: boolean;
904
842
  _globalMaxRetries: number;
905
843
  _timeoutDuration: number;
906
- _heartbeatIntervalId: any;
907
- _pongTimeoutId: any;
908
- _heartbeatInterval: number;
909
- _missedPongCount: number;
910
- _maxMissedPongs: number;
911
844
  ensureConnectionUUID: string | null;
912
- _logger: RunwareLogger;
913
- constructor({ apiKey, url, shouldReconnect, globalMaxRetries, timeoutDuration, heartbeatInterval, enableLogging, }: RunwareBaseType);
845
+ constructor({ apiKey, url, shouldReconnect, globalMaxRetries, timeoutDuration, }: RunwareBaseType);
914
846
  private getUniqueUUID;
915
847
  /**
916
848
  * Shared polling logic for async results.
@@ -922,9 +854,6 @@ declare class RunwareBase {
922
854
  static initialize(props: RunwareBaseType): Promise<RunwareBase>;
923
855
  protected isWebsocketReadyState: () => boolean;
924
856
  protected isInvalidAPIKey: () => boolean;
925
- protected startHeartbeat(): void;
926
- protected stopHeartbeat(): void;
927
- protected handlePongMessage(data: any): boolean;
928
857
  protected addListener({ lis, groupKey, taskUUID, }: {
929
858
  lis: (v: any) => any;
930
859
  groupKey?: string;
@@ -933,7 +862,7 @@ declare class RunwareBase {
933
862
  destroy: () => void;
934
863
  };
935
864
  protected connect(): void;
936
- protected send: (msg: Object) => Promise<void>;
865
+ protected send: (msg: Object) => void;
937
866
  private destroy;
938
867
  private uploadImage;
939
868
  private listenToResponse;
@@ -971,7 +900,7 @@ declare class RunwareBase {
971
900
  * @since 1.2.0
972
901
  * @returns {Promise<IImage>} If called with `inputs.image` or `inputs.video`, returns an object with `mediaUUID` and `mediaURL`. If called with `inputImage`, returns an object with `imageUUID` and `imageURL` (not guaranteed).
973
902
  */
974
- upscaleGan: ({ inputImage, inputs, model, upscaleFactor, outputType, outputFormat, includeCost, outputQuality, customTaskUUID, taskUUID: _taskUUID, retry, includeGenerationTime, includePayload, skipResponse, deliveryMethod, }: IUpscaleGan) => Promise<IImage>;
903
+ upscaleGan: (payload: IUpscaleGan) => Promise<IImage>;
975
904
  upscale: (params: IUpscaleGan) => Promise<IImage>;
976
905
  enhancePrompt: ({ prompt, promptMaxLength, promptVersions, includeCost, customTaskUUID, taskUUID: _taskUUID, retry, includeGenerationTime, includePayload, }: IPromptEnhancer) => Promise<IEnhancedPrompt[]>;
977
906
  promptEnhance: (params: IPromptEnhancer) => Promise<IEnhancedPrompt[]>;
@@ -1009,14 +938,16 @@ declare class RunwareServer extends RunwareBase {
1009
938
  _instantiated: boolean;
1010
939
  _listeners: any[];
1011
940
  _reconnectingIntervalId: null | any;
1012
- private _connecting;
941
+ _pingTimeout: any;
942
+ _pongListener: any;
1013
943
  constructor(props: RunwareBaseType);
1014
944
  protected connect(): Promise<void>;
1015
- protected send: (msg: Object) => Promise<void>;
945
+ protected send: (msg: Object) => void;
1016
946
  protected handleClose(): void;
1017
947
  protected resetConnection: () => void;
948
+ protected heartBeat(): void;
1018
949
  }
1019
950
 
1020
951
  declare let Runware: typeof RunwareClient | typeof RunwareServer;
1021
952
 
1022
- export { EControlMode, EModelArchitecture, EModelConditioning, EModelFormat, EModelType, EOpenPosePreProcessor, EPhotoMakerEnum, EPreProcessor, EPreProcessorGroup, ETaskType, Environment, type GetWithPromiseAsyncCallBackType, type GetWithPromiseCallBackType, type IAddModelResponse, type IAdditionalResponsePayload, type IAsyncResults, type IAudio, type IAudioOutputFormat, type IBflProviderSettings, type IControlNet, type IControlNetGeneral, type IControlNetImage, type IControlNetPreprocess, type IControlNetWithUUID, type IEmbedding, type IEnhancedPrompt, type IError, type IErrorResponse, type IImage, type IImageToText, type IOutpaint, type IOutputFormat, type IOutputType, type IPromptEnhancer, type IProviderSettings, type IRefiner, type IRemoveImage, type IRemoveImageBackground, type IRequestAudio, type IRequestImage, type IRequestImageToText, type IRequestTextInference, type IRequestThreeD, type IRequestVideo, type ITextMessage, type ITextResponse, type ITextToImage, type IThreeDImage, type IThreeDOutputFormat, type IUpscaleGan, type IVideoOutputFormat, type IVideoToImage, type IipAdapter, type ListenerType, LogLevel, type MediaUUID, type ProviderSettings, type ReconnectingWebsocketProps, type RequireAtLeastOne, type RequireOnlyOne, Runware, type RunwareBaseType, RunwareClient, RunwareLogger, RunwareServer, SdkType, type TAcceleratorOptions, type TAddModel, type TAddModelBaseType, type TAddModelCheckPoint, type TAddModelControlNet, type TAddModelLora, type TImageMasking, type TImageMaskingResponse, type TImageUpload, type TImageUploadResponse, type TMediaStorage, type TMediaStorageResponse, type TModel, type TModelSearch, type TModelSearchResponse, type TPhotoMaker, type TPhotoMakerResponse, type TPromptWeighting, type TServerError, type TVectorize, type TVectorizeResponse, type UploadImageType, createLogger };
953
+ export { EControlMode, EModelArchitecture, EModelConditioning, EModelFormat, EModelType, EOpenPosePreProcessor, EPhotoMakerEnum, EPreProcessor, EPreProcessorGroup, ETaskType, Environment, type GetWithPromiseAsyncCallBackType, type GetWithPromiseCallBackType, type IAddModelResponse, type IAdditionalResponsePayload, type IAsyncResults, type IAudio, type IAudioOutputFormat, type IBflProviderSettings, type IControlNet, type IControlNetGeneral, type IControlNetImage, type IControlNetPreprocess, type IControlNetWithUUID, type IEmbedding, type IEnhancedPrompt, type IError, type IErrorResponse, type IImage, type IImageToText, type IOutpaint, type IOutputFormat, type IOutputType, type IPromptEnhancer, type IProviderSettings, type IRefiner, type IRemoveImage, type IRemoveImageBackground, type IRequestAudio, type IRequestImage, type IRequestImageToText, type IRequestTextInference, type IRequestThreeD, type IRequestVideo, type ITextMessage, type ITextResponse, type ITextToImage, type IThreeDImage, type IThreeDOutputFormat, type IUpscaleGan, type IVideoOutputFormat, type IVideoToImage, type IipAdapter, type ListenerType, type MediaUUID, type ProviderSettings, type ReconnectingWebsocketProps, type RequireAtLeastOne, type RequireOnlyOne, Runware, type RunwareBaseType, RunwareClient, RunwareServer, SdkType, type TAcceleratorOptions, type TAddModel, type TAddModelBaseType, type TAddModelCheckPoint, type TAddModelControlNet, type TAddModelLora, type TImageMasking, type TImageMaskingResponse, type TImageUpload, type TImageUploadResponse, type TMediaStorage, type TMediaStorageResponse, type TModel, type TModelSearch, type TModelSearchResponse, type TPhotoMaker, type TPhotoMakerResponse, type TPromptWeighting, type TServerError, type TVectorize, type TVectorizeResponse, type UploadImageType };
package/dist/index.js CHANGED
@@ -1,5 +1,2 @@
1
- var He=Object.create;var me=Object.defineProperty;var Qe=Object.getOwnPropertyDescriptor;var ze=Object.getOwnPropertyNames;var Ye=Object.getPrototypeOf,je=Object.prototype.hasOwnProperty;var Xe=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports);var Je=(a,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of ze(e))!je.call(a,o)&&o!==t&&me(a,o,{get:()=>e[o],enumerable:!(n=Qe(e,o))||n.enumerable});return a};var Ze=(a,e,t)=>(t=a!=null?He(Ye(a)):{},Je(e||!a||!a.__esModule?me(t,"default",{value:a,enumerable:!0}):t,a));var Oe=Xe((Ln,Le)=>{"use strict";var Ae=a=>a&&a.CLOSING===2,mt=()=>typeof WebSocket<"u"&&Ae(WebSocket),It=()=>({constructor:mt()?WebSocket:null,maxReconnectionDelay:1e4,minReconnectionDelay:1500,reconnectionDelayGrowFactor:1.3,connectionTimeout:4e3,maxRetries:1/0,debug:!1}),ht=(a,e,t)=>{Object.defineProperty(e,t,{get:()=>a[t],set:n=>{a[t]=n},enumerable:!0,configurable:!0})},we=a=>a.minReconnectionDelay+Math.random()*a.minReconnectionDelay,yt=(a,e)=>{let t=e*a.reconnectionDelayGrowFactor;return t>a.maxReconnectionDelay?a.maxReconnectionDelay:t},bt=["onopen","onclose","onmessage","onerror"],Ut=(a,e,t)=>{Object.keys(t).forEach(n=>{t[n].forEach(([o,s])=>{a.addEventListener(n,o,s)})}),e&&bt.forEach(n=>{a[n]=e[n]})},Ce=function(a,e,t={}){let n,o,s=0,r=0,i=!0,l={};if(!(this instanceof Ce))throw new TypeError("Failed to construct 'ReconnectingWebSocket': Please use the 'new' operator");let d=It();if(Object.keys(d).filter(p=>t.hasOwnProperty(p)).forEach(p=>d[p]=t[p]),!Ae(d.constructor))throw new TypeError("Invalid WebSocket constructor. Set `options.constructor`");let c=d.debug?(...p)=>console.log("RWS:",...p):()=>{},m=(p,I)=>setTimeout(()=>{let y=new Error(I);y.code=p,Array.isArray(l.error)&&l.error.forEach(([T])=>T(y)),n.onerror&&n.onerror(y)},0),g=()=>{if(c("close"),r++,c("retries count:",r),r>d.maxRetries){m("EHOSTDOWN","Too many failed connection attempts");return}s?s=yt(d,s):s=we(d),c("reconnectDelay:",s),i&&setTimeout(u,s)},u=()=>{c("connect");let p=n;n=new d.constructor(a,e),o=setTimeout(()=>{c("timeout"),n.close(),m("ETIMEDOUT","Connection timeout")},d.connectionTimeout),c("bypass properties");for(let I in n)["addEventListener","removeEventListener","close","send"].indexOf(I)<0&&ht(n,this,I);n.addEventListener("open",()=>{clearTimeout(o),c("open"),s=we(d),c("reconnectDelay:",s),r=0}),n.addEventListener("close",g),Ut(n,p,l)};c("init"),u(),this.close=(p=1e3,I="",{keepClosed:y=!1,fastClose:T=!0,delay:R=0}={})=>{if(R&&(s=R),i=!y,n.close(p,I),T){let h={code:p,reason:I,wasClean:!0};g(),Array.isArray(l.close)&&l.close.forEach(([k,b])=>{k(h),n.removeEventListener("close",k,b)}),n.onclose&&(n.onclose(h),n.onclose=null)}},this.send=p=>{n.send(p)},this.addEventListener=(p,I,y)=>{Array.isArray(l[p])?l[p].some(([T])=>T===I)||l[p].push([I,y]):l[p]=[[I,y]],n.addEventListener(p,I,y)},this.removeEventListener=(p,I,y)=>{Array.isArray(l[p])&&(l[p]=l[p].filter(([T])=>T!==I)),n.removeEventListener(p,I,y)}};Le.exports=Ce});var Ie=(n=>(n.PRODUCTION="PRODUCTION",n.DEVELOPMENT="DEVELOPMENT",n.TEST="TEST",n))(Ie||{}),X=(t=>(t.CLIENT="CLIENT",t.SERVER="SERVER",t))(X||{}),J=(h=>(h.IMAGE_INFERENCE="imageInference",h.IMAGE_UPLOAD="imageUpload",h.UPSCALE="upscale",h.REMOVE_BACKGROUND="removeBackground",h.VIDEO_INFERENCE="videoInference",h.CAPTION="caption",h.AUDIO_INFERENCE="audioInference",h.THREE_D_INFERENCE="3dInference",h.GET_RESPONSE="getResponse",h.PHOTO_MAKER="photoMaker",h.IMAGE_CONTROL_NET_PRE_PROCESS="imageControlNetPreProcess",h.IMAGE_MASKING="imageMasking",h.PROMPT_ENHANCE="promptEnhance",h.AUTHENTICATION="authentication",h.MODEL_UPLOAD="modelUpload",h.MODEL_SEARCH="modelSearch",h.MEDIA_STORAGE="mediaStorage",h.VECTORIZE="vectorize",h.TEXT_INFERENCE="textInference",h))(J||{}),he=(n=>(n.BALANCED="balanced",n.PROMPT="prompt",n.CONTROL_NET="controlnet",n))(he||{}),ye=(g=>(g.canny="canny",g.depth="depth",g.mlsd="mlsd",g.normalbae="normalbae",g.openpose="openpose",g.tile="tile",g.seg="seg",g.lineart="lineart",g.lineart_anime="lineart_anime",g.shuffle="shuffle",g.scribble="scribble",g.softedge="softedge",g))(ye||{}),be=(f=>(f.canny="canny",f.depth_leres="depth_leres",f.depth_midas="depth_midas",f.depth_zoe="depth_zoe",f.inpaint_global_harmonious="inpaint_global_harmonious",f.lineart_anime="lineart_anime",f.lineart_coarse="lineart_coarse",f.lineart_realistic="lineart_realistic",f.lineart_standard="lineart_standard",f.mlsd="mlsd",f.normal_bae="normal_bae",f.scribble_hed="scribble_hed",f.scribble_pidinet="scribble_pidinet",f.seg_ofade20k="seg_ofade20k",f.seg_ofcoco="seg_ofcoco",f.seg_ufade20k="seg_ufade20k",f.shuffle="shuffle",f.softedge_hed="softedge_hed",f.softedge_hedsafe="softedge_hedsafe",f.softedge_pidinet="softedge_pidinet",f.softedge_pidisafe="softedge_pidisafe",f.tile_gaussian="tile_gaussian",f.openpose="openpose",f.openpose_face="openpose_face",f.openpose_faceonly="openpose_faceonly",f.openpose_full="openpose_full",f.openpose_hand="openpose_hand",f))(be||{}),et=(s=>(s.openpose="openpose",s.openpose_face="openpose_face",s.openpose_faceonly="openpose_faceonly",s.openpose_full="openpose_full",s.openpose_hand="openpose_hand",s))(et||{}),tt=(t=>(t.safetensors="safetensors",t.pickletensor="pickletensor",t))(tt||{}),nt=(u=>(u.flux1d="flux1d",u.flux1s="flux1s",u.pony="pony",u.sdhyper="sdhyper",u.sd1x="sd1x",u.sd1xlcm="sd1xlcm",u.sd3="sd3",u.sdxl="sdxl",u.sdxllcm="sdxllcm",u.sdxldistilled="sdxldistilled",u.sdxlhyper="sdxlhyper",u.sdxllightning="sdxllightning",u.sdxlturbo="sdxlturbo",u))(nt||{}),st=(n=>(n.base="base",n.inpainting="inpainting",n.pix2pix="pix2pix",n))(st||{}),rt=(b=>(b.canny="canny",b.depth="depth",b.qrcode="qrcode",b.hed="hed",b.scrible="scrible",b.openpose="openpose",b.seg="segmentation",b.openmlsd="openmlsd",b.softedge="softedge",b.normal="normal bae",b.shuffle="shuffle",b.pix2pix="pix2pix",b.inpaint="inpaint",b.lineart="line art",b.sketch="sketch",b.inpaintdepth="inpaint depth",b.tile="tile",b.outfit="outfit",b.blur="blur",b.gray="gray",b.lowquality="low quality",b))(rt||{}),ot=(m=>(m.NoStyle="No style",m.Cinematic="Cinematic",m.DisneyCharacter="Disney Character",m.DigitalArt="Digital Art",m.Photographic="Photographic",m.FantasyArt="Fantasy art",m.Neonpunk="Neonpunk",m.Enhance="Enhance",m.ComicBook="Comic book",m.Lowpoly="Lowpoly",m.LineArt="Line art",m))(ot||{});import{v4 as it,validate as at}from"uuid";var B=6e4,K=1e3,Ue=100,Z={PRODUCTION:"wss://ws-api.runware.ai/v1",TEST:"ws://localhost:8080"},Te=(a,e)=>{if(a==null)return;let t=a.indexOf(e);t!==-1&&a.splice(t,1)},L=(a,{debugKey:e="debugKey",timeoutDuration:t=B,shouldThrowError:n=!0,pollingInterval:o=Ue})=>(t=t<K?K:t,new Promise((s,r)=>{let i=setTimeout(()=>{l&&clearInterval(l),clearTimeout(i),n?r(`Response could not be received from server for ${e}`):s(void 0)},t),l=setInterval(async()=>{try{a({resolve:s,reject:r,intervalId:l})&&(clearInterval(l),clearTimeout(i))}catch(d){clearInterval(l),clearTimeout(i),r(d)}},o)})),fe=a=>new Promise(e=>{let t=new FileReader;t.readAsDataURL(a),t.onload=function(){e(t.result)}}),D=()=>it(),Re=a=>at(a);var _e=({key:a,data:e,useZero:t=!0,shouldReturnString:n=!1})=>a.split(/\.|\[/).map(r=>r.replace(/\]$/,"")).reduce((r,i)=>{let l=t?0:void 0,d=r?.[i];if(!d)return l;if(Array.isArray(d)&&/^\d+$/.test(i)){let c=parseInt(i,10);return c>=0&&c<d.length?r[i]=d[c]:r[i]??l}else return r[i]??l},e||{})??{},ke=(a,e=1e3)=>new Promise(t=>setTimeout(t,a*e));var De=(a,e)=>a.filter(t=>t.key!==e.key);var _=({key:a,value:e})=>e||e===0||e===!1?{[a]:e}:{},lt=(a,e)=>Math.floor(Math.random()*(e-a+1))+a,ve=()=>lt(1,Number.MAX_SAFE_INTEGER),xe=(a,{debugKey:e="debugKey",timeoutDuration:t=B,shouldThrowError:n=!0,pollingInterval:o=Ue})=>(t=t<K?K:t,new Promise((s,r)=>{let i=setTimeout(()=>{l&&(clearInterval(l),n&&r(`Response could not be received from server for ${e}`)),clearTimeout(i)},t),l=setInterval(async()=>{try{await a({resolve:s,reject:r,intervalId:l})&&(clearInterval(l),clearTimeout(i))}catch(d){clearInterval(l),clearTimeout(i),r(d)}},o)}));var x=async(a,e={})=>{let{delayInSeconds:t=1,callback:n,logger:o}=e,s=e.maxRetries??1,r=s;if(s<=0)return await a();for(;s;)try{let i=await a();return s<r&&o?.retrySuccess(r-s+1),i}catch(i){if(i?.error)throw o?.retrySkippedApiError(i.error?.code||"unknown"),i;if(n?.(),s--,s>0)return o?.retryAttempt(r-s,r,t*1e3),await ke(t),await x(a,{...e,maxRetries:s});throw o?.retryExhausted(r),i}};var U={reset:"\x1B[0m",bold:"\x1B[1m",dim:"\x1B[2m",black:"\x1B[30m",white:"\x1B[37m",gray:"\x1B[90m",green:"\x1B[92m",yellow:"\x1B[93m",blue:"\x1B[94m",magenta:"\x1B[95m",cyan:"\x1B[96m",red:"\x1B[91m",bgGreen:"\x1B[42m",bgYellow:"\x1B[43m",bgBlue:"\x1B[44m",bgMagenta:"\x1B[45m",bgCyan:"\x1B[46m",bgRed:"\x1B[41m",bgWhite:"\x1B[47m"},Ee=(c=>(c.CONNECTION="CONNECTION",c.AUTH="AUTH",c.HEARTBEAT="HEARTBEAT",c.SEND="SEND",c.RECEIVE="RECEIVE",c.RETRY="RETRY",c.REQUEST="REQUEST",c.ERROR="ERROR",c.WARN="WARN",c.INFO="INFO",c))(Ee||{}),Se={CONNECTION:{bg:U.bgBlue,fg:U.blue,icon:"\u{1F50C}"},AUTH:{bg:U.bgGreen,fg:U.green,icon:"\u{1F511}"},HEARTBEAT:{bg:U.bgMagenta,fg:U.magenta,icon:"\u{1F493}"},SEND:{bg:U.bgCyan,fg:U.cyan,icon:"\u{1F4E4}"},RECEIVE:{bg:U.bgCyan,fg:U.cyan,icon:"\u{1F4E5}"},RETRY:{bg:U.bgYellow,fg:U.yellow,icon:"\u{1F504}"},REQUEST:{bg:U.bgBlue,fg:U.blue,icon:"\u{1F4E1}"},ERROR:{bg:U.bgRed,fg:U.red,icon:"\u274C"},WARN:{bg:U.bgYellow,fg:U.yellow,icon:"\u26A0\uFE0F"},INFO:{bg:U.bgWhite,fg:U.gray,icon:"\u2139\uFE0F"}},ut=`${U.bold}${U.magenta}[RUNWARE]${U.reset}`;function ct(){return`${U.dim}${new Date().toISOString()}${U.reset}`}function gt(a){return`${Se[a].bg}${U.bold}${U.black} ${a} ${U.reset}`}function dt(a){if(a==null)return"";if(typeof a=="string")return`${U.dim}${a}${U.reset}`;try{let e=JSON.stringify(a,null,2);return`${U.dim}${e}${U.reset}`}catch{return`${U.dim}[unserializable]${U.reset}`}}var P=class{constructor(e=!1){this.enabled=e}log(e,t,n){if(!this.enabled)return;let o=Se[e],s=["",`${ut} ${gt(e)} ${o.icon} ${o.fg}${U.bold}${t}${U.reset}`,` ${ct()}`];n!==void 0&&s.push(` ${dt(n)}`),s.push(""),e==="ERROR"?console.error(s.join(`
2
- `)):e==="WARN"?console.warn(s.join(`
3
- `)):console.log(s.join(`
4
- `))}connecting(e){this.log("CONNECTION","Connecting to WebSocket",{url:e})}connected(e){this.log("CONNECTION","WebSocket connection established",{connectionSessionUUID:e})}reconnecting(e){this.log("CONNECTION",`Reconnecting... attempt #${e}`)}reconnectScheduled(e){this.log("CONNECTION",`Reconnect scheduled in ${e}ms`)}disconnected(e){this.log("CONNECTION",`WebSocket disconnected${e?`: ${e}`:""}`)}connectionClosed(e){this.log("CONNECTION","WebSocket closed",{code:e})}connectionError(e){this.log("ERROR","WebSocket error",e)}ensureConnectionStart(){this.log("CONNECTION","Connection lost \u2014 waiting for reconnection...")}ensureConnectionSuccess(){this.log("CONNECTION","Reconnection successful")}ensureConnectionTimeout(){this.log("ERROR","Reconnection timed out after max retries")}authenticating(e){this.log("AUTH",e?"Re-authenticating with existing session":"Authenticating with API key")}authenticated(e){this.log("AUTH","Authentication successful",{connectionSessionUUID:e})}authError(e){this.log("ERROR","Authentication failed",e)}heartbeatStarted(e){this.log("HEARTBEAT",`Heartbeat started \u2014 ping every ${e/1e3}s, 3 missed pongs before close`)}heartbeatPingSent(){this.log("HEARTBEAT","Ping sent")}heartbeatPongReceived(){this.log("HEARTBEAT","Pong received \u2014 connection alive")}heartbeatPongMissed(e,t){this.log("WARN",`Pong missed (${e}/${t}) \u2014 ${e>=t?"connection dead, terminating":"will retry next cycle"}`)}heartbeatStopped(){this.log("HEARTBEAT","Heartbeat stopped")}messageSent(e,t){this.log("SEND","Message sent",{taskType:e,...t?{taskUUID:t}:{}})}messageReceived(e,t){this.log("RECEIVE","Message received",{...e?{taskType:e}:{},...t?{taskUUID:t}:{}})}sendReconnecting(){this.log("WARN","Send failed \u2014 WebSocket not ready, attempting reconnection before retry")}sendFailed(e){this.log("ERROR",`Send failed \u2014 ${e}`)}requestStart(e,t){this.log("REQUEST","Request started",{taskType:e,taskUUID:t})}requestComplete(e,t,n){this.log("REQUEST",`Request complete in ${n}ms`,{taskType:e,taskUUID:t})}requestTimeout(e,t){this.log("ERROR",`Request timed out after ${t}ms`,{taskUUID:e})}requestError(e,t){this.log("ERROR","Request failed",{taskUUID:e,error:t?.message||t?.error||t})}retryAttempt(e,t,n){this.log("RETRY",`Retry ${e}/${t} \u2014 waiting ${n}ms before next attempt`)}retrySuccess(e){this.log("RETRY",`Retry succeeded on attempt #${e}`)}retryExhausted(e){this.log("ERROR",`All ${e} retries exhausted \u2014 giving up`)}retrySkippedApiError(e){this.log("ERROR","API error \u2014 skipping retry (not retryable)",{code:e})}info(e,t){this.log("INFO",e,t)}warn(e,t){this.log("WARN",e,t)}error(e,t){this.log("ERROR",e,t)}},pt=new P(!1);function ee(a){return a?new P(!0):pt}var O=class{constructor({apiKey:e,url:t=Z.PRODUCTION,shouldReconnect:n=!0,globalMaxRetries:o=2,timeoutDuration:s=B,heartbeatInterval:r=45e3,enableLogging:i=!1}){this._listeners=[];this._globalMessages={};this._globalImages=[];this._globalErrors=[];this._heartbeatIntervalId=null;this._pongTimeoutId=null;this._missedPongCount=0;this._maxMissedPongs=3;this.ensureConnectionUUID=null;this.isWebsocketReadyState=()=>this._ws?.readyState===1;this.isInvalidAPIKey=()=>this._connectionError?.error?.code==="invalidApiKey";this.send=async e=>{if(!this.isWebsocketReadyState()){if(this._logger.sendReconnecting(),this._ws)try{typeof this._ws.terminate=="function"?this._ws.terminate():this._ws.close()}catch{}this._connectionSessionUUID=void 0,await this.ensureConnection()}let t=e?.taskType,n=e?.taskUUID;this._logger.messageSent(t,n),this._ws.send(JSON.stringify([e]))};this.uploadImage=async e=>{try{return await x(async()=>{let t=D();if(typeof e=="string"&&Re(e))return{imageURL:e,imageUUID:e,taskUUID:t,taskType:"imageUpload"};let n=typeof e=="string"?e:await fe(e);return{imageURL:n,imageUUID:n,taskUUID:t,taskType:"imageUpload"}})}catch(t){throw t}};this.controlNetPreProcess=async({inputImage:e,preProcessorType:t,height:n,width:o,outputType:s,outputFormat:r,highThresholdCanny:i,lowThresholdCanny:l,includeHandsAndFaceOpenPose:d,includeCost:c,outputQuality:m,customTaskUUID:g,taskUUID:u,retry:p,includeGenerationTime:I,includePayload:y})=>{let T=p||this._globalMaxRetries,R,h=Date.now();try{return await x(async()=>{await this.ensureConnection();let k=await this.uploadImage(e);if(!k?.imageUUID)return null;let b=u||g||D(),w={inputImage:k.imageUUID,taskType:"imageControlNetPreProcess",taskUUID:b,preProcessorType:t,..._({key:"height",value:n}),..._({key:"width",value:o}),..._({key:"outputType",value:s}),..._({key:"outputFormat",value:r}),..._({key:"includeCost",value:c}),..._({key:"highThresholdCanny",value:i}),..._({key:"lowThresholdCanny",value:l}),..._({key:"includeHandsAndFaceOpenPose",value:d}),...m?{outputQuality:m}:{}};await this.send({...w}),R=this.globalListener({taskUUID:b});let A=await L(({resolve:E,reject:$})=>{let S=this.getSingleMessage({taskUUID:b});if(S){if(S?.error)return $(S),!0;if(S)return E(S),!0}},{debugKey:"unprocessed-image",timeoutDuration:this._timeoutDuration});return R.destroy(),this.insertAdditionalResponse({response:A,payload:y?w:void 0,startTime:I?h:void 0}),A},{maxRetries:T,callback:()=>{R?.destroy()}})}catch(k){throw k}};this.controlNetPreprocess=async e=>this.controlNetPreProcess(e);this.requestImageToText=async({inputImage:e,inputs:t,includeCost:n,customTaskUUID:o,taskUUID:s,retry:r,includePayload:i,includeGenerationTime:l,deliveryMethod:d,skipResponse:c,model:m})=>{try{let g;e&&(g=await this.uploadImage(e));let p={taskUUID:s||o||D(),taskType:"caption",model:m,inputImage:g?.imageUUID,inputs:t,..._({key:"includeCost",value:n}),retry:r,includePayload:i,includeGenerationTime:l},I=await this.baseSingleRequest({payload:{...p,taskType:"caption"},debugKey:"caption"});if(c)return I;if(d==="async"){let y=I?.taskUUID;return(await this.pollForAsyncResults({taskUUID:y}))[0]}return I}catch(g){throw g}};this.caption=async e=>this.requestImageToText(e);this.removeImageBackground=async e=>{let{skipResponse:t,...n}=e;try{let o=n.deliveryMethod,s=await this.baseSingleRequest({payload:{...n,taskType:"removeBackground"},debugKey:"remove-background"});if(t)return s;if(o==="async"){let r=s?.taskUUID;return(await this.pollForAsyncResults({taskUUID:r}))[0]}return s}catch(o){throw o}};this.removeBackground=async e=>this.removeImageBackground(e);this.vectorize=async e=>this.baseSingleRequest({payload:{...e,taskType:"vectorize"},debugKey:"vectorize"});this.videoInference=async e=>{let{skipResponse:t,inputAudios:n,referenceVideos:o,...s}=e;try{let r=await this.baseSingleRequest({payload:{...s,...n?.length&&{inputAudios:n},...o?.length&&{referenceVideos:o},deliveryMethod:"async",taskType:"videoInference"},debugKey:"video-inference"});if(t)return r;let i=r?.taskUUID;return this.pollForAsyncResults({taskUUID:i,numberResults:e?.numberResults})}catch(r){throw r}};this.audioInference=async e=>{let{skipResponse:t,deliveryMethod:n="sync",...o}=e;try{let r=await(n==="sync"?this.baseSyncRequest:this.baseSingleRequest)({payload:{...o,numberResults:o.numberResults||1,taskType:"audioInference",deliveryMethod:n},groupKey:"REQUEST_AUDIO",debugKey:"audio-inference",skipResponse:t});if(t)return r;let i=r?.taskUUID;return n==="async"?this.pollForAsyncResults({taskUUID:i,numberResults:e?.numberResults}):r}catch(s){throw s}};this.threeDInference=async e=>{let{skipResponse:t,deliveryMethod:n="sync",...o}=e;try{let r=await(n==="sync"?this.baseSyncRequest:this.baseSingleRequest)({payload:{...o,numberResults:o.numberResults||1,taskType:"3dInference",deliveryMethod:n},groupKey:"REQUEST_IMAGES",debugKey:"three-d-inference",skipResponse:t});if(t)return r;let i=r?.taskUUID;return n==="async"?this.pollForAsyncResults({taskUUID:i,numberResults:e?.numberResults}):r}catch(s){throw s}};this.textInference=async e=>{let{skipResponse:t,deliveryMethod:n="sync",...o}=e;try{let r=await(n==="sync"?this.baseSyncRequest:this.baseSingleRequest)({payload:{...o,numberResults:o.numberResults||1,taskType:"textInference",deliveryMethod:n},groupKey:"REQUEST_TEXT",debugKey:"text-inference",skipResponse:t});if(t)return r;let i=r?.taskUUID;return n==="async"?this.pollForAsyncResults({taskUUID:i,numberResults:e?.numberResults}):r}catch(s){throw s}};this.getResponse=async e=>{let t=e.taskUUID;return this.baseSingleRequest({payload:{...e,customTaskUUID:t,taskType:"getResponse"},isMultiple:!0,debugKey:"async-results"})};this.upscaleGan=async({inputImage:e,inputs:t,model:n,upscaleFactor:o,outputType:s,outputFormat:r,includeCost:i,outputQuality:l,customTaskUUID:d,taskUUID:c,retry:m,includeGenerationTime:g,includePayload:u,skipResponse:p,deliveryMethod:I})=>{try{let y;e&&(y=await this.uploadImage(e));let R={taskUUID:c||d||D(),inputImage:y?.imageUUID,taskType:"upscale",inputs:t,model:n,upscaleFactor:o,..._({key:"includeCost",value:i}),...s?{outputType:s}:{},...l?{outputQuality:l}:{},...r?{outputFormat:r}:{},includePayload:u,includeGenerationTime:g,retry:m,deliveryMethod:I},h=await this.baseSingleRequest({payload:{...R,taskType:"upscale"},debugKey:"upscale"});if(p)return h;if(I==="async"){let k=h?.taskUUID;return(await this.pollForAsyncResults({taskUUID:k}))[0]}return h}catch(y){throw y}};this.upscale=async e=>this.upscaleGan(e);this.enhancePrompt=async({prompt:e,promptMaxLength:t=380,promptVersions:n=1,includeCost:o,customTaskUUID:s,taskUUID:r,retry:i,includeGenerationTime:l,includePayload:d})=>{let c=i||this._globalMaxRetries,m,g=Date.now();try{return await x(async()=>{await this.ensureConnection();let u=r||s||D(),p={prompt:e,taskUUID:u,promptMaxLength:t,promptVersions:n,..._({key:"includeCost",value:o}),taskType:"promptEnhance"};await this.send(p),m=this.globalListener({taskUUID:u});let I=await L(({resolve:y,reject:T})=>{let R=this._globalMessages[u];if(R?.error)return T(R),!0;if(R?.length>=n)return delete this._globalMessages[u],y(R),!0},{debugKey:"enhance-prompt",timeoutDuration:this._timeoutDuration});return m.destroy(),this.insertAdditionalResponse({response:I,payload:d?p:void 0,startTime:l?g:void 0}),I},{maxRetries:c,callback:()=>{m?.destroy()}})}catch(u){throw u}};this.promptEnhance=async e=>this.enhancePrompt(e);this.modelUpload=async e=>{let{onUploadStream:t,retry:n,customTaskUUID:o,taskUUID:s,...r}=e,i=n||this._globalMaxRetries,l;try{return await x(async()=>{await this.ensureConnection();let d=s||o||D();await this.send({...r,taskUUID:d,taskType:"modelUpload"});let c,m;l=this.listenToUpload({taskUUID:d,onUploadStream:(u,p)=>{t?.(u,p),u?.status==="ready"?c=u:p&&(m=p)}});let g=await L(({resolve:u,reject:p})=>{if(c)return u(c),!0;if(m)return p(m),!0},{shouldThrowError:!1,timeoutDuration:60*60*1e3});return l?.destroy(),g},{maxRetries:i,callback:()=>{l?.destroy()}})}catch(d){throw d}};this.photoMaker=async(e,t)=>{let{onPartialImages:n,retry:o,customTaskUUID:s,taskUUID:r,numberResults:i,includeGenerationTime:l,includePayload:d,...c}=e,m=o||this._globalMaxRetries,g,u=[],p=0,I=Date.now();try{return await x(async()=>{await this.ensureConnection(),p++;let y=this._globalImages.filter(b=>u.includes(b.taskUUID)),T=r||s||D();u.push(T);let R=i-y.length,h={...c,...c.seed?{seed:c.seed}:{seed:ve()},...t??{},taskUUID:T,taskType:"photoMaker",numberResults:i};await this.send({...h,numberResults:R}),g=this.listenToResponse({onPartialImages:n,taskUUID:T,groupKey:"REQUEST_IMAGES",requestPayload:d?h:void 0,startTime:l?I:void 0});let k=await this.getResponseWithSimilarTaskUUID({taskUUID:u,numberResults:i,lis:g});return g.destroy(),k},{maxRetries:m,callback:()=>{g?.destroy()}})}catch(y){if(y.taskUUID)throw y;if(p>=m)return this.handleIncompleteImages({taskUUIDs:u,error:y})}};this.modelSearch=async e=>this.baseSingleRequest({payload:{...e,taskType:"modelSearch"},debugKey:"model-search"});this.imageMasking=async e=>this.baseSingleRequest({payload:{...e,taskType:"imageMasking"},debugKey:"image-masking"});this.imageUpload=async e=>this.baseSingleRequest({payload:{...e,taskType:"imageUpload"},debugKey:"image-upload"});this.mediaStorage=async e=>this.baseSingleRequest({payload:{...e,operation:e.operation||"upload",taskType:"mediaStorage"},debugKey:"media-storage"});this.baseSingleRequest=async({payload:e,debugKey:t,isMultiple:n})=>{let{retry:o,customTaskUUID:s,taskUUID:r,includePayload:i,includeGenerationTime:l,...d}=e,c=o||this._globalMaxRetries,m,g=Date.now();try{return await x(async()=>{await this.ensureConnection();let u=r||s||D(),p={...d,taskUUID:u};this._logger.requestStart(t,u),await this.send(p),m=this.globalListener({taskUUID:u});let I=await L(({resolve:y,reject:T})=>{let R=n?this.getMultipleMessages({taskUUID:u}):this.getSingleMessage({taskUUID:u});if(R){if(R?.error)return this._logger.requestError(u,R),T(R),!0;if(R)return delete this._globalMessages[u],this._logger.requestComplete(t,u,Date.now()-g),y(R),!0}},{debugKey:t,timeoutDuration:this._timeoutDuration});return this.insertAdditionalResponse({response:I,payload:i?p:void 0,startTime:l?g:void 0}),m.destroy(),I},{maxRetries:c,callback:()=>{m?.destroy()},logger:this._logger})}catch(u){throw u}};this.baseSyncRequest=async({payload:e,groupKey:t,skipResponse:n=!1})=>{let{retry:o,customTaskUUID:s,includePayload:r,numberResults:i=1,onPartialResponse:l,includeGenerationTime:d,...c}=e,m=o||this._globalMaxRetries,g,u=[],p=0,I=Date.now();try{return await x(async()=>{await this.ensureConnection(),p++;let y=this._globalImages.filter(b=>u.includes(b.taskUUID)),T=s||D();u.push(T);let R=i-y.length,h={...c,taskUUID:T,numberResults:R};if(this._logger.requestStart(c.taskType||t,T),await this.send(h),n)return this._logger.info("Async mode (skipResponse) \u2014 waiting for server acknowledgement",{taskUUID:T}),new Promise((b,w)=>{let A=this.addListener({taskUUID:T,groupKey:t,lis:E=>{A.destroy(),E.error?(this._logger.requestError(T,E.error),w(E.error)):(this._logger.requestComplete(c.taskType||t,T,Date.now()-I),b(E[T]))}})});g=this.listenToResponse({onPartialImages:l,taskUUID:T,groupKey:t,requestPayload:r?h:void 0,startTime:d?I:void 0});let k=await this.getResponseWithSimilarTaskUUID({taskUUID:u,numberResults:i,lis:g});return this._logger.requestComplete(c.taskType||t,T,Date.now()-I),g.destroy(),k},{maxRetries:m,callback:()=>{g?.destroy()},logger:this._logger})}catch(y){throw y}};this.getSingleMessage=({taskUUID:e})=>{let t=this._globalMessages[e]?.[0],n=this._globalMessages[e];return!t&&!n?null:n?.error?n:t};this.getMultipleMessages=({taskUUID:e})=>{let t=this._globalMessages[e]?.[0],n=this._globalMessages[e];return!t&&!n?null:n};this.insertAdditionalResponse=({response:e,payload:t,startTime:n})=>{if(!t&&!n)return;let o=e;o.additionalResponse={},t&&(e.additionalResponse.payload=t),n&&(e.additionalResponse.generationTime=Date.now()-n)};this.disconnect=async()=>{this._logger.disconnected("user initiated"),this._shouldReconnect=!1,this._connectionSessionUUID=void 0,this.stopHeartbeat(),this._ws?.terminate?.(),this._ws?.close?.()};this.connected=()=>this.isWebsocketReadyState()&&!!this._connectionSessionUUID;this._apiKey=e,this._url=t,this._sdkType="CLIENT",this._shouldReconnect=n,this._globalMaxRetries=o,this._timeoutDuration=s,this._heartbeatInterval=Math.max(1e4,Math.min(12e4,r)),this._logger=ee(i)}getUniqueUUID(e){return e.mediaUUID||e.audioUUID||e.imageUUID||e.videoUUID||e.outputs?.files?.map(t=>t.uuid).join("-")||e.text}async pollForAsyncResults({taskUUID:e,numberResults:t=1}){let n=new Map;return await xe(async({resolve:o,reject:s})=>{try{let r=await this.getResponse({taskUUID:e});for(let l of r||[])if(l.status==="success"){let d=this.getUniqueUUID(l);d&&n.set(d,l)}return n.size===t?(o(Array.from(n.values())),!0):!1}catch(r){return s(r),!0}},{debugKey:"async-response",pollingInterval:2*1e3,timeoutDuration:10*60*1e3}),Array.from(n.values())}static async initialize(e){try{let t=new this(e);return await t.ensureConnection(),t}catch(t){throw t}}startHeartbeat(){this.stopHeartbeat(),this._logger.heartbeatStarted(this._heartbeatInterval),this._heartbeatIntervalId=setInterval(()=>{if(!this.isWebsocketReadyState()){this.stopHeartbeat();return}try{this._ws.send(JSON.stringify([{taskType:"ping",ping:!0}])),this._logger.heartbeatPingSent()}catch{this.stopHeartbeat();return}this._pongTimeoutId&&(clearTimeout(this._pongTimeoutId),this._pongTimeoutId=null),this._pongTimeoutId=setTimeout(()=>{this._missedPongCount++,this._logger.heartbeatPongMissed(this._missedPongCount,this._maxMissedPongs),this._missedPongCount>=this._maxMissedPongs&&this._ws&&(typeof this._ws.terminate=="function"?this._ws.terminate():this._ws.close())},1e4)},this._heartbeatInterval)}stopHeartbeat(){this._heartbeatIntervalId&&(clearInterval(this._heartbeatIntervalId),this._heartbeatIntervalId=null,this._logger.heartbeatStopped()),this._pongTimeoutId&&(clearTimeout(this._pongTimeoutId),this._pongTimeoutId=null),this._missedPongCount=0}handlePongMessage(e){let t=Array.isArray(e?.data)?e.data:[];for(let n of t)if(n?.taskType==="ping"&&n?.pong===!0)return this._missedPongCount=0,this._pongTimeoutId&&(clearTimeout(this._pongTimeoutId),this._pongTimeoutId=null),this._logger.heartbeatPongReceived(),!0;return!1}addListener({lis:e,groupKey:t,taskUUID:n}){let o=i=>{let l=Array.isArray(i?.data)?i.data:[i.data],d=i?.[0]?.errors?i?.[0]?.errors:Array.isArray(i?.errors)?i.errors:[i.errors],c=l.filter(g=>(g?.taskUUID||g?.taskType)===n);if(d.filter(g=>(g?.taskUUID||g?.taskType)===n).length){e({error:{...d[0]??{}}});return}if(c.length){e({[n]:l});return}},s={key:n||D(),listener:o,groupKey:t};return this._listeners.push(s),{destroy:()=>{this._listeners=De(this._listeners,s)}}}connect(){this._logger.connecting(this._url||"unknown"),this._ws.onopen=async e=>{this._logger.authenticating(!!this._connectionSessionUUID);try{this._connectionSessionUUID?await this.send({taskType:"authentication",apiKey:this._apiKey,connectionSessionUUID:this._connectionSessionUUID}):await this.send({apiKey:this._apiKey,taskType:"authentication"})}catch(n){this._logger.error("Failed to send auth message",n);return}let t=this.addListener({taskUUID:"authentication",lis:n=>{if(n?.error){this._connectionError=n,this._logger.authError(n),t?.destroy?.();return}this._connectionSessionUUID=n?.authentication?.[0]?.connectionSessionUUID,this._connectionError=void 0,this._logger.authenticated(this._connectionSessionUUID||""),t?.destroy?.(),this.startHeartbeat()}})},this._ws.onmessage=e=>{let t;try{t=JSON.parse(e.data)}catch(n){this._logger.error("Failed to parse WebSocket message",n);return}if(!this.handlePongMessage(t)){for(let n of this._listeners)if(n?.listener?.(t))return}},this._ws.onclose=e=>{this._logger.connectionClosed(e?.code),this._connectionSessionUUID=void 0,this.stopHeartbeat(),this.isInvalidAPIKey()},this._ws.onerror=e=>{this._logger.connectionError(e?.message||e)}}destroy(e){Te(this._listeners,e)}listenToResponse({onPartialImages:e,taskUUID:t,groupKey:n,requestPayload:o,startTime:s}){return this.addListener({taskUUID:t,lis:r=>{let i=r?.[t]?.filter(l=>l.taskUUID===t);r.error?(e?.(i,r?.error&&r),this._globalErrors.push(r)):(i=i.map(l=>(this.insertAdditionalResponse({response:l,payload:o||void 0,startTime:s||void 0}),{...l})),e?.(i,r?.error&&r),this._sdkType==="CLIENT"?this._globalImages=[...this._globalImages,...(r?.[t]??[]).map(l=>(this.insertAdditionalResponse({response:l,payload:o||void 0,startTime:s||void 0}),{...l}))]:this._globalImages=[...this._globalImages,...i])},groupKey:n})}listenToUpload({onUploadStream:e,taskUUID:t}){return this.addListener({taskUUID:t,lis:n=>{let o=n?.error,s=n?.[t]?.[0],r=s?.taskUUID===t?s:null;(r||o)&&e?.(r||void 0,o)}})}globalListener({taskUUID:e}){return this.addListener({taskUUID:e,lis:t=>{if(t.error){this._globalMessages[e]=t;return}let n=_e({key:e,data:t,useZero:!1});Array.isArray(n)?n.forEach(o=>{this._globalMessages[o.taskUUID]=[...this._globalMessages[o.taskUUID]??[],o]}):this._globalMessages[n.taskUUID]=n}})}async requestImages({outputType:e,outputFormat:t,uploadEndpoint:n,checkNSFW:o,positivePrompt:s,negativePrompt:r,seedImage:i,maskImage:l,strength:d,height:c,width:m,model:g,steps:u,scheduler:p,seed:I,CFGScale:y,clipSkip:T,usePromptWeighting:R,promptWeighting:h,numberResults:k=1,onPartialImages:b,includeCost:w,customTaskUUID:A,taskUUID:E,retry:$,refiner:S,maskMargin:f,outputQuality:te,controlNet:H,lora:ne,embeddings:se,ipAdapters:re,providerSettings:oe,outpaint:ie,acceleratorOptions:ae,advancedFeatures:le,referenceImages:ue,includeGenerationTime:Pe,includePayload:Fe,...ce},We){let N,ge,F=[],de=0,pe=$||this._globalMaxRetries;try{await this.ensureConnection();let C=null,Q=null,z=[];if(i){let v=await this.uploadImage(i);if(!v)return[];C=v.imageUUID}if(l){let v=await this.uploadImage(l);if(!v)return[];Q=v.imageUUID}if(H?.length)for(let v=0;v<H.length;v++){let M=H[v],{endStep:Y,startStep:W,weight:j,guideImage:q,controlMode:Ke,startStepPercentage:Be,endStepPercentage:Ve,model:Ge}=M,$e=q?await this.uploadImage(q):null;z.push({guideImage:$e?.imageUUID,model:Ge,endStep:Y,startStep:W,weight:j,..._({key:"startStepPercentage",value:Be}),..._({key:"endStepPercentage",value:Ve}),controlMode:Ke||"controlnet"})}ge={taskType:"imageInference",model:g,positivePrompt:s,...r?{negativePrompt:r}:{},...c?{height:c}:{},...m?{width:m}:{},numberResults:k,...e?{outputType:e}:{},...t?{outputFormat:t}:{},...n?{uploadEndpoint:n}:{},..._({key:"checkNSFW",value:o}),..._({key:"strength",value:d}),..._({key:"CFGScale",value:y}),..._({key:"clipSkip",value:T}),..._({key:"maskMargin",value:f}),..._({key:"usePromptWeighting",value:R}),..._({key:"steps",value:u}),...h?{promptWeighting:h}:{},...I?{seed:I}:{},...p?{scheduler:p}:{},...S?{refiner:S}:{},...ie?{outpaint:ie}:{},..._({key:"includeCost",value:w}),...C?{seedImage:C}:{},...Q?{maskImage:Q}:{},...te?{outputQuality:te}:{},...z.length?{controlNet:z}:{},...ne?.length?{lora:ne}:{},...se?.length?{embeddings:se}:{},...re?.length?{ipAdapters:re}:{},...oe?{providerSettings:oe}:{},...ae?{acceleratorOptions:ae}:{},...le?{advancedFeatures:le}:{},...ue?.length?{referenceImages:ue}:{},...ce,...We??{}};let qe=Date.now();return await x(async()=>{de++,N?.destroy();let v=this._globalImages.filter(q=>F.includes(q.taskUUID)),M=E||A||D();F.push(M);let Y=k-v.length,W={...ge,taskUUID:M,numberResults:Y};await this.send(W),N=this.listenToResponse({onPartialImages:b,taskUUID:M,groupKey:"REQUEST_IMAGES",requestPayload:Fe?W:void 0,startTime:Pe?qe:void 0});let j=await this.getResponseWithSimilarTaskUUID({taskUUID:F,numberResults:k,lis:N,deliveryMethod:ce.deliveryMethod});return N.destroy(),j},{maxRetries:pe,callback:()=>{N?.destroy()}})}catch(C){if(de>=pe)return this.handleIncompleteImages({taskUUIDs:F,error:C});throw C}}async imageInference(e,t){return this.requestImages(e,t)}async ensureConnection(){if(this.connected()||this._url===Z.TEST)return;this._logger.ensureConnectionStart();let t=2e3,n=200;try{if(this.isInvalidAPIKey())throw this._connectionError;return new Promise((o,s)=>{let r=0,i=30,l=D(),d,c,m=()=>{this.ensureConnectionUUID=null,clearInterval(d),clearInterval(c)};this._sdkType==="SERVER"&&(d=setInterval(async()=>{try{let g=this.connected(),u=!1;(!this.ensureConnectionUUID||l===this.ensureConnectionUUID)&&(this.ensureConnectionUUID||(this.ensureConnectionUUID=l),u=!0);let p=r%10===0&&u;g?(m(),this._logger.ensureConnectionSuccess(),o(!0)):r>=i?(m(),this._logger.ensureConnectionTimeout(),s(new Error("Retry timed out"))):(p&&(this._logger.reconnecting(r+1),this.connect()),r++)}catch(g){m(),s(g)}},t)),c=setInterval(async()=>{if(this.connected()){m(),this._logger.ensureConnectionSuccess(),o(!0);return}if(this.isInvalidAPIKey()){m(),this._logger.error("Connection failed \u2014 invalid API key"),s(this._connectionError);return}},n)})}catch{throw this.ensureConnectionUUID=null,this._connectionError=void 0,this._connectionError??"Could not connect to server. Ensure your API key is correct"}}async getResponseWithSimilarTaskUUID({taskUUID:e,numberResults:t,shouldThrowError:n,lis:o,deliveryMethod:s}){return await L(({resolve:r,reject:i,intervalId:l})=>{let d=Array.isArray(e)?e:[e],c=this._globalImages.filter(u=>d.includes(u.taskUUID)),m=s==="async"&&c.length>0,g=this._globalErrors.filter(u=>d.includes(u.error.taskUUID));if(g.length>0){let u=g[0];return this._globalErrors=this._globalErrors.filter(p=>!d.includes(p.error.taskUUID)),clearInterval(l),i?.(u),!0}else if(c.length>=t||m)return clearInterval(l),this._globalImages=this._globalImages.filter(u=>!d.includes(u.taskUUID)),r([...c].slice(0,t)),!0},{debugKey:"getting images",shouldThrowError:n,timeoutDuration:this._timeoutDuration})}handleIncompleteImages({taskUUIDs:e,error:t}){let n=this._globalImages.filter(o=>e.includes(o.taskUUID));if(n.length>1)return this._globalImages=this._globalImages.filter(o=>!e.includes(o.taskUUID)),n;throw t}};var Ne=Ze(Oe(),1),V=class extends O{constructor(e){let{shouldReconnect:t,...n}=e;super(n),this._ws=new Ne.default(this._url),this.connect()}};import Tt from"ws";var G=class extends O{constructor(t){super(t);this._instantiated=!1;this._listeners=[];this._reconnectingIntervalId=null;this._connecting=!1;this.send=async t=>{if(!this.isWebsocketReadyState()){if(this._logger.sendReconnecting(),this._ws)try{typeof this._ws.terminate=="function"?this._ws.terminate():this._ws.close()}catch{}this._connectionSessionUUID=void 0,await this.ensureConnection()}let n=t?.taskType,o=t?.taskUUID;this._logger.messageSent(n,o),this._ws.send(JSON.stringify([t]))};this.resetConnection=()=>{this.stopHeartbeat(),this._ws&&(this._listeners.forEach(t=>{t?.destroy?.()}),this._ws.removeAllListeners(),this._ws.readyState===1&&(this._ws.terminate(),this._ws.close()),this._ws=null,this._listeners=[])};this._sdkType="SERVER",this.connect()}async connect(){if(this._url&&!this._connecting){this._connecting=!0,this.resetConnection(),this._logger.connecting(this._url);try{this._ws=new Tt(this._url,{perMessageDeflate:!1})}catch(t){this._connecting=!1,this._logger.connectionError(t);return}this._ws.on("error",t=>{this._connecting=!1,this._logger.connectionError(t?.message||t)}),this._ws.on("close",()=>{this.handleClose()}),this._ws.on("open",async()=>{this._reconnectingIntervalId&&clearInterval(this._reconnectingIntervalId),this._logger.authenticating(!!this._connectionSessionUUID);try{this._connectionSessionUUID&&this.isWebsocketReadyState()?await this.send({taskType:"authentication",apiKey:this._apiKey,connectionSessionUUID:this._connectionSessionUUID}):this.isWebsocketReadyState()&&await this.send({apiKey:this._apiKey,taskType:"authentication"})}catch(n){this._connecting=!1,this._logger.error("Failed to send auth message",n);return}let t=this.addListener({taskUUID:"authentication",lis:n=>{if(this._connecting=!1,n?.error){this._connectionError=n,this._logger.authError(n),t?.destroy?.();return}this._connectionSessionUUID=n?.authentication?.[0]?.connectionSessionUUID,this._connectionError=void 0,this._logger.authenticated(this._connectionSessionUUID||""),t?.destroy?.(),this.startHeartbeat()}})}),this._ws.on("message",(t,n)=>{let o=n?t:t?.toString();if(!o)return;let s;try{s=JSON.parse(o)}catch(r){this._logger.error("Failed to parse WebSocket message",r);return}this.handlePongMessage(s)||this._listeners.forEach(r=>{r.listener(s)})})}}handleClose(){this._connecting=!1,this._logger.connectionClosed(),this._connectionSessionUUID=void 0,this.stopHeartbeat(),!this.isInvalidAPIKey()&&(this._reconnectingIntervalId&&clearInterval(this._reconnectingIntervalId),this._shouldReconnect&&(this._logger.reconnectScheduled(1e3),setTimeout(()=>this.connect(),1e3)))}};var Me;typeof window>"u"?Me=G:Me=V;export{he as EControlMode,nt as EModelArchitecture,rt as EModelConditioning,tt as EModelFormat,st as EModelType,et as EOpenPosePreProcessor,ot as EPhotoMakerEnum,be as EPreProcessor,ye as EPreProcessorGroup,J as ETaskType,Ie as Environment,Ee as LogLevel,Me as Runware,V as RunwareClient,P as RunwareLogger,G as RunwareServer,X as SdkType,ee as createLogger};
1
+ var We=Object.create;var de=Object.defineProperty;var Ve=Object.getOwnPropertyDescriptor;var Be=Object.getOwnPropertyNames;var Ge=Object.getPrototypeOf,He=Object.prototype.hasOwnProperty;var Qe=(u,e)=>()=>(e||u((e={exports:{}}).exports,e),e.exports);var ze=(u,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Be(e))!He.call(u,s)&&s!==t&&de(u,s,{get:()=>e[s],enumerable:!(n=Ve(e,s))||n.enumerable});return u};var je=(u,e,t)=>(t=u!=null?We(Ge(u)):{},ze(e||!u||!u.__esModule?de(t,"default",{value:u,enumerable:!0}):t,u));var we=Qe((bn,Se)=>{"use strict";var xe=u=>u&&u.CLOSING===2,rt=()=>typeof WebSocket<"u"&&xe(WebSocket),at=()=>({constructor:rt()?WebSocket:null,maxReconnectionDelay:1e4,minReconnectionDelay:1500,reconnectionDelayGrowFactor:1.3,connectionTimeout:4e3,maxRetries:1/0,debug:!1}),ot=(u,e,t)=>{Object.defineProperty(e,t,{get:()=>u[t],set:n=>{u[t]=n},enumerable:!0,configurable:!0})},_e=u=>u.minReconnectionDelay+Math.random()*u.minReconnectionDelay,it=(u,e)=>{let t=e*u.reconnectionDelayGrowFactor;return t>u.maxReconnectionDelay?u.maxReconnectionDelay:t},lt=["onopen","onclose","onmessage","onerror"],ut=(u,e,t)=>{Object.keys(t).forEach(n=>{t[n].forEach(([s,a])=>{u.addEventListener(n,s,a)})}),e&&lt.forEach(n=>{u[n]=e[n]})},ve=function(u,e,t={}){let n,s,a=0,r=0,o=!0,i={};if(!(this instanceof ve))throw new TypeError("Failed to construct 'ReconnectingWebSocket': Please use the 'new' operator");let d=at();if(Object.keys(d).filter(c=>t.hasOwnProperty(c)).forEach(c=>d[c]=t[c]),!xe(d.constructor))throw new TypeError("Invalid WebSocket constructor. Set `options.constructor`");let m=d.debug?(...c)=>console.log("RWS:",...c):()=>{},g=(c,y)=>setTimeout(()=>{let U=new Error(y);U.code=c,Array.isArray(i.error)&&i.error.forEach(([b])=>b(U)),n.onerror&&n.onerror(U)},0),p=()=>{if(m("close"),r++,m("retries count:",r),r>d.maxRetries){g("EHOSTDOWN","Too many failed connection attempts");return}a?a=it(d,a):a=_e(d),m("reconnectDelay:",a),o&&setTimeout(l,a)},l=()=>{m("connect");let c=n;n=new d.constructor(u,e),s=setTimeout(()=>{m("timeout"),n.close(),g("ETIMEDOUT","Connection timeout")},d.connectionTimeout),m("bypass properties");for(let y in n)["addEventListener","removeEventListener","close","send"].indexOf(y)<0&&ot(n,this,y);n.addEventListener("open",()=>{clearTimeout(s),m("open"),a=_e(d),m("reconnectDelay:",a),r=0}),n.addEventListener("close",p),ut(n,c,i)};m("init"),l(),this.close=(c=1e3,y="",{keepClosed:U=!1,fastClose:b=!0,delay:f=0}={})=>{if(f&&(a=f),o=!U,n.close(c,y),b){let h={code:c,reason:y,wasClean:!0};p(),Array.isArray(i.close)&&i.close.forEach(([k,I])=>{k(h),n.removeEventListener("close",k,I)}),n.onclose&&(n.onclose(h),n.onclose=null)}},this.send=c=>{n.send(c)},this.addEventListener=(c,y,U)=>{Array.isArray(i[c])?i[c].some(([b])=>b===y)||i[c].push([y,U]):i[c]=[[y,U]],n.addEventListener(c,y,U)},this.removeEventListener=(c,y,U)=>{Array.isArray(i[c])&&(i[c]=i[c].filter(([b])=>b!==y)),n.removeEventListener(c,y,U)}};Se.exports=ve});var pe=(n=>(n.PRODUCTION="PRODUCTION",n.DEVELOPMENT="DEVELOPMENT",n.TEST="TEST",n))(pe||{}),X=(t=>(t.CLIENT="CLIENT",t.SERVER="SERVER",t))(X||{}),J=(h=>(h.IMAGE_INFERENCE="imageInference",h.IMAGE_UPLOAD="imageUpload",h.UPSCALE="upscale",h.REMOVE_BACKGROUND="removeBackground",h.VIDEO_INFERENCE="videoInference",h.CAPTION="caption",h.AUDIO_INFERENCE="audioInference",h.THREE_D_INFERENCE="3dInference",h.GET_RESPONSE="getResponse",h.PHOTO_MAKER="photoMaker",h.IMAGE_CONTROL_NET_PRE_PROCESS="imageControlNetPreProcess",h.IMAGE_MASKING="imageMasking",h.PROMPT_ENHANCE="promptEnhance",h.AUTHENTICATION="authentication",h.MODEL_UPLOAD="modelUpload",h.MODEL_SEARCH="modelSearch",h.MEDIA_STORAGE="mediaStorage",h.VECTORIZE="vectorize",h.TEXT_INFERENCE="textInference",h))(J||{}),ge=(n=>(n.BALANCED="balanced",n.PROMPT="prompt",n.CONTROL_NET="controlnet",n))(ge||{}),me=(p=>(p.canny="canny",p.depth="depth",p.mlsd="mlsd",p.normalbae="normalbae",p.openpose="openpose",p.tile="tile",p.seg="seg",p.lineart="lineart",p.lineart_anime="lineart_anime",p.shuffle="shuffle",p.scribble="scribble",p.softedge="softedge",p))(me||{}),Ie=(T=>(T.canny="canny",T.depth_leres="depth_leres",T.depth_midas="depth_midas",T.depth_zoe="depth_zoe",T.inpaint_global_harmonious="inpaint_global_harmonious",T.lineart_anime="lineart_anime",T.lineart_coarse="lineart_coarse",T.lineart_realistic="lineart_realistic",T.lineart_standard="lineart_standard",T.mlsd="mlsd",T.normal_bae="normal_bae",T.scribble_hed="scribble_hed",T.scribble_pidinet="scribble_pidinet",T.seg_ofade20k="seg_ofade20k",T.seg_ofcoco="seg_ofcoco",T.seg_ufade20k="seg_ufade20k",T.shuffle="shuffle",T.softedge_hed="softedge_hed",T.softedge_hedsafe="softedge_hedsafe",T.softedge_pidinet="softedge_pidinet",T.softedge_pidisafe="softedge_pidisafe",T.tile_gaussian="tile_gaussian",T.openpose="openpose",T.openpose_face="openpose_face",T.openpose_faceonly="openpose_faceonly",T.openpose_full="openpose_full",T.openpose_hand="openpose_hand",T))(Ie||{}),Xe=(a=>(a.openpose="openpose",a.openpose_face="openpose_face",a.openpose_faceonly="openpose_faceonly",a.openpose_full="openpose_full",a.openpose_hand="openpose_hand",a))(Xe||{}),Je=(t=>(t.safetensors="safetensors",t.pickletensor="pickletensor",t))(Je||{}),Ze=(l=>(l.flux1d="flux1d",l.flux1s="flux1s",l.pony="pony",l.sdhyper="sdhyper",l.sd1x="sd1x",l.sd1xlcm="sd1xlcm",l.sd3="sd3",l.sdxl="sdxl",l.sdxllcm="sdxllcm",l.sdxldistilled="sdxldistilled",l.sdxlhyper="sdxlhyper",l.sdxllightning="sdxllightning",l.sdxlturbo="sdxlturbo",l))(Ze||{}),Ye=(n=>(n.base="base",n.inpainting="inpainting",n.pix2pix="pix2pix",n))(Ye||{}),$e=(I=>(I.canny="canny",I.depth="depth",I.qrcode="qrcode",I.hed="hed",I.scrible="scrible",I.openpose="openpose",I.seg="segmentation",I.openmlsd="openmlsd",I.softedge="softedge",I.normal="normal bae",I.shuffle="shuffle",I.pix2pix="pix2pix",I.inpaint="inpaint",I.lineart="line art",I.sketch="sketch",I.inpaintdepth="inpaint depth",I.tile="tile",I.outfit="outfit",I.blur="blur",I.gray="gray",I.lowquality="low quality",I))($e||{}),et=(g=>(g.NoStyle="No style",g.Cinematic="Cinematic",g.DisneyCharacter="Disney Character",g.DigitalArt="Digital Art",g.Photographic="Photographic",g.FantasyArt="Fantasy art",g.Neonpunk="Neonpunk",g.Enhance="Enhance",g.ComicBook="Comic book",g.Lowpoly="Lowpoly",g.LineArt="Line art",g))(et||{});import{v4 as tt,validate as nt}from"uuid";var K=6e4,q=1e3,ye=100,Z={PRODUCTION:"wss://ws-api.runware.ai/v1",TEST:"ws://localhost:8080"},he=(u,e)=>{if(u==null)return;let t=u.indexOf(e);t!==-1&&u.splice(t,1)},M=(u,{debugKey:e="debugKey",timeoutDuration:t=K,shouldThrowError:n=!0,pollingInterval:s=ye})=>(t=t<q?q:t,new Promise((a,r)=>{let o=setTimeout(()=>{i&&(clearInterval(i),n&&r(`Response could not be received from server for ${e}`)),clearTimeout(o)},t),i=setInterval(async()=>{u({resolve:a,reject:r,intervalId:i})&&(clearInterval(i),clearTimeout(o))},s)})),Ue=u=>new Promise(e=>{let t=new FileReader;t.readAsDataURL(u),t.onload=function(){e(t.result)}}),D=()=>tt(),Te=u=>nt(u);var be=({key:u,data:e,useZero:t=!0,shouldReturnString:n=!1})=>u.split(/\.|\[/).map(r=>r.replace(/\]$/,"")).reduce((r,o)=>{let i=t?0:void 0,d=r?.[o];if(!d)return i;if(Array.isArray(d)&&/^\d+$/.test(o)){let m=parseInt(o,10);return m>=0&&m<d.length?r[o]=d[m]:r[o]??i}else return r[o]??i},e||{})??{},fe=(u,e=1e3)=>new Promise(t=>setTimeout(t,u*e));var Re=(u,e)=>u.filter(t=>t.key!==e.key);var R=({key:u,value:e})=>e||e===0||e===!1?{[u]:e}:{},st=(u,e)=>Math.floor(Math.random()*(e-u+1))+u,ke=()=>st(1,Number.MAX_SAFE_INTEGER),De=(u,{debugKey:e="debugKey",timeoutDuration:t=K,shouldThrowError:n=!0,pollingInterval:s=ye})=>(t=t<q?q:t,new Promise((a,r)=>{let o=setTimeout(()=>{i&&(clearInterval(i),n&&r(`Response could not be received from server for ${e}`)),clearTimeout(o)},t),i=setInterval(async()=>{try{await u({resolve:a,reject:r,intervalId:i})&&(clearInterval(i),clearTimeout(o))}catch(d){clearInterval(i),clearTimeout(o),r(d)}},s)}));var x=async(u,e={})=>{let{delayInSeconds:t=1,callback:n}=e,s=e.maxRetries??1;for(;s;)try{return await u()}catch(a){if(n?.(),a?.error)throw a;if(s--,s>0)await fe(t),await x(u,{...e,maxRetries:s});else throw a}};var C=class{constructor({apiKey:e,url:t=Z.PRODUCTION,shouldReconnect:n=!0,globalMaxRetries:s=2,timeoutDuration:a=K}){this._listeners=[];this._globalMessages={};this._globalImages=[];this._globalErrors=[];this.ensureConnectionUUID=null;this.isWebsocketReadyState=()=>this._ws?.readyState===1;this.isInvalidAPIKey=()=>this._connectionError?.error?.code==="invalidApiKey";this.send=e=>{this._ws.send(JSON.stringify([e]))};this.uploadImage=async e=>{try{return await x(async()=>{let t=D();if(typeof e=="string"&&Te(e))return{imageURL:e,imageUUID:e,taskUUID:t,taskType:"imageUpload"};let n=typeof e=="string"?e:await Ue(e);return{imageURL:n,imageUUID:n,taskUUID:t,taskType:"imageUpload"}})}catch(t){throw t}};this.controlNetPreProcess=async({inputImage:e,preProcessorType:t,height:n,width:s,outputType:a,outputFormat:r,highThresholdCanny:o,lowThresholdCanny:i,includeHandsAndFaceOpenPose:d,includeCost:m,outputQuality:g,customTaskUUID:p,taskUUID:l,retry:c,includeGenerationTime:y,includePayload:U})=>{let b=c||this._globalMaxRetries,f,h=Date.now();try{return await x(async()=>{await this.ensureConnection();let k=await this.uploadImage(e);if(!k?.imageUUID)return null;let I=l||p||D(),w={inputImage:k.imageUUID,taskType:"imageControlNetPreProcess",taskUUID:I,preProcessorType:t,...R({key:"height",value:n}),...R({key:"width",value:s}),...R({key:"outputType",value:a}),...R({key:"outputFormat",value:r}),...R({key:"includeCost",value:m}),...R({key:"highThresholdCanny",value:o}),...R({key:"lowThresholdCanny",value:i}),...R({key:"includeHandsAndFaceOpenPose",value:d}),...g?{outputQuality:g}:{}};this.send({...w}),f=this.globalListener({taskUUID:I});let A=await M(({resolve:S,reject:B})=>{let v=this.getSingleMessage({taskUUID:I});if(v){if(v?.error)return B(v),!0;if(v)return S(v),!0}},{debugKey:"unprocessed-image",timeoutDuration:this._timeoutDuration});return f.destroy(),this.insertAdditionalResponse({response:A,payload:U?w:void 0,startTime:y?h:void 0}),A},{maxRetries:b,callback:()=>{f?.destroy()}})}catch(k){throw k}};this.controlNetPreprocess=async e=>this.controlNetPreProcess(e);this.requestImageToText=async({inputImage:e,inputs:t,includeCost:n,customTaskUUID:s,taskUUID:a,retry:r,includePayload:o,includeGenerationTime:i,deliveryMethod:d,skipResponse:m,model:g})=>{try{let p;e&&(p=await this.uploadImage(e));let c={taskUUID:a||s||D(),taskType:"caption",model:g,inputImage:p?.imageUUID,inputs:t,...R({key:"includeCost",value:n}),retry:r,includePayload:o,includeGenerationTime:i},y=await this.baseSingleRequest({payload:{...c,taskType:"caption"},debugKey:"caption"});if(m)return y;if(d==="async"){let U=y?.taskUUID;return(await this.pollForAsyncResults({taskUUID:U}))[0]}return y}catch(p){throw p}};this.caption=async e=>this.requestImageToText(e);this.removeImageBackground=async e=>{let{skipResponse:t,...n}=e;try{let s=n.deliveryMethod,a=await this.baseSingleRequest({payload:{...n,taskType:"removeBackground"},debugKey:"remove-background"});if(t)return a;if(s==="async"){let r=a?.taskUUID;return(await this.pollForAsyncResults({taskUUID:r}))[0]}return a}catch(s){throw s}};this.removeBackground=async e=>this.removeImageBackground(e);this.vectorize=async e=>this.baseSingleRequest({payload:{...e,taskType:"vectorize"},debugKey:"vectorize"});this.videoInference=async e=>{let{skipResponse:t,inputAudios:n,referenceVideos:s,...a}=e;try{let r=await this.baseSingleRequest({payload:{...a,...n?.length&&{inputAudios:n},...s?.length&&{referenceVideos:s},deliveryMethod:"async",taskType:"videoInference"},debugKey:"video-inference"});if(t)return r;let o=r?.taskUUID;return this.pollForAsyncResults({taskUUID:o,numberResults:e?.numberResults})}catch(r){throw r}};this.audioInference=async e=>{let{skipResponse:t,deliveryMethod:n="sync",...s}=e;try{let r=await(n==="sync"?this.baseSyncRequest:this.baseSingleRequest)({payload:{...s,numberResults:s.numberResults||1,taskType:"audioInference",deliveryMethod:n},groupKey:"REQUEST_AUDIO",debugKey:"audio-inference",skipResponse:t});if(t)return r;let o=r?.taskUUID;return n==="async"?this.pollForAsyncResults({taskUUID:o,numberResults:e?.numberResults}):r}catch(a){throw a}};this.threeDInference=async e=>{let{skipResponse:t,deliveryMethod:n="sync",...s}=e;try{let r=await(n==="sync"?this.baseSyncRequest:this.baseSingleRequest)({payload:{...s,numberResults:s.numberResults||1,taskType:"3dInference",deliveryMethod:n},groupKey:"REQUEST_IMAGES",debugKey:"three-d-inference",skipResponse:t});if(t)return r;let o=r?.taskUUID;return n==="async"?this.pollForAsyncResults({taskUUID:o,numberResults:e?.numberResults}):r}catch(a){throw a}};this.textInference=async e=>{let{skipResponse:t,deliveryMethod:n="sync",...s}=e;try{let r=await(n==="sync"?this.baseSyncRequest:this.baseSingleRequest)({payload:{...s,numberResults:s.numberResults||1,taskType:"textInference",deliveryMethod:n},groupKey:"REQUEST_TEXT",debugKey:"text-inference",skipResponse:t});if(t)return r;let o=r?.taskUUID;return n==="async"?this.pollForAsyncResults({taskUUID:o,numberResults:e?.numberResults}):r}catch(a){throw a}};this.getResponse=async e=>{let t=e.taskUUID;return this.baseSingleRequest({payload:{...e,customTaskUUID:t,taskType:"getResponse"},isMultiple:!0,debugKey:"async-results"})};this.upscaleGan=async e=>{let{inputImage:t,skipResponse:n,deliveryMethod:s="sync",...a}=e;try{let r;t&&(r=await this.uploadImage(t));let o=await this.baseSingleRequest({payload:{...a,...r?.imageUUID?{inputImage:r.imageUUID}:{},taskType:"upscale",deliveryMethod:s},debugKey:"upscale"});if(n)return o;if(s==="async"){let i=o?.taskUUID;return(await this.pollForAsyncResults({taskUUID:i}))[0]}return o}catch(r){throw r}};this.upscale=async e=>this.upscaleGan(e);this.enhancePrompt=async({prompt:e,promptMaxLength:t=380,promptVersions:n=1,includeCost:s,customTaskUUID:a,taskUUID:r,retry:o,includeGenerationTime:i,includePayload:d})=>{let m=o||this._globalMaxRetries,g,p=Date.now();try{return await x(async()=>{await this.ensureConnection();let l=r||a||D(),c={prompt:e,taskUUID:l,promptMaxLength:t,promptVersions:n,...R({key:"includeCost",value:s}),taskType:"promptEnhance"};this.send(c),g=this.globalListener({taskUUID:l});let y=await M(({resolve:U,reject:b})=>{let f=this._globalMessages[l];if(f?.error)return b(f),!0;if(f?.length>=n)return delete this._globalMessages[l],U(f),!0},{debugKey:"enhance-prompt",timeoutDuration:this._timeoutDuration});return g.destroy(),this.insertAdditionalResponse({response:y,payload:d?c:void 0,startTime:i?p:void 0}),y},{maxRetries:m,callback:()=>{g?.destroy()}})}catch(l){throw l}};this.promptEnhance=async e=>this.enhancePrompt(e);this.modelUpload=async e=>{let{onUploadStream:t,retry:n,customTaskUUID:s,taskUUID:a,...r}=e,o=n||this._globalMaxRetries,i;try{return await x(async()=>{await this.ensureConnection();let d=a||s||D();this.send({...r,taskUUID:d,taskType:"modelUpload"});let m,g;return i=this.listenToUpload({taskUUID:d,onUploadStream:(l,c)=>{t?.(l,c),l?.status==="ready"?m=l:c&&(g=c)}}),await M(({resolve:l,reject:c})=>{if(m)return l(m),!0;if(g)return c(g),!1},{shouldThrowError:!1,timeoutDuration:60*60*1e3})},{maxRetries:o,callback:()=>{i?.destroy()}})}catch(d){throw d}};this.photoMaker=async(e,t)=>{let{onPartialImages:n,retry:s,customTaskUUID:a,taskUUID:r,numberResults:o,includeGenerationTime:i,includePayload:d,...m}=e,g=s||this._globalMaxRetries,p,l=[],c=0,y=Date.now();try{return await x(async()=>{await this.ensureConnection(),c++;let U=this._globalImages.filter(I=>l.includes(I.taskUUID)),b=r||a||D();l.push(b);let f=o-U.length,h={...m,...m.seed?{seed:m.seed}:{seed:ke()},...t??{},taskUUID:b,taskType:"photoMaker",numberResults:o};this.send({...h,numberResults:f}),p=this.listenToResponse({onPartialImages:n,taskUUID:b,groupKey:"REQUEST_IMAGES",requestPayload:d?h:void 0,startTime:i?y:void 0});let k=await this.getResponseWithSimilarTaskUUID({taskUUID:l,numberResults:o,lis:p});return p.destroy(),k},{maxRetries:g,callback:()=>{p?.destroy()}})}catch(U){if(U.taskUUID)throw U;if(c>=g)return this.handleIncompleteImages({taskUUIDs:l,error:U})}};this.modelSearch=async e=>this.baseSingleRequest({payload:{...e,taskType:"modelSearch"},debugKey:"model-search"});this.imageMasking=async e=>this.baseSingleRequest({payload:{...e,taskType:"imageMasking"},debugKey:"image-masking"});this.imageUpload=async e=>this.baseSingleRequest({payload:{...e,taskType:"imageUpload"},debugKey:"image-upload"});this.mediaStorage=async e=>this.baseSingleRequest({payload:{...e,operation:e.operation||"upload",taskType:"mediaStorage"},debugKey:"media-storage"});this.baseSingleRequest=async({payload:e,debugKey:t,isMultiple:n})=>{let{retry:s,customTaskUUID:a,taskUUID:r,includePayload:o,includeGenerationTime:i,...d}=e,m=s||this._globalMaxRetries,g,p=Date.now();try{return await x(async()=>{await this.ensureConnection();let l=r||a||D(),c={...d,taskUUID:l};this.send(c),g=this.globalListener({taskUUID:l});let y=await M(({resolve:U,reject:b})=>{let f=n?this.getMultipleMessages({taskUUID:l}):this.getSingleMessage({taskUUID:l});if(f){if(f?.error)return b(f),!0;if(f)return delete this._globalMessages[l],U(f),!0}},{debugKey:t,timeoutDuration:this._timeoutDuration});return this.insertAdditionalResponse({response:y,payload:o?c:void 0,startTime:i?p:void 0}),g.destroy(),y},{maxRetries:m,callback:()=>{g?.destroy()}})}catch(l){throw l}};this.baseSyncRequest=async({payload:e,groupKey:t,skipResponse:n=!1})=>{let{retry:s,customTaskUUID:a,includePayload:r,numberResults:o=1,onPartialResponse:i,includeGenerationTime:d,...m}=e,g=s||this._globalMaxRetries,p,l=[],c=0,y=Date.now();try{return await x(async()=>{await this.ensureConnection(),c++;let U=this._globalImages.filter(I=>l.includes(I.taskUUID)),b=a||D();l.push(b);let f=o-U.length,h={...m,taskUUID:b,numberResults:f};if(this.send(h),n)return new Promise((I,w)=>{let A=this.addListener({taskUUID:b,groupKey:t,lis:S=>{A.destroy(),S.error?w(S.error):I(S[b])}})});p=this.listenToResponse({onPartialImages:i,taskUUID:b,groupKey:t,requestPayload:r?h:void 0,startTime:d?y:void 0});let k=await this.getResponseWithSimilarTaskUUID({taskUUID:l,numberResults:o,lis:p});return p.destroy(),k},{maxRetries:g,callback:()=>{p?.destroy()}})}catch(U){throw U}};this.getSingleMessage=({taskUUID:e})=>{let t=this._globalMessages[e]?.[0],n=this._globalMessages[e];return!t&&!n?null:n?.error?n:t};this.getMultipleMessages=({taskUUID:e})=>{let t=this._globalMessages[e]?.[0],n=this._globalMessages[e];return!t&&!n?null:n};this.insertAdditionalResponse=({response:e,payload:t,startTime:n})=>{if(!t&&!n)return;let s=e;s.additionalResponse={},t&&(e.additionalResponse.payload=t),n&&(e.additionalResponse.generationTime=Date.now()-n)};this.disconnect=async()=>{this._shouldReconnect=!1,this._ws?.terminate?.(),this._ws?.close?.()};this.connected=()=>this.isWebsocketReadyState()&&!!this._connectionSessionUUID;this._apiKey=e,this._url=t,this._sdkType="CLIENT",this._shouldReconnect=n,this._globalMaxRetries=s,this._timeoutDuration=a}getUniqueUUID(e){return e.mediaUUID||e.audioUUID||e.imageUUID||e.videoUUID||e.outputs?.files?.map(t=>t.uuid).join("-")||e.text}async pollForAsyncResults({taskUUID:e,numberResults:t=1}){let n=new Map;return await De(async({resolve:s,reject:a})=>{try{let r=await this.getResponse({taskUUID:e});for(let i of r||[])if(i.status==="success"){let d=this.getUniqueUUID(i);d&&n.set(d,i)}return n.size===t?(s(Array.from(n.values())),!0):!1}catch(r){return a(r),!0}},{debugKey:"async-response",pollingInterval:2*1e3,timeoutDuration:10*60*1e3}),Array.from(n.values())}static async initialize(e){try{let t=new this(e);return await t.ensureConnection(),t}catch(t){throw t}}addListener({lis:e,groupKey:t,taskUUID:n}){let s=o=>{let i=Array.isArray(o?.data)?o.data:[o.data],d=o?.[0]?.errors?o?.[0]?.errors:Array.isArray(o?.errors)?o.errors:[o.errors],m=i.filter(p=>(p?.taskUUID||p?.taskType)===n);if(d.filter(p=>(p?.taskUUID||p?.taskType)===n).length){e({error:{...d[0]??{}}});return}if(m.length){e({[n]:i});return}},a={key:n||D(),listener:s,groupKey:t};return this._listeners.push(a),{destroy:()=>{this._listeners=Re(this._listeners,a)}}}connect(){this._ws.onopen=e=>{this._connectionSessionUUID?this.send({taskType:"authentication",apiKey:this._apiKey,connectionSessionUUID:this._connectionSessionUUID}):this.send({apiKey:this._apiKey,taskType:"authentication"}),this.addListener({taskUUID:"authentication",lis:t=>{if(t?.error){this._connectionError=t;return}this._connectionSessionUUID=t?.authentication?.[0]?.connectionSessionUUID,this._connectionError=void 0}})},this._ws.onmessage=e=>{let t=JSON.parse(e.data);for(let n of this._listeners)if(n?.listener?.(t))return},this._ws.onclose=e=>{this.isInvalidAPIKey()}}destroy(e){he(this._listeners,e)}listenToResponse({onPartialImages:e,taskUUID:t,groupKey:n,requestPayload:s,startTime:a}){return this.addListener({taskUUID:t,lis:r=>{let o=r?.[t]?.filter(i=>i.taskUUID===t);r.error?(e?.(o,r?.error&&r),this._globalErrors.push(r)):(o=o.map(i=>(this.insertAdditionalResponse({response:i,payload:s||void 0,startTime:a||void 0}),{...i})),e?.(o,r?.error&&r),this._sdkType==="CLIENT"?this._globalImages=[...this._globalImages,...(r?.[t]??[]).map(i=>(this.insertAdditionalResponse({response:i,payload:s||void 0,startTime:a||void 0}),{...i}))]:this._globalImages=[...this._globalImages,...o])},groupKey:n})}listenToUpload({onUploadStream:e,taskUUID:t}){return this.addListener({taskUUID:t,lis:n=>{let s=n?.error,a=n?.[t]?.[0],r=a?.taskUUID===t?a:null;(r||s)&&e?.(r||void 0,s)}})}globalListener({taskUUID:e}){return this.addListener({taskUUID:e,lis:t=>{if(t.error){this._globalMessages[e]=t;return}let n=be({key:e,data:t,useZero:!1});Array.isArray(n)?n.forEach(s=>{this._globalMessages[s.taskUUID]=[...this._globalMessages[s.taskUUID]??[],s]}):this._globalMessages[n.taskUUID]=n}})}async requestImages({outputType:e,outputFormat:t,uploadEndpoint:n,checkNSFW:s,positivePrompt:a,negativePrompt:r,seedImage:o,maskImage:i,strength:d,height:m,width:g,model:p,steps:l,scheduler:c,seed:y,CFGScale:U,clipSkip:b,usePromptWeighting:f,promptWeighting:h,numberResults:k=1,onPartialImages:I,includeCost:w,customTaskUUID:A,taskUUID:S,retry:B,refiner:v,maskMargin:T,outputQuality:Y,controlNet:G,lora:$,embeddings:ee,ipAdapters:te,providerSettings:ne,outpaint:se,acceleratorOptions:re,advancedFeatures:ae,referenceImages:oe,includeGenerationTime:Me,includePayload:Ce,...ie},Oe){let O,le,P=[],ue=0,ce=B||this._globalMaxRetries;try{await this.ensureConnection();let E=null,H=null,Q=[];if(o){let _=await this.uploadImage(o);if(!_)return[];E=_.imageUUID}if(i){let _=await this.uploadImage(i);if(!_)return[];H=_.imageUUID}if(G?.length)for(let _=0;_<G.length;_++){let N=G[_],{endStep:z,startStep:L,weight:j,guideImage:F,controlMode:Pe,startStepPercentage:Le,endStepPercentage:Fe,model:qe}=N,Ke=F?await this.uploadImage(F):null;Q.push({guideImage:Ke?.imageUUID,model:qe,endStep:z,startStep:L,weight:j,...R({key:"startStepPercentage",value:Le}),...R({key:"endStepPercentage",value:Fe}),controlMode:Pe||"controlnet"})}le={taskType:"imageInference",model:p,positivePrompt:a,...r?{negativePrompt:r}:{},...m?{height:m}:{},...g?{width:g}:{},numberResults:k,...e?{outputType:e}:{},...t?{outputFormat:t}:{},...n?{uploadEndpoint:n}:{},...R({key:"checkNSFW",value:s}),...R({key:"strength",value:d}),...R({key:"CFGScale",value:U}),...R({key:"clipSkip",value:b}),...R({key:"maskMargin",value:T}),...R({key:"usePromptWeighting",value:f}),...R({key:"steps",value:l}),...h?{promptWeighting:h}:{},...y?{seed:y}:{},...c?{scheduler:c}:{},...v?{refiner:v}:{},...se?{outpaint:se}:{},...R({key:"includeCost",value:w}),...E?{seedImage:E}:{},...H?{maskImage:H}:{},...Y?{outputQuality:Y}:{},...Q.length?{controlNet:Q}:{},...$?.length?{lora:$}:{},...ee?.length?{embeddings:ee}:{},...te?.length?{ipAdapters:te}:{},...ne?{providerSettings:ne}:{},...re?{acceleratorOptions:re}:{},...ae?{advancedFeatures:ae}:{},...oe?.length?{referenceImages:oe}:{},...ie,...Oe??{}};let Ne=Date.now();return await x(async()=>{ue++,O?.destroy();let _=this._globalImages.filter(F=>P.includes(F.taskUUID)),N=S||A||D();P.push(N);let z=k-_.length,L={...le,taskUUID:N,numberResults:z};this.send(L),O=this.listenToResponse({onPartialImages:I,taskUUID:N,groupKey:"REQUEST_IMAGES",requestPayload:Ce?L:void 0,startTime:Me?Ne:void 0});let j=await this.getResponseWithSimilarTaskUUID({taskUUID:P,numberResults:k,lis:O,deliveryMethod:ie.deliveryMethod});return O.destroy(),j},{maxRetries:ce,callback:()=>{O?.destroy()}})}catch(E){if(ue>=ce)return this.handleIncompleteImages({taskUUIDs:P,error:E});throw E}}async imageInference(e,t){return this.requestImages(e,t)}async ensureConnection(){if(this.connected()||this._url===Z.TEST)return;let t=2e3,n=200;try{if(this.isInvalidAPIKey())throw this._connectionError;return new Promise((s,a)=>{let r=0,o=30,i=D(),d,m,g=()=>{this.ensureConnectionUUID=null,clearInterval(d),clearInterval(m)};this._sdkType==="SERVER"&&(d=setInterval(async()=>{try{let p=this.connected(),l=!1;(!this.ensureConnectionUUID||i===this.ensureConnectionUUID)&&(this.ensureConnectionUUID||(this.ensureConnectionUUID=i),l=!0);let c=r%10===0&&l;p?(g(),s(!0)):r>=o?(g(),a(new Error("Retry timed out"))):(c&&this.connect(),r++)}catch(p){g(),a(p)}},t)),m=setInterval(async()=>{if(this.connected()){g(),s(!0);return}if(this.isInvalidAPIKey()){g(),a(this._connectionError);return}},n)})}catch{throw this.ensureConnectionUUID=null,this._connectionError=void 0,this._connectionError??"Could not connect to server. Ensure your API key is correct"}}async getResponseWithSimilarTaskUUID({taskUUID:e,numberResults:t,shouldThrowError:n,lis:s,deliveryMethod:a}){return await M(({resolve:r,reject:o,intervalId:i})=>{let d=Array.isArray(e)?e:[e],m=this._globalImages.filter(l=>d.includes(l.taskUUID)),g=a==="async"&&m.length>0,p=this._globalErrors.filter(l=>d.includes(l.error.taskUUID));if(p.length>0){let l=p[0];return this._globalErrors=this._globalErrors.filter(c=>!d.includes(c.error.taskUUID)),clearInterval(i),o?.(l),!0}else if(m.length>=t||g)return clearInterval(i),this._globalImages=this._globalImages.filter(l=>!d.includes(l.taskUUID)),r([...m].slice(0,t)),!0},{debugKey:"getting images",shouldThrowError:n,timeoutDuration:this._timeoutDuration})}handleIncompleteImages({taskUUIDs:e,error:t}){let n=this._globalImages.filter(s=>e.includes(s.taskUUID));if(n.length>1)return this._globalImages=this._globalImages.filter(s=>!e.includes(s.taskUUID)),n;throw t}};var Ae=je(we(),1),W=class extends C{constructor(e){let{shouldReconnect:t,...n}=e;super(n),this._ws=new Ae.default(this._url),this.connect()}};import ct from"ws";var V=class extends C{constructor(t){super(t);this._instantiated=!1;this._listeners=[];this._reconnectingIntervalId=null;this.send=t=>{this._ws.send(JSON.stringify([t]))};this.resetConnection=()=>{this._ws&&(this._listeners.forEach(t=>{t?.destroy?.()}),this._ws.removeAllListeners(),this._ws.readyState===1&&(this._ws.terminate(),this._ws.close()),this._ws=null,this._listeners=[])};this._sdkType="SERVER",this.connect()}async connect(){this._url&&(this.resetConnection(),this._ws=new ct(this._url,{perMessageDeflate:!1}),this._ws.on("error",()=>{}),this._ws.on("close",()=>{this.handleClose()}),this._ws.on("open",()=>{this._reconnectingIntervalId&&clearInterval(this._reconnectingIntervalId),this._connectionSessionUUID&&this.isWebsocketReadyState()?this.send({taskType:"authentication",apiKey:this._apiKey,connectionSessionUUID:this._connectionSessionUUID}):this.isWebsocketReadyState()&&this.send({apiKey:this._apiKey,taskType:"authentication"}),this.addListener({taskUUID:"authentication",lis:t=>{if(t?.error){this._connectionError=t;return}this._connectionSessionUUID=t?.authentication?.[0]?.connectionSessionUUID,this._connectionError=void 0}})}),this._ws.on("message",(t,n)=>{let s=n?t:t?.toString();if(!s)return;let a=JSON.parse(s);this._listeners.forEach(r=>{r.listener(a)})}))}handleClose(){this.isInvalidAPIKey()||(this._reconnectingIntervalId&&clearInterval(this._reconnectingIntervalId),this._shouldReconnect&&setTimeout(()=>this.connect(),1e3))}heartBeat(){clearTimeout(this._pingTimeout),this._pingTimeout=setTimeout(()=>{this.isWebsocketReadyState()&&this.send({ping:!0})},5e3)}};var Ee;typeof window>"u"?Ee=V:Ee=W;export{ge as EControlMode,Ze as EModelArchitecture,$e as EModelConditioning,Je as EModelFormat,Ye as EModelType,Xe as EOpenPosePreProcessor,et as EPhotoMakerEnum,Ie as EPreProcessor,me as EPreProcessorGroup,J as ETaskType,pe as Environment,Ee as Runware,W as RunwareClient,V as RunwareServer,X as SdkType};
5
2
  //# sourceMappingURL=index.js.map