@runware/sdk-js 1.1.36 → 1.1.37

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
@@ -125,15 +125,23 @@ interface IRequestImage {
125
125
  promptWeighting?: TPromptWeighting;
126
126
  numberResults?: number;
127
127
  includeCost?: boolean;
128
- customTaskUUID?: string;
129
128
  outputQuality?: number;
130
129
  controlNet?: IControlNet[];
131
130
  lora?: ILora[];
132
131
  embeddings?: IEmbedding[];
133
132
  ipAdapters?: IipAdapter[];
133
+ outpaint?: IOutpaint;
134
+ refiner?: IRefiner;
135
+ customTaskUUID?: string;
134
136
  onPartialImages?: (images: IImage[], error?: IError) => void;
135
137
  retry?: number;
136
- refiner?: IRefiner;
138
+ }
139
+ interface IOutpaint {
140
+ top?: number;
141
+ bottom?: number;
142
+ right?: number;
143
+ left?: number;
144
+ blur?: number;
137
145
  }
138
146
  interface IEmbedding {
139
147
  model: string;
@@ -335,21 +343,25 @@ type TAddModelLora = {
335
343
  } & TAddModelBaseType;
336
344
  type TAddModel = TAddModelCheckPoint | TAddModelControlNet | TAddModelLora;
337
345
  type TPhotoMaker = {
338
- model?: string;
339
- inputImages: string[];
340
346
  style: EPhotoMakerEnum;
341
- strength?: number;
347
+ inputImages: string[];
348
+ outputType?: string;
349
+ outputFormat?: string;
350
+ uploadEndpoint?: string;
351
+ checkNSFW?: boolean;
342
352
  positivePrompt: string;
343
353
  negativePrompt?: string;
354
+ strength?: number;
344
355
  height: number;
345
356
  width: number;
346
- scheduler?: string;
357
+ model?: string;
347
358
  steps?: number;
359
+ scheduler?: string;
360
+ seed?: number;
348
361
  CFGScale?: number;
349
- outputFormat?: string;
350
- includeCost?: boolean;
362
+ clipSkip?: number;
351
363
  numberResults: number;
352
- seed?: number;
364
+ includeCost?: boolean;
353
365
  outputQuality?: number;
354
366
  customTaskUUID?: string;
355
367
  retry?: number;
@@ -542,14 +554,14 @@ declare class RunwareBase {
542
554
  private listenToImages;
543
555
  private listenToUpload;
544
556
  private globalListener;
545
- requestImages({ outputType, outputFormat, uploadEndpoint, checkNSFW, positivePrompt, negativePrompt, seedImage, maskImage, strength, height, width, model, steps, scheduler, seed, CFGScale, clipSkip, usePromptWeighting, promptWeighting, numberResults, onPartialImages, includeCost, customTaskUUID, retry, refiner, maskMargin, outputQuality, controlNet, lora, embeddings, ipAdapters, }: IRequestImage, moreOptions?: Record<string, any>): Promise<ITextToImage[] | undefined>;
557
+ requestImages({ outputType, outputFormat, uploadEndpoint, checkNSFW, positivePrompt, negativePrompt, seedImage, maskImage, strength, height, width, model, steps, scheduler, seed, CFGScale, clipSkip, usePromptWeighting, promptWeighting, numberResults, onPartialImages, includeCost, customTaskUUID, retry, refiner, maskMargin, outputQuality, controlNet, lora, embeddings, ipAdapters, outpaint, }: IRequestImage, moreOptions?: Record<string, any>): Promise<ITextToImage[] | undefined>;
546
558
  controlNetPreProcess: ({ inputImage, preProcessorType, height, width, outputType, outputFormat, highThresholdCanny, lowThresholdCanny, includeHandsAndFaceOpenPose, includeCost, outputQuality, customTaskUUID, retry, }: IControlNetPreprocess) => Promise<IControlNetImage | null>;
547
559
  requestImageToText: ({ inputImage, includeCost, customTaskUUID, retry, }: IRequestImageToText) => Promise<IImageToText>;
548
560
  removeImageBackground: ({ inputImage, outputType, outputFormat, rgba, postProcessMask, returnOnlyMask, alphaMatting, alphaMattingForegroundThreshold, alphaMattingBackgroundThreshold, alphaMattingErodeSize, outputQuality, includeCost, customTaskUUID, retry, }: IRemoveImageBackground) => Promise<IRemoveImage>;
549
561
  upscaleGan: ({ inputImage, upscaleFactor, outputType, outputFormat, includeCost, outputQuality, customTaskUUID, retry, }: IUpscaleGan) => Promise<IImage>;
550
562
  enhancePrompt: ({ prompt, promptMaxLength, promptVersions, includeCost, customTaskUUID, retry, }: IPromptEnhancer) => Promise<IEnhancedPrompt[]>;
551
563
  modelUpload: (payload: TAddModel) => Promise<any>;
552
- photoMaker: (payload: TPhotoMaker) => Promise<TPhotoMakerResponse[] | undefined>;
564
+ photoMaker: (payload: TPhotoMaker, moreOptions?: Record<string, any>) => Promise<TPhotoMakerResponse[] | undefined>;
553
565
  modelSearch: (payload: TModelSearch) => Promise<TModelSearchResponse>;
554
566
  imageMasking: (payload: TImageMasking) => Promise<TImageMaskingResponse>;
555
567
  protected baseSingleRequest: <T>({ payload, debugKey, }: {
@@ -584,4 +596,4 @@ declare class RunwareServer extends RunwareBase {
584
596
 
585
597
  declare let Runware: typeof RunwareClient | typeof RunwareServer;
586
598
 
587
- export { EControlMode, EModelArchitecture, EModelConditioning, EModelFormat, EModelType, EOpenPosePreProcessor, EPhotoMakerEnum, EPreProcessor, EPreProcessorGroup, ETaskType, Environment, type GetWithPromiseCallBackType, type IAddModelResponse, type IControlNet, type IControlNetGeneral, type IControlNetImage, type IControlNetPreprocess, type IControlNetWithUUID, type IEmbedding, type IEnhancedPrompt, type IError, type IErrorResponse, type IImage, type IImageToText, type IOutputFormat, type IOutputType, type IPromptEnhancer, type IRefiner, type IRemoveImage, type IRemoveImageBackground, type IRequestImage, type IRequestImageToText, type ITextToImage, type IUpscaleGan, type IipAdapter, type ListenerType, type ReconnectingWebsocketProps, type RequireAtLeastOne, type RequireOnlyOne, Runware, type RunwareBaseType, RunwareClient, RunwareServer, SdkType, type TAddModel, type TAddModelBaseType, type TAddModelCheckPoint, type TAddModelControlNet, type TAddModelLora, type TImageMasking, type TImageMaskingResponse, type TModel, type TModelSearch, type TModelSearchResponse, type TPhotoMaker, type TPhotoMakerResponse, type TPromptWeighting, type TServerError, type UploadImageType };
599
+ export { EControlMode, EModelArchitecture, EModelConditioning, EModelFormat, EModelType, EOpenPosePreProcessor, EPhotoMakerEnum, EPreProcessor, EPreProcessorGroup, ETaskType, Environment, type GetWithPromiseCallBackType, type IAddModelResponse, 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 ITextToImage, type IUpscaleGan, type IipAdapter, type ListenerType, type ReconnectingWebsocketProps, type RequireAtLeastOne, type RequireOnlyOne, Runware, type RunwareBaseType, RunwareClient, RunwareServer, SdkType, type TAddModel, type TAddModelBaseType, type TAddModelCheckPoint, type TAddModelControlNet, type TAddModelLora, type TImageMasking, type TImageMaskingResponse, type TModel, type TModelSearch, type TModelSearchResponse, type TPhotoMaker, type TPhotoMakerResponse, type TPromptWeighting, type TServerError, type UploadImageType };
package/dist/index.d.ts CHANGED
@@ -125,15 +125,23 @@ interface IRequestImage {
125
125
  promptWeighting?: TPromptWeighting;
126
126
  numberResults?: number;
127
127
  includeCost?: boolean;
128
- customTaskUUID?: string;
129
128
  outputQuality?: number;
130
129
  controlNet?: IControlNet[];
131
130
  lora?: ILora[];
132
131
  embeddings?: IEmbedding[];
133
132
  ipAdapters?: IipAdapter[];
133
+ outpaint?: IOutpaint;
134
+ refiner?: IRefiner;
135
+ customTaskUUID?: string;
134
136
  onPartialImages?: (images: IImage[], error?: IError) => void;
135
137
  retry?: number;
136
- refiner?: IRefiner;
138
+ }
139
+ interface IOutpaint {
140
+ top?: number;
141
+ bottom?: number;
142
+ right?: number;
143
+ left?: number;
144
+ blur?: number;
137
145
  }
138
146
  interface IEmbedding {
139
147
  model: string;
@@ -335,21 +343,25 @@ type TAddModelLora = {
335
343
  } & TAddModelBaseType;
336
344
  type TAddModel = TAddModelCheckPoint | TAddModelControlNet | TAddModelLora;
337
345
  type TPhotoMaker = {
338
- model?: string;
339
- inputImages: string[];
340
346
  style: EPhotoMakerEnum;
341
- strength?: number;
347
+ inputImages: string[];
348
+ outputType?: string;
349
+ outputFormat?: string;
350
+ uploadEndpoint?: string;
351
+ checkNSFW?: boolean;
342
352
  positivePrompt: string;
343
353
  negativePrompt?: string;
354
+ strength?: number;
344
355
  height: number;
345
356
  width: number;
346
- scheduler?: string;
357
+ model?: string;
347
358
  steps?: number;
359
+ scheduler?: string;
360
+ seed?: number;
348
361
  CFGScale?: number;
349
- outputFormat?: string;
350
- includeCost?: boolean;
362
+ clipSkip?: number;
351
363
  numberResults: number;
352
- seed?: number;
364
+ includeCost?: boolean;
353
365
  outputQuality?: number;
354
366
  customTaskUUID?: string;
355
367
  retry?: number;
@@ -542,14 +554,14 @@ declare class RunwareBase {
542
554
  private listenToImages;
543
555
  private listenToUpload;
544
556
  private globalListener;
545
- requestImages({ outputType, outputFormat, uploadEndpoint, checkNSFW, positivePrompt, negativePrompt, seedImage, maskImage, strength, height, width, model, steps, scheduler, seed, CFGScale, clipSkip, usePromptWeighting, promptWeighting, numberResults, onPartialImages, includeCost, customTaskUUID, retry, refiner, maskMargin, outputQuality, controlNet, lora, embeddings, ipAdapters, }: IRequestImage, moreOptions?: Record<string, any>): Promise<ITextToImage[] | undefined>;
557
+ requestImages({ outputType, outputFormat, uploadEndpoint, checkNSFW, positivePrompt, negativePrompt, seedImage, maskImage, strength, height, width, model, steps, scheduler, seed, CFGScale, clipSkip, usePromptWeighting, promptWeighting, numberResults, onPartialImages, includeCost, customTaskUUID, retry, refiner, maskMargin, outputQuality, controlNet, lora, embeddings, ipAdapters, outpaint, }: IRequestImage, moreOptions?: Record<string, any>): Promise<ITextToImage[] | undefined>;
546
558
  controlNetPreProcess: ({ inputImage, preProcessorType, height, width, outputType, outputFormat, highThresholdCanny, lowThresholdCanny, includeHandsAndFaceOpenPose, includeCost, outputQuality, customTaskUUID, retry, }: IControlNetPreprocess) => Promise<IControlNetImage | null>;
547
559
  requestImageToText: ({ inputImage, includeCost, customTaskUUID, retry, }: IRequestImageToText) => Promise<IImageToText>;
548
560
  removeImageBackground: ({ inputImage, outputType, outputFormat, rgba, postProcessMask, returnOnlyMask, alphaMatting, alphaMattingForegroundThreshold, alphaMattingBackgroundThreshold, alphaMattingErodeSize, outputQuality, includeCost, customTaskUUID, retry, }: IRemoveImageBackground) => Promise<IRemoveImage>;
549
561
  upscaleGan: ({ inputImage, upscaleFactor, outputType, outputFormat, includeCost, outputQuality, customTaskUUID, retry, }: IUpscaleGan) => Promise<IImage>;
550
562
  enhancePrompt: ({ prompt, promptMaxLength, promptVersions, includeCost, customTaskUUID, retry, }: IPromptEnhancer) => Promise<IEnhancedPrompt[]>;
551
563
  modelUpload: (payload: TAddModel) => Promise<any>;
552
- photoMaker: (payload: TPhotoMaker) => Promise<TPhotoMakerResponse[] | undefined>;
564
+ photoMaker: (payload: TPhotoMaker, moreOptions?: Record<string, any>) => Promise<TPhotoMakerResponse[] | undefined>;
553
565
  modelSearch: (payload: TModelSearch) => Promise<TModelSearchResponse>;
554
566
  imageMasking: (payload: TImageMasking) => Promise<TImageMaskingResponse>;
555
567
  protected baseSingleRequest: <T>({ payload, debugKey, }: {
@@ -584,4 +596,4 @@ declare class RunwareServer extends RunwareBase {
584
596
 
585
597
  declare let Runware: typeof RunwareClient | typeof RunwareServer;
586
598
 
587
- export { EControlMode, EModelArchitecture, EModelConditioning, EModelFormat, EModelType, EOpenPosePreProcessor, EPhotoMakerEnum, EPreProcessor, EPreProcessorGroup, ETaskType, Environment, type GetWithPromiseCallBackType, type IAddModelResponse, type IControlNet, type IControlNetGeneral, type IControlNetImage, type IControlNetPreprocess, type IControlNetWithUUID, type IEmbedding, type IEnhancedPrompt, type IError, type IErrorResponse, type IImage, type IImageToText, type IOutputFormat, type IOutputType, type IPromptEnhancer, type IRefiner, type IRemoveImage, type IRemoveImageBackground, type IRequestImage, type IRequestImageToText, type ITextToImage, type IUpscaleGan, type IipAdapter, type ListenerType, type ReconnectingWebsocketProps, type RequireAtLeastOne, type RequireOnlyOne, Runware, type RunwareBaseType, RunwareClient, RunwareServer, SdkType, type TAddModel, type TAddModelBaseType, type TAddModelCheckPoint, type TAddModelControlNet, type TAddModelLora, type TImageMasking, type TImageMaskingResponse, type TModel, type TModelSearch, type TModelSearchResponse, type TPhotoMaker, type TPhotoMakerResponse, type TPromptWeighting, type TServerError, type UploadImageType };
599
+ export { EControlMode, EModelArchitecture, EModelConditioning, EModelFormat, EModelType, EOpenPosePreProcessor, EPhotoMakerEnum, EPreProcessor, EPreProcessorGroup, ETaskType, Environment, type GetWithPromiseCallBackType, type IAddModelResponse, 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 ITextToImage, type IUpscaleGan, type IipAdapter, type ListenerType, type ReconnectingWebsocketProps, type RequireAtLeastOne, type RequireOnlyOne, Runware, type RunwareBaseType, RunwareClient, RunwareServer, SdkType, type TAddModel, type TAddModelBaseType, type TAddModelCheckPoint, type TAddModelControlNet, type TAddModelLora, type TImageMasking, type TImageMaskingResponse, 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 we=Object.create;var te=Object.defineProperty;var Ae=Object.getOwnPropertyDescriptor;var Ce=Object.getOwnPropertyNames;var Me=Object.getPrototypeOf,Ee=Object.prototype.hasOwnProperty;var Ne=(c,t)=>()=>(t||c((t={exports:{}}).exports,t),t.exports);var Oe=(c,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of Ce(t))!Ee.call(c,a)&&a!==e&&te(c,a,{get:()=>t[a],enumerable:!(n=Ae(t,a))||n.enumerable});return c};var Le=(c,t,e)=>(e=c!=null?we(Me(c)):{},Oe(t||!c||!c.__esModule?te(e,"default",{value:c,enumerable:!0}):e,c));var he=Ne((Ht,Ie)=>{"use strict";var me=c=>c&&c.CLOSING===2,Qe=()=>typeof WebSocket<"u"&&me(WebSocket),Je=()=>({constructor:Qe()?WebSocket:null,maxReconnectionDelay:1e4,minReconnectionDelay:1500,reconnectionDelayGrowFactor:1.3,connectionTimeout:4e3,maxRetries:1/0,debug:!1}),ze=(c,t,e)=>{Object.defineProperty(t,e,{get:()=>c[e],set:n=>{c[e]=n},enumerable:!0,configurable:!0})},pe=c=>c.minReconnectionDelay+Math.random()*c.minReconnectionDelay,Ye=(c,t)=>{let e=t*c.reconnectionDelayGrowFactor;return e>c.maxReconnectionDelay?c.maxReconnectionDelay:e},Ze=["onopen","onclose","onmessage","onerror"],$e=(c,t,e)=>{Object.keys(e).forEach(n=>{e[n].forEach(([a,o])=>{c.addEventListener(n,a,o)})}),t&&Ze.forEach(n=>{c[n]=t[n]})},ye=function(c,t,e={}){let n,a,o=0,i=0,l=!0,s={};if(!(this instanceof ye))throw new TypeError("Failed to construct 'ReconnectingWebSocket': Please use the 'new' operator");let u=Je();if(Object.keys(u).filter(m=>e.hasOwnProperty(m)).forEach(m=>u[m]=e[m]),!me(u.constructor))throw new TypeError("Invalid WebSocket constructor. Set `options.constructor`");let g=u.debug?(...m)=>console.log("RWS:",...m):()=>{},d=(m,f)=>setTimeout(()=>{let b=new Error(f);b.code=m,Array.isArray(s.error)&&s.error.forEach(([T])=>T(b)),n.onerror&&n.onerror(b)},0),r=()=>{if(g("close"),i++,g("retries count:",i),i>u.maxRetries){d("EHOSTDOWN","Too many failed connection attempts");return}o?o=Ye(u,o):o=pe(u),g("reconnectDelay:",o),l&&setTimeout(p,o)},p=()=>{g("connect");let m=n;n=new u.constructor(c,t),a=setTimeout(()=>{g("timeout"),n.close(),d("ETIMEDOUT","Connection timeout")},u.connectionTimeout),g("bypass properties");for(let f in n)["addEventListener","removeEventListener","close","send"].indexOf(f)<0&&ze(n,this,f);n.addEventListener("open",()=>{clearTimeout(a),g("open"),o=pe(u),g("reconnectDelay:",o),i=0}),n.addEventListener("close",r),$e(n,m,s)};g("init"),p(),this.close=(m=1e3,f="",{keepClosed:b=!1,fastClose:T=!0,delay:k=0}={})=>{if(k&&(o=k),l=!b,n.close(m,f),T){let D={code:m,reason:f,wasClean:!0};r(),Array.isArray(s.close)&&s.close.forEach(([x,y])=>{x(D),n.removeEventListener("close",x,y)}),n.onclose&&(n.onclose(D),n.onclose=null)}},this.send=m=>{n.send(m)},this.addEventListener=(m,f,b)=>{Array.isArray(s[m])?s[m].some(([T])=>T===f)||s[m].push([f,b]):s[m]=[[f,b]],n.addEventListener(m,f,b)},this.removeEventListener=(m,f,b)=>{Array.isArray(s[m])&&(s[m]=s[m].filter(([T])=>T!==f)),n.removeEventListener(m,f,b)}};Ie.exports=ye});var ne=(n=>(n.PRODUCTION="PRODUCTION",n.DEVELOPMENT="DEVELOPMENT",n.TEST="TEST",n))(ne||{}),q=(e=>(e.CLIENT="CLIENT",e.SERVER="SERVER",e))(q||{}),H=(r=>(r.IMAGE_INFERENCE="imageInference",r.IMAGE_UPLOAD="imageUpload",r.IMAGE_UPSCALE="imageUpscale",r.IMAGE_BACKGROUND_REMOVAL="imageBackgroundRemoval",r.IMAGE_CAPTION="imageCaption",r.IMAGE_CONTROL_NET_PRE_PROCESS="imageControlNetPreProcess",r.PROMPT_ENHANCE="promptEnhance",r.AUTHENTICATION="authentication",r.MODEL_UPLOAD="modelUpload",r.PHOTO_MAKER="photoMaker",r.MODEL_SEARCH="modelSearch",r.IMAGE_MASKING="imageMasking",r))(H||{}),re=(n=>(n.BALANCED="balanced",n.PROMPT="prompt",n.CONTROL_NET="controlnet",n))(re||{}),se=(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))(se||{}),ae=(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))(ae||{}),Ke=(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))(Ke||{}),We=(e=>(e.safetensors="safetensors",e.pickletensor="pickletensor",e))(We||{}),Fe=(p=>(p.flux1d="flux1d",p.flux1s="flux1s",p.pony="pony",p.sdhyper="sdhyper",p.sd1x="sd1x",p.sd1xlcm="sd1xlcm",p.sd3="sd3",p.sdxl="sdxl",p.sdxllcm="sdxllcm",p.sdxldistilled="sdxldistilled",p.sdxlhyper="sdxlhyper",p.sdxllightning="sdxllightning",p.sdxlturbo="sdxlturbo",p))(Fe||{}),Pe=(n=>(n.base="base",n.inpainting="inpainting",n.pix2pix="pix2pix",n))(Pe||{}),Ge=(y=>(y.canny="canny",y.depth="depth",y.qrcode="qrcode",y.hed="hed",y.scrible="scrible",y.openpose="openpose",y.seg="segmentation",y.openmlsd="openmlsd",y.softedge="softedge",y.normal="normal bae",y.shuffle="shuffle",y.pix2pix="pix2pix",y.inpaint="inpaint",y.lineart="line art",y.sketch="sketch",y.inpaintdepth="inpaint depth",y.tile="tile",y.outfit="outfit",y.blur="blur",y.gray="gray",y.lowquality="low quality",y))(Ge||{}),Be=(d=>(d.NoStyle="No style",d.Cinematic="Cinematic",d.DisneyCharacter="Disney Character",d.DigitalArt="Digital Art",d.Photographic="Photographic",d.FantasyArt="Fantasy art",d.Neonpunk="Neonpunk",d.Enhance="Enhance",d.ComicBook="Comic book",d.Lowpoly="Lowpoly",d.LineArt="Line art",d))(Be||{});import{v4 as qe,validate as He}from"uuid";var V=6e4,oe=1e3,Ve=100,j={PRODUCTION:"wss://ws-api.runware.ai/v1",TEST:"ws://localhost:8080"},ie=(c,t)=>{if(c==null)return;let e=c.indexOf(t);e!==-1&&c.splice(e,1)},v=(c,{debugKey:t="debugKey",timeoutDuration:e=V,shouldThrowError:n=!0})=>(e=e<oe?oe:e,new Promise((a,o)=>{let i=setTimeout(()=>{l&&(clearInterval(l),n&&o(`Response could not be received from server for ${t}`)),clearTimeout(i)},e),l=setInterval(async()=>{c({resolve:a,reject:o,intervalId:l})&&(clearInterval(l),clearTimeout(i))},Ve)})),le=c=>new Promise(t=>{let e=new FileReader;e.readAsDataURL(c),e.onload=function(){t(e.result)}}),U=()=>qe(),ce=c=>He(c);var ue=({key:c,data:t,useZero:e=!0,shouldReturnString:n=!1})=>c.split(/\.|\[/).map(i=>i.replace(/\]$/,"")).reduce((i,l)=>{let s=e?0:void 0,u=i?.[l];if(!u)return s;if(Array.isArray(u)&&/^\d+$/.test(l)){let g=parseInt(l,10);return g>=0&&g<u.length?i[l]=u[g]:i[l]??s}else return i[l]??s},t||{})??{},ge=(c,t=1e3)=>new Promise(e=>setTimeout(e,c*t));var de=(c,t)=>c.filter(e=>e.key!==t.key);var I=({key:c,value:t})=>t||t===0||t===!1?{[c]:t}:{},je=(c,t)=>Math.floor(Math.random()*(t-c+1))+c,Q=()=>je(1,Number.MAX_SAFE_INTEGER);var _=async(c,t={})=>{let{delayInSeconds:e=1,callback:n}=t,a=t.maxRetries??1;for(;a;)try{return await c()}catch(o){if(n?.(),a--,a>0)await ge(e),await _(c,{...t,maxRetries:a});else throw o}};var A=class{constructor({apiKey:t,url:e=j.PRODUCTION,shouldReconnect:n=!0,globalMaxRetries:a=2,timeoutDuration:o=V}){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 _(async()=>{let e=U();if(typeof t=="string"&&ce(t))return{imageURL:t,imageUUID:t,taskUUID:e,taskType:"imageUpload"};let n=typeof t=="string"?t:await le(t);return{imageURL:n,imageUUID:n,taskUUID:e,taskType:"imageUpload"}})}catch(e){throw e}};this.controlNetPreProcess=async({inputImage:t,preProcessorType:e,height:n,width:a,outputType:o,outputFormat:i,highThresholdCanny:l,lowThresholdCanny:s,includeHandsAndFaceOpenPose:u,includeCost:g,outputQuality:d,customTaskUUID:r,retry:p})=>{let m=p||this._globalMaxRetries,f;try{return await _(async()=>{await this.ensureConnection();let b=await this.uploadImage(t);if(!b?.imageUUID)return null;let T=r||U();this.send({inputImage:b.imageUUID,taskType:"imageControlNetPreProcess",taskUUID:T,preProcessorType:e,...I({key:"height",value:n}),...I({key:"width",value:a}),...I({key:"outputType",value:o}),...I({key:"outputFormat",value:i}),...I({key:"includeCost",value:g}),...I({key:"highThresholdCanny",value:l}),...I({key:"lowThresholdCanny",value:s}),...I({key:"includeHandsAndFaceOpenPose",value:u}),...d?{outputQuality:d}:{}}),f=this.globalListener({taskUUID:T});let k=await v(({resolve:D,reject:x})=>{let y=this.getSingleMessage({taskUUID:T});if(y){if(y?.error)return x(y),!0;if(y)return D(y),!0}},{debugKey:"unprocessed-image",timeoutDuration:this._timeoutDuration});return f.destroy(),k},{maxRetries:m,callback:()=>{f?.destroy()}})}catch(b){throw b}};this.requestImageToText=async({inputImage:t,includeCost:e,customTaskUUID:n,retry:a})=>{let o=a||this._globalMaxRetries,i;try{return await _(async()=>{await this.ensureConnection();let l=t?await this.uploadImage(t):null,s=n||U();this.send({taskUUID:s,taskType:"imageCaption",inputImage:l?.imageUUID,...I({key:"includeCost",value:e})}),i=this.globalListener({taskUUID:s});let u=await v(({resolve:g,reject:d})=>{let r=this.getSingleMessage({taskUUID:s});if(r){if(r?.error)return d(r),!0;if(r)return delete this._globalMessages[s],g(r),!0}},{debugKey:"remove-image-background",timeoutDuration:this._timeoutDuration});return i.destroy(),u},{maxRetries:o,callback:()=>{i?.destroy()}})}catch(l){throw l}};this.removeImageBackground=async({inputImage:t,outputType:e,outputFormat:n,rgba:a,postProcessMask:o,returnOnlyMask:i,alphaMatting:l,alphaMattingForegroundThreshold:s,alphaMattingBackgroundThreshold:u,alphaMattingErodeSize:g,outputQuality:d,includeCost:r,customTaskUUID:p,retry:m})=>{let f=m||this._globalMaxRetries,b;try{return await _(async()=>{await this.ensureConnection();let T=t?await this.uploadImage(t):null,k=p||U();this.send({taskType:"imageBackgroundRemoval",taskUUID:k,inputImage:T?.imageUUID,...I({key:"rgba",value:a}),...I({key:"postProcessMask",value:o}),...I({key:"returnOnlyMask",value:i}),...I({key:"alphaMatting",value:l}),...I({key:"includeCost",value:r}),...I({key:"alphaMattingForegroundThreshold",value:s}),...I({key:"alphaMattingBackgroundThreshold",value:u}),...I({key:"alphaMattingErodeSize",value:g}),...I({key:"outputType",value:e}),...I({key:"outputFormat",value:n}),...d?{outputQuality:d}:{}}),b=this.globalListener({taskUUID:k});let D=await v(({resolve:x,reject:y})=>{let S=this.getSingleMessage({taskUUID:k});if(S){if(S?.error)return y(S),!0;if(S)return delete this._globalMessages[k],x(S),!0}},{debugKey:"remove-image-background",timeoutDuration:this._timeoutDuration});return b.destroy(),D},{maxRetries:f,callback:()=>{b?.destroy()}})}catch(T){throw T}};this.upscaleGan=async({inputImage:t,upscaleFactor:e,outputType:n,outputFormat:a,includeCost:o,outputQuality:i,customTaskUUID:l,retry:s})=>{let u=s||this._globalMaxRetries,g;try{return await _(async()=>{await this.ensureConnection();let d;d=await this.uploadImage(t);let r=l||U();this.send({taskUUID:r,inputImage:d?.imageUUID,taskType:"imageUpscale",upscaleFactor:e,...I({key:"includeCost",value:o}),...n?{outputType:n}:{},...i?{outputQuality:i}:{},...a?{outputFormat:a}:{}}),g=this.globalListener({taskUUID:r});let p=await v(({resolve:m,reject:f})=>{let b=this.getSingleMessage({taskUUID:r});if(b){if(b?.error)return f(b),!0;if(b)return delete this._globalMessages[r],m(b),!0}},{debugKey:"upscale-gan",timeoutDuration:this._timeoutDuration});return g.destroy(),p},{maxRetries:u,callback:()=>{g?.destroy()}})}catch(d){throw d}};this.enhancePrompt=async({prompt:t,promptMaxLength:e=380,promptVersions:n=1,includeCost:a,customTaskUUID:o,retry:i})=>{let l=i||this._globalMaxRetries,s;try{return await _(async()=>{await this.ensureConnection();let u=o||U();this.send({prompt:t,taskUUID:u,promptMaxLength:e,promptVersions:n,...I({key:"includeCost",value:a}),taskType:"promptEnhance"}),s=this.globalListener({taskUUID:u});let g=await v(({resolve:d,reject:r})=>{let p=this._globalMessages[u];if(p?.error)return r(p),!0;if(p?.length>=n)return delete this._globalMessages[u],d(p),!0},{debugKey:"enhance-prompt",timeoutDuration:this._timeoutDuration});return s.destroy(),g},{maxRetries:l,callback:()=>{s?.destroy()}})}catch(u){throw u}};this.modelUpload=async t=>{let{onUploadStream:e,retry:n,customTaskUUID:a,...o}=t,i=n||this._globalMaxRetries,l;try{return await _(async()=>{await this.ensureConnection();let s=a||U();this.send({...o,taskUUID:s,taskType:"modelUpload"});let u,g;return l=this.listenToUpload({taskUUID:s,onUploadStream:(r,p)=>{e?.(r,p),r?.status==="ready"?u=r:p&&(g=p)}}),await v(({resolve:r,reject:p})=>{if(u)return r(u),!0;if(g)return p(g),!1},{shouldThrowError:!1,timeoutDuration:60*60*1e3})},{maxRetries:i,callback:()=>{l?.destroy()}})}catch(s){throw s}};this.photoMaker=async t=>{let{onPartialImages:e,retry:n,customTaskUUID:a,numberResults:o,...i}=t,l=n||this._globalMaxRetries,s,u=[],g=0;try{return await _(async()=>{await this.ensureConnection(),g++;let d=this._globalImages.filter(f=>u.includes(f.taskUUID)),r=a||U();u.push(r);let p=o-d.length;this.send({...i,...i.seed?{seed:i.seed}:{seed:Q()},numberResults:p,taskUUID:r,taskType:"photoMaker"}),s=this.listenToImages({onPartialImages:e,taskUUID:r,groupKey:"REQUEST_IMAGES",positivePrompt:i.positivePrompt});let m=await this.getSimilarImages({taskUUID:u,numberResults:o,lis:s});return s.destroy(),m},{maxRetries:l,callback:()=>{s?.destroy()}})}catch(d){if(d.taskUUID)throw d;if(g>=l)return this.handleIncompleteImages({taskUUIDs:u,error:d})}};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.baseSingleRequest=async({payload:t,debugKey:e})=>{let{retry:n,customTaskUUID:a,...o}=t,i=n||this._globalMaxRetries,l;try{return await _(async()=>{await this.ensureConnection();let s=a||U();this.send({...o,taskUUID:s}),l=this.globalListener({taskUUID:s});let u=await v(({resolve:g,reject:d})=>{let r=this.getSingleMessage({taskUUID:s});if(r){if(r?.error)return d(r),!0;if(r)return delete this._globalMessages[s],g(r),!0}},{debugKey:e,timeoutDuration:this._timeoutDuration});return l.destroy(),u},{maxRetries:i,callback:()=>{l?.destroy()}})}catch(s){throw s}};this.getSingleMessage=({taskUUID:t})=>{let e=this._globalMessages[t]?.[0],n=this._globalMessages[t];return!e&&!n?null:n?.error?n:e};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=a,this._timeoutDuration=o}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 a=l=>{let s=Array.isArray(l?.data)?l.data:[l.data],u=l?.[0]?.errors?l?.[0]?.errors:Array.isArray(l?.errors)?l.errors:[l.errors],g=s.filter(r=>(r?.taskUUID||r?.taskType)===n);if(u.filter(r=>(r?.taskUUID||r?.taskType)===n).length){t({error:{...u[0]??{}}});return}if(g.length){t({[n]:s});return}},o={key:n||U(),listener:a,groupKey:e};return this._listeners.push(o),{destroy:()=>{this._listeners=de(this._listeners,o)}}}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){ie(this._listeners,t)}listenToImages({onPartialImages:t,taskUUID:e,groupKey:n,positivePrompt:a,negativePrompt:o}){return this.addListener({taskUUID:e,lis:i=>{let l=i?.[e]?.filter(s=>s.taskUUID===e);i.error?(t?.(l,i?.error&&i),this._globalError=i):(l=l.map(s=>({...s,positivePrompt:a,negativePrompt:o})),t?.(l,i?.error&&i),this._sdkType==="CLIENT"?this._globalImages=[...this._globalImages,...(i?.[e]??[]).map(s=>({...s,positivePrompt:a,negativePrompt:o}))]:this._globalImages=[...this._globalImages,...l])},groupKey:n})}listenToUpload({onUploadStream:t,taskUUID:e}){return this.addListener({taskUUID:e,lis:n=>{let a=n?.error,o=n?.[e]?.[0],i=o?.taskUUID===e?o:null;(i||a)&&t?.(i||void 0,a)}})}globalListener({taskUUID:t}){return this.addListener({taskUUID:t,lis:e=>{if(e.error){this._globalMessages[t]=e;return}let n=ue({key:t,data:e,useZero:!1});Array.isArray(n)?n.forEach(a=>{this._globalMessages[a.taskUUID]=[...this._globalMessages[a.taskUUID]??[],a]}):this._globalMessages[n.taskUUID]=n}})}async requestImages({outputType:t,outputFormat:e,uploadEndpoint:n,checkNSFW:a,positivePrompt:o,negativePrompt:i,seedImage:l,maskImage:s,strength:u,height:g,width:d,model:r,steps:p,scheduler:m,seed:f,CFGScale:b,clipSkip:T,usePromptWeighting:k,promptWeighting:D,numberResults:x=1,onPartialImages:y,includeCost:S,customTaskUUID:Te,retry:Ue,refiner:J,maskMargin:_e,outputQuality:h,controlNet:K,lora:z,embeddings:Y,ipAdapters:Z},ke){let C,$,E=[],X=0,ee=Ue||this._globalMaxRetries;try{await this.ensureConnection();let w=null,W=null,F=[];if(l){let R=await this.uploadImage(l);if(!R)return[];w=R.imageUUID}if(s){let R=await this.uploadImage(s);if(!R)return[];W=R.imageUUID}if(K?.length)for(let R=0;R<K.length;R++){let M=K[R],{endStep:P,startStep:G,weight:B,guideImage:N,controlMode:Re,startStepPercentage:xe,endStepPercentage:De,model:ve}=M,Se=N?await this.uploadImage(N):null;F.push({guideImage:Se?.imageUUID,model:ve,endStep:P,startStep:G,weight:B,...I({key:"startStepPercentage",value:xe}),...I({key:"endStepPercentage",value:De}),controlMode:Re||"controlnet"})}return $={taskType:"imageInference",model:r,positivePrompt:o,...i?{negativePrompt:i}:{},...g?{height:g}:{},...d?{width:d}:{},numberResults:x,...t?{outputType:t}:{},...e?{outputFormat:e}:{},...n?{uploadEndpoint:n}:{},...I({key:"checkNSFW",value:a}),...I({key:"strength",value:u}),...I({key:"CFGScale",value:b}),...I({key:"clipSkip",value:T}),...I({key:"maskMargin",value:_e}),...I({key:"usePromptWeighting",value:k}),...I({key:"steps",value:p}),...D?{promptWeighting:D}:{},...f?{seed:f}:{seed:Q()},...m?{scheduler:m}:{},...J?{refiner:J}:{},...I({key:"includeCost",value:S}),...w?{seedImage:w}:{},...W?{maskImage:W}:{},...h?{outputQuality:h}:{},...F.length?{controlNet:F}:{},...z?.length?{lora:z}:{},...Y?.length?{embeddings:Y}:{},...Z?.length?{ipAdapters:Z}:{},...ke??{}},await _(async()=>{X++,C?.destroy();let R=this._globalImages.filter(N=>E.includes(N.taskUUID)),M=Te||U();E.push(M);let P=x-R.length,G={...$,taskUUID:M,numberResults:P};this.send(G),C=this.listenToImages({onPartialImages:y,taskUUID:M,groupKey:"REQUEST_IMAGES",positivePrompt:o,negativePrompt:i});let B=await this.getSimilarImages({taskUUID:E,numberResults:x,lis:C});return C.destroy(),B},{maxRetries:ee,callback:()=>{C?.destroy()}})}catch(w){if(X>=ee)return this.handleIncompleteImages({taskUUIDs:E,error:w});throw w}}async ensureConnection(){if(this.connected()||this._url===j.TEST)return;let e=2e3,n=200;try{if(this.isInvalidAPIKey())throw this._connectionError;return new Promise((a,o)=>{let i=0,l=30,s=U(),u,g,d=()=>{this.ensureConnectionUUID=null,clearInterval(u),clearInterval(g)};this._sdkType==="SERVER"&&(u=setInterval(async()=>{try{let r=this.connected(),p=!1;(!this.ensureConnectionUUID||s===this.ensureConnectionUUID)&&(this.ensureConnectionUUID||(this.ensureConnectionUUID=s),p=!0);let m=i%10===0&&p;r?(d(),a(!0)):i>=l?(d(),o(new Error("Retry timed out"))):(m&&this.connect(),i++)}catch(r){d(),o(r)}},e)),g=setInterval(async()=>{if(this.connected()){d(),a(!0);return}if(this.isInvalidAPIKey()){d(),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:t,numberResults:e,shouldThrowError:n,lis:a}){return await v(({resolve:o,reject:i,intervalId:l})=>{let s=Array.isArray(t)?t:[t],u=this._globalImages.filter(g=>s.includes(g.taskUUID));if(this._globalError){let g=this._globalError;return this._globalError=void 0,clearInterval(l),i?.(g),!0}else if(u.length>=e)return clearInterval(l),this._globalImages=this._globalImages.filter(g=>!s.includes(g.taskUUID)),o([...u].slice(0,e)),!0},{debugKey:"getting images",shouldThrowError:n,timeoutDuration:this._timeoutDuration})}handleIncompleteImages({taskUUIDs:t,error:e}){let n=this._globalImages.filter(a=>t.includes(a.taskUUID));if(n.length>1)return this._globalImages=this._globalImages.filter(a=>!t.includes(a.taskUUID)),n;throw e}};var fe=Le(he(),1),O=class extends A{constructor(t){let{shouldReconnect:e,...n}=t;super(n),this._ws=new fe.default(this._url),this.connect()}};import Xe from"ws";var L=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 Xe(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 a=n?e:e?.toString();if(!a)return;let o=JSON.parse(a);this._listeners.forEach(i=>{i.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 be;typeof window>"u"?be=L:be=O;export{re as EControlMode,Fe as EModelArchitecture,Ge as EModelConditioning,We as EModelFormat,Pe as EModelType,Ke as EOpenPosePreProcessor,Be as EPhotoMakerEnum,ae as EPreProcessor,se as EPreProcessorGroup,H as ETaskType,ne as Environment,be as Runware,O as RunwareClient,L as RunwareServer,q as SdkType};
1
+ var Ae=Object.create;var ne=Object.defineProperty;var Ce=Object.getOwnPropertyDescriptor;var Me=Object.getOwnPropertyNames;var Ee=Object.getPrototypeOf,Ne=Object.prototype.hasOwnProperty;var Oe=(c,t)=>()=>(t||c((t={exports:{}}).exports,t),t.exports);var Le=(c,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of Me(t))!Ne.call(c,a)&&a!==e&&ne(c,a,{get:()=>t[a],enumerable:!(n=Ce(t,a))||n.enumerable});return c};var Ke=(c,t,e)=>(e=c!=null?Ae(Ee(c)):{},Le(t||!c||!c.__esModule?ne(e,"default",{value:c,enumerable:!0}):e,c));var fe=Oe((Vt,he)=>{"use strict";var ye=c=>c&&c.CLOSING===2,Je=()=>typeof WebSocket<"u"&&ye(WebSocket),ze=()=>({constructor:Je()?WebSocket:null,maxReconnectionDelay:1e4,minReconnectionDelay:1500,reconnectionDelayGrowFactor:1.3,connectionTimeout:4e3,maxRetries:1/0,debug:!1}),Ye=(c,t,e)=>{Object.defineProperty(t,e,{get:()=>c[e],set:n=>{c[e]=n},enumerable:!0,configurable:!0})},me=c=>c.minReconnectionDelay+Math.random()*c.minReconnectionDelay,Ze=(c,t)=>{let e=t*c.reconnectionDelayGrowFactor;return e>c.maxReconnectionDelay?c.maxReconnectionDelay:e},$e=["onopen","onclose","onmessage","onerror"],Xe=(c,t,e)=>{Object.keys(e).forEach(n=>{e[n].forEach(([a,o])=>{c.addEventListener(n,a,o)})}),t&&$e.forEach(n=>{c[n]=t[n]})},Ie=function(c,t,e={}){let n,a,o=0,l=0,i=!0,s={};if(!(this instanceof Ie))throw new TypeError("Failed to construct 'ReconnectingWebSocket': Please use the 'new' operator");let u=ze();if(Object.keys(u).filter(m=>e.hasOwnProperty(m)).forEach(m=>u[m]=e[m]),!ye(u.constructor))throw new TypeError("Invalid WebSocket constructor. Set `options.constructor`");let g=u.debug?(...m)=>console.log("RWS:",...m):()=>{},d=(m,b)=>setTimeout(()=>{let h=new Error(b);h.code=m,Array.isArray(s.error)&&s.error.forEach(([T])=>T(h)),n.onerror&&n.onerror(h)},0),r=()=>{if(g("close"),l++,g("retries count:",l),l>u.maxRetries){d("EHOSTDOWN","Too many failed connection attempts");return}o?o=Ze(u,o):o=me(u),g("reconnectDelay:",o),i&&setTimeout(p,o)},p=()=>{g("connect");let m=n;n=new u.constructor(c,t),a=setTimeout(()=>{g("timeout"),n.close(),d("ETIMEDOUT","Connection timeout")},u.connectionTimeout),g("bypass properties");for(let b in n)["addEventListener","removeEventListener","close","send"].indexOf(b)<0&&Ye(n,this,b);n.addEventListener("open",()=>{clearTimeout(a),g("open"),o=me(u),g("reconnectDelay:",o),l=0}),n.addEventListener("close",r),Xe(n,m,s)};g("init"),p(),this.close=(m=1e3,b="",{keepClosed:h=!1,fastClose:T=!0,delay:k=0}={})=>{if(k&&(o=k),i=!h,n.close(m,b),T){let D={code:m,reason:b,wasClean:!0};r(),Array.isArray(s.close)&&s.close.forEach(([x,y])=>{x(D),n.removeEventListener("close",x,y)}),n.onclose&&(n.onclose(D),n.onclose=null)}},this.send=m=>{n.send(m)},this.addEventListener=(m,b,h)=>{Array.isArray(s[m])?s[m].some(([T])=>T===b)||s[m].push([b,h]):s[m]=[[b,h]],n.addEventListener(m,b,h)},this.removeEventListener=(m,b,h)=>{Array.isArray(s[m])&&(s[m]=s[m].filter(([T])=>T!==b)),n.removeEventListener(m,b,h)}};he.exports=Ie});var re=(n=>(n.PRODUCTION="PRODUCTION",n.DEVELOPMENT="DEVELOPMENT",n.TEST="TEST",n))(re||{}),q=(e=>(e.CLIENT="CLIENT",e.SERVER="SERVER",e))(q||{}),H=(r=>(r.IMAGE_INFERENCE="imageInference",r.IMAGE_UPLOAD="imageUpload",r.IMAGE_UPSCALE="imageUpscale",r.IMAGE_BACKGROUND_REMOVAL="imageBackgroundRemoval",r.IMAGE_CAPTION="imageCaption",r.IMAGE_CONTROL_NET_PRE_PROCESS="imageControlNetPreProcess",r.PROMPT_ENHANCE="promptEnhance",r.AUTHENTICATION="authentication",r.MODEL_UPLOAD="modelUpload",r.PHOTO_MAKER="photoMaker",r.MODEL_SEARCH="modelSearch",r.IMAGE_MASKING="imageMasking",r))(H||{}),se=(n=>(n.BALANCED="balanced",n.PROMPT="prompt",n.CONTROL_NET="controlnet",n))(se||{}),ae=(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))(ae||{}),oe=(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))(oe||{}),We=(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))(We||{}),Fe=(e=>(e.safetensors="safetensors",e.pickletensor="pickletensor",e))(Fe||{}),Pe=(p=>(p.flux1d="flux1d",p.flux1s="flux1s",p.pony="pony",p.sdhyper="sdhyper",p.sd1x="sd1x",p.sd1xlcm="sd1xlcm",p.sd3="sd3",p.sdxl="sdxl",p.sdxllcm="sdxllcm",p.sdxldistilled="sdxldistilled",p.sdxlhyper="sdxlhyper",p.sdxllightning="sdxllightning",p.sdxlturbo="sdxlturbo",p))(Pe||{}),Ge=(n=>(n.base="base",n.inpainting="inpainting",n.pix2pix="pix2pix",n))(Ge||{}),Be=(y=>(y.canny="canny",y.depth="depth",y.qrcode="qrcode",y.hed="hed",y.scrible="scrible",y.openpose="openpose",y.seg="segmentation",y.openmlsd="openmlsd",y.softedge="softedge",y.normal="normal bae",y.shuffle="shuffle",y.pix2pix="pix2pix",y.inpaint="inpaint",y.lineart="line art",y.sketch="sketch",y.inpaintdepth="inpaint depth",y.tile="tile",y.outfit="outfit",y.blur="blur",y.gray="gray",y.lowquality="low quality",y))(Be||{}),qe=(d=>(d.NoStyle="No style",d.Cinematic="Cinematic",d.DisneyCharacter="Disney Character",d.DigitalArt="Digital Art",d.Photographic="Photographic",d.FantasyArt="Fantasy art",d.Neonpunk="Neonpunk",d.Enhance="Enhance",d.ComicBook="Comic book",d.Lowpoly="Lowpoly",d.LineArt="Line art",d))(qe||{});import{v4 as He,validate as Ve}from"uuid";var V=6e4,ie=1e3,je=100,j={PRODUCTION:"wss://ws-api.runware.ai/v1",TEST:"ws://localhost:8080"},le=(c,t)=>{if(c==null)return;let e=c.indexOf(t);e!==-1&&c.splice(e,1)},v=(c,{debugKey:t="debugKey",timeoutDuration:e=V,shouldThrowError:n=!0})=>(e=e<ie?ie:e,new Promise((a,o)=>{let l=setTimeout(()=>{i&&(clearInterval(i),n&&o(`Response could not be received from server for ${t}`)),clearTimeout(l)},e),i=setInterval(async()=>{c({resolve:a,reject:o,intervalId:i})&&(clearInterval(i),clearTimeout(l))},je)})),ce=c=>new Promise(t=>{let e=new FileReader;e.readAsDataURL(c),e.onload=function(){t(e.result)}}),U=()=>He(),ue=c=>Ve(c);var ge=({key:c,data:t,useZero:e=!0,shouldReturnString:n=!1})=>c.split(/\.|\[/).map(l=>l.replace(/\]$/,"")).reduce((l,i)=>{let s=e?0:void 0,u=l?.[i];if(!u)return s;if(Array.isArray(u)&&/^\d+$/.test(i)){let g=parseInt(i,10);return g>=0&&g<u.length?l[i]=u[g]:l[i]??s}else return l[i]??s},t||{})??{},de=(c,t=1e3)=>new Promise(e=>setTimeout(e,c*t));var pe=(c,t)=>c.filter(e=>e.key!==t.key);var I=({key:c,value:t})=>t||t===0||t===!1?{[c]:t}:{},Qe=(c,t)=>Math.floor(Math.random()*(t-c+1))+c,Q=()=>Qe(1,Number.MAX_SAFE_INTEGER);var _=async(c,t={})=>{let{delayInSeconds:e=1,callback:n}=t,a=t.maxRetries??1;for(;a;)try{return await c()}catch(o){if(n?.(),a--,a>0)await de(e),await _(c,{...t,maxRetries:a});else throw o}};var A=class{constructor({apiKey:t,url:e=j.PRODUCTION,shouldReconnect:n=!0,globalMaxRetries:a=2,timeoutDuration:o=V}){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 _(async()=>{let e=U();if(typeof t=="string"&&ue(t))return{imageURL:t,imageUUID:t,taskUUID:e,taskType:"imageUpload"};let n=typeof t=="string"?t:await ce(t);return{imageURL:n,imageUUID:n,taskUUID:e,taskType:"imageUpload"}})}catch(e){throw e}};this.controlNetPreProcess=async({inputImage:t,preProcessorType:e,height:n,width:a,outputType:o,outputFormat:l,highThresholdCanny:i,lowThresholdCanny:s,includeHandsAndFaceOpenPose:u,includeCost:g,outputQuality:d,customTaskUUID:r,retry:p})=>{let m=p||this._globalMaxRetries,b;try{return await _(async()=>{await this.ensureConnection();let h=await this.uploadImage(t);if(!h?.imageUUID)return null;let T=r||U();this.send({inputImage:h.imageUUID,taskType:"imageControlNetPreProcess",taskUUID:T,preProcessorType:e,...I({key:"height",value:n}),...I({key:"width",value:a}),...I({key:"outputType",value:o}),...I({key:"outputFormat",value:l}),...I({key:"includeCost",value:g}),...I({key:"highThresholdCanny",value:i}),...I({key:"lowThresholdCanny",value:s}),...I({key:"includeHandsAndFaceOpenPose",value:u}),...d?{outputQuality:d}:{}}),b=this.globalListener({taskUUID:T});let k=await v(({resolve:D,reject:x})=>{let y=this.getSingleMessage({taskUUID:T});if(y){if(y?.error)return x(y),!0;if(y)return D(y),!0}},{debugKey:"unprocessed-image",timeoutDuration:this._timeoutDuration});return b.destroy(),k},{maxRetries:m,callback:()=>{b?.destroy()}})}catch(h){throw h}};this.requestImageToText=async({inputImage:t,includeCost:e,customTaskUUID:n,retry:a})=>{let o=a||this._globalMaxRetries,l;try{return await _(async()=>{await this.ensureConnection();let i=t?await this.uploadImage(t):null,s=n||U();this.send({taskUUID:s,taskType:"imageCaption",inputImage:i?.imageUUID,...I({key:"includeCost",value:e})}),l=this.globalListener({taskUUID:s});let u=await v(({resolve:g,reject:d})=>{let r=this.getSingleMessage({taskUUID:s});if(r){if(r?.error)return d(r),!0;if(r)return delete this._globalMessages[s],g(r),!0}},{debugKey:"remove-image-background",timeoutDuration:this._timeoutDuration});return l.destroy(),u},{maxRetries:o,callback:()=>{l?.destroy()}})}catch(i){throw i}};this.removeImageBackground=async({inputImage:t,outputType:e,outputFormat:n,rgba:a,postProcessMask:o,returnOnlyMask:l,alphaMatting:i,alphaMattingForegroundThreshold:s,alphaMattingBackgroundThreshold:u,alphaMattingErodeSize:g,outputQuality:d,includeCost:r,customTaskUUID:p,retry:m})=>{let b=m||this._globalMaxRetries,h;try{return await _(async()=>{await this.ensureConnection();let T=t?await this.uploadImage(t):null,k=p||U();this.send({taskType:"imageBackgroundRemoval",taskUUID:k,inputImage:T?.imageUUID,...I({key:"rgba",value:a}),...I({key:"postProcessMask",value:o}),...I({key:"returnOnlyMask",value:l}),...I({key:"alphaMatting",value:i}),...I({key:"includeCost",value:r}),...I({key:"alphaMattingForegroundThreshold",value:s}),...I({key:"alphaMattingBackgroundThreshold",value:u}),...I({key:"alphaMattingErodeSize",value:g}),...I({key:"outputType",value:e}),...I({key:"outputFormat",value:n}),...d?{outputQuality:d}:{}}),h=this.globalListener({taskUUID:k});let D=await v(({resolve:x,reject:y})=>{let S=this.getSingleMessage({taskUUID:k});if(S){if(S?.error)return y(S),!0;if(S)return delete this._globalMessages[k],x(S),!0}},{debugKey:"remove-image-background",timeoutDuration:this._timeoutDuration});return h.destroy(),D},{maxRetries:b,callback:()=>{h?.destroy()}})}catch(T){throw T}};this.upscaleGan=async({inputImage:t,upscaleFactor:e,outputType:n,outputFormat:a,includeCost:o,outputQuality:l,customTaskUUID:i,retry:s})=>{let u=s||this._globalMaxRetries,g;try{return await _(async()=>{await this.ensureConnection();let d;d=await this.uploadImage(t);let r=i||U();this.send({taskUUID:r,inputImage:d?.imageUUID,taskType:"imageUpscale",upscaleFactor:e,...I({key:"includeCost",value:o}),...n?{outputType:n}:{},...l?{outputQuality:l}:{},...a?{outputFormat:a}:{}}),g=this.globalListener({taskUUID:r});let p=await v(({resolve:m,reject:b})=>{let h=this.getSingleMessage({taskUUID:r});if(h){if(h?.error)return b(h),!0;if(h)return delete this._globalMessages[r],m(h),!0}},{debugKey:"upscale-gan",timeoutDuration:this._timeoutDuration});return g.destroy(),p},{maxRetries:u,callback:()=>{g?.destroy()}})}catch(d){throw d}};this.enhancePrompt=async({prompt:t,promptMaxLength:e=380,promptVersions:n=1,includeCost:a,customTaskUUID:o,retry:l})=>{let i=l||this._globalMaxRetries,s;try{return await _(async()=>{await this.ensureConnection();let u=o||U();this.send({prompt:t,taskUUID:u,promptMaxLength:e,promptVersions:n,...I({key:"includeCost",value:a}),taskType:"promptEnhance"}),s=this.globalListener({taskUUID:u});let g=await v(({resolve:d,reject:r})=>{let p=this._globalMessages[u];if(p?.error)return r(p),!0;if(p?.length>=n)return delete this._globalMessages[u],d(p),!0},{debugKey:"enhance-prompt",timeoutDuration:this._timeoutDuration});return s.destroy(),g},{maxRetries:i,callback:()=>{s?.destroy()}})}catch(u){throw u}};this.modelUpload=async t=>{let{onUploadStream:e,retry:n,customTaskUUID:a,...o}=t,l=n||this._globalMaxRetries,i;try{return await _(async()=>{await this.ensureConnection();let s=a||U();this.send({...o,taskUUID:s,taskType:"modelUpload"});let u,g;return i=this.listenToUpload({taskUUID:s,onUploadStream:(r,p)=>{e?.(r,p),r?.status==="ready"?u=r:p&&(g=p)}}),await v(({resolve:r,reject:p})=>{if(u)return r(u),!0;if(g)return p(g),!1},{shouldThrowError:!1,timeoutDuration:60*60*1e3})},{maxRetries:l,callback:()=>{i?.destroy()}})}catch(s){throw s}};this.photoMaker=async(t,e)=>{let{onPartialImages:n,retry:a,customTaskUUID:o,numberResults:l,...i}=t,s=a||this._globalMaxRetries,u,g=[],d=0;try{return await _(async()=>{await this.ensureConnection(),d++;let r=this._globalImages.filter(h=>g.includes(h.taskUUID)),p=o||U();g.push(p);let m=l-r.length;this.send({...i,...i.seed?{seed:i.seed}:{seed:Q()},...e??{},numberResults:m,taskUUID:p,taskType:"photoMaker"}),u=this.listenToImages({onPartialImages:n,taskUUID:p,groupKey:"REQUEST_IMAGES",positivePrompt:i.positivePrompt});let b=await this.getSimilarImages({taskUUID:g,numberResults:l,lis:u});return u.destroy(),b},{maxRetries:s,callback:()=>{u?.destroy()}})}catch(r){if(r.taskUUID)throw r;if(d>=s)return this.handleIncompleteImages({taskUUIDs:g,error:r})}};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.baseSingleRequest=async({payload:t,debugKey:e})=>{let{retry:n,customTaskUUID:a,...o}=t,l=n||this._globalMaxRetries,i;try{return await _(async()=>{await this.ensureConnection();let s=a||U();this.send({...o,taskUUID:s}),i=this.globalListener({taskUUID:s});let u=await v(({resolve:g,reject:d})=>{let r=this.getSingleMessage({taskUUID:s});if(r){if(r?.error)return d(r),!0;if(r)return delete this._globalMessages[s],g(r),!0}},{debugKey:e,timeoutDuration:this._timeoutDuration});return i.destroy(),u},{maxRetries:l,callback:()=>{i?.destroy()}})}catch(s){throw s}};this.getSingleMessage=({taskUUID:t})=>{let e=this._globalMessages[t]?.[0],n=this._globalMessages[t];return!e&&!n?null:n?.error?n:e};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=a,this._timeoutDuration=o}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 a=i=>{let s=Array.isArray(i?.data)?i.data:[i.data],u=i?.[0]?.errors?i?.[0]?.errors:Array.isArray(i?.errors)?i.errors:[i.errors],g=s.filter(r=>(r?.taskUUID||r?.taskType)===n);if(u.filter(r=>(r?.taskUUID||r?.taskType)===n).length){t({error:{...u[0]??{}}});return}if(g.length){t({[n]:s});return}},o={key:n||U(),listener:a,groupKey:e};return this._listeners.push(o),{destroy:()=>{this._listeners=pe(this._listeners,o)}}}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){le(this._listeners,t)}listenToImages({onPartialImages:t,taskUUID:e,groupKey:n,positivePrompt:a,negativePrompt:o}){return this.addListener({taskUUID:e,lis:l=>{let i=l?.[e]?.filter(s=>s.taskUUID===e);l.error?(t?.(i,l?.error&&l),this._globalError=l):(i=i.map(s=>({...s,positivePrompt:a,negativePrompt:o})),t?.(i,l?.error&&l),this._sdkType==="CLIENT"?this._globalImages=[...this._globalImages,...(l?.[e]??[]).map(s=>({...s,positivePrompt:a,negativePrompt:o}))]:this._globalImages=[...this._globalImages,...i])},groupKey:n})}listenToUpload({onUploadStream:t,taskUUID:e}){return this.addListener({taskUUID:e,lis:n=>{let a=n?.error,o=n?.[e]?.[0],l=o?.taskUUID===e?o:null;(l||a)&&t?.(l||void 0,a)}})}globalListener({taskUUID:t}){return this.addListener({taskUUID:t,lis:e=>{if(e.error){this._globalMessages[t]=e;return}let n=ge({key:t,data:e,useZero:!1});Array.isArray(n)?n.forEach(a=>{this._globalMessages[a.taskUUID]=[...this._globalMessages[a.taskUUID]??[],a]}):this._globalMessages[n.taskUUID]=n}})}async requestImages({outputType:t,outputFormat:e,uploadEndpoint:n,checkNSFW:a,positivePrompt:o,negativePrompt:l,seedImage:i,maskImage:s,strength:u,height:g,width:d,model:r,steps:p,scheduler:m,seed:b,CFGScale:h,clipSkip:T,usePromptWeighting:k,promptWeighting:D,numberResults:x=1,onPartialImages:y,includeCost:S,customTaskUUID:Ue,retry:_e,refiner:J,maskMargin:ke,outputQuality:f,controlNet:K,lora:z,embeddings:Y,ipAdapters:Z,outpaint:$},Re){let C,X,E=[],ee=0,te=_e||this._globalMaxRetries;try{await this.ensureConnection();let w=null,W=null,F=[];if(i){let R=await this.uploadImage(i);if(!R)return[];w=R.imageUUID}if(s){let R=await this.uploadImage(s);if(!R)return[];W=R.imageUUID}if(K?.length)for(let R=0;R<K.length;R++){let M=K[R],{endStep:P,startStep:G,weight:B,guideImage:N,controlMode:xe,startStepPercentage:De,endStepPercentage:ve,model:Se}=M,we=N?await this.uploadImage(N):null;F.push({guideImage:we?.imageUUID,model:Se,endStep:P,startStep:G,weight:B,...I({key:"startStepPercentage",value:De}),...I({key:"endStepPercentage",value:ve}),controlMode:xe||"controlnet"})}return X={taskType:"imageInference",model:r,positivePrompt:o,...l?{negativePrompt:l}:{},...g?{height:g}:{},...d?{width:d}:{},numberResults:x,...t?{outputType:t}:{},...e?{outputFormat:e}:{},...n?{uploadEndpoint:n}:{},...I({key:"checkNSFW",value:a}),...I({key:"strength",value:u}),...I({key:"CFGScale",value:h}),...I({key:"clipSkip",value:T}),...I({key:"maskMargin",value:ke}),...I({key:"usePromptWeighting",value:k}),...I({key:"steps",value:p}),...D?{promptWeighting:D}:{},...b?{seed:b}:{seed:Q()},...m?{scheduler:m}:{},...J?{refiner:J}:{},...$?{outpaint:$}:{},...I({key:"includeCost",value:S}),...w?{seedImage:w}:{},...W?{maskImage:W}:{},...f?{outputQuality:f}:{},...F.length?{controlNet:F}:{},...z?.length?{lora:z}:{},...Y?.length?{embeddings:Y}:{},...Z?.length?{ipAdapters:Z}:{},...Re??{}},await _(async()=>{ee++,C?.destroy();let R=this._globalImages.filter(N=>E.includes(N.taskUUID)),M=Ue||U();E.push(M);let P=x-R.length,G={...X,taskUUID:M,numberResults:P};this.send(G),C=this.listenToImages({onPartialImages:y,taskUUID:M,groupKey:"REQUEST_IMAGES",positivePrompt:o,negativePrompt:l});let B=await this.getSimilarImages({taskUUID:E,numberResults:x,lis:C});return C.destroy(),B},{maxRetries:te,callback:()=>{C?.destroy()}})}catch(w){if(ee>=te)return this.handleIncompleteImages({taskUUIDs:E,error:w});throw w}}async ensureConnection(){if(this.connected()||this._url===j.TEST)return;let e=2e3,n=200;try{if(this.isInvalidAPIKey())throw this._connectionError;return new Promise((a,o)=>{let l=0,i=30,s=U(),u,g,d=()=>{this.ensureConnectionUUID=null,clearInterval(u),clearInterval(g)};this._sdkType==="SERVER"&&(u=setInterval(async()=>{try{let r=this.connected(),p=!1;(!this.ensureConnectionUUID||s===this.ensureConnectionUUID)&&(this.ensureConnectionUUID||(this.ensureConnectionUUID=s),p=!0);let m=l%10===0&&p;r?(d(),a(!0)):l>=i?(d(),o(new Error("Retry timed out"))):(m&&this.connect(),l++)}catch(r){d(),o(r)}},e)),g=setInterval(async()=>{if(this.connected()){d(),a(!0);return}if(this.isInvalidAPIKey()){d(),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:t,numberResults:e,shouldThrowError:n,lis:a}){return await v(({resolve:o,reject:l,intervalId:i})=>{let s=Array.isArray(t)?t:[t],u=this._globalImages.filter(g=>s.includes(g.taskUUID));if(this._globalError){let g=this._globalError;return this._globalError=void 0,clearInterval(i),l?.(g),!0}else if(u.length>=e)return clearInterval(i),this._globalImages=this._globalImages.filter(g=>!s.includes(g.taskUUID)),o([...u].slice(0,e)),!0},{debugKey:"getting images",shouldThrowError:n,timeoutDuration:this._timeoutDuration})}handleIncompleteImages({taskUUIDs:t,error:e}){let n=this._globalImages.filter(a=>t.includes(a.taskUUID));if(n.length>1)return this._globalImages=this._globalImages.filter(a=>!t.includes(a.taskUUID)),n;throw e}};var be=Ke(fe(),1),O=class extends A{constructor(t){let{shouldReconnect:e,...n}=t;super(n),this._ws=new be.default(this._url),this.connect()}};import et from"ws";var L=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 et(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 a=n?e:e?.toString();if(!a)return;let o=JSON.parse(a);this._listeners.forEach(l=>{l.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 Te;typeof window>"u"?Te=L:Te=O;export{se as EControlMode,Pe as EModelArchitecture,Be as EModelConditioning,Fe as EModelFormat,Ge as EModelType,We as EOpenPosePreProcessor,qe as EPhotoMakerEnum,oe as EPreProcessor,ae as EPreProcessorGroup,H as ETaskType,re as Environment,Te as Runware,O as RunwareClient,L as RunwareServer,q as SdkType};
2
2
  //# sourceMappingURL=index.js.map