@runware/sdk-js 1.1.41-beta.3 → 1.1.41-beta.5

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
@@ -232,11 +232,14 @@ interface IRequestVideo extends IRequestImageToText {
232
232
  width?: number;
233
233
  height?: number;
234
234
  numberResults?: number;
235
+ skipResponse?: boolean;
235
236
  customTaskUUID?: string;
236
237
  retry?: number;
238
+ [key: string]: any;
237
239
  }
238
240
  interface IAsyncResults {
239
241
  taskUUID: string;
242
+ onPartialImages?: (images: IImage[], error?: IError) => void;
240
243
  }
241
244
  interface IRemoveImage {
242
245
  taskType: ETaskType;
@@ -283,6 +286,11 @@ type GetWithPromiseCallBackType = ({ resolve, reject, intervalId, }: {
283
286
  reject: <T>(value: T) => void;
284
287
  intervalId: any;
285
288
  }) => boolean | undefined;
289
+ type GetWithPromiseAsyncCallBackType = ({ resolve, reject, intervalId, }: {
290
+ resolve: <T>(value: T) => void;
291
+ reject: <T>(value: T) => void;
292
+ intervalId: any;
293
+ }) => any;
286
294
  declare enum EPreProcessorGroup {
287
295
  "canny" = "canny",
288
296
  "depth" = "depth",
@@ -624,8 +632,8 @@ declare class RunwareBase {
624
632
  controlNetPreProcess: ({ inputImage, preProcessorType, height, width, outputType, outputFormat, highThresholdCanny, lowThresholdCanny, includeHandsAndFaceOpenPose, includeCost, outputQuality, customTaskUUID, retry, includeGenerationTime, includePayload, }: IControlNetPreprocess) => Promise<IControlNetImage | null>;
625
633
  requestImageToText: ({ inputImage, includeCost, customTaskUUID, retry, includePayload, includeGenerationTime, }: IRequestImageToText) => Promise<IImageToText>;
626
634
  removeImageBackground: (payload: IRemoveImageBackground) => Promise<IRemoveImage>;
627
- videoInference: (payload: IRequestVideo) => Promise<IVideoToImage>;
628
- getResponse: (payload: IAsyncResults) => Promise<IVideoToImage>;
635
+ videoInference: (payload: IRequestVideo) => Promise<IVideoToImage[] | IVideoToImage>;
636
+ getResponse: (payload: IAsyncResults) => Promise<IVideoToImage[]>;
629
637
  upscaleGan: ({ inputImage, upscaleFactor, outputType, outputFormat, includeCost, outputQuality, customTaskUUID, retry, includeGenerationTime, includePayload, }: IUpscaleGan) => Promise<IImage>;
630
638
  enhancePrompt: ({ prompt, promptMaxLength, promptVersions, includeCost, customTaskUUID, retry, includeGenerationTime, includePayload, }: IPromptEnhancer) => Promise<IEnhancedPrompt[]>;
631
639
  modelUpload: (payload: TAddModel) => Promise<any>;
@@ -633,14 +641,16 @@ declare class RunwareBase {
633
641
  modelSearch: (payload: TModelSearch) => Promise<TModelSearchResponse>;
634
642
  imageMasking: (payload: TImageMasking) => Promise<TImageMaskingResponse>;
635
643
  imageUpload: (payload: TImageUpload) => Promise<TImageUploadResponse>;
636
- protected baseSingleRequest: <T>({ payload, debugKey, mockResponse, }: {
644
+ protected baseSingleRequest: <T>({ payload, debugKey, mockResponse, isMultiple, }: {
637
645
  payload: Record<string, any>;
638
646
  debugKey: string;
639
647
  mockResponse?: any;
648
+ isMultiple?: boolean | undefined;
640
649
  }) => Promise<T>;
641
650
  ensureConnection(): Promise<unknown>;
642
651
  private getSimilarImages;
643
652
  private getSingleMessage;
653
+ private getMultipleMessages;
644
654
  private insertAdditionalResponse;
645
655
  private handleIncompleteImages;
646
656
  disconnect: () => Promise<void>;
@@ -667,4 +677,4 @@ declare class RunwareServer extends RunwareBase {
667
677
 
668
678
  declare let Runware: typeof RunwareClient | typeof RunwareServer;
669
679
 
670
- export { EControlMode, EModelArchitecture, EModelConditioning, EModelFormat, EModelType, EOpenPosePreProcessor, EPhotoMakerEnum, EPreProcessor, EPreProcessorGroup, ETaskType, Environment, type GetWithPromiseCallBackType, type IAddModelResponse, type IAdditionalResponsePayload, type IAsyncResults, 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 IRefiner, type IRemoveImage, type IRemoveImageBackground, type IRequestImage, type IRequestImageToText, type IRequestVideo, type ITextToImage, type IUpscaleGan, type IVideoToImage, type IipAdapter, type ListenerType, 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 TModel, type TModelSearch, type TModelSearchResponse, type TPhotoMaker, type TPhotoMakerResponse, type TPromptWeighting, type TServerError, type UploadImageType };
680
+ export { EControlMode, EModelArchitecture, EModelConditioning, EModelFormat, EModelType, EOpenPosePreProcessor, EPhotoMakerEnum, EPreProcessor, EPreProcessorGroup, ETaskType, Environment, type GetWithPromiseAsyncCallBackType, type GetWithPromiseCallBackType, type IAddModelResponse, type IAdditionalResponsePayload, type IAsyncResults, 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 IRefiner, type IRemoveImage, type IRemoveImageBackground, type IRequestImage, type IRequestImageToText, type IRequestVideo, type ITextToImage, type IUpscaleGan, type IVideoToImage, type IipAdapter, type ListenerType, 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 TModel, type TModelSearch, type TModelSearchResponse, type TPhotoMaker, type TPhotoMakerResponse, type TPromptWeighting, type TServerError, type UploadImageType };
package/dist/index.d.ts CHANGED
@@ -232,11 +232,14 @@ interface IRequestVideo extends IRequestImageToText {
232
232
  width?: number;
233
233
  height?: number;
234
234
  numberResults?: number;
235
+ skipResponse?: boolean;
235
236
  customTaskUUID?: string;
236
237
  retry?: number;
238
+ [key: string]: any;
237
239
  }
238
240
  interface IAsyncResults {
239
241
  taskUUID: string;
242
+ onPartialImages?: (images: IImage[], error?: IError) => void;
240
243
  }
241
244
  interface IRemoveImage {
242
245
  taskType: ETaskType;
@@ -283,6 +286,11 @@ type GetWithPromiseCallBackType = ({ resolve, reject, intervalId, }: {
283
286
  reject: <T>(value: T) => void;
284
287
  intervalId: any;
285
288
  }) => boolean | undefined;
289
+ type GetWithPromiseAsyncCallBackType = ({ resolve, reject, intervalId, }: {
290
+ resolve: <T>(value: T) => void;
291
+ reject: <T>(value: T) => void;
292
+ intervalId: any;
293
+ }) => any;
286
294
  declare enum EPreProcessorGroup {
287
295
  "canny" = "canny",
288
296
  "depth" = "depth",
@@ -624,8 +632,8 @@ declare class RunwareBase {
624
632
  controlNetPreProcess: ({ inputImage, preProcessorType, height, width, outputType, outputFormat, highThresholdCanny, lowThresholdCanny, includeHandsAndFaceOpenPose, includeCost, outputQuality, customTaskUUID, retry, includeGenerationTime, includePayload, }: IControlNetPreprocess) => Promise<IControlNetImage | null>;
625
633
  requestImageToText: ({ inputImage, includeCost, customTaskUUID, retry, includePayload, includeGenerationTime, }: IRequestImageToText) => Promise<IImageToText>;
626
634
  removeImageBackground: (payload: IRemoveImageBackground) => Promise<IRemoveImage>;
627
- videoInference: (payload: IRequestVideo) => Promise<IVideoToImage>;
628
- getResponse: (payload: IAsyncResults) => Promise<IVideoToImage>;
635
+ videoInference: (payload: IRequestVideo) => Promise<IVideoToImage[] | IVideoToImage>;
636
+ getResponse: (payload: IAsyncResults) => Promise<IVideoToImage[]>;
629
637
  upscaleGan: ({ inputImage, upscaleFactor, outputType, outputFormat, includeCost, outputQuality, customTaskUUID, retry, includeGenerationTime, includePayload, }: IUpscaleGan) => Promise<IImage>;
630
638
  enhancePrompt: ({ prompt, promptMaxLength, promptVersions, includeCost, customTaskUUID, retry, includeGenerationTime, includePayload, }: IPromptEnhancer) => Promise<IEnhancedPrompt[]>;
631
639
  modelUpload: (payload: TAddModel) => Promise<any>;
@@ -633,14 +641,16 @@ declare class RunwareBase {
633
641
  modelSearch: (payload: TModelSearch) => Promise<TModelSearchResponse>;
634
642
  imageMasking: (payload: TImageMasking) => Promise<TImageMaskingResponse>;
635
643
  imageUpload: (payload: TImageUpload) => Promise<TImageUploadResponse>;
636
- protected baseSingleRequest: <T>({ payload, debugKey, mockResponse, }: {
644
+ protected baseSingleRequest: <T>({ payload, debugKey, mockResponse, isMultiple, }: {
637
645
  payload: Record<string, any>;
638
646
  debugKey: string;
639
647
  mockResponse?: any;
648
+ isMultiple?: boolean | undefined;
640
649
  }) => Promise<T>;
641
650
  ensureConnection(): Promise<unknown>;
642
651
  private getSimilarImages;
643
652
  private getSingleMessage;
653
+ private getMultipleMessages;
644
654
  private insertAdditionalResponse;
645
655
  private handleIncompleteImages;
646
656
  disconnect: () => Promise<void>;
@@ -667,4 +677,4 @@ declare class RunwareServer extends RunwareBase {
667
677
 
668
678
  declare let Runware: typeof RunwareClient | typeof RunwareServer;
669
679
 
670
- export { EControlMode, EModelArchitecture, EModelConditioning, EModelFormat, EModelType, EOpenPosePreProcessor, EPhotoMakerEnum, EPreProcessor, EPreProcessorGroup, ETaskType, Environment, type GetWithPromiseCallBackType, type IAddModelResponse, type IAdditionalResponsePayload, type IAsyncResults, 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 IRefiner, type IRemoveImage, type IRemoveImageBackground, type IRequestImage, type IRequestImageToText, type IRequestVideo, type ITextToImage, type IUpscaleGan, type IVideoToImage, type IipAdapter, type ListenerType, 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 TModel, type TModelSearch, type TModelSearchResponse, type TPhotoMaker, type TPhotoMakerResponse, type TPromptWeighting, type TServerError, type UploadImageType };
680
+ export { EControlMode, EModelArchitecture, EModelConditioning, EModelFormat, EModelType, EOpenPosePreProcessor, EPhotoMakerEnum, EPreProcessor, EPreProcessorGroup, ETaskType, Environment, type GetWithPromiseAsyncCallBackType, type GetWithPromiseCallBackType, type IAddModelResponse, type IAdditionalResponsePayload, type IAsyncResults, 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 IRefiner, type IRemoveImage, type IRemoveImageBackground, type IRequestImage, type IRequestImageToText, type IRequestVideo, type ITextToImage, type IUpscaleGan, type IVideoToImage, type IipAdapter, type ListenerType, 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 TModel, type TModelSearch, type TModelSearchResponse, type TPhotoMaker, type TPhotoMakerResponse, type TPromptWeighting, type TServerError, type UploadImageType };
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- var Le=Object.create;var ie=Object.defineProperty;var Ke=Object.getOwnPropertyDescriptor;var Pe=Object.getOwnPropertyNames;var Fe=Object.getPrototypeOf,We=Object.prototype.hasOwnProperty;var Ge=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports);var Be=(i,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Pe(e))!We.call(i,s)&&s!==t&&ie(i,s,{get:()=>e[s],enumerable:!(n=Ke(e,s))||n.enumerable});return i};var qe=(i,e,t)=>(t=i!=null?Le(Fe(i)):{},Be(e||!i||!i.__esModule?ie(t,"default",{value:i,enumerable:!0}):t,i));var Re=Ge((sn,_e)=>{"use strict";var Te=i=>i&&i.CLOSING===2,et=()=>typeof WebSocket<"u"&&Te(WebSocket),tt=()=>({constructor:et()?WebSocket:null,maxReconnectionDelay:1e4,minReconnectionDelay:1500,reconnectionDelayGrowFactor:1.3,connectionTimeout:4e3,maxRetries:1/0,debug:!1}),nt=(i,e,t)=>{Object.defineProperty(e,t,{get:()=>i[t],set:n=>{i[t]=n},enumerable:!0,configurable:!0})},be=i=>i.minReconnectionDelay+Math.random()*i.minReconnectionDelay,st=(i,e)=>{let t=e*i.reconnectionDelayGrowFactor;return t>i.maxReconnectionDelay?i.maxReconnectionDelay:t},rt=["onopen","onclose","onmessage","onerror"],at=(i,e,t)=>{Object.keys(t).forEach(n=>{t[n].forEach(([s,o])=>{i.addEventListener(n,s,o)})}),e&&rt.forEach(n=>{i[n]=e[n]})},Ue=function(i,e,t={}){let n,s,o=0,c=0,u=!0,l={};if(!(this instanceof Ue))throw new TypeError("Failed to construct 'ReconnectingWebSocket': Please use the 'new' operator");let p=tt();if(Object.keys(p).filter(a=>t.hasOwnProperty(a)).forEach(a=>p[a]=t[a]),!Te(p.constructor))throw new TypeError("Invalid WebSocket constructor. Set `options.constructor`");let d=p.debug?(...a)=>console.log("RWS:",...a):()=>{},g=(a,y)=>setTimeout(()=>{let I=new Error(y);I.code=a,Array.isArray(l.error)&&l.error.forEach(([f])=>f(I)),n.onerror&&n.onerror(I)},0),r=()=>{if(d("close"),c++,d("retries count:",c),c>p.maxRetries){g("EHOSTDOWN","Too many failed connection attempts");return}o?o=st(p,o):o=be(p),d("reconnectDelay:",o),u&&setTimeout(m,o)},m=()=>{d("connect");let a=n;n=new p.constructor(i,e),s=setTimeout(()=>{d("timeout"),n.close(),g("ETIMEDOUT","Connection timeout")},p.connectionTimeout),d("bypass properties");for(let y in n)["addEventListener","removeEventListener","close","send"].indexOf(y)<0&&nt(n,this,y);n.addEventListener("open",()=>{clearTimeout(s),d("open"),o=be(p),d("reconnectDelay:",o),c=0}),n.addEventListener("close",r),at(n,a,l)};d("init"),m(),this.close=(a=1e3,y="",{keepClosed:I=!1,fastClose:f=!0,delay:k=0}={})=>{if(k&&(o=k),u=!I,n.close(a,y),f){let _={code:a,reason:y,wasClean:!0};r(),Array.isArray(l.close)&&l.close.forEach(([U,b])=>{U(_),n.removeEventListener("close",U,b)}),n.onclose&&(n.onclose(_),n.onclose=null)}},this.send=a=>{n.send(a)},this.addEventListener=(a,y,I)=>{Array.isArray(l[a])?l[a].some(([f])=>f===y)||l[a].push([y,I]):l[a]=[[y,I]],n.addEventListener(a,y,I)},this.removeEventListener=(a,y,I)=>{Array.isArray(l[a])&&(l[a]=l[a].filter(([f])=>f!==y)),n.removeEventListener(a,y,I)}};_e.exports=Ue});var le=(n=>(n.PRODUCTION="PRODUCTION",n.DEVELOPMENT="DEVELOPMENT",n.TEST="TEST",n))(le||{}),j=(t=>(t.CLIENT="CLIENT",t.SERVER="SERVER",t))(j||{}),Q=(a=>(a.IMAGE_INFERENCE="imageInference",a.IMAGE_UPLOAD="imageUpload",a.IMAGE_UPSCALE="imageUpscale",a.IMAGE_BACKGROUND_REMOVAL="imageBackgroundRemoval",a.VIDEO_INFERENCE="videoInference",a.GET_RESPONSE="getResponse",a.PHOTO_MAKER="photoMaker",a.IMAGE_CAPTION="imageCaption",a.IMAGE_CONTROL_NET_PRE_PROCESS="imageControlNetPreProcess",a.IMAGE_MASKING="imageMasking",a.PROMPT_ENHANCE="promptEnhance",a.AUTHENTICATION="authentication",a.MODEL_UPLOAD="modelUpload",a.MODEL_SEARCH="modelSearch",a))(Q||{}),ce=(n=>(n.BALANCED="balanced",n.PROMPT="prompt",n.CONTROL_NET="controlnet",n))(ce||{}),ue=(r=>(r.canny="canny",r.depth="depth",r.mlsd="mlsd",r.normalbae="normalbae",r.openpose="openpose",r.tile="tile",r.seg="seg",r.lineart="lineart",r.lineart_anime="lineart_anime",r.shuffle="shuffle",r.scribble="scribble",r.softedge="softedge",r))(ue||{}),de=(h=>(h.canny="canny",h.depth_leres="depth_leres",h.depth_midas="depth_midas",h.depth_zoe="depth_zoe",h.inpaint_global_harmonious="inpaint_global_harmonious",h.lineart_anime="lineart_anime",h.lineart_coarse="lineart_coarse",h.lineart_realistic="lineart_realistic",h.lineart_standard="lineart_standard",h.mlsd="mlsd",h.normal_bae="normal_bae",h.scribble_hed="scribble_hed",h.scribble_pidinet="scribble_pidinet",h.seg_ofade20k="seg_ofade20k",h.seg_ofcoco="seg_ofcoco",h.seg_ufade20k="seg_ufade20k",h.shuffle="shuffle",h.softedge_hed="softedge_hed",h.softedge_hedsafe="softedge_hedsafe",h.softedge_pidinet="softedge_pidinet",h.softedge_pidisafe="softedge_pidisafe",h.tile_gaussian="tile_gaussian",h.openpose="openpose",h.openpose_face="openpose_face",h.openpose_faceonly="openpose_faceonly",h.openpose_full="openpose_full",h.openpose_hand="openpose_hand",h))(de||{}),Ve=(o=>(o.openpose="openpose",o.openpose_face="openpose_face",o.openpose_faceonly="openpose_faceonly",o.openpose_full="openpose_full",o.openpose_hand="openpose_hand",o))(Ve||{}),He=(t=>(t.safetensors="safetensors",t.pickletensor="pickletensor",t))(He||{}),je=(m=>(m.flux1d="flux1d",m.flux1s="flux1s",m.pony="pony",m.sdhyper="sdhyper",m.sd1x="sd1x",m.sd1xlcm="sd1xlcm",m.sd3="sd3",m.sdxl="sdxl",m.sdxllcm="sdxllcm",m.sdxldistilled="sdxldistilled",m.sdxlhyper="sdxlhyper",m.sdxllightning="sdxllightning",m.sdxlturbo="sdxlturbo",m))(je||{}),Qe=(n=>(n.base="base",n.inpainting="inpainting",n.pix2pix="pix2pix",n))(Qe||{}),Je=(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))(Je||{}),Ye=(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))(Ye||{});import{v4 as ze,validate as Ze}from"uuid";var J=6e4,pe=1e3,$e=100,Y={PRODUCTION:"wss://ws-api.runware.ai/v1",TEST:"ws://localhost:8080"},ge=(i,e)=>{if(i==null)return;let t=i.indexOf(e);t!==-1&&i.splice(t,1)},S=(i,{debugKey:e="debugKey",timeoutDuration:t=J,shouldThrowError:n=!0})=>(t=t<pe?pe:t,new Promise((s,o)=>{let c=setTimeout(()=>{u&&(clearInterval(u),n&&o(`Response could not be received from server for ${e}`)),clearTimeout(c)},t),u=setInterval(async()=>{i({resolve:s,reject:o,intervalId:u})&&(clearInterval(u),clearTimeout(c))},$e)})),me=i=>new Promise(e=>{let t=new FileReader;t.readAsDataURL(i),t.onload=function(){e(t.result)}}),R=()=>ze(),ye=i=>Ze(i);var Ie=({key:i,data:e,useZero:t=!0,shouldReturnString:n=!1})=>i.split(/\.|\[/).map(c=>c.replace(/\]$/,"")).reduce((c,u)=>{let l=t?0:void 0,p=c?.[u];if(!p)return l;if(Array.isArray(p)&&/^\d+$/.test(u)){let d=parseInt(u,10);return d>=0&&d<p.length?c[u]=p[d]:c[u]??l}else return c[u]??l},e||{})??{},he=(i,e=1e3)=>new Promise(t=>setTimeout(t,i*e));var fe=(i,e)=>i.filter(t=>t.key!==e.key);var T=({key:i,value:e})=>e||e===0||e===!1?{[i]:e}:{},Xe=(i,e)=>Math.floor(Math.random()*(e-i+1))+i,z=()=>Xe(1,Number.MAX_SAFE_INTEGER);var x=async(i,e={})=>{let{delayInSeconds:t=1,callback:n}=e,s=e.maxRetries??1;for(;s;)try{return await i()}catch(o){if(n?.(),s--,s>0)await he(t),await x(i,{...e,maxRetries:s});else throw o}};var A=class{constructor({apiKey:e,url:t=Y.PRODUCTION,shouldReconnect:n=!0,globalMaxRetries:s=2,timeoutDuration:o=J}){this._listeners=[];this._globalMessages={};this._globalImages=[];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=R();if(typeof e=="string"&&ye(e))return{imageURL:e,imageUUID:e,taskUUID:t,taskType:"imageUpload"};let n=typeof e=="string"?e:await me(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:o,outputFormat:c,highThresholdCanny:u,lowThresholdCanny:l,includeHandsAndFaceOpenPose:p,includeCost:d,outputQuality:g,customTaskUUID:r,retry:m,includeGenerationTime:a,includePayload:y})=>{let I=m||this._globalMaxRetries,f,k=Date.now();try{return await x(async()=>{await this.ensureConnection();let _=await this.uploadImage(e);if(!_?.imageUUID)return null;let U=r||R(),b={inputImage:_.imageUUID,taskType:"imageControlNetPreProcess",taskUUID:U,preProcessorType:t,...T({key:"height",value:n}),...T({key:"width",value:s}),...T({key:"outputType",value:o}),...T({key:"outputFormat",value:c}),...T({key:"includeCost",value:d}),...T({key:"highThresholdCanny",value:u}),...T({key:"lowThresholdCanny",value:l}),...T({key:"includeHandsAndFaceOpenPose",value:p}),...g?{outputQuality:g}:{}};this.send({...b}),f=this.globalListener({taskUUID:U});let O=await S(({resolve:F,reject:W})=>{let v=this.getSingleMessage({taskUUID:U});if(v){if(v?.error)return W(v),!0;if(v)return F(v),!0}},{debugKey:"unprocessed-image",timeoutDuration:this._timeoutDuration});return f.destroy(),this.insertAdditionalResponse({response:O,payload:y?b:void 0,startTime:a?k:void 0}),O},{maxRetries:I,callback:()=>{f?.destroy()}})}catch(_){throw _}};this.requestImageToText=async({inputImage:e,includeCost:t,customTaskUUID:n,retry:s,includePayload:o,includeGenerationTime:c})=>{let u=s||this._globalMaxRetries,l,p=Date.now();try{return await x(async()=>{await this.ensureConnection();let d=e?await this.uploadImage(e):null,g=n||R(),r={taskUUID:g,taskType:"imageCaption",inputImage:d?.imageUUID,...T({key:"includeCost",value:t})};this.send(r),l=this.globalListener({taskUUID:g});let m=await S(({resolve:a,reject:y})=>{let I=this.getSingleMessage({taskUUID:g});if(I){if(I?.error)return y(I),!0;if(I)return delete this._globalMessages[g],a(I),!0}},{debugKey:"remove-image-background",timeoutDuration:this._timeoutDuration});return l.destroy(),this.insertAdditionalResponse({response:m,payload:o?r:void 0,startTime:c?p:void 0}),m},{maxRetries:u,callback:()=>{l?.destroy()}})}catch(d){throw d}};this.removeImageBackground=async e=>this.baseSingleRequest({payload:{...e,taskType:"imageBackgroundRemoval"},debugKey:"remove-image-background"});this.videoInference=async e=>this.baseSingleRequest({payload:{...e,deliveryMethod:"async",taskType:"videoInference"},debugKey:"video-inference"});this.getResponse=async e=>{let t=e.taskUUID;return this.baseSingleRequest({payload:{...e,customTaskUUID:t,taskType:"getResponse"},debugKey:"async-results"})};this.upscaleGan=async({inputImage:e,upscaleFactor:t,outputType:n,outputFormat:s,includeCost:o,outputQuality:c,customTaskUUID:u,retry:l,includeGenerationTime:p,includePayload:d})=>{let g=l||this._globalMaxRetries,r,m=Date.now();try{return await x(async()=>{await this.ensureConnection();let a;a=await this.uploadImage(e);let y=u||R(),I={taskUUID:y,inputImage:a?.imageUUID,taskType:"imageUpscale",upscaleFactor:t,...T({key:"includeCost",value:o}),...n?{outputType:n}:{},...c?{outputQuality:c}:{},...s?{outputFormat:s}:{}};this.send(I),r=this.globalListener({taskUUID:y});let f=await S(({resolve:k,reject:_})=>{let U=this.getSingleMessage({taskUUID:y});if(U){if(U?.error)return _(U),!0;if(U)return delete this._globalMessages[y],k(U),!0}},{debugKey:"upscale-gan",timeoutDuration:this._timeoutDuration});return r.destroy(),this.insertAdditionalResponse({response:f,payload:d?I:void 0,startTime:p?m:void 0}),f},{maxRetries:g,callback:()=>{r?.destroy()}})}catch(a){throw a}};this.enhancePrompt=async({prompt:e,promptMaxLength:t=380,promptVersions:n=1,includeCost:s,customTaskUUID:o,retry:c,includeGenerationTime:u,includePayload:l})=>{let p=c||this._globalMaxRetries,d,g=Date.now();try{return await x(async()=>{await this.ensureConnection();let r=o||R(),m={prompt:e,taskUUID:r,promptMaxLength:t,promptVersions:n,...T({key:"includeCost",value:s}),taskType:"promptEnhance"};this.send(m),d=this.globalListener({taskUUID:r});let a=await S(({resolve:y,reject:I})=>{let f=this._globalMessages[r];if(f?.error)return I(f),!0;if(f?.length>=n)return delete this._globalMessages[r],y(f),!0},{debugKey:"enhance-prompt",timeoutDuration:this._timeoutDuration});return d.destroy(),this.insertAdditionalResponse({response:a,payload:l?m:void 0,startTime:u?g:void 0}),a},{maxRetries:p,callback:()=>{d?.destroy()}})}catch(r){throw r}};this.modelUpload=async e=>{let{onUploadStream:t,retry:n,customTaskUUID:s,...o}=e,c=n||this._globalMaxRetries,u;try{return await x(async()=>{await this.ensureConnection();let l=s||R();this.send({...o,taskUUID:l,taskType:"modelUpload"});let p,d;return u=this.listenToUpload({taskUUID:l,onUploadStream:(r,m)=>{t?.(r,m),r?.status==="ready"?p=r:m&&(d=m)}}),await S(({resolve:r,reject:m})=>{if(p)return r(p),!0;if(d)return m(d),!1},{shouldThrowError:!1,timeoutDuration:60*60*1e3})},{maxRetries:c,callback:()=>{u?.destroy()}})}catch(l){throw l}};this.photoMaker=async(e,t)=>{let{onPartialImages:n,retry:s,customTaskUUID:o,numberResults:c,includeGenerationTime:u,includePayload:l,...p}=e,d=s||this._globalMaxRetries,g,r=[],m=0,a=Date.now();try{return await x(async()=>{await this.ensureConnection(),m++;let y=this._globalImages.filter(U=>r.includes(U.taskUUID)),I=o||R();r.push(I);let f=c-y.length,k={...p,...p.seed?{seed:p.seed}:{seed:z()},...t??{},taskUUID:I,taskType:"photoMaker",numberResults:c};this.send({...k,numberResults:f}),g=this.listenToImages({onPartialImages:n,taskUUID:I,groupKey:"REQUEST_IMAGES",requestPayload:l?k:void 0,startTime:u?a:void 0});let _=await this.getSimilarImages({taskUUID:r,numberResults:c,lis:g});return g.destroy(),_},{maxRetries:d,callback:()=>{g?.destroy()}})}catch(y){if(y.taskUUID)throw y;if(m>=d)return this.handleIncompleteImages({taskUUIDs:r,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.baseSingleRequest=async({payload:e,debugKey:t,mockResponse:n})=>{let{retry:s,customTaskUUID:o,includePayload:c,includeGenerationTime:u,...l}=e,p=s||this._globalMaxRetries,d,g=Date.now();try{return await x(async()=>{await this.ensureConnection();let r=o||R(),m={...l,taskUUID:r};n?setTimeout(()=>{this._globalMessages[r]=n},1e3):this.send(m),d=this.globalListener({taskUUID:r});let a=await S(({resolve:y,reject:I})=>{let f=this.getSingleMessage({taskUUID:r});if(f){if(f?.error)return I(f),!0;if(f)return delete this._globalMessages[r],y(f),!0}},{debugKey:t,timeoutDuration:this._timeoutDuration});return this.insertAdditionalResponse({response:a,payload:c?m:void 0,startTime:u?g:void 0}),d.destroy(),a},{maxRetries:p,callback:()=>{d?.destroy()}})}catch(r){throw r}};this.getSingleMessage=({taskUUID:e})=>{let t=this._globalMessages[e]?.[0],n=this._globalMessages[e];return!t&&!n?null:n?.error?n:t};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=o}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=u=>{let l=Array.isArray(u?.data)?u.data:[u.data],p=u?.[0]?.errors?u?.[0]?.errors:Array.isArray(u?.errors)?u.errors:[u.errors],d=l.filter(r=>(r?.taskUUID||r?.taskType)===n);if(p.filter(r=>(r?.taskUUID||r?.taskType)===n).length){e({error:{...p[0]??{}}});return}if(d.length){e({[n]:l});return}},o={key:n||R(),listener:s,groupKey:t};return this._listeners.push(o),{destroy:()=>{this._listeners=fe(this._listeners,o)}}}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){ge(this._listeners,e)}listenToImages({onPartialImages:e,taskUUID:t,groupKey:n,requestPayload:s,startTime:o}){return this.addListener({taskUUID:t,lis:c=>{let u=c?.[t]?.filter(l=>l.taskUUID===t);c.error?(e?.(u,c?.error&&c),this._globalError=c):(u=u.map(l=>(this.insertAdditionalResponse({response:l,payload:s||void 0,startTime:o||void 0}),{...l})),e?.(u,c?.error&&c),this._sdkType==="CLIENT"?this._globalImages=[...this._globalImages,...(c?.[t]??[]).map(l=>(this.insertAdditionalResponse({response:l,payload:s||void 0,startTime:o||void 0}),{...l}))]:this._globalImages=[...this._globalImages,...u])},groupKey:n})}listenToUpload({onUploadStream:e,taskUUID:t}){return this.addListener({taskUUID:t,lis:n=>{let s=n?.error,o=n?.[t]?.[0],c=o?.taskUUID===t?o:null;(c||s)&&e?.(c||void 0,s)}})}globalListener({taskUUID:e}){return this.addListener({taskUUID:e,lis:t=>{if(t.error){this._globalMessages[e]=t;return}let n=Ie({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:o,negativePrompt:c,seedImage:u,maskImage:l,strength:p,height:d,width:g,model:r,steps:m,scheduler:a,seed:y,CFGScale:I,clipSkip:f,usePromptWeighting:k,promptWeighting:_,numberResults:U=1,onPartialImages:b,includeCost:O,customTaskUUID:F,retry:W,refiner:v,maskMargin:xe,outputQuality:h,controlNet:G,lora:Z,embeddings:$,ipAdapters:X,outpaint:ee,acceleratorOptions:te,advancedFeatures:ne,referenceImages:se,includeGenerationTime:ve,includePayload:Se},we){let C,re,N=[],ae=0,oe=W||this._globalMaxRetries;try{await this.ensureConnection();let w=null,B=null,q=[];if(u){let D=await this.uploadImage(u);if(!D)return[];w=D.imageUUID}if(l){let D=await this.uploadImage(l);if(!D)return[];B=D.imageUUID}if(G?.length)for(let D=0;D<G.length;D++){let E=G[D],{endStep:V,startStep:M,weight:H,guideImage:L,controlMode:Ce,startStepPercentage:Ee,endStepPercentage:Oe,model:Ne}=E,Me=L?await this.uploadImage(L):null;q.push({guideImage:Me?.imageUUID,model:Ne,endStep:V,startStep:M,weight:H,...T({key:"startStepPercentage",value:Ee}),...T({key:"endStepPercentage",value:Oe}),controlMode:Ce||"controlnet"})}re={taskType:"imageInference",model:r,positivePrompt:o,...c?{negativePrompt:c}:{},...d?{height:d}:{},...g?{width:g}:{},numberResults:U,...e?{outputType:e}:{},...t?{outputFormat:t}:{},...n?{uploadEndpoint:n}:{},...T({key:"checkNSFW",value:s}),...T({key:"strength",value:p}),...T({key:"CFGScale",value:I}),...T({key:"clipSkip",value:f}),...T({key:"maskMargin",value:xe}),...T({key:"usePromptWeighting",value:k}),...T({key:"steps",value:m}),..._?{promptWeighting:_}:{},...y?{seed:y}:{seed:z()},...a?{scheduler:a}:{},...v?{refiner:v}:{},...ee?{outpaint:ee}:{},...T({key:"includeCost",value:O}),...w?{seedImage:w}:{},...B?{maskImage:B}:{},...h?{outputQuality:h}:{},...q.length?{controlNet:q}:{},...Z?.length?{lora:Z}:{},...$?.length?{embeddings:$}:{},...X?.length?{ipAdapters:X}:{},...te?{acceleratorOptions:te}:{},...ne?{advancedFeatures:ne}:{},...se?.length?{referenceImages:se}:{},...we??{}};let Ae=Date.now();return await x(async()=>{ae++,C?.destroy();let D=this._globalImages.filter(L=>N.includes(L.taskUUID)),E=F||R();N.push(E);let V=U-D.length,M={...re,taskUUID:E,numberResults:V};this.send(M),C=this.listenToImages({onPartialImages:b,taskUUID:E,groupKey:"REQUEST_IMAGES",requestPayload:Se?M:void 0,startTime:ve?Ae:void 0});let H=await this.getSimilarImages({taskUUID:N,numberResults:U,lis:C});return C.destroy(),H},{maxRetries:oe,callback:()=>{C?.destroy()}})}catch(w){if(ae>=oe)return this.handleIncompleteImages({taskUUIDs:N,error:w});throw w}}async ensureConnection(){if(this.connected()||this._url===Y.TEST)return;let t=2e3,n=200;try{if(this.isInvalidAPIKey())throw this._connectionError;return new Promise((s,o)=>{let c=0,u=30,l=R(),p,d,g=()=>{this.ensureConnectionUUID=null,clearInterval(p),clearInterval(d)};this._sdkType==="SERVER"&&(p=setInterval(async()=>{try{let r=this.connected(),m=!1;(!this.ensureConnectionUUID||l===this.ensureConnectionUUID)&&(this.ensureConnectionUUID||(this.ensureConnectionUUID=l),m=!0);let a=c%10===0&&m;r?(g(),s(!0)):c>=u?(g(),o(new Error("Retry timed out"))):(a&&this.connect(),c++)}catch(r){g(),o(r)}},t)),d=setInterval(async()=>{if(this.connected()){g(),s(!0);return}if(this.isInvalidAPIKey()){g(),o(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 getSimilarImages({taskUUID:e,numberResults:t,shouldThrowError:n,lis:s}){return await S(({resolve:o,reject:c,intervalId:u})=>{let l=Array.isArray(e)?e:[e],p=this._globalImages.filter(d=>l.includes(d.taskUUID));if(this._globalError){let d=this._globalError;return this._globalError=void 0,clearInterval(u),c?.(d),!0}else if(p.length>=t)return clearInterval(u),this._globalImages=this._globalImages.filter(d=>!l.includes(d.taskUUID)),o([...p].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 ke=qe(Re(),1),K=class extends A{constructor(e){let{shouldReconnect:t,...n}=e;super(n),this._ws=new ke.default(this._url),this.connect()}};import ot from"ws";var P=class extends A{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 ot(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 o=JSON.parse(s);this._listeners.forEach(c=>{c.listener(o)})}))}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 De;typeof window>"u"?De=P:De=K;export{ce as EControlMode,je as EModelArchitecture,Je as EModelConditioning,He as EModelFormat,Qe as EModelType,Ve as EOpenPosePreProcessor,Ye as EPhotoMakerEnum,de as EPreProcessor,ue as EPreProcessorGroup,Q as ETaskType,le as Environment,De as Runware,K as RunwareClient,P as RunwareServer,j as SdkType};
1
+ var Ke=Object.create;var le=Object.defineProperty;var We=Object.getOwnPropertyDescriptor;var Fe=Object.getOwnPropertyNames;var Ge=Object.getPrototypeOf,Be=Object.prototype.hasOwnProperty;var qe=(u,t)=>()=>(t||u((t={exports:{}}).exports,t),t.exports);var Ve=(u,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Fe(t))!Be.call(u,s)&&s!==e&&le(u,s,{get:()=>t[s],enumerable:!(n=We(t,s))||n.enumerable});return u};var He=(u,t,e)=>(e=u!=null?Ke(Ge(u)):{},Ve(t||!u||!u.__esModule?le(e,"default",{value:u,enumerable:!0}):e,u));var De=qe((an,ke)=>{"use strict";var _e=u=>u&&u.CLOSING===2,tt=()=>typeof WebSocket<"u"&&_e(WebSocket),nt=()=>({constructor:tt()?WebSocket:null,maxReconnectionDelay:1e4,minReconnectionDelay:1500,reconnectionDelayGrowFactor:1.3,connectionTimeout:4e3,maxRetries:1/0,debug:!1}),st=(u,t,e)=>{Object.defineProperty(t,e,{get:()=>u[e],set:n=>{u[e]=n},enumerable:!0,configurable:!0})},Ue=u=>u.minReconnectionDelay+Math.random()*u.minReconnectionDelay,rt=(u,t)=>{let e=t*u.reconnectionDelayGrowFactor;return e>u.maxReconnectionDelay?u.maxReconnectionDelay:e},at=["onopen","onclose","onmessage","onerror"],ot=(u,t,e)=>{Object.keys(e).forEach(n=>{e[n].forEach(([s,a])=>{u.addEventListener(n,s,a)})}),t&&at.forEach(n=>{u[n]=t[n]})},Re=function(u,t,e={}){let n,s,a=0,i=0,c=!0,r={};if(!(this instanceof Re))throw new TypeError("Failed to construct 'ReconnectingWebSocket': Please use the 'new' operator");let p=nt();if(Object.keys(p).filter(o=>e.hasOwnProperty(o)).forEach(o=>p[o]=e[o]),!_e(p.constructor))throw new TypeError("Invalid WebSocket constructor. Set `options.constructor`");let d=p.debug?(...o)=>console.log("RWS:",...o):()=>{},m=(o,y)=>setTimeout(()=>{let I=new Error(y);I.code=o,Array.isArray(r.error)&&r.error.forEach(([b])=>b(I)),n.onerror&&n.onerror(I)},0),l=()=>{if(d("close"),i++,d("retries count:",i),i>p.maxRetries){m("EHOSTDOWN","Too many failed connection attempts");return}a?a=rt(p,a):a=Ue(p),d("reconnectDelay:",a),c&&setTimeout(g,a)},g=()=>{d("connect");let o=n;n=new p.constructor(u,t),s=setTimeout(()=>{d("timeout"),n.close(),m("ETIMEDOUT","Connection timeout")},p.connectionTimeout),d("bypass properties");for(let y in n)["addEventListener","removeEventListener","close","send"].indexOf(y)<0&&st(n,this,y);n.addEventListener("open",()=>{clearTimeout(s),d("open"),a=Ue(p),d("reconnectDelay:",a),i=0}),n.addEventListener("close",l),ot(n,o,r)};d("init"),g(),this.close=(o=1e3,y="",{keepClosed:I=!1,fastClose:b=!0,delay:_=0}={})=>{if(_&&(a=_),c=!I,n.close(o,y),b){let R={code:o,reason:y,wasClean:!0};l(),Array.isArray(r.close)&&r.close.forEach(([U,f])=>{U(R),n.removeEventListener("close",U,f)}),n.onclose&&(n.onclose(R),n.onclose=null)}},this.send=o=>{n.send(o)},this.addEventListener=(o,y,I)=>{Array.isArray(r[o])?r[o].some(([b])=>b===y)||r[o].push([y,I]):r[o]=[[y,I]],n.addEventListener(o,y,I)},this.removeEventListener=(o,y,I)=>{Array.isArray(r[o])&&(r[o]=r[o].filter(([b])=>b!==y)),n.removeEventListener(o,y,I)}};ke.exports=Re});var ce=(n=>(n.PRODUCTION="PRODUCTION",n.DEVELOPMENT="DEVELOPMENT",n.TEST="TEST",n))(ce||{}),J=(e=>(e.CLIENT="CLIENT",e.SERVER="SERVER",e))(J||{}),z=(o=>(o.IMAGE_INFERENCE="imageInference",o.IMAGE_UPLOAD="imageUpload",o.IMAGE_UPSCALE="imageUpscale",o.IMAGE_BACKGROUND_REMOVAL="imageBackgroundRemoval",o.VIDEO_INFERENCE="videoInference",o.GET_RESPONSE="getResponse",o.PHOTO_MAKER="photoMaker",o.IMAGE_CAPTION="imageCaption",o.IMAGE_CONTROL_NET_PRE_PROCESS="imageControlNetPreProcess",o.IMAGE_MASKING="imageMasking",o.PROMPT_ENHANCE="promptEnhance",o.AUTHENTICATION="authentication",o.MODEL_UPLOAD="modelUpload",o.MODEL_SEARCH="modelSearch",o))(z||{}),ue=(n=>(n.BALANCED="balanced",n.PROMPT="prompt",n.CONTROL_NET="controlnet",n))(ue||{}),de=(l=>(l.canny="canny",l.depth="depth",l.mlsd="mlsd",l.normalbae="normalbae",l.openpose="openpose",l.tile="tile",l.seg="seg",l.lineart="lineart",l.lineart_anime="lineart_anime",l.shuffle="shuffle",l.scribble="scribble",l.softedge="softedge",l))(de||{}),pe=(h=>(h.canny="canny",h.depth_leres="depth_leres",h.depth_midas="depth_midas",h.depth_zoe="depth_zoe",h.inpaint_global_harmonious="inpaint_global_harmonious",h.lineart_anime="lineart_anime",h.lineart_coarse="lineart_coarse",h.lineart_realistic="lineart_realistic",h.lineart_standard="lineart_standard",h.mlsd="mlsd",h.normal_bae="normal_bae",h.scribble_hed="scribble_hed",h.scribble_pidinet="scribble_pidinet",h.seg_ofade20k="seg_ofade20k",h.seg_ofcoco="seg_ofcoco",h.seg_ufade20k="seg_ufade20k",h.shuffle="shuffle",h.softedge_hed="softedge_hed",h.softedge_hedsafe="softedge_hedsafe",h.softedge_pidinet="softedge_pidinet",h.softedge_pidisafe="softedge_pidisafe",h.tile_gaussian="tile_gaussian",h.openpose="openpose",h.openpose_face="openpose_face",h.openpose_faceonly="openpose_faceonly",h.openpose_full="openpose_full",h.openpose_hand="openpose_hand",h))(pe||{}),je=(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))(je||{}),Qe=(e=>(e.safetensors="safetensors",e.pickletensor="pickletensor",e))(Qe||{}),Je=(g=>(g.flux1d="flux1d",g.flux1s="flux1s",g.pony="pony",g.sdhyper="sdhyper",g.sd1x="sd1x",g.sd1xlcm="sd1xlcm",g.sd3="sd3",g.sdxl="sdxl",g.sdxllcm="sdxllcm",g.sdxldistilled="sdxldistilled",g.sdxlhyper="sdxlhyper",g.sdxllightning="sdxllightning",g.sdxlturbo="sdxlturbo",g))(Je||{}),ze=(n=>(n.base="base",n.inpainting="inpainting",n.pix2pix="pix2pix",n))(ze||{}),Ye=(f=>(f.canny="canny",f.depth="depth",f.qrcode="qrcode",f.hed="hed",f.scrible="scrible",f.openpose="openpose",f.seg="segmentation",f.openmlsd="openmlsd",f.softedge="softedge",f.normal="normal bae",f.shuffle="shuffle",f.pix2pix="pix2pix",f.inpaint="inpaint",f.lineart="line art",f.sketch="sketch",f.inpaintdepth="inpaint depth",f.tile="tile",f.outfit="outfit",f.blur="blur",f.gray="gray",f.lowquality="low quality",f))(Ye||{}),$e=(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))($e||{});import{v4 as Ze,validate as Xe}from"uuid";var K=6e4,P=1e3,ge=100,Y={PRODUCTION:"wss://ws-api.runware.ai/v1",TEST:"ws://localhost:8080"},me=(u,t)=>{if(u==null)return;let e=u.indexOf(t);e!==-1&&u.splice(e,1)},w=(u,{debugKey:t="debugKey",timeoutDuration:e=K,shouldThrowError:n=!0,pollingInterval:s=ge})=>(e=e<P?P:e,new Promise((a,i)=>{let c=setTimeout(()=>{r&&(clearInterval(r),n&&i(`Response could not be received from server for ${t}`)),clearTimeout(c)},e),r=setInterval(async()=>{u({resolve:a,reject:i,intervalId:r})&&(clearInterval(r),clearTimeout(c))},s)})),ye=u=>new Promise(t=>{let e=new FileReader;e.readAsDataURL(u),e.onload=function(){t(e.result)}}),k=()=>Ze(),Ie=u=>Xe(u);var he=({key:u,data:t,useZero:e=!0,shouldReturnString:n=!1})=>u.split(/\.|\[/).map(i=>i.replace(/\]$/,"")).reduce((i,c)=>{let r=e?0:void 0,p=i?.[c];if(!p)return r;if(Array.isArray(p)&&/^\d+$/.test(c)){let d=parseInt(c,10);return d>=0&&d<p.length?i[c]=p[d]:i[c]??r}else return i[c]??r},t||{})??{},fe=(u,t=1e3)=>new Promise(e=>setTimeout(e,u*t));var be=(u,t)=>u.filter(e=>e.key!==t.key);var T=({key:u,value:t})=>t||t===0||t===!1?{[u]:t}:{},et=(u,t)=>Math.floor(Math.random()*(t-u+1))+u,$=()=>et(1,Number.MAX_SAFE_INTEGER);var Te=(u,{debugKey:t="debugKey",timeoutDuration:e=K,shouldThrowError:n=!0,pollingInterval:s=ge})=>(e=e<P?P:e,new Promise((a,i)=>{let c=setTimeout(()=>{r&&(clearInterval(r),n&&i(`Response could not be received from server for ${t}`)),clearTimeout(c)},e),r=setInterval(async()=>{try{await u({resolve:a,reject:i,intervalId:r})&&(clearInterval(r),clearTimeout(c))}catch(p){clearInterval(r),clearTimeout(c),i(p)}},s)}));var v=async(u,t={})=>{let{delayInSeconds:e=1,callback:n}=t,s=t.maxRetries??1;for(;s;)try{return await u()}catch(a){if(n?.(),a?.error)throw a;if(s--,s>0)await fe(e),await v(u,{...t,maxRetries:s});else throw a}};var A=class{constructor({apiKey:t,url:e=Y.PRODUCTION,shouldReconnect:n=!0,globalMaxRetries:s=2,timeoutDuration:a=K}){this._listeners=[];this._globalMessages={};this._globalImages=[];this.ensureConnectionUUID=null;this.isWebsocketReadyState=()=>this._ws?.readyState===1;this.isInvalidAPIKey=()=>this._connectionError?.error?.code==="invalidApiKey";this.send=t=>{this._ws.send(JSON.stringify([t]))};this.uploadImage=async t=>{try{return await v(async()=>{let e=k();if(typeof t=="string"&&Ie(t))return{imageURL:t,imageUUID:t,taskUUID:e,taskType:"imageUpload"};let n=typeof t=="string"?t:await ye(t);return{imageURL:n,imageUUID:n,taskUUID:e,taskType:"imageUpload"}})}catch(e){throw e}};this.controlNetPreProcess=async({inputImage:t,preProcessorType:e,height:n,width:s,outputType:a,outputFormat:i,highThresholdCanny:c,lowThresholdCanny:r,includeHandsAndFaceOpenPose:p,includeCost:d,outputQuality:m,customTaskUUID:l,retry:g,includeGenerationTime:o,includePayload:y})=>{let I=g||this._globalMaxRetries,b,_=Date.now();try{return await v(async()=>{await this.ensureConnection();let R=await this.uploadImage(t);if(!R?.imageUUID)return null;let U=l||k(),f={inputImage:R.imageUUID,taskType:"imageControlNetPreProcess",taskUUID:U,preProcessorType:e,...T({key:"height",value:n}),...T({key:"width",value:s}),...T({key:"outputType",value:a}),...T({key:"outputFormat",value:i}),...T({key:"includeCost",value:d}),...T({key:"highThresholdCanny",value:c}),...T({key:"lowThresholdCanny",value:r}),...T({key:"includeHandsAndFaceOpenPose",value:p}),...m?{outputQuality:m}:{}};this.send({...f}),b=this.globalListener({taskUUID:U});let M=await w(({resolve:G,reject:B})=>{let x=this.getSingleMessage({taskUUID:U});if(x){if(x?.error)return B(x),!0;if(x)return G(x),!0}},{debugKey:"unprocessed-image",timeoutDuration:this._timeoutDuration});return b.destroy(),this.insertAdditionalResponse({response:M,payload:y?f:void 0,startTime:o?_:void 0}),M},{maxRetries:I,callback:()=>{b?.destroy()}})}catch(R){throw R}};this.requestImageToText=async({inputImage:t,includeCost:e,customTaskUUID:n,retry:s,includePayload:a,includeGenerationTime:i})=>{let c=s||this._globalMaxRetries,r,p=Date.now();try{return await v(async()=>{await this.ensureConnection();let d=t?await this.uploadImage(t):null,m=n||k(),l={taskUUID:m,taskType:"imageCaption",inputImage:d?.imageUUID,...T({key:"includeCost",value:e})};this.send(l),r=this.globalListener({taskUUID:m});let g=await w(({resolve:o,reject:y})=>{let I=this.getSingleMessage({taskUUID:m});if(I){if(I?.error)return y(I),!0;if(I)return delete this._globalMessages[m],o(I),!0}},{debugKey:"remove-image-background",timeoutDuration:this._timeoutDuration});return r.destroy(),this.insertAdditionalResponse({response:g,payload:a?l:void 0,startTime:i?p:void 0}),g},{maxRetries:c,callback:()=>{r?.destroy()}})}catch(d){throw d}};this.removeImageBackground=async t=>this.baseSingleRequest({payload:{...t,taskType:"imageBackgroundRemoval"},debugKey:"remove-image-background"});this.videoInference=async t=>{let{skipResponse:e,...n}=t;try{let s=await this.baseSingleRequest({payload:{...n,deliveryMethod:"async",taskType:"videoInference"},debugKey:"video-inference"});if(e)return s;let a=s?.taskUUID,i=t?.numberResults??1,c=new Map;return await Te(async({resolve:r,reject:p})=>{try{let d=await this.getResponse({taskUUID:a});for(let l of d||[])l.videoUUID&&c.set(l.videoUUID,l);return c.size===i?(r(Array.from(c.values())),!0):!1}catch(d){return p(d),!0}},{debugKey:"async-response",pollingInterval:2*1e3,timeoutDuration:10*60*1e3}),Array.from(c.values())}catch(s){throw s}};this.getResponse=async t=>{let e=t.taskUUID;return this.baseSingleRequest({payload:{...t,customTaskUUID:e,taskType:"getResponse"},isMultiple:!0,debugKey:"async-results"})};this.upscaleGan=async({inputImage:t,upscaleFactor:e,outputType:n,outputFormat:s,includeCost:a,outputQuality:i,customTaskUUID:c,retry:r,includeGenerationTime:p,includePayload:d})=>{let m=r||this._globalMaxRetries,l,g=Date.now();try{return await v(async()=>{await this.ensureConnection();let o;o=await this.uploadImage(t);let y=c||k(),I={taskUUID:y,inputImage:o?.imageUUID,taskType:"imageUpscale",upscaleFactor:e,...T({key:"includeCost",value:a}),...n?{outputType:n}:{},...i?{outputQuality:i}:{},...s?{outputFormat:s}:{}};this.send(I),l=this.globalListener({taskUUID:y});let b=await w(({resolve:_,reject:R})=>{let U=this.getSingleMessage({taskUUID:y});if(U){if(U?.error)return R(U),!0;if(U)return delete this._globalMessages[y],_(U),!0}},{debugKey:"upscale-gan",timeoutDuration:this._timeoutDuration});return l.destroy(),this.insertAdditionalResponse({response:b,payload:d?I:void 0,startTime:p?g:void 0}),b},{maxRetries:m,callback:()=>{l?.destroy()}})}catch(o){throw o}};this.enhancePrompt=async({prompt:t,promptMaxLength:e=380,promptVersions:n=1,includeCost:s,customTaskUUID:a,retry:i,includeGenerationTime:c,includePayload:r})=>{let p=i||this._globalMaxRetries,d,m=Date.now();try{return await v(async()=>{await this.ensureConnection();let l=a||k(),g={prompt:t,taskUUID:l,promptMaxLength:e,promptVersions:n,...T({key:"includeCost",value:s}),taskType:"promptEnhance"};this.send(g),d=this.globalListener({taskUUID:l});let o=await w(({resolve:y,reject:I})=>{let b=this._globalMessages[l];if(b?.error)return I(b),!0;if(b?.length>=n)return delete this._globalMessages[l],y(b),!0},{debugKey:"enhance-prompt",timeoutDuration:this._timeoutDuration});return d.destroy(),this.insertAdditionalResponse({response:o,payload:r?g:void 0,startTime:c?m:void 0}),o},{maxRetries:p,callback:()=>{d?.destroy()}})}catch(l){throw l}};this.modelUpload=async t=>{let{onUploadStream:e,retry:n,customTaskUUID:s,...a}=t,i=n||this._globalMaxRetries,c;try{return await v(async()=>{await this.ensureConnection();let r=s||k();this.send({...a,taskUUID:r,taskType:"modelUpload"});let p,d;return c=this.listenToUpload({taskUUID:r,onUploadStream:(l,g)=>{e?.(l,g),l?.status==="ready"?p=l:g&&(d=g)}}),await w(({resolve:l,reject:g})=>{if(p)return l(p),!0;if(d)return g(d),!1},{shouldThrowError:!1,timeoutDuration:60*60*1e3})},{maxRetries:i,callback:()=>{c?.destroy()}})}catch(r){throw r}};this.photoMaker=async(t,e)=>{let{onPartialImages:n,retry:s,customTaskUUID:a,numberResults:i,includeGenerationTime:c,includePayload:r,...p}=t,d=s||this._globalMaxRetries,m,l=[],g=0,o=Date.now();try{return await v(async()=>{await this.ensureConnection(),g++;let y=this._globalImages.filter(U=>l.includes(U.taskUUID)),I=a||k();l.push(I);let b=i-y.length,_={...p,...p.seed?{seed:p.seed}:{seed:$()},...e??{},taskUUID:I,taskType:"photoMaker",numberResults:i};this.send({..._,numberResults:b}),m=this.listenToImages({onPartialImages:n,taskUUID:I,groupKey:"REQUEST_IMAGES",requestPayload:r?_:void 0,startTime:c?o:void 0});let R=await this.getSimilarImages({taskUUID:l,numberResults:i,lis:m});return m.destroy(),R},{maxRetries:d,callback:()=>{m?.destroy()}})}catch(y){if(y.taskUUID)throw y;if(g>=d)return this.handleIncompleteImages({taskUUIDs:l,error:y})}};this.modelSearch=async t=>this.baseSingleRequest({payload:{...t,taskType:"modelSearch"},debugKey:"model-search"});this.imageMasking=async t=>this.baseSingleRequest({payload:{...t,taskType:"imageMasking"},debugKey:"image-masking"});this.imageUpload=async t=>this.baseSingleRequest({payload:{...t,taskType:"imageUpload"},debugKey:"image-upload"});this.baseSingleRequest=async({payload:t,debugKey:e,mockResponse:n,isMultiple:s})=>{let{retry:a,customTaskUUID:i,includePayload:c,includeGenerationTime:r,...p}=t,d=a||this._globalMaxRetries,m,l=Date.now();try{return await v(async()=>{await this.ensureConnection();let g=i||k(),o={...p,taskUUID:g};n?setTimeout(()=>{this._globalMessages[g]=n},1e3):this.send(o),m=this.globalListener({taskUUID:g});let y=await w(({resolve:I,reject:b})=>{let _=s?this.getMultipleMessages({taskUUID:g}):this.getSingleMessage({taskUUID:g});if(_){if(_?.error)return b(_),!0;if(_)return delete this._globalMessages[g],I(_),!0}},{debugKey:e,timeoutDuration:this._timeoutDuration});return this.insertAdditionalResponse({response:y,payload:c?o:void 0,startTime:r?l:void 0}),m.destroy(),y},{maxRetries:d,callback:()=>{m?.destroy()}})}catch(g){throw g}};this.getSingleMessage=({taskUUID:t})=>{let e=this._globalMessages[t]?.[0],n=this._globalMessages[t];return!e&&!n?null:n?.error?n:e};this.getMultipleMessages=({taskUUID:t})=>{let e=this._globalMessages[t]?.[0],n=this._globalMessages[t];return!e&&!n?null:n};this.insertAdditionalResponse=({response:t,payload:e,startTime:n})=>{if(!e&&!n)return;let s=t;s.additionalResponse={},e&&(t.additionalResponse.payload=e),n&&(t.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=t,this._url=e,this._sdkType="CLIENT",this._shouldReconnect=n,this._globalMaxRetries=s,this._timeoutDuration=a}static async initialize(t){try{let e=new this(t);return await e.ensureConnection(),e}catch(e){throw e}}addListener({lis:t,groupKey:e,taskUUID:n}){let s=c=>{let r=Array.isArray(c?.data)?c.data:[c.data],p=c?.[0]?.errors?c?.[0]?.errors:Array.isArray(c?.errors)?c.errors:[c.errors],d=r.filter(l=>(l?.taskUUID||l?.taskType)===n);if(p.filter(l=>(l?.taskUUID||l?.taskType)===n).length){t({error:{...p[0]??{}}});return}if(d.length){t({[n]:r});return}},a={key:n||k(),listener:s,groupKey:e};return this._listeners.push(a),{destroy:()=>{this._listeners=be(this._listeners,a)}}}connect(){this._ws.onopen=t=>{this._connectionSessionUUID?this.send({taskType:"authentication",apiKey:this._apiKey,connectionSessionUUID:this._connectionSessionUUID}):this.send({apiKey:this._apiKey,taskType:"authentication"}),this.addListener({taskUUID:"authentication",lis:e=>{if(e?.error){this._connectionError=e;return}this._connectionSessionUUID=e?.authentication?.[0]?.connectionSessionUUID,this._connectionError=void 0}})},this._ws.onmessage=t=>{let e=JSON.parse(t.data);for(let n of this._listeners)if(n?.listener?.(e))return},this._ws.onclose=t=>{this.isInvalidAPIKey()}}destroy(t){me(this._listeners,t)}listenToImages({onPartialImages:t,taskUUID:e,groupKey:n,requestPayload:s,startTime:a}){return this.addListener({taskUUID:e,lis:i=>{let c=i?.[e]?.filter(r=>r.taskUUID===e);i.error?(t?.(c,i?.error&&i),this._globalError=i):(c=c.map(r=>(this.insertAdditionalResponse({response:r,payload:s||void 0,startTime:a||void 0}),{...r})),t?.(c,i?.error&&i),this._sdkType==="CLIENT"?this._globalImages=[...this._globalImages,...(i?.[e]??[]).map(r=>(this.insertAdditionalResponse({response:r,payload:s||void 0,startTime:a||void 0}),{...r}))]:this._globalImages=[...this._globalImages,...c])},groupKey:n})}listenToUpload({onUploadStream:t,taskUUID:e}){return this.addListener({taskUUID:e,lis:n=>{let s=n?.error,a=n?.[e]?.[0],i=a?.taskUUID===e?a:null;(i||s)&&t?.(i||void 0,s)}})}globalListener({taskUUID:t}){return this.addListener({taskUUID:t,lis:e=>{if(e.error){this._globalMessages[t]=e;return}let n=he({key:t,data:e,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:t,outputFormat:e,uploadEndpoint:n,checkNSFW:s,positivePrompt:a,negativePrompt:i,seedImage:c,maskImage:r,strength:p,height:d,width:m,model:l,steps:g,scheduler:o,seed:y,CFGScale:I,clipSkip:b,usePromptWeighting:_,promptWeighting:R,numberResults:U=1,onPartialImages:f,includeCost:M,customTaskUUID:G,retry:B,refiner:x,maskMargin:we,outputQuality:h,controlNet:q,lora:Z,embeddings:X,ipAdapters:ee,outpaint:te,acceleratorOptions:ne,advancedFeatures:se,referenceImages:re,includeGenerationTime:Se,includePayload:Ae},Ce){let C,ae,O=[],oe=0,ie=B||this._globalMaxRetries;try{await this.ensureConnection();let S=null,V=null,H=[];if(c){let D=await this.uploadImage(c);if(!D)return[];S=D.imageUUID}if(r){let D=await this.uploadImage(r);if(!D)return[];V=D.imageUUID}if(q?.length)for(let D=0;D<q.length;D++){let E=q[D],{endStep:j,startStep:N,weight:Q,guideImage:L,controlMode:Me,startStepPercentage:Oe,endStepPercentage:Ne,model:Le}=E,Pe=L?await this.uploadImage(L):null;H.push({guideImage:Pe?.imageUUID,model:Le,endStep:j,startStep:N,weight:Q,...T({key:"startStepPercentage",value:Oe}),...T({key:"endStepPercentage",value:Ne}),controlMode:Me||"controlnet"})}ae={taskType:"imageInference",model:l,positivePrompt:a,...i?{negativePrompt:i}:{},...d?{height:d}:{},...m?{width:m}:{},numberResults:U,...t?{outputType:t}:{},...e?{outputFormat:e}:{},...n?{uploadEndpoint:n}:{},...T({key:"checkNSFW",value:s}),...T({key:"strength",value:p}),...T({key:"CFGScale",value:I}),...T({key:"clipSkip",value:b}),...T({key:"maskMargin",value:we}),...T({key:"usePromptWeighting",value:_}),...T({key:"steps",value:g}),...R?{promptWeighting:R}:{},...y?{seed:y}:{seed:$()},...o?{scheduler:o}:{},...x?{refiner:x}:{},...te?{outpaint:te}:{},...T({key:"includeCost",value:M}),...S?{seedImage:S}:{},...V?{maskImage:V}:{},...h?{outputQuality:h}:{},...H.length?{controlNet:H}:{},...Z?.length?{lora:Z}:{},...X?.length?{embeddings:X}:{},...ee?.length?{ipAdapters:ee}:{},...ne?{acceleratorOptions:ne}:{},...se?{advancedFeatures:se}:{},...re?.length?{referenceImages:re}:{},...Ce??{}};let Ee=Date.now();return await v(async()=>{oe++,C?.destroy();let D=this._globalImages.filter(L=>O.includes(L.taskUUID)),E=G||k();O.push(E);let j=U-D.length,N={...ae,taskUUID:E,numberResults:j};this.send(N),C=this.listenToImages({onPartialImages:f,taskUUID:E,groupKey:"REQUEST_IMAGES",requestPayload:Ae?N:void 0,startTime:Se?Ee:void 0});let Q=await this.getSimilarImages({taskUUID:O,numberResults:U,lis:C});return C.destroy(),Q},{maxRetries:ie,callback:()=>{C?.destroy()}})}catch(S){if(oe>=ie)return this.handleIncompleteImages({taskUUIDs:O,error:S});throw S}}async ensureConnection(){if(this.connected()||this._url===Y.TEST)return;let e=2e3,n=200;try{if(this.isInvalidAPIKey())throw this._connectionError;return new Promise((s,a)=>{let i=0,c=30,r=k(),p,d,m=()=>{this.ensureConnectionUUID=null,clearInterval(p),clearInterval(d)};this._sdkType==="SERVER"&&(p=setInterval(async()=>{try{let l=this.connected(),g=!1;(!this.ensureConnectionUUID||r===this.ensureConnectionUUID)&&(this.ensureConnectionUUID||(this.ensureConnectionUUID=r),g=!0);let o=i%10===0&&g;l?(m(),s(!0)):i>=c?(m(),a(new Error("Retry timed out"))):(o&&this.connect(),i++)}catch(l){m(),a(l)}},e)),d=setInterval(async()=>{if(this.connected()){m(),s(!0);return}if(this.isInvalidAPIKey()){m(),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 getSimilarImages({taskUUID:t,numberResults:e,shouldThrowError:n,lis:s}){return await w(({resolve:a,reject:i,intervalId:c})=>{let r=Array.isArray(t)?t:[t],p=this._globalImages.filter(d=>r.includes(d.taskUUID));if(this._globalError){let d=this._globalError;return this._globalError=void 0,clearInterval(c),i?.(d),!0}else if(p.length>=e)return clearInterval(c),this._globalImages=this._globalImages.filter(d=>!r.includes(d.taskUUID)),a([...p].slice(0,e)),!0},{debugKey:"getting images",shouldThrowError:n,timeoutDuration:this._timeoutDuration})}handleIncompleteImages({taskUUIDs:t,error:e}){let n=this._globalImages.filter(s=>t.includes(s.taskUUID));if(n.length>1)return this._globalImages=this._globalImages.filter(s=>!t.includes(s.taskUUID)),n;throw e}};var ve=He(De(),1),W=class extends A{constructor(t){let{shouldReconnect:e,...n}=t;super(n),this._ws=new ve.default(this._url),this.connect()}};import it from"ws";var F=class extends A{constructor(e){super(e);this._instantiated=!1;this._listeners=[];this._reconnectingIntervalId=null;this.send=e=>{this._ws.send(JSON.stringify([e]))};this.resetConnection=()=>{this._ws&&(this._listeners.forEach(e=>{e?.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 it(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:e=>{if(e?.error){this._connectionError=e;return}this._connectionSessionUUID=e?.authentication?.[0]?.connectionSessionUUID,this._connectionError=void 0}})}),this._ws.on("message",(e,n)=>{let s=n?e:e?.toString();if(!s)return;let a=JSON.parse(s);this._listeners.forEach(i=>{i.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 xe;typeof window>"u"?xe=F:xe=W;export{ue as EControlMode,Je as EModelArchitecture,Ye as EModelConditioning,Qe as EModelFormat,ze as EModelType,je as EOpenPosePreProcessor,$e as EPhotoMakerEnum,pe as EPreProcessor,de as EPreProcessorGroup,z as ETaskType,ce as Environment,xe as Runware,W as RunwareClient,F as RunwareServer,J as SdkType};
2
2
  //# sourceMappingURL=index.js.map