@runware/sdk-js 1.2.5 → 1.2.7
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.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +7 -3
- package/dist/index.d.ts +7 -3
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
- package/readme.md +9 -0
package/dist/index.d.cts
CHANGED
|
@@ -302,6 +302,8 @@ interface IRequestVideo extends IRequestImageToText {
|
|
|
302
302
|
speech?: {
|
|
303
303
|
voice: string;
|
|
304
304
|
text: string;
|
|
305
|
+
} & {
|
|
306
|
+
[key: string]: unknown;
|
|
305
307
|
};
|
|
306
308
|
skipResponse?: boolean;
|
|
307
309
|
customTaskUUID?: string;
|
|
@@ -437,7 +439,7 @@ interface IEnhancedPrompt extends IImageToText {
|
|
|
437
439
|
}
|
|
438
440
|
interface IUpscaleGan extends IAdditionalResponsePayload {
|
|
439
441
|
inputImage?: File | string;
|
|
440
|
-
upscaleFactor
|
|
442
|
+
upscaleFactor?: number;
|
|
441
443
|
outputType?: IOutputType;
|
|
442
444
|
outputFormat?: IOutputFormat | "MP4" | "WEBM" | "MOV";
|
|
443
445
|
includeCost?: boolean;
|
|
@@ -454,6 +456,7 @@ interface IUpscaleGan extends IAdditionalResponsePayload {
|
|
|
454
456
|
retry?: number;
|
|
455
457
|
skipResponse?: boolean;
|
|
456
458
|
deliveryMethod?: string;
|
|
459
|
+
[key: string]: any;
|
|
457
460
|
}
|
|
458
461
|
type ReconnectingWebsocketProps = {
|
|
459
462
|
addEventListener: (type: string, listener: EventListener, options: any) => void;
|
|
@@ -818,6 +821,7 @@ type MediaUUID = {
|
|
|
818
821
|
text?: string;
|
|
819
822
|
};
|
|
820
823
|
|
|
824
|
+
declare const SDK_VERSION: string;
|
|
821
825
|
declare enum LISTEN_TO_MEDIA_KEY {
|
|
822
826
|
REQUEST_IMAGES = "REQUEST_IMAGES",
|
|
823
827
|
REQUEST_TEXT = "REQUEST_TEXT",
|
|
@@ -897,7 +901,7 @@ declare class RunwareBase {
|
|
|
897
901
|
* @since 1.2.0
|
|
898
902
|
* @returns {Promise<IImage>} If called with `inputs.image` or `inputs.video`, returns an object with `mediaUUID` and `mediaURL`. If called with `inputImage`, returns an object with `imageUUID` and `imageURL` (not guaranteed).
|
|
899
903
|
*/
|
|
900
|
-
upscaleGan: (
|
|
904
|
+
upscaleGan: (payload: IUpscaleGan) => Promise<IImage>;
|
|
901
905
|
upscale: (params: IUpscaleGan) => Promise<IImage>;
|
|
902
906
|
enhancePrompt: ({ prompt, promptMaxLength, promptVersions, includeCost, customTaskUUID, taskUUID: _taskUUID, retry, includeGenerationTime, includePayload, }: IPromptEnhancer) => Promise<IEnhancedPrompt[]>;
|
|
903
907
|
promptEnhance: (params: IPromptEnhancer) => Promise<IEnhancedPrompt[]>;
|
|
@@ -947,4 +951,4 @@ declare class RunwareServer extends RunwareBase {
|
|
|
947
951
|
|
|
948
952
|
declare let Runware: typeof RunwareClient | typeof RunwareServer;
|
|
949
953
|
|
|
950
|
-
export { EControlMode, EModelArchitecture, EModelConditioning, EModelFormat, EModelType, EOpenPosePreProcessor, EPhotoMakerEnum, EPreProcessor, EPreProcessorGroup, ETaskType, Environment, type GetWithPromiseAsyncCallBackType, type GetWithPromiseCallBackType, type IAddModelResponse, type IAdditionalResponsePayload, type IAsyncResults, type IAudio, type IAudioOutputFormat, type IBflProviderSettings, type IControlNet, type IControlNetGeneral, type IControlNetImage, type IControlNetPreprocess, type IControlNetWithUUID, type IEmbedding, type IEnhancedPrompt, type IError, type IErrorResponse, type IImage, type IImageToText, type IOutpaint, type IOutputFormat, type IOutputType, type IPromptEnhancer, type IProviderSettings, type IRefiner, type IRemoveImage, type IRemoveImageBackground, type IRequestAudio, type IRequestImage, type IRequestImageToText, type IRequestTextInference, type IRequestThreeD, type IRequestVideo, type ITextMessage, type ITextResponse, type ITextToImage, type IThreeDImage, type IThreeDOutputFormat, type IUpscaleGan, type IVideoOutputFormat, type IVideoToImage, type IipAdapter, type ListenerType, type MediaUUID, type ProviderSettings, type ReconnectingWebsocketProps, type RequireAtLeastOne, type RequireOnlyOne, Runware, type RunwareBaseType, RunwareClient, RunwareServer, SdkType, type TAcceleratorOptions, type TAddModel, type TAddModelBaseType, type TAddModelCheckPoint, type TAddModelControlNet, type TAddModelLora, type TImageMasking, type TImageMaskingResponse, type TImageUpload, type TImageUploadResponse, type TMediaStorage, type TMediaStorageResponse, type TModel, type TModelSearch, type TModelSearchResponse, type TPhotoMaker, type TPhotoMakerResponse, type TPromptWeighting, type TServerError, type TVectorize, type TVectorizeResponse, type UploadImageType };
|
|
954
|
+
export { EControlMode, EModelArchitecture, EModelConditioning, EModelFormat, EModelType, EOpenPosePreProcessor, EPhotoMakerEnum, EPreProcessor, EPreProcessorGroup, ETaskType, Environment, type GetWithPromiseAsyncCallBackType, type GetWithPromiseCallBackType, type IAddModelResponse, type IAdditionalResponsePayload, type IAsyncResults, type IAudio, type IAudioOutputFormat, type IBflProviderSettings, type IControlNet, type IControlNetGeneral, type IControlNetImage, type IControlNetPreprocess, type IControlNetWithUUID, type IEmbedding, type IEnhancedPrompt, type IError, type IErrorResponse, type IImage, type IImageToText, type IOutpaint, type IOutputFormat, type IOutputType, type IPromptEnhancer, type IProviderSettings, type IRefiner, type IRemoveImage, type IRemoveImageBackground, type IRequestAudio, type IRequestImage, type IRequestImageToText, type IRequestTextInference, type IRequestThreeD, type IRequestVideo, type ITextMessage, type ITextResponse, type ITextToImage, type IThreeDImage, type IThreeDOutputFormat, type IUpscaleGan, type IVideoOutputFormat, type IVideoToImage, type IipAdapter, type ListenerType, type MediaUUID, type ProviderSettings, type ReconnectingWebsocketProps, type RequireAtLeastOne, type RequireOnlyOne, Runware, type RunwareBaseType, RunwareClient, RunwareServer, SDK_VERSION, SdkType, type TAcceleratorOptions, type TAddModel, type TAddModelBaseType, type TAddModelCheckPoint, type TAddModelControlNet, type TAddModelLora, type TImageMasking, type TImageMaskingResponse, type TImageUpload, type TImageUploadResponse, type TMediaStorage, type TMediaStorageResponse, type TModel, type TModelSearch, type TModelSearchResponse, type TPhotoMaker, type TPhotoMakerResponse, type TPromptWeighting, type TServerError, type TVectorize, type TVectorizeResponse, type UploadImageType };
|
package/dist/index.d.ts
CHANGED
|
@@ -302,6 +302,8 @@ interface IRequestVideo extends IRequestImageToText {
|
|
|
302
302
|
speech?: {
|
|
303
303
|
voice: string;
|
|
304
304
|
text: string;
|
|
305
|
+
} & {
|
|
306
|
+
[key: string]: unknown;
|
|
305
307
|
};
|
|
306
308
|
skipResponse?: boolean;
|
|
307
309
|
customTaskUUID?: string;
|
|
@@ -437,7 +439,7 @@ interface IEnhancedPrompt extends IImageToText {
|
|
|
437
439
|
}
|
|
438
440
|
interface IUpscaleGan extends IAdditionalResponsePayload {
|
|
439
441
|
inputImage?: File | string;
|
|
440
|
-
upscaleFactor
|
|
442
|
+
upscaleFactor?: number;
|
|
441
443
|
outputType?: IOutputType;
|
|
442
444
|
outputFormat?: IOutputFormat | "MP4" | "WEBM" | "MOV";
|
|
443
445
|
includeCost?: boolean;
|
|
@@ -454,6 +456,7 @@ interface IUpscaleGan extends IAdditionalResponsePayload {
|
|
|
454
456
|
retry?: number;
|
|
455
457
|
skipResponse?: boolean;
|
|
456
458
|
deliveryMethod?: string;
|
|
459
|
+
[key: string]: any;
|
|
457
460
|
}
|
|
458
461
|
type ReconnectingWebsocketProps = {
|
|
459
462
|
addEventListener: (type: string, listener: EventListener, options: any) => void;
|
|
@@ -818,6 +821,7 @@ type MediaUUID = {
|
|
|
818
821
|
text?: string;
|
|
819
822
|
};
|
|
820
823
|
|
|
824
|
+
declare const SDK_VERSION: string;
|
|
821
825
|
declare enum LISTEN_TO_MEDIA_KEY {
|
|
822
826
|
REQUEST_IMAGES = "REQUEST_IMAGES",
|
|
823
827
|
REQUEST_TEXT = "REQUEST_TEXT",
|
|
@@ -897,7 +901,7 @@ declare class RunwareBase {
|
|
|
897
901
|
* @since 1.2.0
|
|
898
902
|
* @returns {Promise<IImage>} If called with `inputs.image` or `inputs.video`, returns an object with `mediaUUID` and `mediaURL`. If called with `inputImage`, returns an object with `imageUUID` and `imageURL` (not guaranteed).
|
|
899
903
|
*/
|
|
900
|
-
upscaleGan: (
|
|
904
|
+
upscaleGan: (payload: IUpscaleGan) => Promise<IImage>;
|
|
901
905
|
upscale: (params: IUpscaleGan) => Promise<IImage>;
|
|
902
906
|
enhancePrompt: ({ prompt, promptMaxLength, promptVersions, includeCost, customTaskUUID, taskUUID: _taskUUID, retry, includeGenerationTime, includePayload, }: IPromptEnhancer) => Promise<IEnhancedPrompt[]>;
|
|
903
907
|
promptEnhance: (params: IPromptEnhancer) => Promise<IEnhancedPrompt[]>;
|
|
@@ -947,4 +951,4 @@ declare class RunwareServer extends RunwareBase {
|
|
|
947
951
|
|
|
948
952
|
declare let Runware: typeof RunwareClient | typeof RunwareServer;
|
|
949
953
|
|
|
950
|
-
export { EControlMode, EModelArchitecture, EModelConditioning, EModelFormat, EModelType, EOpenPosePreProcessor, EPhotoMakerEnum, EPreProcessor, EPreProcessorGroup, ETaskType, Environment, type GetWithPromiseAsyncCallBackType, type GetWithPromiseCallBackType, type IAddModelResponse, type IAdditionalResponsePayload, type IAsyncResults, type IAudio, type IAudioOutputFormat, type IBflProviderSettings, type IControlNet, type IControlNetGeneral, type IControlNetImage, type IControlNetPreprocess, type IControlNetWithUUID, type IEmbedding, type IEnhancedPrompt, type IError, type IErrorResponse, type IImage, type IImageToText, type IOutpaint, type IOutputFormat, type IOutputType, type IPromptEnhancer, type IProviderSettings, type IRefiner, type IRemoveImage, type IRemoveImageBackground, type IRequestAudio, type IRequestImage, type IRequestImageToText, type IRequestTextInference, type IRequestThreeD, type IRequestVideo, type ITextMessage, type ITextResponse, type ITextToImage, type IThreeDImage, type IThreeDOutputFormat, type IUpscaleGan, type IVideoOutputFormat, type IVideoToImage, type IipAdapter, type ListenerType, type MediaUUID, type ProviderSettings, type ReconnectingWebsocketProps, type RequireAtLeastOne, type RequireOnlyOne, Runware, type RunwareBaseType, RunwareClient, RunwareServer, SdkType, type TAcceleratorOptions, type TAddModel, type TAddModelBaseType, type TAddModelCheckPoint, type TAddModelControlNet, type TAddModelLora, type TImageMasking, type TImageMaskingResponse, type TImageUpload, type TImageUploadResponse, type TMediaStorage, type TMediaStorageResponse, type TModel, type TModelSearch, type TModelSearchResponse, type TPhotoMaker, type TPhotoMakerResponse, type TPromptWeighting, type TServerError, type TVectorize, type TVectorizeResponse, type UploadImageType };
|
|
954
|
+
export { EControlMode, EModelArchitecture, EModelConditioning, EModelFormat, EModelType, EOpenPosePreProcessor, EPhotoMakerEnum, EPreProcessor, EPreProcessorGroup, ETaskType, Environment, type GetWithPromiseAsyncCallBackType, type GetWithPromiseCallBackType, type IAddModelResponse, type IAdditionalResponsePayload, type IAsyncResults, type IAudio, type IAudioOutputFormat, type IBflProviderSettings, type IControlNet, type IControlNetGeneral, type IControlNetImage, type IControlNetPreprocess, type IControlNetWithUUID, type IEmbedding, type IEnhancedPrompt, type IError, type IErrorResponse, type IImage, type IImageToText, type IOutpaint, type IOutputFormat, type IOutputType, type IPromptEnhancer, type IProviderSettings, type IRefiner, type IRemoveImage, type IRemoveImageBackground, type IRequestAudio, type IRequestImage, type IRequestImageToText, type IRequestTextInference, type IRequestThreeD, type IRequestVideo, type ITextMessage, type ITextResponse, type ITextToImage, type IThreeDImage, type IThreeDOutputFormat, type IUpscaleGan, type IVideoOutputFormat, type IVideoToImage, type IipAdapter, type ListenerType, type MediaUUID, type ProviderSettings, type ReconnectingWebsocketProps, type RequireAtLeastOne, type RequireOnlyOne, Runware, type RunwareBaseType, RunwareClient, RunwareServer, SDK_VERSION, SdkType, type TAcceleratorOptions, type TAddModel, type TAddModelBaseType, type TAddModelCheckPoint, type TAddModelControlNet, type TAddModelLora, type TImageMasking, type TImageMaskingResponse, type TImageUpload, type TImageUploadResponse, type TMediaStorage, type TMediaStorageResponse, type TModel, type TModelSearch, type TModelSearchResponse, type TPhotoMaker, type TPhotoMakerResponse, type TPromptWeighting, type TServerError, type TVectorize, type TVectorizeResponse, type UploadImageType };
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var We=Object.create;var de=Object.defineProperty;var Ve=Object.getOwnPropertyDescriptor;var Be=Object.getOwnPropertyNames;var Ge=Object.getPrototypeOf,He=Object.prototype.hasOwnProperty;var Qe=(u,e)=>()=>(e||u((e={exports:{}}).exports,e),e.exports);var ze=(u,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Be(e))!He.call(u,s)&&s!==t&&de(u,s,{get:()=>e[s],enumerable:!(n=Ve(e,s))||n.enumerable});return u};var je=(u,e,t)=>(t=u!=null?We(Ge(u)):{},ze(e||!u||!u.__esModule?de(t,"default",{value:u,enumerable:!0}):t,u));var we=Qe((bn,Se)=>{"use strict";var xe=u=>u&&u.CLOSING===2,rt=()=>typeof WebSocket<"u"&&xe(WebSocket),at=()=>({constructor:rt()?WebSocket:null,maxReconnectionDelay:1e4,minReconnectionDelay:1500,reconnectionDelayGrowFactor:1.3,connectionTimeout:4e3,maxRetries:1/0,debug:!1}),ot=(u,e,t)=>{Object.defineProperty(e,t,{get:()=>u[t],set:n=>{u[t]=n},enumerable:!0,configurable:!0})},_e=u=>u.minReconnectionDelay+Math.random()*u.minReconnectionDelay,it=(u,e)=>{let t=e*u.reconnectionDelayGrowFactor;return t>u.maxReconnectionDelay?u.maxReconnectionDelay:t},lt=["onopen","onclose","onmessage","onerror"],ut=(u,e,t)=>{Object.keys(t).forEach(n=>{t[n].forEach(([s,r])=>{u.addEventListener(n,s,r)})}),e&<.forEach(n=>{u[n]=e[n]})},ve=function(u,e,t={}){let n,s,r=0,a=0,i=!0,o={};if(!(this instanceof ve))throw new TypeError("Failed to construct 'ReconnectingWebSocket': Please use the 'new' operator");let p=at();if(Object.keys(p).filter(c=>t.hasOwnProperty(c)).forEach(c=>p[c]=t[c]),!xe(p.constructor))throw new TypeError("Invalid WebSocket constructor. Set `options.constructor`");let m=p.debug?(...c)=>console.log("RWS:",...c):()=>{},g=(c,I)=>setTimeout(()=>{let h=new Error(I);h.code=c,Array.isArray(o.error)&&o.error.forEach(([b])=>b(h)),n.onerror&&n.onerror(h)},0),d=()=>{if(m("close"),a++,m("retries count:",a),a>p.maxRetries){g("EHOSTDOWN","Too many failed connection attempts");return}r?r=it(p,r):r=_e(p),m("reconnectDelay:",r),i&&setTimeout(l,r)},l=()=>{m("connect");let c=n;n=new p.constructor(u,e),s=setTimeout(()=>{m("timeout"),n.close(),g("ETIMEDOUT","Connection timeout")},p.connectionTimeout),m("bypass properties");for(let I in n)["addEventListener","removeEventListener","close","send"].indexOf(I)<0&&ot(n,this,I);n.addEventListener("open",()=>{clearTimeout(s),m("open"),r=_e(p),m("reconnectDelay:",r),a=0}),n.addEventListener("close",d),ut(n,c,o)};m("init"),l(),this.close=(c=1e3,I="",{keepClosed:h=!1,fastClose:b=!0,delay:f=0}={})=>{if(f&&(r=f),i=!h,n.close(c,I),b){let y={code:c,reason:I,wasClean:!0};d(),Array.isArray(o.close)&&o.close.forEach(([k,U])=>{k(y),n.removeEventListener("close",k,U)}),n.onclose&&(n.onclose(y),n.onclose=null)}},this.send=c=>{n.send(c)},this.addEventListener=(c,I,h)=>{Array.isArray(o[c])?o[c].some(([b])=>b===I)||o[c].push([I,h]):o[c]=[[I,h]],n.addEventListener(c,I,h)},this.removeEventListener=(c,I,h)=>{Array.isArray(o[c])&&(o[c]=o[c].filter(([b])=>b!==I)),n.removeEventListener(c,I,h)}};Se.exports=ve});var pe=(n=>(n.PRODUCTION="PRODUCTION",n.DEVELOPMENT="DEVELOPMENT",n.TEST="TEST",n))(pe||{}),X=(t=>(t.CLIENT="CLIENT",t.SERVER="SERVER",t))(X||{}),J=(y=>(y.IMAGE_INFERENCE="imageInference",y.IMAGE_UPLOAD="imageUpload",y.UPSCALE="upscale",y.REMOVE_BACKGROUND="removeBackground",y.VIDEO_INFERENCE="videoInference",y.CAPTION="caption",y.AUDIO_INFERENCE="audioInference",y.THREE_D_INFERENCE="3dInference",y.GET_RESPONSE="getResponse",y.PHOTO_MAKER="photoMaker",y.IMAGE_CONTROL_NET_PRE_PROCESS="imageControlNetPreProcess",y.IMAGE_MASKING="imageMasking",y.PROMPT_ENHANCE="promptEnhance",y.AUTHENTICATION="authentication",y.MODEL_UPLOAD="modelUpload",y.MODEL_SEARCH="modelSearch",y.MEDIA_STORAGE="mediaStorage",y.VECTORIZE="vectorize",y.TEXT_INFERENCE="textInference",y))(J||{}),ge=(n=>(n.BALANCED="balanced",n.PROMPT="prompt",n.CONTROL_NET="controlnet",n))(ge||{}),me=(d=>(d.canny="canny",d.depth="depth",d.mlsd="mlsd",d.normalbae="normalbae",d.openpose="openpose",d.tile="tile",d.seg="seg",d.lineart="lineart",d.lineart_anime="lineart_anime",d.shuffle="shuffle",d.scribble="scribble",d.softedge="softedge",d))(me||{}),Ie=(T=>(T.canny="canny",T.depth_leres="depth_leres",T.depth_midas="depth_midas",T.depth_zoe="depth_zoe",T.inpaint_global_harmonious="inpaint_global_harmonious",T.lineart_anime="lineart_anime",T.lineart_coarse="lineart_coarse",T.lineart_realistic="lineart_realistic",T.lineart_standard="lineart_standard",T.mlsd="mlsd",T.normal_bae="normal_bae",T.scribble_hed="scribble_hed",T.scribble_pidinet="scribble_pidinet",T.seg_ofade20k="seg_ofade20k",T.seg_ofcoco="seg_ofcoco",T.seg_ufade20k="seg_ufade20k",T.shuffle="shuffle",T.softedge_hed="softedge_hed",T.softedge_hedsafe="softedge_hedsafe",T.softedge_pidinet="softedge_pidinet",T.softedge_pidisafe="softedge_pidisafe",T.tile_gaussian="tile_gaussian",T.openpose="openpose",T.openpose_face="openpose_face",T.openpose_faceonly="openpose_faceonly",T.openpose_full="openpose_full",T.openpose_hand="openpose_hand",T))(Ie||{}),Xe=(r=>(r.openpose="openpose",r.openpose_face="openpose_face",r.openpose_faceonly="openpose_faceonly",r.openpose_full="openpose_full",r.openpose_hand="openpose_hand",r))(Xe||{}),Je=(t=>(t.safetensors="safetensors",t.pickletensor="pickletensor",t))(Je||{}),Ze=(l=>(l.flux1d="flux1d",l.flux1s="flux1s",l.pony="pony",l.sdhyper="sdhyper",l.sd1x="sd1x",l.sd1xlcm="sd1xlcm",l.sd3="sd3",l.sdxl="sdxl",l.sdxllcm="sdxllcm",l.sdxldistilled="sdxldistilled",l.sdxlhyper="sdxlhyper",l.sdxllightning="sdxllightning",l.sdxlturbo="sdxlturbo",l))(Ze||{}),Ye=(n=>(n.base="base",n.inpainting="inpainting",n.pix2pix="pix2pix",n))(Ye||{}),$e=(U=>(U.canny="canny",U.depth="depth",U.qrcode="qrcode",U.hed="hed",U.scrible="scrible",U.openpose="openpose",U.seg="segmentation",U.openmlsd="openmlsd",U.softedge="softedge",U.normal="normal bae",U.shuffle="shuffle",U.pix2pix="pix2pix",U.inpaint="inpaint",U.lineart="line art",U.sketch="sketch",U.inpaintdepth="inpaint depth",U.tile="tile",U.outfit="outfit",U.blur="blur",U.gray="gray",U.lowquality="low quality",U))($e||{}),et=(g=>(g.NoStyle="No style",g.Cinematic="Cinematic",g.DisneyCharacter="Disney Character",g.DigitalArt="Digital Art",g.Photographic="Photographic",g.FantasyArt="Fantasy art",g.Neonpunk="Neonpunk",g.Enhance="Enhance",g.ComicBook="Comic book",g.Lowpoly="Lowpoly",g.LineArt="Line art",g))(et||{});import{v4 as tt,validate as nt}from"uuid";var K=6e4,q=1e3,ye=100,Z={PRODUCTION:"wss://ws-api.runware.ai/v1",TEST:"ws://localhost:8080"},he=(u,e)=>{if(u==null)return;let t=u.indexOf(e);t!==-1&&u.splice(t,1)},M=(u,{debugKey:e="debugKey",timeoutDuration:t=K,shouldThrowError:n=!0,pollingInterval:s=ye})=>(t=t<q?q:t,new Promise((r,a)=>{let i=setTimeout(()=>{o&&(clearInterval(o),n&&a(`Response could not be received from server for ${e}`)),clearTimeout(i)},t),o=setInterval(async()=>{u({resolve:r,reject:a,intervalId:o})&&(clearInterval(o),clearTimeout(i))},s)})),Ue=u=>new Promise(e=>{let t=new FileReader;t.readAsDataURL(u),t.onload=function(){e(t.result)}}),D=()=>tt(),Te=u=>nt(u);var be=({key:u,data:e,useZero:t=!0,shouldReturnString:n=!1})=>u.split(/\.|\[/).map(a=>a.replace(/\]$/,"")).reduce((a,i)=>{let o=t?0:void 0,p=a?.[i];if(!p)return o;if(Array.isArray(p)&&/^\d+$/.test(i)){let m=parseInt(i,10);return m>=0&&m<p.length?a[i]=p[m]:a[i]??o}else return a[i]??o},e||{})??{},fe=(u,e=1e3)=>new Promise(t=>setTimeout(t,u*e));var Re=(u,e)=>u.filter(t=>t.key!==e.key);var R=({key:u,value:e})=>e||e===0||e===!1?{[u]:e}:{},st=(u,e)=>Math.floor(Math.random()*(e-u+1))+u,ke=()=>st(1,Number.MAX_SAFE_INTEGER),De=(u,{debugKey:e="debugKey",timeoutDuration:t=K,shouldThrowError:n=!0,pollingInterval:s=ye})=>(t=t<q?q:t,new Promise((r,a)=>{let i=setTimeout(()=>{o&&(clearInterval(o),n&&a(`Response could not be received from server for ${e}`)),clearTimeout(i)},t),o=setInterval(async()=>{try{await u({resolve:r,reject:a,intervalId:o})&&(clearInterval(o),clearTimeout(i))}catch(p){clearInterval(o),clearTimeout(i),a(p)}},s)}));var x=async(u,e={})=>{let{delayInSeconds:t=1,callback:n}=e,s=e.maxRetries??1;for(;s;)try{return await u()}catch(r){if(n?.(),r?.error)throw r;if(s--,s>0)await fe(t),await x(u,{...e,maxRetries:s});else throw r}};var C=class{constructor({apiKey:e,url:t=Z.PRODUCTION,shouldReconnect:n=!0,globalMaxRetries:s=2,timeoutDuration:r=K}){this._listeners=[];this._globalMessages={};this._globalImages=[];this._globalErrors=[];this.ensureConnectionUUID=null;this.isWebsocketReadyState=()=>this._ws?.readyState===1;this.isInvalidAPIKey=()=>this._connectionError?.error?.code==="invalidApiKey";this.send=e=>{this._ws.send(JSON.stringify([e]))};this.uploadImage=async e=>{try{return await x(async()=>{let t=D();if(typeof e=="string"&&Te(e))return{imageURL:e,imageUUID:e,taskUUID:t,taskType:"imageUpload"};let n=typeof e=="string"?e:await Ue(e);return{imageURL:n,imageUUID:n,taskUUID:t,taskType:"imageUpload"}})}catch(t){throw t}};this.controlNetPreProcess=async({inputImage:e,preProcessorType:t,height:n,width:s,outputType:r,outputFormat:a,highThresholdCanny:i,lowThresholdCanny:o,includeHandsAndFaceOpenPose:p,includeCost:m,outputQuality:g,customTaskUUID:d,taskUUID:l,retry:c,includeGenerationTime:I,includePayload:h})=>{let b=c||this._globalMaxRetries,f,y=Date.now();try{return await x(async()=>{await this.ensureConnection();let k=await this.uploadImage(e);if(!k?.imageUUID)return null;let U=l||d||D(),w={inputImage:k.imageUUID,taskType:"imageControlNetPreProcess",taskUUID:U,preProcessorType:t,...R({key:"height",value:n}),...R({key:"width",value:s}),...R({key:"outputType",value:r}),...R({key:"outputFormat",value:a}),...R({key:"includeCost",value:m}),...R({key:"highThresholdCanny",value:i}),...R({key:"lowThresholdCanny",value:o}),...R({key:"includeHandsAndFaceOpenPose",value:p}),...g?{outputQuality:g}:{}};this.send({...w}),f=this.globalListener({taskUUID:U});let A=await M(({resolve:S,reject:B})=>{let v=this.getSingleMessage({taskUUID:U});if(v){if(v?.error)return B(v),!0;if(v)return S(v),!0}},{debugKey:"unprocessed-image",timeoutDuration:this._timeoutDuration});return f.destroy(),this.insertAdditionalResponse({response:A,payload:h?w:void 0,startTime:I?y:void 0}),A},{maxRetries:b,callback:()=>{f?.destroy()}})}catch(k){throw k}};this.controlNetPreprocess=async e=>this.controlNetPreProcess(e);this.requestImageToText=async({inputImage:e,inputs:t,includeCost:n,customTaskUUID:s,taskUUID:r,retry:a,includePayload:i,includeGenerationTime:o,deliveryMethod:p,skipResponse:m,model:g})=>{try{let d;e&&(d=await this.uploadImage(e));let c={taskUUID:r||s||D(),taskType:"caption",model:g,inputImage:d?.imageUUID,inputs:t,...R({key:"includeCost",value:n}),retry:a,includePayload:i,includeGenerationTime:o},I=await this.baseSingleRequest({payload:{...c,taskType:"caption"},debugKey:"caption"});if(m)return I;if(p==="async"){let h=I?.taskUUID;return(await this.pollForAsyncResults({taskUUID:h}))[0]}return I}catch(d){throw d}};this.caption=async e=>this.requestImageToText(e);this.removeImageBackground=async e=>{let{skipResponse:t,...n}=e;try{let s=n.deliveryMethod,r=await this.baseSingleRequest({payload:{...n,taskType:"removeBackground"},debugKey:"remove-background"});if(t)return r;if(s==="async"){let a=r?.taskUUID;return(await this.pollForAsyncResults({taskUUID:a}))[0]}return r}catch(s){throw s}};this.removeBackground=async e=>this.removeImageBackground(e);this.vectorize=async e=>this.baseSingleRequest({payload:{...e,taskType:"vectorize"},debugKey:"vectorize"});this.videoInference=async e=>{let{skipResponse:t,inputAudios:n,referenceVideos:s,...r}=e;try{let a=await this.baseSingleRequest({payload:{...r,...n?.length&&{inputAudios:n},...s?.length&&{referenceVideos:s},deliveryMethod:"async",taskType:"videoInference"},debugKey:"video-inference"});if(t)return a;let i=a?.taskUUID;return this.pollForAsyncResults({taskUUID:i,numberResults:e?.numberResults})}catch(a){throw a}};this.audioInference=async e=>{let{skipResponse:t,deliveryMethod:n="sync",...s}=e;try{let a=await(n==="sync"?this.baseSyncRequest:this.baseSingleRequest)({payload:{...s,numberResults:s.numberResults||1,taskType:"audioInference",deliveryMethod:n},groupKey:"REQUEST_AUDIO",debugKey:"audio-inference",skipResponse:t});if(t)return a;let i=a?.taskUUID;return n==="async"?this.pollForAsyncResults({taskUUID:i,numberResults:e?.numberResults}):a}catch(r){throw r}};this.threeDInference=async e=>{let{skipResponse:t,deliveryMethod:n="sync",...s}=e;try{let a=await(n==="sync"?this.baseSyncRequest:this.baseSingleRequest)({payload:{...s,numberResults:s.numberResults||1,taskType:"3dInference",deliveryMethod:n},groupKey:"REQUEST_IMAGES",debugKey:"three-d-inference",skipResponse:t});if(t)return a;let i=a?.taskUUID;return n==="async"?this.pollForAsyncResults({taskUUID:i,numberResults:e?.numberResults}):a}catch(r){throw r}};this.textInference=async e=>{let{skipResponse:t,deliveryMethod:n="sync",...s}=e;try{let a=await(n==="sync"?this.baseSyncRequest:this.baseSingleRequest)({payload:{...s,numberResults:s.numberResults||1,taskType:"textInference",deliveryMethod:n},groupKey:"REQUEST_TEXT",debugKey:"text-inference",skipResponse:t});if(t)return a;let i=a?.taskUUID;return n==="async"?this.pollForAsyncResults({taskUUID:i,numberResults:e?.numberResults}):a}catch(r){throw r}};this.getResponse=async e=>{let t=e.taskUUID;return this.baseSingleRequest({payload:{...e,customTaskUUID:t,taskType:"getResponse"},isMultiple:!0,debugKey:"async-results"})};this.upscaleGan=async({inputImage:e,inputs:t,model:n,upscaleFactor:s,outputType:r,outputFormat:a,includeCost:i,outputQuality:o,customTaskUUID:p,taskUUID:m,retry:g,includeGenerationTime:d,includePayload:l,skipResponse:c,deliveryMethod:I})=>{try{let h;e&&(h=await this.uploadImage(e));let f={taskUUID:m||p||D(),inputImage:h?.imageUUID,taskType:"upscale",inputs:t,model:n,upscaleFactor:s,...R({key:"includeCost",value:i}),...r?{outputType:r}:{},...o?{outputQuality:o}:{},...a?{outputFormat:a}:{},includePayload:l,includeGenerationTime:d,retry:g,deliveryMethod:I},y=await this.baseSingleRequest({payload:{...f,taskType:"upscale"},debugKey:"upscale"});if(c)return y;if(I==="async"){let k=y?.taskUUID;return(await this.pollForAsyncResults({taskUUID:k}))[0]}return y}catch(h){throw h}};this.upscale=async e=>this.upscaleGan(e);this.enhancePrompt=async({prompt:e,promptMaxLength:t=380,promptVersions:n=1,includeCost:s,customTaskUUID:r,taskUUID:a,retry:i,includeGenerationTime:o,includePayload:p})=>{let m=i||this._globalMaxRetries,g,d=Date.now();try{return await x(async()=>{await this.ensureConnection();let l=a||r||D(),c={prompt:e,taskUUID:l,promptMaxLength:t,promptVersions:n,...R({key:"includeCost",value:s}),taskType:"promptEnhance"};this.send(c),g=this.globalListener({taskUUID:l});let I=await M(({resolve:h,reject:b})=>{let f=this._globalMessages[l];if(f?.error)return b(f),!0;if(f?.length>=n)return delete this._globalMessages[l],h(f),!0},{debugKey:"enhance-prompt",timeoutDuration:this._timeoutDuration});return g.destroy(),this.insertAdditionalResponse({response:I,payload:p?c:void 0,startTime:o?d:void 0}),I},{maxRetries:m,callback:()=>{g?.destroy()}})}catch(l){throw l}};this.promptEnhance=async e=>this.enhancePrompt(e);this.modelUpload=async e=>{let{onUploadStream:t,retry:n,customTaskUUID:s,taskUUID:r,...a}=e,i=n||this._globalMaxRetries,o;try{return await x(async()=>{await this.ensureConnection();let p=r||s||D();this.send({...a,taskUUID:p,taskType:"modelUpload"});let m,g;return o=this.listenToUpload({taskUUID:p,onUploadStream:(l,c)=>{t?.(l,c),l?.status==="ready"?m=l:c&&(g=c)}}),await M(({resolve:l,reject:c})=>{if(m)return l(m),!0;if(g)return c(g),!1},{shouldThrowError:!1,timeoutDuration:60*60*1e3})},{maxRetries:i,callback:()=>{o?.destroy()}})}catch(p){throw p}};this.photoMaker=async(e,t)=>{let{onPartialImages:n,retry:s,customTaskUUID:r,taskUUID:a,numberResults:i,includeGenerationTime:o,includePayload:p,...m}=e,g=s||this._globalMaxRetries,d,l=[],c=0,I=Date.now();try{return await x(async()=>{await this.ensureConnection(),c++;let h=this._globalImages.filter(U=>l.includes(U.taskUUID)),b=a||r||D();l.push(b);let f=i-h.length,y={...m,...m.seed?{seed:m.seed}:{seed:ke()},...t??{},taskUUID:b,taskType:"photoMaker",numberResults:i};this.send({...y,numberResults:f}),d=this.listenToResponse({onPartialImages:n,taskUUID:b,groupKey:"REQUEST_IMAGES",requestPayload:p?y:void 0,startTime:o?I:void 0});let k=await this.getResponseWithSimilarTaskUUID({taskUUID:l,numberResults:i,lis:d});return d.destroy(),k},{maxRetries:g,callback:()=>{d?.destroy()}})}catch(h){if(h.taskUUID)throw h;if(c>=g)return this.handleIncompleteImages({taskUUIDs:l,error:h})}};this.modelSearch=async e=>this.baseSingleRequest({payload:{...e,taskType:"modelSearch"},debugKey:"model-search"});this.imageMasking=async e=>this.baseSingleRequest({payload:{...e,taskType:"imageMasking"},debugKey:"image-masking"});this.imageUpload=async e=>this.baseSingleRequest({payload:{...e,taskType:"imageUpload"},debugKey:"image-upload"});this.mediaStorage=async e=>this.baseSingleRequest({payload:{...e,operation:e.operation||"upload",taskType:"mediaStorage"},debugKey:"media-storage"});this.baseSingleRequest=async({payload:e,debugKey:t,isMultiple:n})=>{let{retry:s,customTaskUUID:r,taskUUID:a,includePayload:i,includeGenerationTime:o,...p}=e,m=s||this._globalMaxRetries,g,d=Date.now();try{return await x(async()=>{await this.ensureConnection();let l=a||r||D(),c={...p,taskUUID:l};this.send(c),g=this.globalListener({taskUUID:l});let I=await M(({resolve:h,reject:b})=>{let f=n?this.getMultipleMessages({taskUUID:l}):this.getSingleMessage({taskUUID:l});if(f){if(f?.error)return b(f),!0;if(f)return delete this._globalMessages[l],h(f),!0}},{debugKey:t,timeoutDuration:this._timeoutDuration});return this.insertAdditionalResponse({response:I,payload:i?c:void 0,startTime:o?d:void 0}),g.destroy(),I},{maxRetries:m,callback:()=>{g?.destroy()}})}catch(l){throw l}};this.baseSyncRequest=async({payload:e,groupKey:t,skipResponse:n=!1})=>{let{retry:s,customTaskUUID:r,includePayload:a,numberResults:i=1,onPartialResponse:o,includeGenerationTime:p,...m}=e,g=s||this._globalMaxRetries,d,l=[],c=0,I=Date.now();try{return await x(async()=>{await this.ensureConnection(),c++;let h=this._globalImages.filter(U=>l.includes(U.taskUUID)),b=r||D();l.push(b);let f=i-h.length,y={...m,taskUUID:b,numberResults:f};if(this.send(y),n)return new Promise((U,w)=>{let A=this.addListener({taskUUID:b,groupKey:t,lis:S=>{A.destroy(),S.error?w(S.error):U(S[b])}})});d=this.listenToResponse({onPartialImages:o,taskUUID:b,groupKey:t,requestPayload:a?y:void 0,startTime:p?I:void 0});let k=await this.getResponseWithSimilarTaskUUID({taskUUID:l,numberResults:i,lis:d});return d.destroy(),k},{maxRetries:g,callback:()=>{d?.destroy()}})}catch(h){throw h}};this.getSingleMessage=({taskUUID:e})=>{let t=this._globalMessages[e]?.[0],n=this._globalMessages[e];return!t&&!n?null:n?.error?n:t};this.getMultipleMessages=({taskUUID:e})=>{let t=this._globalMessages[e]?.[0],n=this._globalMessages[e];return!t&&!n?null:n};this.insertAdditionalResponse=({response:e,payload:t,startTime:n})=>{if(!t&&!n)return;let s=e;s.additionalResponse={},t&&(e.additionalResponse.payload=t),n&&(e.additionalResponse.generationTime=Date.now()-n)};this.disconnect=async()=>{this._shouldReconnect=!1,this._ws?.terminate?.(),this._ws?.close?.()};this.connected=()=>this.isWebsocketReadyState()&&!!this._connectionSessionUUID;this._apiKey=e,this._url=t,this._sdkType="CLIENT",this._shouldReconnect=n,this._globalMaxRetries=s,this._timeoutDuration=r}getUniqueUUID(e){return e.mediaUUID||e.audioUUID||e.imageUUID||e.videoUUID||e.outputs?.files?.map(t=>t.uuid).join("-")||e.text}async pollForAsyncResults({taskUUID:e,numberResults:t=1}){let n=new Map;return await De(async({resolve:s,reject:r})=>{try{let a=await this.getResponse({taskUUID:e});for(let o of a||[])if(o.status==="success"){let p=this.getUniqueUUID(o);p&&n.set(p,o)}return n.size===t?(s(Array.from(n.values())),!0):!1}catch(a){return r(a),!0}},{debugKey:"async-response",pollingInterval:2*1e3,timeoutDuration:10*60*1e3}),Array.from(n.values())}static async initialize(e){try{let t=new this(e);return await t.ensureConnection(),t}catch(t){throw t}}addListener({lis:e,groupKey:t,taskUUID:n}){let s=i=>{let o=Array.isArray(i?.data)?i.data:[i.data],p=i?.[0]?.errors?i?.[0]?.errors:Array.isArray(i?.errors)?i.errors:[i.errors],m=o.filter(d=>(d?.taskUUID||d?.taskType)===n);if(p.filter(d=>(d?.taskUUID||d?.taskType)===n).length){e({error:{...p[0]??{}}});return}if(m.length){e({[n]:o});return}},r={key:n||D(),listener:s,groupKey:t};return this._listeners.push(r),{destroy:()=>{this._listeners=Re(this._listeners,r)}}}connect(){this._ws.onopen=e=>{this._connectionSessionUUID?this.send({taskType:"authentication",apiKey:this._apiKey,connectionSessionUUID:this._connectionSessionUUID}):this.send({apiKey:this._apiKey,taskType:"authentication"}),this.addListener({taskUUID:"authentication",lis:t=>{if(t?.error){this._connectionError=t;return}this._connectionSessionUUID=t?.authentication?.[0]?.connectionSessionUUID,this._connectionError=void 0}})},this._ws.onmessage=e=>{let t=JSON.parse(e.data);for(let n of this._listeners)if(n?.listener?.(t))return},this._ws.onclose=e=>{this.isInvalidAPIKey()}}destroy(e){he(this._listeners,e)}listenToResponse({onPartialImages:e,taskUUID:t,groupKey:n,requestPayload:s,startTime:r}){return this.addListener({taskUUID:t,lis:a=>{let i=a?.[t]?.filter(o=>o.taskUUID===t);a.error?(e?.(i,a?.error&&a),this._globalErrors.push(a)):(i=i.map(o=>(this.insertAdditionalResponse({response:o,payload:s||void 0,startTime:r||void 0}),{...o})),e?.(i,a?.error&&a),this._sdkType==="CLIENT"?this._globalImages=[...this._globalImages,...(a?.[t]??[]).map(o=>(this.insertAdditionalResponse({response:o,payload:s||void 0,startTime:r||void 0}),{...o}))]:this._globalImages=[...this._globalImages,...i])},groupKey:n})}listenToUpload({onUploadStream:e,taskUUID:t}){return this.addListener({taskUUID:t,lis:n=>{let s=n?.error,r=n?.[t]?.[0],a=r?.taskUUID===t?r:null;(a||s)&&e?.(a||void 0,s)}})}globalListener({taskUUID:e}){return this.addListener({taskUUID:e,lis:t=>{if(t.error){this._globalMessages[e]=t;return}let n=be({key:e,data:t,useZero:!1});Array.isArray(n)?n.forEach(s=>{this._globalMessages[s.taskUUID]=[...this._globalMessages[s.taskUUID]??[],s]}):this._globalMessages[n.taskUUID]=n}})}async requestImages({outputType:e,outputFormat:t,uploadEndpoint:n,checkNSFW:s,positivePrompt:r,negativePrompt:a,seedImage:i,maskImage:o,strength:p,height:m,width:g,model:d,steps:l,scheduler:c,seed:I,CFGScale:h,clipSkip:b,usePromptWeighting:f,promptWeighting:y,numberResults:k=1,onPartialImages:U,includeCost:w,customTaskUUID:A,taskUUID:S,retry:B,refiner:v,maskMargin:T,outputQuality:Y,controlNet:G,lora:$,embeddings:ee,ipAdapters:te,providerSettings:ne,outpaint:se,acceleratorOptions:re,advancedFeatures:ae,referenceImages:oe,includeGenerationTime:Me,includePayload:Ce,...ie},Oe){let O,le,P=[],ue=0,ce=B||this._globalMaxRetries;try{await this.ensureConnection();let E=null,H=null,Q=[];if(i){let _=await this.uploadImage(i);if(!_)return[];E=_.imageUUID}if(o){let _=await this.uploadImage(o);if(!_)return[];H=_.imageUUID}if(G?.length)for(let _=0;_<G.length;_++){let N=G[_],{endStep:z,startStep:L,weight:j,guideImage:F,controlMode:Pe,startStepPercentage:Le,endStepPercentage:Fe,model:qe}=N,Ke=F?await this.uploadImage(F):null;Q.push({guideImage:Ke?.imageUUID,model:qe,endStep:z,startStep:L,weight:j,...R({key:"startStepPercentage",value:Le}),...R({key:"endStepPercentage",value:Fe}),controlMode:Pe||"controlnet"})}le={taskType:"imageInference",model:d,positivePrompt:r,...a?{negativePrompt:a}:{},...m?{height:m}:{},...g?{width:g}:{},numberResults:k,...e?{outputType:e}:{},...t?{outputFormat:t}:{},...n?{uploadEndpoint:n}:{},...R({key:"checkNSFW",value:s}),...R({key:"strength",value:p}),...R({key:"CFGScale",value:h}),...R({key:"clipSkip",value:b}),...R({key:"maskMargin",value:T}),...R({key:"usePromptWeighting",value:f}),...R({key:"steps",value:l}),...y?{promptWeighting:y}:{},...I?{seed:I}:{},...c?{scheduler:c}:{},...v?{refiner:v}:{},...se?{outpaint:se}:{},...R({key:"includeCost",value:w}),...E?{seedImage:E}:{},...H?{maskImage:H}:{},...Y?{outputQuality:Y}:{},...Q.length?{controlNet:Q}:{},...$?.length?{lora:$}:{},...ee?.length?{embeddings:ee}:{},...te?.length?{ipAdapters:te}:{},...ne?{providerSettings:ne}:{},...re?{acceleratorOptions:re}:{},...ae?{advancedFeatures:ae}:{},...oe?.length?{referenceImages:oe}:{},...ie,...Oe??{}};let Ne=Date.now();return await x(async()=>{ue++,O?.destroy();let _=this._globalImages.filter(F=>P.includes(F.taskUUID)),N=S||A||D();P.push(N);let z=k-_.length,L={...le,taskUUID:N,numberResults:z};this.send(L),O=this.listenToResponse({onPartialImages:U,taskUUID:N,groupKey:"REQUEST_IMAGES",requestPayload:Ce?L:void 0,startTime:Me?Ne:void 0});let j=await this.getResponseWithSimilarTaskUUID({taskUUID:P,numberResults:k,lis:O,deliveryMethod:ie.deliveryMethod});return O.destroy(),j},{maxRetries:ce,callback:()=>{O?.destroy()}})}catch(E){if(ue>=ce)return this.handleIncompleteImages({taskUUIDs:P,error:E});throw E}}async imageInference(e,t){return this.requestImages(e,t)}async ensureConnection(){if(this.connected()||this._url===Z.TEST)return;let t=2e3,n=200;try{if(this.isInvalidAPIKey())throw this._connectionError;return new Promise((s,r)=>{let a=0,i=30,o=D(),p,m,g=()=>{this.ensureConnectionUUID=null,clearInterval(p),clearInterval(m)};this._sdkType==="SERVER"&&(p=setInterval(async()=>{try{let d=this.connected(),l=!1;(!this.ensureConnectionUUID||o===this.ensureConnectionUUID)&&(this.ensureConnectionUUID||(this.ensureConnectionUUID=o),l=!0);let c=a%10===0&&l;d?(g(),s(!0)):a>=i?(g(),r(new Error("Retry timed out"))):(c&&this.connect(),a++)}catch(d){g(),r(d)}},t)),m=setInterval(async()=>{if(this.connected()){g(),s(!0);return}if(this.isInvalidAPIKey()){g(),r(this._connectionError);return}},n)})}catch{throw this.ensureConnectionUUID=null,this._connectionError=void 0,this._connectionError??"Could not connect to server. Ensure your API key is correct"}}async getResponseWithSimilarTaskUUID({taskUUID:e,numberResults:t,shouldThrowError:n,lis:s,deliveryMethod:r}){return await M(({resolve:a,reject:i,intervalId:o})=>{let p=Array.isArray(e)?e:[e],m=this._globalImages.filter(l=>p.includes(l.taskUUID)),g=r==="async"&&m.length>0,d=this._globalErrors.filter(l=>p.includes(l.error.taskUUID));if(d.length>0){let l=d[0];return this._globalErrors=this._globalErrors.filter(c=>!p.includes(c.error.taskUUID)),clearInterval(o),i?.(l),!0}else if(m.length>=t||g)return clearInterval(o),this._globalImages=this._globalImages.filter(l=>!p.includes(l.taskUUID)),a([...m].slice(0,t)),!0},{debugKey:"getting images",shouldThrowError:n,timeoutDuration:this._timeoutDuration})}handleIncompleteImages({taskUUIDs:e,error:t}){let n=this._globalImages.filter(s=>e.includes(s.taskUUID));if(n.length>1)return this._globalImages=this._globalImages.filter(s=>!e.includes(s.taskUUID)),n;throw t}};var Ae=je(we(),1),W=class extends C{constructor(e){let{shouldReconnect:t,...n}=e;super(n),this._ws=new Ae.default(this._url),this.connect()}};import ct from"ws";var V=class extends C{constructor(t){super(t);this._instantiated=!1;this._listeners=[];this._reconnectingIntervalId=null;this.send=t=>{this._ws.send(JSON.stringify([t]))};this.resetConnection=()=>{this._ws&&(this._listeners.forEach(t=>{t?.destroy?.()}),this._ws.removeAllListeners(),this._ws.readyState===1&&(this._ws.terminate(),this._ws.close()),this._ws=null,this._listeners=[])};this._sdkType="SERVER",this.connect()}async connect(){this._url&&(this.resetConnection(),this._ws=new ct(this._url,{perMessageDeflate:!1}),this._ws.on("error",()=>{}),this._ws.on("close",()=>{this.handleClose()}),this._ws.on("open",()=>{this._reconnectingIntervalId&&clearInterval(this._reconnectingIntervalId),this._connectionSessionUUID&&this.isWebsocketReadyState()?this.send({taskType:"authentication",apiKey:this._apiKey,connectionSessionUUID:this._connectionSessionUUID}):this.isWebsocketReadyState()&&this.send({apiKey:this._apiKey,taskType:"authentication"}),this.addListener({taskUUID:"authentication",lis:t=>{if(t?.error){this._connectionError=t;return}this._connectionSessionUUID=t?.authentication?.[0]?.connectionSessionUUID,this._connectionError=void 0}})}),this._ws.on("message",(t,n)=>{let s=n?t:t?.toString();if(!s)return;let r=JSON.parse(s);this._listeners.forEach(a=>{a.listener(r)})}))}handleClose(){this.isInvalidAPIKey()||(this._reconnectingIntervalId&&clearInterval(this._reconnectingIntervalId),this._shouldReconnect&&setTimeout(()=>this.connect(),1e3))}heartBeat(){clearTimeout(this._pingTimeout),this._pingTimeout=setTimeout(()=>{this.isWebsocketReadyState()&&this.send({ping:!0})},5e3)}};var Ee;typeof window>"u"?Ee=V:Ee=W;export{ge as EControlMode,Ze as EModelArchitecture,$e as EModelConditioning,Je as EModelFormat,Ye as EModelType,Xe as EOpenPosePreProcessor,et as EPhotoMakerEnum,Ie as EPreProcessor,me as EPreProcessorGroup,J as ETaskType,pe as Environment,Ee as Runware,W as RunwareClient,V as RunwareServer,X as SdkType};
|
|
1
|
+
var Ge=Object.create;var ge=Object.defineProperty;var He=Object.getOwnPropertyDescriptor;var je=Object.getOwnPropertyNames;var Qe=Object.getPrototypeOf,ze=Object.prototype.hasOwnProperty;var Xe=(l,e)=>()=>(e||l((e={exports:{}}).exports,e),e.exports);var $e=(l,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of je(e))!ze.call(l,n)&&n!==t&&ge(l,n,{get:()=>e[n],enumerable:!(s=He(e,n))||s.enumerable});return l};var Je=(l,e,t)=>(t=l!=null?Ge(Qe(l)):{},$e(e||!l||!l.__esModule?ge(t,"default",{value:l,enumerable:!0}):t,l));var Me=Xe((_s,Ee)=>{"use strict";var we=l=>l&&l.CLOSING===2,lt=()=>typeof WebSocket<"u"&&we(WebSocket),ut=()=>({constructor:lt()?WebSocket:null,maxReconnectionDelay:1e4,minReconnectionDelay:1500,reconnectionDelayGrowFactor:1.3,connectionTimeout:4e3,maxRetries:1/0,debug:!1}),ct=(l,e,t)=>{Object.defineProperty(e,t,{get:()=>l[t],set:s=>{l[t]=s},enumerable:!0,configurable:!0})},Se=l=>l.minReconnectionDelay+Math.random()*l.minReconnectionDelay,dt=(l,e)=>{let t=e*l.reconnectionDelayGrowFactor;return t>l.maxReconnectionDelay?l.maxReconnectionDelay:t},pt=["onopen","onclose","onmessage","onerror"],gt=(l,e,t)=>{Object.keys(t).forEach(s=>{t[s].forEach(([n,o])=>{l.addEventListener(s,n,o)})}),e&&pt.forEach(s=>{l[s]=e[s]})},Ae=function(l,e,t={}){let s,n,o=0,r=0,a=!0,i={};if(!(this instanceof Ae))throw new TypeError("Failed to construct 'ReconnectingWebSocket': Please use the 'new' operator");let d=ut();if(Object.keys(d).filter(c=>t.hasOwnProperty(c)).forEach(c=>d[c]=t[c]),!we(d.constructor))throw new TypeError("Invalid WebSocket constructor. Set `options.constructor`");let m=d.debug?(...c)=>console.log("RWS:",...c):()=>{},g=(c,y)=>setTimeout(()=>{let U=new Error(y);U.code=c,Array.isArray(i.error)&&i.error.forEach(([b])=>b(U)),s.onerror&&s.onerror(U)},0),p=()=>{if(m("close"),r++,m("retries count:",r),r>d.maxRetries){g("EHOSTDOWN","Too many failed connection attempts");return}o?o=dt(d,o):o=Se(d),m("reconnectDelay:",o),a&&setTimeout(u,o)},u=()=>{m("connect");let c=s;s=new d.constructor(l,e),n=setTimeout(()=>{m("timeout"),s.close(),g("ETIMEDOUT","Connection timeout")},d.connectionTimeout),m("bypass properties");for(let y in s)["addEventListener","removeEventListener","close","send"].indexOf(y)<0&&ct(s,this,y);s.addEventListener("open",()=>{clearTimeout(n),m("open"),o=Se(d),m("reconnectDelay:",o),r=0}),s.addEventListener("close",p),gt(s,c,i)};m("init"),u(),this.close=(c=1e3,y="",{keepClosed:U=!1,fastClose:b=!0,delay:f=0}={})=>{if(f&&(o=f),a=!U,s.close(c,y),b){let h={code:c,reason:y,wasClean:!0};p(),Array.isArray(i.close)&&i.close.forEach(([k,I])=>{k(h),s.removeEventListener("close",k,I)}),s.onclose&&(s.onclose(h),s.onclose=null)}},this.send=c=>{s.send(c)},this.addEventListener=(c,y,U)=>{Array.isArray(i[c])?i[c].some(([b])=>b===y)||i[c].push([y,U]):i[c]=[[y,U]],s.addEventListener(c,y,U)},this.removeEventListener=(c,y,U)=>{Array.isArray(i[c])&&(i[c]=i[c].filter(([b])=>b!==y)),s.removeEventListener(c,y,U)}};Ee.exports=Ae});var me=(s=>(s.PRODUCTION="PRODUCTION",s.DEVELOPMENT="DEVELOPMENT",s.TEST="TEST",s))(me||{}),J=(t=>(t.CLIENT="CLIENT",t.SERVER="SERVER",t))(J||{}),Z=(h=>(h.IMAGE_INFERENCE="imageInference",h.IMAGE_UPLOAD="imageUpload",h.UPSCALE="upscale",h.REMOVE_BACKGROUND="removeBackground",h.VIDEO_INFERENCE="videoInference",h.CAPTION="caption",h.AUDIO_INFERENCE="audioInference",h.THREE_D_INFERENCE="3dInference",h.GET_RESPONSE="getResponse",h.PHOTO_MAKER="photoMaker",h.IMAGE_CONTROL_NET_PRE_PROCESS="imageControlNetPreProcess",h.IMAGE_MASKING="imageMasking",h.PROMPT_ENHANCE="promptEnhance",h.AUTHENTICATION="authentication",h.MODEL_UPLOAD="modelUpload",h.MODEL_SEARCH="modelSearch",h.MEDIA_STORAGE="mediaStorage",h.VECTORIZE="vectorize",h.TEXT_INFERENCE="textInference",h))(Z||{}),Ie=(s=>(s.BALANCED="balanced",s.PROMPT="prompt",s.CONTROL_NET="controlnet",s))(Ie||{}),ye=(p=>(p.canny="canny",p.depth="depth",p.mlsd="mlsd",p.normalbae="normalbae",p.openpose="openpose",p.tile="tile",p.seg="seg",p.lineart="lineart",p.lineart_anime="lineart_anime",p.shuffle="shuffle",p.scribble="scribble",p.softedge="softedge",p))(ye||{}),he=(T=>(T.canny="canny",T.depth_leres="depth_leres",T.depth_midas="depth_midas",T.depth_zoe="depth_zoe",T.inpaint_global_harmonious="inpaint_global_harmonious",T.lineart_anime="lineart_anime",T.lineart_coarse="lineart_coarse",T.lineart_realistic="lineart_realistic",T.lineart_standard="lineart_standard",T.mlsd="mlsd",T.normal_bae="normal_bae",T.scribble_hed="scribble_hed",T.scribble_pidinet="scribble_pidinet",T.seg_ofade20k="seg_ofade20k",T.seg_ofcoco="seg_ofcoco",T.seg_ufade20k="seg_ufade20k",T.shuffle="shuffle",T.softedge_hed="softedge_hed",T.softedge_hedsafe="softedge_hedsafe",T.softedge_pidinet="softedge_pidinet",T.softedge_pidisafe="softedge_pidisafe",T.tile_gaussian="tile_gaussian",T.openpose="openpose",T.openpose_face="openpose_face",T.openpose_faceonly="openpose_faceonly",T.openpose_full="openpose_full",T.openpose_hand="openpose_hand",T))(he||{}),Ze=(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))(Ze||{}),Ye=(t=>(t.safetensors="safetensors",t.pickletensor="pickletensor",t))(Ye||{}),et=(u=>(u.flux1d="flux1d",u.flux1s="flux1s",u.pony="pony",u.sdhyper="sdhyper",u.sd1x="sd1x",u.sd1xlcm="sd1xlcm",u.sd3="sd3",u.sdxl="sdxl",u.sdxllcm="sdxllcm",u.sdxldistilled="sdxldistilled",u.sdxlhyper="sdxlhyper",u.sdxllightning="sdxllightning",u.sdxlturbo="sdxlturbo",u))(et||{}),tt=(s=>(s.base="base",s.inpainting="inpainting",s.pix2pix="pix2pix",s))(tt||{}),st=(I=>(I.canny="canny",I.depth="depth",I.qrcode="qrcode",I.hed="hed",I.scrible="scrible",I.openpose="openpose",I.seg="segmentation",I.openmlsd="openmlsd",I.softedge="softedge",I.normal="normal bae",I.shuffle="shuffle",I.pix2pix="pix2pix",I.inpaint="inpaint",I.lineart="line art",I.sketch="sketch",I.inpaintdepth="inpaint depth",I.tile="tile",I.outfit="outfit",I.blur="blur",I.gray="gray",I.lowquality="low quality",I))(st||{}),nt=(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))(nt||{});import{v4 as ot,validate as at}from"uuid";var Ue={name:"@runware/sdk-js",version:"1.2.7",description:"The SDK is used to run image inference with the Runware API, powered by the RunWare inference platform. It can be used to generate imaged with text-to-image and image-to-image. It also allows the use of an existing gallery of models or selecting any model or LoRA from the CivitAI gallery. The API also supports upscaling, background removal, inpainting and outpainting, and a series of other ControlNet models.",main:"dist/index.js",module:"dist/index.js",types:"dist/index.d.ts",type:"module",exports:{".":{types:"./dist/index.d.ts",require:"./dist/index.cjs",import:"./dist/index.js"}},files:["dist/"],scripts:{build:"tsup",lint:"tsc",pkg:"npx pkgfiles","dev:test":"vitest --reporter verbose",test:"vitest run --reporter verbose","test:single":"vitest run --reporter verbose tests/Runware/upscale-gan.test.ts",debug:"tsx tests/script.ts","beta:tag":"npm publish --tag beta"},keywords:["runware","sdk","ai"],author:"",license:"ISC",devDependencies:{"@types/uuid":"^9.0.6","@types/ws":"^8.5.8",dotenv:"^16.4.5","mock-socket":"^9.3.1",tsup:"^8.3.5",typescript:"^5.2.2",vitest:"^0.34.6"},dependencies:{uuid:"^9.0.1",ws:"^8.18.0"},optionalDependencies:{bufferutil:"^4.0.8"},directories:{test:"tests"}};var q=Ue.version;function W(l){let e=l.includes("?")?"&":"?";return`${l}${e}sdk=js&version=${q}`}var V=6e4,K=1e3,Te=100,Y={PRODUCTION:"wss://ws-api.runware.ai/v1",TEST:"ws://localhost:8080"},be=(l,e)=>{if(l==null)return;let t=l.indexOf(e);t!==-1&&l.splice(t,1)},M=(l,{debugKey:e="debugKey",timeoutDuration:t=V,shouldThrowError:s=!0,pollingInterval:n=Te})=>(t=t<K?K:t,new Promise((o,r)=>{let a=setTimeout(()=>{i&&(clearInterval(i),s&&r(`Response could not be received from server for ${e}`)),clearTimeout(a)},t),i=setInterval(async()=>{l({resolve:o,reject:r,intervalId:i})&&(clearInterval(i),clearTimeout(a))},n)})),fe=l=>new Promise(e=>{let t=new FileReader;t.readAsDataURL(l),t.onload=function(){e(t.result)}}),D=()=>ot(),Re=l=>at(l);var ke=({key:l,data:e,useZero:t=!0,shouldReturnString:s=!1})=>l.split(/\.|\[/).map(r=>r.replace(/\]$/,"")).reduce((r,a)=>{let i=t?0:void 0,d=r?.[a];if(!d)return i;if(Array.isArray(d)&&/^\d+$/.test(a)){let m=parseInt(a,10);return m>=0&&m<d.length?r[a]=d[m]:r[a]??i}else return r[a]??i},e||{})??{},De=(l,e=1e3)=>new Promise(t=>setTimeout(t,l*e));var _e=(l,e)=>l.filter(t=>t.key!==e.key);var R=({key:l,value:e})=>e||e===0||e===!1?{[l]:e}:{},it=(l,e)=>Math.floor(Math.random()*(e-l+1))+l,xe=()=>it(1,Number.MAX_SAFE_INTEGER),ve=(l,{debugKey:e="debugKey",timeoutDuration:t=V,shouldThrowError:s=!0,pollingInterval:n=Te})=>(t=t<K?K:t,new Promise((o,r)=>{let a=setTimeout(()=>{i&&(clearInterval(i),s&&r(`Response could not be received from server for ${e}`)),clearTimeout(a)},t),i=setInterval(async()=>{try{await l({resolve:o,reject:r,intervalId:i})&&(clearInterval(i),clearTimeout(a))}catch(d){clearInterval(i),clearTimeout(a),r(d)}},n)}));var x=async(l,e={})=>{let{delayInSeconds:t=1,callback:s}=e,n=e.maxRetries??1;for(;n;)try{return await l()}catch(o){if(s?.(),o?.error)throw o;if(n--,n>0)return await De(t),await x(l,{...e,maxRetries:n});throw o}};var C=class{constructor({apiKey:e,url:t=Y.PRODUCTION,shouldReconnect:s=!0,globalMaxRetries:n=2,timeoutDuration:o=V}){this._listeners=[];this._globalMessages={};this._globalImages=[];this._globalErrors=[];this.ensureConnectionUUID=null;this.isWebsocketReadyState=()=>this._ws?.readyState===1;this.isInvalidAPIKey=()=>this._connectionError?.error?.code==="invalidApiKey";this.send=e=>{this._ws.send(JSON.stringify([e]))};this.uploadImage=async e=>{try{return await x(async()=>{let t=D();if(typeof e=="string"&&Re(e))return{imageURL:e,imageUUID:e,taskUUID:t,taskType:"imageUpload"};let s=typeof e=="string"?e:await fe(e);return{imageURL:s,imageUUID:s,taskUUID:t,taskType:"imageUpload"}})}catch(t){throw t}};this.controlNetPreProcess=async({inputImage:e,preProcessorType:t,height:s,width:n,outputType:o,outputFormat:r,highThresholdCanny:a,lowThresholdCanny:i,includeHandsAndFaceOpenPose:d,includeCost:m,outputQuality:g,customTaskUUID:p,taskUUID:u,retry:c,includeGenerationTime:y,includePayload:U})=>{let b=c||this._globalMaxRetries,f,h=Date.now();try{return await x(async()=>{await this.ensureConnection();let k=await this.uploadImage(e);if(!k?.imageUUID)return null;let I=u||p||D(),w={inputImage:k.imageUUID,taskType:"imageControlNetPreProcess",taskUUID:I,preProcessorType:t,...R({key:"height",value:s}),...R({key:"width",value:n}),...R({key:"outputType",value:o}),...R({key:"outputFormat",value:r}),...R({key:"includeCost",value:m}),...R({key:"highThresholdCanny",value:a}),...R({key:"lowThresholdCanny",value:i}),...R({key:"includeHandsAndFaceOpenPose",value:d}),...g?{outputQuality:g}:{}};this.send({...w}),f=this.globalListener({taskUUID:I});let A=await M(({resolve:S,reject:H})=>{let v=this.getSingleMessage({taskUUID:I});if(v){if(v?.error)return H(v),!0;if(v)return S(v),!0}},{debugKey:"unprocessed-image",timeoutDuration:this._timeoutDuration});return f.destroy(),this.insertAdditionalResponse({response:A,payload:U?w:void 0,startTime:y?h:void 0}),A},{maxRetries:b,callback:()=>{f?.destroy()}})}catch(k){throw k}};this.controlNetPreprocess=async e=>this.controlNetPreProcess(e);this.requestImageToText=async({inputImage:e,inputs:t,includeCost:s,customTaskUUID:n,taskUUID:o,retry:r,includePayload:a,includeGenerationTime:i,deliveryMethod:d,skipResponse:m,model:g})=>{try{let p;e&&(p=await this.uploadImage(e));let c={taskUUID:o||n||D(),taskType:"caption",model:g,inputImage:p?.imageUUID,inputs:t,...R({key:"includeCost",value:s}),retry:r,includePayload:a,includeGenerationTime:i},y=await this.baseSingleRequest({payload:{...c,taskType:"caption"},debugKey:"caption"});if(m)return y;if(d==="async"){let U=y?.taskUUID;return(await this.pollForAsyncResults({taskUUID:U}))[0]}return y}catch(p){throw p}};this.caption=async e=>this.requestImageToText(e);this.removeImageBackground=async e=>{let{skipResponse:t,...s}=e;try{let n=s.deliveryMethod,o=await this.baseSingleRequest({payload:{...s,taskType:"removeBackground"},debugKey:"remove-background"});if(t)return o;if(n==="async"){let r=o?.taskUUID;return(await this.pollForAsyncResults({taskUUID:r}))[0]}return o}catch(n){throw n}};this.removeBackground=async e=>this.removeImageBackground(e);this.vectorize=async e=>this.baseSingleRequest({payload:{...e,taskType:"vectorize"},debugKey:"vectorize"});this.videoInference=async e=>{let{skipResponse:t,inputAudios:s,referenceVideos:n,...o}=e;try{let r=await this.baseSingleRequest({payload:{...o,...s?.length&&{inputAudios:s},...n?.length&&{referenceVideos:n},deliveryMethod:"async",taskType:"videoInference"},debugKey:"video-inference"});if(t)return r;let a=r?.taskUUID;return this.pollForAsyncResults({taskUUID:a,numberResults:e?.numberResults})}catch(r){throw r}};this.audioInference=async e=>{let{skipResponse:t,deliveryMethod:s="sync",...n}=e;try{let r=await(s==="sync"?this.baseSyncRequest:this.baseSingleRequest)({payload:{...n,numberResults:n.numberResults||1,taskType:"audioInference",deliveryMethod:s},groupKey:"REQUEST_AUDIO",debugKey:"audio-inference",skipResponse:t});if(t)return r;let a=r?.taskUUID;return s==="async"?this.pollForAsyncResults({taskUUID:a,numberResults:e?.numberResults}):r}catch(o){throw o}};this.threeDInference=async e=>{let{skipResponse:t,deliveryMethod:s="sync",...n}=e;try{let r=await(s==="sync"?this.baseSyncRequest:this.baseSingleRequest)({payload:{...n,numberResults:n.numberResults||1,taskType:"3dInference",deliveryMethod:s},groupKey:"REQUEST_IMAGES",debugKey:"three-d-inference",skipResponse:t});if(t)return r;let a=r?.taskUUID;return s==="async"?this.pollForAsyncResults({taskUUID:a,numberResults:e?.numberResults}):r}catch(o){throw o}};this.textInference=async e=>{let{skipResponse:t,deliveryMethod:s="sync",...n}=e;try{let r=await(s==="sync"?this.baseSyncRequest:this.baseSingleRequest)({payload:{...n,numberResults:n.numberResults||1,taskType:"textInference",deliveryMethod:s},groupKey:"REQUEST_TEXT",debugKey:"text-inference",skipResponse:t});if(t)return r;let a=r?.taskUUID;return s==="async"?this.pollForAsyncResults({taskUUID:a,numberResults:e?.numberResults}):r}catch(o){throw o}};this.getResponse=async e=>{let t=e.taskUUID;return this.baseSingleRequest({payload:{...e,customTaskUUID:t,taskType:"getResponse"},isMultiple:!0,debugKey:"async-results"})};this.upscaleGan=async e=>{let{inputImage:t,skipResponse:s,deliveryMethod:n="sync",...o}=e;try{let r;t&&(r=await this.uploadImage(t));let a=await this.baseSingleRequest({payload:{...o,...r?.imageUUID?{inputImage:r.imageUUID}:{},taskType:"upscale",deliveryMethod:n},debugKey:"upscale"});if(s)return a;if(n==="async"){let i=a?.taskUUID;return(await this.pollForAsyncResults({taskUUID:i}))[0]}return a}catch(r){throw r}};this.upscale=async e=>this.upscaleGan(e);this.enhancePrompt=async({prompt:e,promptMaxLength:t=380,promptVersions:s=1,includeCost:n,customTaskUUID:o,taskUUID:r,retry:a,includeGenerationTime:i,includePayload:d})=>{let m=a||this._globalMaxRetries,g,p=Date.now();try{return await x(async()=>{await this.ensureConnection();let u=r||o||D(),c={prompt:e,taskUUID:u,promptMaxLength:t,promptVersions:s,...R({key:"includeCost",value:n}),taskType:"promptEnhance"};this.send(c),g=this.globalListener({taskUUID:u});let y=await M(({resolve:U,reject:b})=>{let f=this._globalMessages[u];if(f?.error)return b(f),!0;if(f?.length>=s)return delete this._globalMessages[u],U(f),!0},{debugKey:"enhance-prompt",timeoutDuration:this._timeoutDuration});return g.destroy(),this.insertAdditionalResponse({response:y,payload:d?c:void 0,startTime:i?p:void 0}),y},{maxRetries:m,callback:()=>{g?.destroy()}})}catch(u){throw u}};this.promptEnhance=async e=>this.enhancePrompt(e);this.modelUpload=async e=>{let{onUploadStream:t,retry:s,customTaskUUID:n,taskUUID:o,...r}=e,a=s||this._globalMaxRetries,i;try{return await x(async()=>{await this.ensureConnection();let d=o||n||D();this.send({...r,taskUUID:d,taskType:"modelUpload"});let m,g;return i=this.listenToUpload({taskUUID:d,onUploadStream:(u,c)=>{t?.(u,c),u?.status==="ready"?m=u:c&&(g=c)}}),await M(({resolve:u,reject:c})=>{if(m)return u(m),!0;if(g)return c(g),!1},{shouldThrowError:!1,timeoutDuration:60*60*1e3})},{maxRetries:a,callback:()=>{i?.destroy()}})}catch(d){throw d}};this.photoMaker=async(e,t)=>{let{onPartialImages:s,retry:n,customTaskUUID:o,taskUUID:r,numberResults:a,includeGenerationTime:i,includePayload:d,...m}=e,g=n||this._globalMaxRetries,p,u=[],c=0,y=Date.now();try{return await x(async()=>{await this.ensureConnection(),c++;let U=this._globalImages.filter(I=>u.includes(I.taskUUID)),b=r||o||D();u.push(b);let f=a-U.length,h={...m,...m.seed?{seed:m.seed}:{seed:xe()},...t??{},taskUUID:b,taskType:"photoMaker",numberResults:a};this.send({...h,numberResults:f}),p=this.listenToResponse({onPartialImages:s,taskUUID:b,groupKey:"REQUEST_IMAGES",requestPayload:d?h:void 0,startTime:i?y:void 0});let k=await this.getResponseWithSimilarTaskUUID({taskUUID:u,numberResults:a,lis:p});return p.destroy(),k},{maxRetries:g,callback:()=>{p?.destroy()}})}catch(U){if(U.taskUUID)throw U;if(c>=g)return this.handleIncompleteImages({taskUUIDs:u,error:U})}};this.modelSearch=async e=>this.baseSingleRequest({payload:{...e,taskType:"modelSearch"},debugKey:"model-search"});this.imageMasking=async e=>this.baseSingleRequest({payload:{...e,taskType:"imageMasking"},debugKey:"image-masking"});this.imageUpload=async e=>this.baseSingleRequest({payload:{...e,taskType:"imageUpload"},debugKey:"image-upload"});this.mediaStorage=async e=>this.baseSingleRequest({payload:{...e,operation:e.operation||"upload",taskType:"mediaStorage"},debugKey:"media-storage"});this.baseSingleRequest=async({payload:e,debugKey:t,isMultiple:s})=>{let{retry:n,customTaskUUID:o,taskUUID:r,includePayload:a,includeGenerationTime:i,...d}=e,m=n||this._globalMaxRetries,g,p=Date.now();try{return await x(async()=>{await this.ensureConnection();let u=r||o||D(),c={...d,taskUUID:u};this.send(c),g=this.globalListener({taskUUID:u});let y=await M(({resolve:U,reject:b})=>{let f=s?this.getMultipleMessages({taskUUID:u}):this.getSingleMessage({taskUUID:u});if(f){if(f?.error)return b(f),!0;if(f)return delete this._globalMessages[u],U(f),!0}},{debugKey:t,timeoutDuration:this._timeoutDuration});return this.insertAdditionalResponse({response:y,payload:a?c:void 0,startTime:i?p:void 0}),g.destroy(),y},{maxRetries:m,callback:()=>{g?.destroy()}})}catch(u){throw u}};this.baseSyncRequest=async({payload:e,groupKey:t,skipResponse:s=!1})=>{let{retry:n,customTaskUUID:o,includePayload:r,numberResults:a=1,onPartialResponse:i,includeGenerationTime:d,...m}=e,g=n||this._globalMaxRetries,p,u=[],c=0,y=Date.now();try{return await x(async()=>{await this.ensureConnection(),c++;let U=this._globalImages.filter(I=>u.includes(I.taskUUID)),b=o||D();u.push(b);let f=a-U.length,h={...m,taskUUID:b,numberResults:f};if(this.send(h),s)return new Promise((I,w)=>{let A=this.addListener({taskUUID:b,groupKey:t,lis:S=>{A.destroy(),S.error?w(S.error):I(S[b])}})});p=this.listenToResponse({onPartialImages:i,taskUUID:b,groupKey:t,requestPayload:r?h:void 0,startTime:d?y:void 0});let k=await this.getResponseWithSimilarTaskUUID({taskUUID:u,numberResults:a,lis:p});return p.destroy(),k},{maxRetries:g,callback:()=>{p?.destroy()}})}catch(U){throw U}};this.getSingleMessage=({taskUUID:e})=>{let t=this._globalMessages[e]?.[0],s=this._globalMessages[e];return!t&&!s?null:s?.error?s:t};this.getMultipleMessages=({taskUUID:e})=>{let t=this._globalMessages[e]?.[0],s=this._globalMessages[e];return!t&&!s?null:s};this.insertAdditionalResponse=({response:e,payload:t,startTime:s})=>{if(!t&&!s)return;let n=e;n.additionalResponse={},t&&(e.additionalResponse.payload=t),s&&(e.additionalResponse.generationTime=Date.now()-s)};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=s,this._globalMaxRetries=n,this._timeoutDuration=o}getUniqueUUID(e){return e.mediaUUID||e.audioUUID||e.imageUUID||e.videoUUID||e.outputs?.files?.map(t=>t.uuid).join("-")||e.text}async pollForAsyncResults({taskUUID:e,numberResults:t=1}){let s=new Map;return await ve(async({resolve:n,reject:o})=>{try{let r=await this.getResponse({taskUUID:e});for(let i of r||[])if(i.status==="success"){let d=this.getUniqueUUID(i);d&&s.set(d,i)}return s.size===t?(n(Array.from(s.values())),!0):!1}catch(r){return o(r),!0}},{debugKey:"async-response",pollingInterval:2*1e3,timeoutDuration:10*60*1e3}),Array.from(s.values())}static async initialize(e){try{let t=new this(e);return await t.ensureConnection(),t}catch(t){throw t}}addListener({lis:e,groupKey:t,taskUUID:s}){let n=a=>{let i=Array.isArray(a?.data)?a.data:[a.data],d=a?.[0]?.errors?a?.[0]?.errors:Array.isArray(a?.errors)?a.errors:[a.errors],m=i.filter(p=>(p?.taskUUID||p?.taskType)===s);if(d.filter(p=>(p?.taskUUID||p?.taskType)===s).length){e({error:{...d[0]??{}}});return}if(m.length){e({[s]:i});return}},o={key:s||D(),listener:n,groupKey:t};return this._listeners.push(o),{destroy:()=>{this._listeners=_e(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 s of this._listeners)if(s?.listener?.(t))return},this._ws.onclose=e=>{this.isInvalidAPIKey()}}destroy(e){be(this._listeners,e)}listenToResponse({onPartialImages:e,taskUUID:t,groupKey:s,requestPayload:n,startTime:o}){return this.addListener({taskUUID:t,lis:r=>{let a=r?.[t]?.filter(i=>i.taskUUID===t);r.error?(e?.(a,r?.error&&r),this._globalErrors.push(r)):(a=a.map(i=>(this.insertAdditionalResponse({response:i,payload:n||void 0,startTime:o||void 0}),{...i})),e?.(a,r?.error&&r),this._sdkType==="CLIENT"?this._globalImages=[...this._globalImages,...(r?.[t]??[]).map(i=>(this.insertAdditionalResponse({response:i,payload:n||void 0,startTime:o||void 0}),{...i}))]:this._globalImages=[...this._globalImages,...a])},groupKey:s})}listenToUpload({onUploadStream:e,taskUUID:t}){return this.addListener({taskUUID:t,lis:s=>{let n=s?.error,o=s?.[t]?.[0],r=o?.taskUUID===t?o:null;(r||n)&&e?.(r||void 0,n)}})}globalListener({taskUUID:e}){return this.addListener({taskUUID:e,lis:t=>{if(t.error){this._globalMessages[e]=t;return}let s=ke({key:e,data:t,useZero:!1});Array.isArray(s)?s.forEach(n=>{this._globalMessages[n.taskUUID]=[...this._globalMessages[n.taskUUID]??[],n]}):this._globalMessages[s.taskUUID]=s}})}async requestImages({outputType:e,outputFormat:t,uploadEndpoint:s,checkNSFW:n,positivePrompt:o,negativePrompt:r,seedImage:a,maskImage:i,strength:d,height:m,width:g,model:p,steps:u,scheduler:c,seed:y,CFGScale:U,clipSkip:b,usePromptWeighting:f,promptWeighting:h,numberResults:k=1,onPartialImages:I,includeCost:w,customTaskUUID:A,taskUUID:S,retry:H,refiner:v,maskMargin:T,outputQuality:ee,controlNet:j,lora:te,embeddings:se,ipAdapters:ne,providerSettings:re,outpaint:oe,acceleratorOptions:ae,advancedFeatures:ie,referenceImages:le,includeGenerationTime:Ne,includePayload:Pe,...ue},Le){let O,ce,P=[],de=0,pe=H||this._globalMaxRetries;try{await this.ensureConnection();let E=null,Q=null,z=[];if(a){let _=await this.uploadImage(a);if(!_)return[];E=_.imageUUID}if(i){let _=await this.uploadImage(i);if(!_)return[];Q=_.imageUUID}if(j?.length)for(let _=0;_<j.length;_++){let N=j[_],{endStep:X,startStep:L,weight:$,guideImage:F,controlMode:Ke,startStepPercentage:qe,endStepPercentage:We,model:Ve}=N,Be=F?await this.uploadImage(F):null;z.push({guideImage:Be?.imageUUID,model:Ve,endStep:X,startStep:L,weight:$,...R({key:"startStepPercentage",value:qe}),...R({key:"endStepPercentage",value:We}),controlMode:Ke||"controlnet"})}ce={taskType:"imageInference",model:p,positivePrompt:o,...r?{negativePrompt:r}:{},...m?{height:m}:{},...g?{width:g}:{},numberResults:k,...e?{outputType:e}:{},...t?{outputFormat:t}:{},...s?{uploadEndpoint:s}:{},...R({key:"checkNSFW",value:n}),...R({key:"strength",value:d}),...R({key:"CFGScale",value:U}),...R({key:"clipSkip",value:b}),...R({key:"maskMargin",value:T}),...R({key:"usePromptWeighting",value:f}),...R({key:"steps",value:u}),...h?{promptWeighting:h}:{},...y?{seed:y}:{},...c?{scheduler:c}:{},...v?{refiner:v}:{},...oe?{outpaint:oe}:{},...R({key:"includeCost",value:w}),...E?{seedImage:E}:{},...Q?{maskImage:Q}:{},...ee?{outputQuality:ee}:{},...z.length?{controlNet:z}:{},...te?.length?{lora:te}:{},...se?.length?{embeddings:se}:{},...ne?.length?{ipAdapters:ne}:{},...re?{providerSettings:re}:{},...ae?{acceleratorOptions:ae}:{},...ie?{advancedFeatures:ie}:{},...le?.length?{referenceImages:le}:{},...ue,...Le??{}};let Fe=Date.now();return await x(async()=>{de++,O?.destroy();let _=this._globalImages.filter(F=>P.includes(F.taskUUID)),N=S||A||D();P.push(N);let X=k-_.length,L={...ce,taskUUID:N,numberResults:X};this.send(L),O=this.listenToResponse({onPartialImages:I,taskUUID:N,groupKey:"REQUEST_IMAGES",requestPayload:Pe?L:void 0,startTime:Ne?Fe:void 0});let $=await this.getResponseWithSimilarTaskUUID({taskUUID:P,numberResults:k,lis:O,deliveryMethod:ue.deliveryMethod});return O.destroy(),$},{maxRetries:pe,callback:()=>{O?.destroy()}})}catch(E){if(de>=pe)return this.handleIncompleteImages({taskUUIDs:P,error:E});throw E}}async imageInference(e,t){return this.requestImages(e,t)}async ensureConnection(){if(this.connected()||this._url===Y.TEST)return;let t=2e3,s=200;try{if(this.isInvalidAPIKey())throw this._connectionError;return new Promise((n,o)=>{let r=0,a=30,i=D(),d,m,g=()=>{this.ensureConnectionUUID=null,clearInterval(d),clearInterval(m)};this._sdkType==="SERVER"&&(d=setInterval(async()=>{try{let p=this.connected(),u=!1;(!this.ensureConnectionUUID||i===this.ensureConnectionUUID)&&(this.ensureConnectionUUID||(this.ensureConnectionUUID=i),u=!0);let c=r%10===0&&u;p?(g(),n(!0)):r>=a?(g(),o(new Error("Retry timed out"))):(c&&this.connect(),r++)}catch(p){g(),o(p)}},t)),m=setInterval(async()=>{if(this.connected()){g(),n(!0);return}if(this.isInvalidAPIKey()){g(),o(this._connectionError);return}},s)})}catch{throw this.ensureConnectionUUID=null,this._connectionError=void 0,this._connectionError??"Could not connect to server. Ensure your API key is correct"}}async getResponseWithSimilarTaskUUID({taskUUID:e,numberResults:t,shouldThrowError:s,lis:n,deliveryMethod:o}){return await M(({resolve:r,reject:a,intervalId:i})=>{let d=Array.isArray(e)?e:[e],m=this._globalImages.filter(u=>d.includes(u.taskUUID)),g=o==="async"&&m.length>0,p=this._globalErrors.filter(u=>d.includes(u.error.taskUUID));if(p.length>0){let u=p[0];return this._globalErrors=this._globalErrors.filter(c=>!d.includes(c.error.taskUUID)),clearInterval(i),a?.(u),!0}else if(m.length>=t||g)return clearInterval(i),this._globalImages=this._globalImages.filter(u=>!d.includes(u.taskUUID)),r([...m].slice(0,t)),!0},{debugKey:"getting images",shouldThrowError:s,timeoutDuration:this._timeoutDuration})}handleIncompleteImages({taskUUIDs:e,error:t}){let s=this._globalImages.filter(n=>e.includes(n.taskUUID));if(s.length>1)return this._globalImages=this._globalImages.filter(n=>!e.includes(n.taskUUID)),s;throw t}};var Ce=Je(Me(),1);var B=class extends C{constructor(e){let{shouldReconnect:t,...s}=e;super(s);let n=W(this._url||"");this._ws=new Ce.default(n),this.connect()}};import mt from"ws";var G=class extends C{constructor(t){super(t);this._instantiated=!1;this._listeners=[];this._reconnectingIntervalId=null;this.send=t=>{this._ws.send(JSON.stringify([t]))};this.resetConnection=()=>{this._ws&&(this._listeners.forEach(t=>{t?.destroy?.()}),this._ws.removeAllListeners(),this._ws.readyState===1&&(this._ws.terminate(),this._ws.close()),this._ws=null,this._listeners=[])};this._sdkType="SERVER",this.connect()}async connect(){if(!this._url)return;this.resetConnection();let t=W(this._url);this._ws=new mt(t,{perMessageDeflate:!1,headers:{"X-SDK-Name":"js","X-SDK-Version":q}}),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:s=>{if(s?.error){this._connectionError=s;return}this._connectionSessionUUID=s?.authentication?.[0]?.connectionSessionUUID,this._connectionError=void 0}})}),this._ws.on("message",(s,n)=>{let o=n?s:s?.toString();if(!o)return;let r=JSON.parse(o);this._listeners.forEach(a=>{a.listener(r)})})}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 Oe;typeof window>"u"?Oe=G:Oe=B;export{Ie as EControlMode,et as EModelArchitecture,st as EModelConditioning,Ye as EModelFormat,tt as EModelType,Ze as EOpenPosePreProcessor,nt as EPhotoMakerEnum,he as EPreProcessor,ye as EPreProcessorGroup,Z as ETaskType,me as Environment,Oe as Runware,B as RunwareClient,G as RunwareServer,q as SDK_VERSION,J as SdkType};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|