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

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 CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";var Je=Object.create;var W=Object.defineProperty;var ze=Object.getOwnPropertyDescriptor;var Ye=Object.getOwnPropertyNames;var $e=Object.getPrototypeOf,Ze=Object.prototype.hasOwnProperty;var Xe=(o,t)=>()=>(t||o((t={exports:{}}).exports,t),t.exports),et=(o,t)=>{for(var e in t)W(o,e,{get:t[e],enumerable:!0})},ye=(o,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Ye(t))!Ze.call(o,s)&&s!==e&&W(o,s,{get:()=>t[s],enumerable:!(n=ze(t,s))||n.enumerable});return o};var Ie=(o,t,e)=>(e=o!=null?Je($e(o)):{},ye(t||!o||!o.__esModule?W(e,"default",{value:o,enumerable:!0}):e,o)),tt=o=>ye(W({},"__esModule",{value:!0}),o);var Ne=Xe((on,Oe)=>{"use strict";var Ee=o=>o&&o.CLOSING===2,st=()=>typeof WebSocket<"u"&&Ee(WebSocket),rt=()=>({constructor:st()?WebSocket:null,maxReconnectionDelay:1e4,minReconnectionDelay:1500,reconnectionDelayGrowFactor:1.3,connectionTimeout:4e3,maxRetries:1/0,debug:!1}),at=(o,t,e)=>{Object.defineProperty(t,e,{get:()=>o[e],set:n=>{o[e]=n},enumerable:!0,configurable:!0})},Ce=o=>o.minReconnectionDelay+Math.random()*o.minReconnectionDelay,ot=(o,t)=>{let e=t*o.reconnectionDelayGrowFactor;return e>o.maxReconnectionDelay?o.maxReconnectionDelay:e},it=["onopen","onclose","onmessage","onerror"],lt=(o,t,e)=>{Object.keys(e).forEach(n=>{e[n].forEach(([s,a])=>{o.addEventListener(n,s,a)})}),t&&it.forEach(n=>{o[n]=t[n]})},Me=function(o,t,e={}){let n,s,a=0,l=0,u=!0,r={};if(!(this instanceof Me))throw new TypeError("Failed to construct 'ReconnectingWebSocket': Please use the 'new' operator");let p=rt();if(Object.keys(p).filter(i=>e.hasOwnProperty(i)).forEach(i=>p[i]=e[i]),!Ee(p.constructor))throw new TypeError("Invalid WebSocket constructor. Set `options.constructor`");let d=p.debug?(...i)=>console.log("RWS:",...i):()=>{},m=(i,y)=>setTimeout(()=>{let I=new Error(y);I.code=i,Array.isArray(r.error)&&r.error.forEach(([b])=>b(I)),n.onerror&&n.onerror(I)},0),c=()=>{if(d("close"),l++,d("retries count:",l),l>p.maxRetries){m("EHOSTDOWN","Too many failed connection attempts");return}a?a=ot(p,a):a=Ce(p),d("reconnectDelay:",a),u&&setTimeout(g,a)},g=()=>{d("connect");let i=n;n=new p.constructor(o,t),s=setTimeout(()=>{d("timeout"),n.close(),m("ETIMEDOUT","Connection timeout")},p.connectionTimeout),d("bypass properties");for(let y in n)["addEventListener","removeEventListener","close","send"].indexOf(y)<0&&at(n,this,y);n.addEventListener("open",()=>{clearTimeout(s),d("open"),a=Ce(p),d("reconnectDelay:",a),l=0}),n.addEventListener("close",c),lt(n,i,r)};d("init"),g(),this.close=(i=1e3,y="",{keepClosed:I=!1,fastClose:b=!0,delay:_=0}={})=>{if(_&&(a=_),u=!I,n.close(i,y),b){let R={code:i,reason:y,wasClean:!0};c(),Array.isArray(r.close)&&r.close.forEach(([U,f])=>{U(R),n.removeEventListener("close",U,f)}),n.onclose&&(n.onclose(R),n.onclose=null)}},this.send=i=>{n.send(i)},this.addEventListener=(i,y,I)=>{Array.isArray(r[i])?r[i].some(([b])=>b===y)||r[i].push([y,I]):r[i]=[[y,I]],n.addEventListener(i,y,I)},this.removeEventListener=(i,y,I)=>{Array.isArray(r[i])&&(r[i]=r[i].filter(([b])=>b!==y)),n.removeEventListener(i,y,I)}};Oe.exports=Me});var ct={};et(ct,{EControlMode:()=>X,EModelArchitecture:()=>be,EModelConditioning:()=>Ue,EModelFormat:()=>fe,EModelType:()=>Te,EOpenPosePreProcessor:()=>he,EPhotoMakerEnum:()=>_e,EPreProcessor:()=>te,EPreProcessorGroup:()=>ee,ETaskType:()=>G,Environment:()=>Z,Runware:()=>re,RunwareClient:()=>M,RunwareServer:()=>O,SdkType:()=>F});module.exports=tt(ct);var Z=(n=>(n.PRODUCTION="PRODUCTION",n.DEVELOPMENT="DEVELOPMENT",n.TEST="TEST",n))(Z||{}),F=(e=>(e.CLIENT="CLIENT",e.SERVER="SERVER",e))(F||{}),G=(i=>(i.IMAGE_INFERENCE="imageInference",i.IMAGE_UPLOAD="imageUpload",i.IMAGE_UPSCALE="imageUpscale",i.IMAGE_BACKGROUND_REMOVAL="imageBackgroundRemoval",i.VIDEO_INFERENCE="videoInference",i.GET_RESPONSE="getResponse",i.PHOTO_MAKER="photoMaker",i.IMAGE_CAPTION="imageCaption",i.IMAGE_CONTROL_NET_PRE_PROCESS="imageControlNetPreProcess",i.IMAGE_MASKING="imageMasking",i.PROMPT_ENHANCE="promptEnhance",i.AUTHENTICATION="authentication",i.MODEL_UPLOAD="modelUpload",i.MODEL_SEARCH="modelSearch",i))(G||{}),X=(n=>(n.BALANCED="balanced",n.PROMPT="prompt",n.CONTROL_NET="controlnet",n))(X||{}),ee=(c=>(c.canny="canny",c.depth="depth",c.mlsd="mlsd",c.normalbae="normalbae",c.openpose="openpose",c.tile="tile",c.seg="seg",c.lineart="lineart",c.lineart_anime="lineart_anime",c.shuffle="shuffle",c.scribble="scribble",c.softedge="softedge",c))(ee||{}),te=(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))(te||{}),he=(a=>(a.openpose="openpose",a.openpose_face="openpose_face",a.openpose_faceonly="openpose_faceonly",a.openpose_full="openpose_full",a.openpose_hand="openpose_hand",a))(he||{}),fe=(e=>(e.safetensors="safetensors",e.pickletensor="pickletensor",e))(fe||{}),be=(g=>(g.flux1d="flux1d",g.flux1s="flux1s",g.pony="pony",g.sdhyper="sdhyper",g.sd1x="sd1x",g.sd1xlcm="sd1xlcm",g.sd3="sd3",g.sdxl="sdxl",g.sdxllcm="sdxllcm",g.sdxldistilled="sdxldistilled",g.sdxlhyper="sdxlhyper",g.sdxllightning="sdxllightning",g.sdxlturbo="sdxlturbo",g))(be||{}),Te=(n=>(n.base="base",n.inpainting="inpainting",n.pix2pix="pix2pix",n))(Te||{}),Ue=(f=>(f.canny="canny",f.depth="depth",f.qrcode="qrcode",f.hed="hed",f.scrible="scrible",f.openpose="openpose",f.seg="segmentation",f.openmlsd="openmlsd",f.softedge="softedge",f.normal="normal bae",f.shuffle="shuffle",f.pix2pix="pix2pix",f.inpaint="inpaint",f.lineart="line art",f.sketch="sketch",f.inpaintdepth="inpaint depth",f.tile="tile",f.outfit="outfit",f.blur="blur",f.gray="gray",f.lowquality="low quality",f))(Ue||{}),_e=(m=>(m.NoStyle="No style",m.Cinematic="Cinematic",m.DisneyCharacter="Disney Character",m.DigitalArt="Digital Art",m.Photographic="Photographic",m.FantasyArt="Fantasy art",m.Neonpunk="Neonpunk",m.Enhance="Enhance",m.ComicBook="Comic book",m.Lowpoly="Lowpoly",m.LineArt="Line art",m))(_e||{});var q=require("uuid"),V=6e4,B=1e3,Re=100,ne={PRODUCTION:"wss://ws-api.runware.ai/v1",TEST:"ws://localhost:8080"},ke=(o,t)=>{if(o==null)return;let e=o.indexOf(t);e!==-1&&o.splice(e,1)},w=(o,{debugKey:t="debugKey",timeoutDuration:e=V,shouldThrowError:n=!0,pollingInterval:s=Re})=>(e=e<B?B:e,new Promise((a,l)=>{let u=setTimeout(()=>{r&&(clearInterval(r),n&&l(`Response could not be received from server for ${t}`)),clearTimeout(u)},e),r=setInterval(async()=>{o({resolve:a,reject:l,intervalId:r})&&(clearInterval(r),clearTimeout(u))},s)})),De=o=>new Promise(t=>{let e=new FileReader;e.readAsDataURL(o),e.onload=function(){t(e.result)}}),k=()=>(0,q.v4)(),ve=o=>(0,q.validate)(o);var xe=({key:o,data:t,useZero:e=!0,shouldReturnString:n=!1})=>o.split(/\.|\[/).map(l=>l.replace(/\]$/,"")).reduce((l,u)=>{let r=e?0:void 0,p=l?.[u];if(!p)return r;if(Array.isArray(p)&&/^\d+$/.test(u)){let d=parseInt(u,10);return d>=0&&d<p.length?l[u]=p[d]:l[u]??r}else return l[u]??r},t||{})??{},we=(o,t=1e3)=>new Promise(e=>setTimeout(e,o*t));var Se=(o,t)=>o.filter(e=>e.key!==t.key);var T=({key:o,value:t})=>t||t===0||t===!1?{[o]:t}:{},nt=(o,t)=>Math.floor(Math.random()*(t-o+1))+o,se=()=>nt(1,Number.MAX_SAFE_INTEGER);var Ae=(o,{debugKey:t="debugKey",timeoutDuration:e=V,shouldThrowError:n=!0,pollingInterval:s=Re})=>(e=e<B?B:e,new Promise((a,l)=>{let u=setTimeout(()=>{r&&(clearInterval(r),n&&l(`Response could not be received from server for ${t}`)),clearTimeout(u)},e),r=setInterval(async()=>{try{await o({resolve:a,reject:l,intervalId:r})&&(clearInterval(r),clearTimeout(u))}catch(p){clearInterval(r),clearTimeout(u),l(p)}},s)}));var v=async(o,t={})=>{let{delayInSeconds:e=1,callback:n}=t,s=t.maxRetries??1;for(;s;)try{return await o()}catch(a){if(n?.(),a?.error)throw a;if(s--,s>0)await we(e),await v(o,{...t,maxRetries:s});else throw a}};var A=class{constructor({apiKey:t,url:e=ne.PRODUCTION,shouldReconnect:n=!0,globalMaxRetries:s=2,timeoutDuration:a=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 v(async()=>{let e=k();if(typeof t=="string"&&ve(t))return{imageURL:t,imageUUID:t,taskUUID:e,taskType:"imageUpload"};let n=typeof t=="string"?t:await De(t);return{imageURL:n,imageUUID:n,taskUUID:e,taskType:"imageUpload"}})}catch(e){throw e}};this.controlNetPreProcess=async({inputImage:t,preProcessorType:e,height:n,width:s,outputType:a,outputFormat:l,highThresholdCanny:u,lowThresholdCanny:r,includeHandsAndFaceOpenPose:p,includeCost:d,outputQuality:m,customTaskUUID:c,retry:g,includeGenerationTime:i,includePayload:y})=>{let I=g||this._globalMaxRetries,b,_=Date.now();try{return await v(async()=>{await this.ensureConnection();let R=await this.uploadImage(t);if(!R?.imageUUID)return null;let U=c||k(),f={inputImage:R.imageUUID,taskType:"imageControlNetPreProcess",taskUUID:U,preProcessorType:e,...T({key:"height",value:n}),...T({key:"width",value:s}),...T({key:"outputType",value:a}),...T({key:"outputFormat",value:l}),...T({key:"includeCost",value:d}),...T({key:"highThresholdCanny",value:u}),...T({key:"lowThresholdCanny",value:r}),...T({key:"includeHandsAndFaceOpenPose",value:p}),...m?{outputQuality:m}:{}};this.send({...f}),b=this.globalListener({taskUUID:U});let N=await w(({resolve:H,reject:j})=>{let x=this.getSingleMessage({taskUUID:U});if(x){if(x?.error)return j(x),!0;if(x)return H(x),!0}},{debugKey:"unprocessed-image",timeoutDuration:this._timeoutDuration});return b.destroy(),this.insertAdditionalResponse({response:N,payload:y?f:void 0,startTime:i?_:void 0}),N},{maxRetries:I,callback:()=>{b?.destroy()}})}catch(R){throw R}};this.requestImageToText=async({inputImage:t,includeCost:e,customTaskUUID:n,retry:s,includePayload:a,includeGenerationTime:l})=>{let u=s||this._globalMaxRetries,r,p=Date.now();try{return await v(async()=>{await this.ensureConnection();let d=t?await this.uploadImage(t):null,m=n||k(),c={taskUUID:m,taskType:"imageCaption",inputImage:d?.imageUUID,...T({key:"includeCost",value:e})};this.send(c),r=this.globalListener({taskUUID:m});let g=await w(({resolve:i,reject:y})=>{let I=this.getSingleMessage({taskUUID:m});if(I){if(I?.error)return y(I),!0;if(I)return delete this._globalMessages[m],i(I),!0}},{debugKey:"remove-image-background",timeoutDuration:this._timeoutDuration});return r.destroy(),this.insertAdditionalResponse({response:g,payload:a?c:void 0,startTime:l?p:void 0}),g},{maxRetries:u,callback:()=>{r?.destroy()}})}catch(d){throw d}};this.removeImageBackground=async t=>this.baseSingleRequest({payload:{...t,taskType:"imageBackgroundRemoval"},debugKey:"remove-image-background"});this.videoInference=async t=>{let{skipResponse:e,...n}=t;try{let s=await this.baseSingleRequest({payload:{...n,deliveryMethod:"async",taskType:"videoInference"},debugKey:"video-inference"});if(e)return s;let a=s?.taskUUID,l=t?.numberResults??1,u=new Map;return await Ae(async({resolve:r,reject:p})=>{try{let d=await this.getResponse({taskUUID:a});for(let c of d||[])c.videoUUID&&u.set(c.videoUUID,c);return u.size===l?(r(Array.from(u.values())),!0):!1}catch(d){return p(d),!0}},{debugKey:"async-response",pollingInterval:2*1e3,timeoutDuration:10*60*1e3}),Array.from(u.values())}catch(s){throw s}};this.getResponse=async t=>{let e=t.taskUUID;return this.baseSingleRequest({payload:{...t,customTaskUUID:e,taskType:"getResponse"},isMultiple:!0,debugKey:"async-results"})};this.upscaleGan=async({inputImage:t,upscaleFactor:e,outputType:n,outputFormat:s,includeCost:a,outputQuality:l,customTaskUUID:u,retry:r,includeGenerationTime:p,includePayload:d})=>{let m=r||this._globalMaxRetries,c,g=Date.now();try{return await v(async()=>{await this.ensureConnection();let i;i=await this.uploadImage(t);let y=u||k(),I={taskUUID:y,inputImage:i?.imageUUID,taskType:"imageUpscale",upscaleFactor:e,...T({key:"includeCost",value:a}),...n?{outputType:n}:{},...l?{outputQuality:l}:{},...s?{outputFormat:s}:{}};this.send(I),c=this.globalListener({taskUUID:y});let b=await w(({resolve:_,reject:R})=>{let U=this.getSingleMessage({taskUUID:y});if(U){if(U?.error)return R(U),!0;if(U)return delete this._globalMessages[y],_(U),!0}},{debugKey:"upscale-gan",timeoutDuration:this._timeoutDuration});return c.destroy(),this.insertAdditionalResponse({response:b,payload:d?I:void 0,startTime:p?g:void 0}),b},{maxRetries:m,callback:()=>{c?.destroy()}})}catch(i){throw i}};this.enhancePrompt=async({prompt:t,promptMaxLength:e=380,promptVersions:n=1,includeCost:s,customTaskUUID:a,retry:l,includeGenerationTime:u,includePayload:r})=>{let p=l||this._globalMaxRetries,d,m=Date.now();try{return await v(async()=>{await this.ensureConnection();let c=a||k(),g={prompt:t,taskUUID:c,promptMaxLength:e,promptVersions:n,...T({key:"includeCost",value:s}),taskType:"promptEnhance"};this.send(g),d=this.globalListener({taskUUID:c});let i=await w(({resolve:y,reject:I})=>{let b=this._globalMessages[c];if(b?.error)return I(b),!0;if(b?.length>=n)return delete this._globalMessages[c],y(b),!0},{debugKey:"enhance-prompt",timeoutDuration:this._timeoutDuration});return d.destroy(),this.insertAdditionalResponse({response:i,payload:r?g:void 0,startTime:u?m:void 0}),i},{maxRetries:p,callback:()=>{d?.destroy()}})}catch(c){throw c}};this.modelUpload=async t=>{let{onUploadStream:e,retry:n,customTaskUUID:s,...a}=t,l=n||this._globalMaxRetries,u;try{return await v(async()=>{await this.ensureConnection();let r=s||k();this.send({...a,taskUUID:r,taskType:"modelUpload"});let p,d;return u=this.listenToUpload({taskUUID:r,onUploadStream:(c,g)=>{e?.(c,g),c?.status==="ready"?p=c:g&&(d=g)}}),await w(({resolve:c,reject:g})=>{if(p)return c(p),!0;if(d)return g(d),!1},{shouldThrowError:!1,timeoutDuration:60*60*1e3})},{maxRetries:l,callback:()=>{u?.destroy()}})}catch(r){throw r}};this.photoMaker=async(t,e)=>{let{onPartialImages:n,retry:s,customTaskUUID:a,numberResults:l,includeGenerationTime:u,includePayload:r,...p}=t,d=s||this._globalMaxRetries,m,c=[],g=0,i=Date.now();try{return await v(async()=>{await this.ensureConnection(),g++;let y=this._globalImages.filter(U=>c.includes(U.taskUUID)),I=a||k();c.push(I);let b=l-y.length,_={...p,...p.seed?{seed:p.seed}:{seed:se()},...e??{},taskUUID:I,taskType:"photoMaker",numberResults:l};this.send({..._,numberResults:b}),m=this.listenToImages({onPartialImages:n,taskUUID:I,groupKey:"REQUEST_IMAGES",requestPayload:r?_:void 0,startTime:u?i:void 0});let R=await this.getSimilarImages({taskUUID:c,numberResults:l,lis:m});return m.destroy(),R},{maxRetries:d,callback:()=>{m?.destroy()}})}catch(y){if(y.taskUUID)throw y;if(g>=d)return this.handleIncompleteImages({taskUUIDs:c,error:y})}};this.modelSearch=async t=>this.baseSingleRequest({payload:{...t,taskType:"modelSearch"},debugKey:"model-search"});this.imageMasking=async t=>this.baseSingleRequest({payload:{...t,taskType:"imageMasking"},debugKey:"image-masking"});this.imageUpload=async t=>this.baseSingleRequest({payload:{...t,taskType:"imageUpload"},debugKey:"image-upload"});this.baseSingleRequest=async({payload:t,debugKey:e,mockResponse:n,isMultiple:s})=>{let{retry:a,customTaskUUID:l,includePayload:u,includeGenerationTime:r,...p}=t,d=a||this._globalMaxRetries,m,c=Date.now();try{return await v(async()=>{await this.ensureConnection();let g=l||k(),i={...p,taskUUID:g};n?setTimeout(()=>{this._globalMessages[g]=n},1e3):this.send(i),m=this.globalListener({taskUUID:g});let y=await w(({resolve:I,reject:b})=>{let _=s?this.getMultipleMessages({taskUUID:g}):this.getSingleMessage({taskUUID:g});if(_){if(_?.error)return b(_),!0;if(_)return delete this._globalMessages[g],I(_),!0}},{debugKey:e,timeoutDuration:this._timeoutDuration});return this.insertAdditionalResponse({response:y,payload:u?i:void 0,startTime:r?c:void 0}),m.destroy(),y},{maxRetries:d,callback:()=>{m?.destroy()}})}catch(g){throw g}};this.getSingleMessage=({taskUUID:t})=>{let e=this._globalMessages[t]?.[0],n=this._globalMessages[t];return!e&&!n?null:n?.error?n:e};this.getMultipleMessages=({taskUUID:t})=>{let e=this._globalMessages[t]?.[0],n=this._globalMessages[t];return!e&&!n?null:n};this.insertAdditionalResponse=({response:t,payload:e,startTime:n})=>{if(!e&&!n)return;let s=t;s.additionalResponse={},e&&(t.additionalResponse.payload=e),n&&(t.additionalResponse.generationTime=Date.now()-n)};this.disconnect=async()=>{this._shouldReconnect=!1,this._ws?.terminate?.(),this._ws?.close?.()};this.connected=()=>this.isWebsocketReadyState()&&!!this._connectionSessionUUID;this._apiKey=t,this._url=e,this._sdkType="CLIENT",this._shouldReconnect=n,this._globalMaxRetries=s,this._timeoutDuration=a}static async initialize(t){try{let e=new this(t);return await e.ensureConnection(),e}catch(e){throw e}}addListener({lis:t,groupKey:e,taskUUID:n}){let s=u=>{let r=Array.isArray(u?.data)?u.data:[u.data],p=u?.[0]?.errors?u?.[0]?.errors:Array.isArray(u?.errors)?u.errors:[u.errors],d=r.filter(c=>(c?.taskUUID||c?.taskType)===n);if(p.filter(c=>(c?.taskUUID||c?.taskType)===n).length){t({error:{...p[0]??{}}});return}if(d.length){t({[n]:r});return}},a={key:n||k(),listener:s,groupKey:e};return this._listeners.push(a),{destroy:()=>{this._listeners=Se(this._listeners,a)}}}connect(){this._ws.onopen=t=>{this._connectionSessionUUID?this.send({taskType:"authentication",apiKey:this._apiKey,connectionSessionUUID:this._connectionSessionUUID}):this.send({apiKey:this._apiKey,taskType:"authentication"}),this.addListener({taskUUID:"authentication",lis:e=>{if(e?.error){this._connectionError=e;return}this._connectionSessionUUID=e?.authentication?.[0]?.connectionSessionUUID,this._connectionError=void 0}})},this._ws.onmessage=t=>{let e=JSON.parse(t.data);for(let n of this._listeners)if(n?.listener?.(e))return},this._ws.onclose=t=>{this.isInvalidAPIKey()}}destroy(t){ke(this._listeners,t)}listenToImages({onPartialImages:t,taskUUID:e,groupKey:n,requestPayload:s,startTime:a}){return this.addListener({taskUUID:e,lis:l=>{let u=l?.[e]?.filter(r=>r.taskUUID===e);l.error?(t?.(u,l?.error&&l),this._globalError=l):(u=u.map(r=>(this.insertAdditionalResponse({response:r,payload:s||void 0,startTime:a||void 0}),{...r})),t?.(u,l?.error&&l),this._sdkType==="CLIENT"?this._globalImages=[...this._globalImages,...(l?.[e]??[]).map(r=>(this.insertAdditionalResponse({response:r,payload:s||void 0,startTime:a||void 0}),{...r}))]:this._globalImages=[...this._globalImages,...u])},groupKey:n})}listenToUpload({onUploadStream:t,taskUUID:e}){return this.addListener({taskUUID:e,lis:n=>{let s=n?.error,a=n?.[e]?.[0],l=a?.taskUUID===e?a:null;(l||s)&&t?.(l||void 0,s)}})}globalListener({taskUUID:t}){return this.addListener({taskUUID:t,lis:e=>{if(e.error){this._globalMessages[t]=e;return}let n=xe({key:t,data:e,useZero:!1});Array.isArray(n)?n.forEach(s=>{this._globalMessages[s.taskUUID]=[...this._globalMessages[s.taskUUID]??[],s]}):this._globalMessages[n.taskUUID]=n}})}async requestImages({outputType:t,outputFormat:e,uploadEndpoint:n,checkNSFW:s,positivePrompt:a,negativePrompt:l,seedImage:u,maskImage:r,strength:p,height:d,width:m,model:c,steps:g,scheduler:i,seed:y,CFGScale:I,clipSkip:b,usePromptWeighting:_,promptWeighting:R,numberResults:U=1,onPartialImages:f,includeCost:N,customTaskUUID:H,retry:j,refiner:x,maskMargin:Ke,outputQuality:h,controlNet:Q,lora:ae,embeddings:oe,ipAdapters:ie,outpaint:le,acceleratorOptions:ce,advancedFeatures:ue,referenceImages:de,includeGenerationTime:We,includePayload:Fe},Ge){let C,pe,L=[],ge=0,me=j||this._globalMaxRetries;try{await this.ensureConnection();let S=null,J=null,z=[];if(u){let D=await this.uploadImage(u);if(!D)return[];S=D.imageUUID}if(r){let D=await this.uploadImage(r);if(!D)return[];J=D.imageUUID}if(Q?.length)for(let D=0;D<Q.length;D++){let E=Q[D],{endStep:Y,startStep:P,weight:$,guideImage:K,controlMode:qe,startStepPercentage:Ve,endStepPercentage:He,model:je}=E,Qe=K?await this.uploadImage(K):null;z.push({guideImage:Qe?.imageUUID,model:je,endStep:Y,startStep:P,weight:$,...T({key:"startStepPercentage",value:Ve}),...T({key:"endStepPercentage",value:He}),controlMode:qe||"controlnet"})}pe={taskType:"imageInference",model:c,positivePrompt:a,...l?{negativePrompt:l}:{},...d?{height:d}:{},...m?{width:m}:{},numberResults:U,...t?{outputType:t}:{},...e?{outputFormat:e}:{},...n?{uploadEndpoint:n}:{},...T({key:"checkNSFW",value:s}),...T({key:"strength",value:p}),...T({key:"CFGScale",value:I}),...T({key:"clipSkip",value:b}),...T({key:"maskMargin",value:Ke}),...T({key:"usePromptWeighting",value:_}),...T({key:"steps",value:g}),...R?{promptWeighting:R}:{},...y?{seed:y}:{seed:se()},...i?{scheduler:i}:{},...x?{refiner:x}:{},...le?{outpaint:le}:{},...T({key:"includeCost",value:N}),...S?{seedImage:S}:{},...J?{maskImage:J}:{},...h?{outputQuality:h}:{},...z.length?{controlNet:z}:{},...ae?.length?{lora:ae}:{},...oe?.length?{embeddings:oe}:{},...ie?.length?{ipAdapters:ie}:{},...ce?{acceleratorOptions:ce}:{},...ue?{advancedFeatures:ue}:{},...de?.length?{referenceImages:de}:{},...Ge??{}};let Be=Date.now();return await v(async()=>{ge++,C?.destroy();let D=this._globalImages.filter(K=>L.includes(K.taskUUID)),E=H||k();L.push(E);let Y=U-D.length,P={...pe,taskUUID:E,numberResults:Y};this.send(P),C=this.listenToImages({onPartialImages:f,taskUUID:E,groupKey:"REQUEST_IMAGES",requestPayload:Fe?P:void 0,startTime:We?Be:void 0});let $=await this.getSimilarImages({taskUUID:L,numberResults:U,lis:C});return C.destroy(),$},{maxRetries:me,callback:()=>{C?.destroy()}})}catch(S){if(ge>=me)return this.handleIncompleteImages({taskUUIDs:L,error:S});throw S}}async ensureConnection(){if(this.connected()||this._url===ne.TEST)return;let e=2e3,n=200;try{if(this.isInvalidAPIKey())throw this._connectionError;return new Promise((s,a)=>{let l=0,u=30,r=k(),p,d,m=()=>{this.ensureConnectionUUID=null,clearInterval(p),clearInterval(d)};this._sdkType==="SERVER"&&(p=setInterval(async()=>{try{let c=this.connected(),g=!1;(!this.ensureConnectionUUID||r===this.ensureConnectionUUID)&&(this.ensureConnectionUUID||(this.ensureConnectionUUID=r),g=!0);let i=l%10===0&&g;c?(m(),s(!0)):l>=u?(m(),a(new Error("Retry timed out"))):(i&&this.connect(),l++)}catch(c){m(),a(c)}},e)),d=setInterval(async()=>{if(this.connected()){m(),s(!0);return}if(this.isInvalidAPIKey()){m(),a(this._connectionError);return}},n)})}catch{throw this.ensureConnectionUUID=null,this._connectionError=void 0,this._connectionError??"Could not connect to server. Ensure your API key is correct"}}async getSimilarImages({taskUUID:t,numberResults:e,shouldThrowError:n,lis:s}){return await w(({resolve:a,reject:l,intervalId:u})=>{let r=Array.isArray(t)?t:[t],p=this._globalImages.filter(d=>r.includes(d.taskUUID));if(this._globalError){let d=this._globalError;return this._globalError=void 0,clearInterval(u),l?.(d),!0}else if(p.length>=e)return clearInterval(u),this._globalImages=this._globalImages.filter(d=>!r.includes(d.taskUUID)),a([...p].slice(0,e)),!0},{debugKey:"getting images",shouldThrowError:n,timeoutDuration:this._timeoutDuration})}handleIncompleteImages({taskUUIDs:t,error:e}){let n=this._globalImages.filter(s=>t.includes(s.taskUUID));if(n.length>1)return this._globalImages=this._globalImages.filter(s=>!t.includes(s.taskUUID)),n;throw e}};var Le=Ie(Ne(),1),M=class extends A{constructor(t){let{shouldReconnect:e,...n}=t;super(n),this._ws=new Le.default(this._url),this.connect()}};var Pe=Ie(require("ws"),1);var O=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 Pe.default(this._url,{perMessageDeflate:!1}),this._ws.on("error",()=>{}),this._ws.on("close",()=>{this.handleClose()}),this._ws.on("open",()=>{this._reconnectingIntervalId&&clearInterval(this._reconnectingIntervalId),this._connectionSessionUUID&&this.isWebsocketReadyState()?this.send({taskType:"authentication",apiKey:this._apiKey,connectionSessionUUID:this._connectionSessionUUID}):this.isWebsocketReadyState()&&this.send({apiKey:this._apiKey,taskType:"authentication"}),this.addListener({taskUUID:"authentication",lis:e=>{if(e?.error){this._connectionError=e;return}this._connectionSessionUUID=e?.authentication?.[0]?.connectionSessionUUID,this._connectionError=void 0}})}),this._ws.on("message",(e,n)=>{let s=n?e:e?.toString();if(!s)return;let a=JSON.parse(s);this._listeners.forEach(l=>{l.listener(a)})}))}handleClose(){this.isInvalidAPIKey()||(this._reconnectingIntervalId&&clearInterval(this._reconnectingIntervalId),this._shouldReconnect&&setTimeout(()=>this.connect(),1e3))}heartBeat(){clearTimeout(this._pingTimeout),this._pingTimeout=setTimeout(()=>{this.isWebsocketReadyState()&&this.send({ping:!0})},5e3)}};var re;typeof window>"u"?re=O:re=M;0&&(module.exports={EControlMode,EModelArchitecture,EModelConditioning,EModelFormat,EModelType,EOpenPosePreProcessor,EPhotoMakerEnum,EPreProcessor,EPreProcessorGroup,ETaskType,Environment,Runware,RunwareClient,RunwareServer,SdkType});
1
+ "use strict";var Je=Object.create;var W=Object.defineProperty;var ze=Object.getOwnPropertyDescriptor;var Ye=Object.getOwnPropertyNames;var $e=Object.getPrototypeOf,Ze=Object.prototype.hasOwnProperty;var Xe=(o,t)=>()=>(t||o((t={exports:{}}).exports,t),t.exports),et=(o,t)=>{for(var e in t)W(o,e,{get:t[e],enumerable:!0})},ye=(o,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Ye(t))!Ze.call(o,s)&&s!==e&&W(o,s,{get:()=>t[s],enumerable:!(n=ze(t,s))||n.enumerable});return o};var Ie=(o,t,e)=>(e=o!=null?Je($e(o)):{},ye(t||!o||!o.__esModule?W(e,"default",{value:o,enumerable:!0}):e,o)),tt=o=>ye(W({},"__esModule",{value:!0}),o);var Ne=Xe((an,Oe)=>{"use strict";var Ee=o=>o&&o.CLOSING===2,st=()=>typeof WebSocket<"u"&&Ee(WebSocket),rt=()=>({constructor:st()?WebSocket:null,maxReconnectionDelay:1e4,minReconnectionDelay:1500,reconnectionDelayGrowFactor:1.3,connectionTimeout:4e3,maxRetries:1/0,debug:!1}),at=(o,t,e)=>{Object.defineProperty(t,e,{get:()=>o[e],set:n=>{o[e]=n},enumerable:!0,configurable:!0})},Ce=o=>o.minReconnectionDelay+Math.random()*o.minReconnectionDelay,ot=(o,t)=>{let e=t*o.reconnectionDelayGrowFactor;return e>o.maxReconnectionDelay?o.maxReconnectionDelay:e},it=["onopen","onclose","onmessage","onerror"],lt=(o,t,e)=>{Object.keys(e).forEach(n=>{e[n].forEach(([s,a])=>{o.addEventListener(n,s,a)})}),t&&it.forEach(n=>{o[n]=t[n]})},Me=function(o,t,e={}){let n,s,a=0,l=0,u=!0,r={};if(!(this instanceof Me))throw new TypeError("Failed to construct 'ReconnectingWebSocket': Please use the 'new' operator");let p=rt();if(Object.keys(p).filter(i=>e.hasOwnProperty(i)).forEach(i=>p[i]=e[i]),!Ee(p.constructor))throw new TypeError("Invalid WebSocket constructor. Set `options.constructor`");let d=p.debug?(...i)=>console.log("RWS:",...i):()=>{},m=(i,y)=>setTimeout(()=>{let I=new Error(y);I.code=i,Array.isArray(r.error)&&r.error.forEach(([b])=>b(I)),n.onerror&&n.onerror(I)},0),c=()=>{if(d("close"),l++,d("retries count:",l),l>p.maxRetries){m("EHOSTDOWN","Too many failed connection attempts");return}a?a=ot(p,a):a=Ce(p),d("reconnectDelay:",a),u&&setTimeout(g,a)},g=()=>{d("connect");let i=n;n=new p.constructor(o,t),s=setTimeout(()=>{d("timeout"),n.close(),m("ETIMEDOUT","Connection timeout")},p.connectionTimeout),d("bypass properties");for(let y in n)["addEventListener","removeEventListener","close","send"].indexOf(y)<0&&at(n,this,y);n.addEventListener("open",()=>{clearTimeout(s),d("open"),a=Ce(p),d("reconnectDelay:",a),l=0}),n.addEventListener("close",c),lt(n,i,r)};d("init"),g(),this.close=(i=1e3,y="",{keepClosed:I=!1,fastClose:b=!0,delay:_=0}={})=>{if(_&&(a=_),u=!I,n.close(i,y),b){let R={code:i,reason:y,wasClean:!0};c(),Array.isArray(r.close)&&r.close.forEach(([U,f])=>{U(R),n.removeEventListener("close",U,f)}),n.onclose&&(n.onclose(R),n.onclose=null)}},this.send=i=>{n.send(i)},this.addEventListener=(i,y,I)=>{Array.isArray(r[i])?r[i].some(([b])=>b===y)||r[i].push([y,I]):r[i]=[[y,I]],n.addEventListener(i,y,I)},this.removeEventListener=(i,y,I)=>{Array.isArray(r[i])&&(r[i]=r[i].filter(([b])=>b!==y)),n.removeEventListener(i,y,I)}};Oe.exports=Me});var ct={};et(ct,{EControlMode:()=>X,EModelArchitecture:()=>be,EModelConditioning:()=>Ue,EModelFormat:()=>fe,EModelType:()=>Te,EOpenPosePreProcessor:()=>he,EPhotoMakerEnum:()=>_e,EPreProcessor:()=>te,EPreProcessorGroup:()=>ee,ETaskType:()=>G,Environment:()=>Z,Runware:()=>re,RunwareClient:()=>M,RunwareServer:()=>O,SdkType:()=>F});module.exports=tt(ct);var Z=(n=>(n.PRODUCTION="PRODUCTION",n.DEVELOPMENT="DEVELOPMENT",n.TEST="TEST",n))(Z||{}),F=(e=>(e.CLIENT="CLIENT",e.SERVER="SERVER",e))(F||{}),G=(i=>(i.IMAGE_INFERENCE="imageInference",i.IMAGE_UPLOAD="imageUpload",i.IMAGE_UPSCALE="imageUpscale",i.IMAGE_BACKGROUND_REMOVAL="imageBackgroundRemoval",i.VIDEO_INFERENCE="videoInference",i.GET_RESPONSE="getResponse",i.PHOTO_MAKER="photoMaker",i.IMAGE_CAPTION="imageCaption",i.IMAGE_CONTROL_NET_PRE_PROCESS="imageControlNetPreProcess",i.IMAGE_MASKING="imageMasking",i.PROMPT_ENHANCE="promptEnhance",i.AUTHENTICATION="authentication",i.MODEL_UPLOAD="modelUpload",i.MODEL_SEARCH="modelSearch",i))(G||{}),X=(n=>(n.BALANCED="balanced",n.PROMPT="prompt",n.CONTROL_NET="controlnet",n))(X||{}),ee=(c=>(c.canny="canny",c.depth="depth",c.mlsd="mlsd",c.normalbae="normalbae",c.openpose="openpose",c.tile="tile",c.seg="seg",c.lineart="lineart",c.lineart_anime="lineart_anime",c.shuffle="shuffle",c.scribble="scribble",c.softedge="softedge",c))(ee||{}),te=(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))(te||{}),he=(a=>(a.openpose="openpose",a.openpose_face="openpose_face",a.openpose_faceonly="openpose_faceonly",a.openpose_full="openpose_full",a.openpose_hand="openpose_hand",a))(he||{}),fe=(e=>(e.safetensors="safetensors",e.pickletensor="pickletensor",e))(fe||{}),be=(g=>(g.flux1d="flux1d",g.flux1s="flux1s",g.pony="pony",g.sdhyper="sdhyper",g.sd1x="sd1x",g.sd1xlcm="sd1xlcm",g.sd3="sd3",g.sdxl="sdxl",g.sdxllcm="sdxllcm",g.sdxldistilled="sdxldistilled",g.sdxlhyper="sdxlhyper",g.sdxllightning="sdxllightning",g.sdxlturbo="sdxlturbo",g))(be||{}),Te=(n=>(n.base="base",n.inpainting="inpainting",n.pix2pix="pix2pix",n))(Te||{}),Ue=(f=>(f.canny="canny",f.depth="depth",f.qrcode="qrcode",f.hed="hed",f.scrible="scrible",f.openpose="openpose",f.seg="segmentation",f.openmlsd="openmlsd",f.softedge="softedge",f.normal="normal bae",f.shuffle="shuffle",f.pix2pix="pix2pix",f.inpaint="inpaint",f.lineart="line art",f.sketch="sketch",f.inpaintdepth="inpaint depth",f.tile="tile",f.outfit="outfit",f.blur="blur",f.gray="gray",f.lowquality="low quality",f))(Ue||{}),_e=(m=>(m.NoStyle="No style",m.Cinematic="Cinematic",m.DisneyCharacter="Disney Character",m.DigitalArt="Digital Art",m.Photographic="Photographic",m.FantasyArt="Fantasy art",m.Neonpunk="Neonpunk",m.Enhance="Enhance",m.ComicBook="Comic book",m.Lowpoly="Lowpoly",m.LineArt="Line art",m))(_e||{});var q=require("uuid"),V=6e4,B=1e3,Re=100,ne={PRODUCTION:"wss://ws-api.runware.ai/v1",TEST:"ws://localhost:8080"},ke=(o,t)=>{if(o==null)return;let e=o.indexOf(t);e!==-1&&o.splice(e,1)},w=(o,{debugKey:t="debugKey",timeoutDuration:e=V,shouldThrowError:n=!0,pollingInterval:s=Re})=>(e=e<B?B:e,new Promise((a,l)=>{let u=setTimeout(()=>{r&&(clearInterval(r),n&&l(`Response could not be received from server for ${t}`)),clearTimeout(u)},e),r=setInterval(async()=>{o({resolve:a,reject:l,intervalId:r})&&(clearInterval(r),clearTimeout(u))},s)})),De=o=>new Promise(t=>{let e=new FileReader;e.readAsDataURL(o),e.onload=function(){t(e.result)}}),k=()=>(0,q.v4)(),ve=o=>(0,q.validate)(o);var xe=({key:o,data:t,useZero:e=!0,shouldReturnString:n=!1})=>o.split(/\.|\[/).map(l=>l.replace(/\]$/,"")).reduce((l,u)=>{let r=e?0:void 0,p=l?.[u];if(!p)return r;if(Array.isArray(p)&&/^\d+$/.test(u)){let d=parseInt(u,10);return d>=0&&d<p.length?l[u]=p[d]:l[u]??r}else return l[u]??r},t||{})??{},we=(o,t=1e3)=>new Promise(e=>setTimeout(e,o*t));var Se=(o,t)=>o.filter(e=>e.key!==t.key);var T=({key:o,value:t})=>t||t===0||t===!1?{[o]:t}:{},nt=(o,t)=>Math.floor(Math.random()*(t-o+1))+o,se=()=>nt(1,Number.MAX_SAFE_INTEGER);var Ae=(o,{debugKey:t="debugKey",timeoutDuration:e=V,shouldThrowError:n=!0,pollingInterval:s=Re})=>(e=e<B?B:e,new Promise((a,l)=>{let u=setTimeout(()=>{r&&(clearInterval(r),n&&l(`Response could not be received from server for ${t}`)),clearTimeout(u)},e),r=setInterval(async()=>{try{await o({resolve:a,reject:l,intervalId:r})&&(clearInterval(r),clearTimeout(u))}catch(p){clearInterval(r),clearTimeout(u),l(p)}},s)}));var v=async(o,t={})=>{let{delayInSeconds:e=1,callback:n}=t,s=t.maxRetries??1;for(;s;)try{return await o()}catch(a){if(n?.(),a?.error)throw a;if(s--,s>0)await we(e),await v(o,{...t,maxRetries:s});else throw a}};var A=class{constructor({apiKey:t,url:e=ne.PRODUCTION,shouldReconnect:n=!0,globalMaxRetries:s=2,timeoutDuration:a=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 v(async()=>{let e=k();if(typeof t=="string"&&ve(t))return{imageURL:t,imageUUID:t,taskUUID:e,taskType:"imageUpload"};let n=typeof t=="string"?t:await De(t);return{imageURL:n,imageUUID:n,taskUUID:e,taskType:"imageUpload"}})}catch(e){throw e}};this.controlNetPreProcess=async({inputImage:t,preProcessorType:e,height:n,width:s,outputType:a,outputFormat:l,highThresholdCanny:u,lowThresholdCanny:r,includeHandsAndFaceOpenPose:p,includeCost:d,outputQuality:m,customTaskUUID:c,retry:g,includeGenerationTime:i,includePayload:y})=>{let I=g||this._globalMaxRetries,b,_=Date.now();try{return await v(async()=>{await this.ensureConnection();let R=await this.uploadImage(t);if(!R?.imageUUID)return null;let U=c||k(),f={inputImage:R.imageUUID,taskType:"imageControlNetPreProcess",taskUUID:U,preProcessorType:e,...T({key:"height",value:n}),...T({key:"width",value:s}),...T({key:"outputType",value:a}),...T({key:"outputFormat",value:l}),...T({key:"includeCost",value:d}),...T({key:"highThresholdCanny",value:u}),...T({key:"lowThresholdCanny",value:r}),...T({key:"includeHandsAndFaceOpenPose",value:p}),...m?{outputQuality:m}:{}};this.send({...f}),b=this.globalListener({taskUUID:U});let N=await w(({resolve:H,reject:j})=>{let x=this.getSingleMessage({taskUUID:U});if(x){if(x?.error)return j(x),!0;if(x)return H(x),!0}},{debugKey:"unprocessed-image",timeoutDuration:this._timeoutDuration});return b.destroy(),this.insertAdditionalResponse({response:N,payload:y?f:void 0,startTime:i?_:void 0}),N},{maxRetries:I,callback:()=>{b?.destroy()}})}catch(R){throw R}};this.requestImageToText=async({inputImage:t,includeCost:e,customTaskUUID:n,retry:s,includePayload:a,includeGenerationTime:l})=>{let u=s||this._globalMaxRetries,r,p=Date.now();try{return await v(async()=>{await this.ensureConnection();let d=t?await this.uploadImage(t):null,m=n||k(),c={taskUUID:m,taskType:"imageCaption",inputImage:d?.imageUUID,...T({key:"includeCost",value:e})};this.send(c),r=this.globalListener({taskUUID:m});let g=await w(({resolve:i,reject:y})=>{let I=this.getSingleMessage({taskUUID:m});if(I){if(I?.error)return y(I),!0;if(I)return delete this._globalMessages[m],i(I),!0}},{debugKey:"remove-image-background",timeoutDuration:this._timeoutDuration});return r.destroy(),this.insertAdditionalResponse({response:g,payload:a?c:void 0,startTime:l?p:void 0}),g},{maxRetries:u,callback:()=>{r?.destroy()}})}catch(d){throw d}};this.removeImageBackground=async t=>this.baseSingleRequest({payload:{...t,taskType:"imageBackgroundRemoval"},debugKey:"remove-image-background"});this.videoInference=async t=>{let{skipResponse:e,...n}=t;try{let s=await this.baseSingleRequest({payload:{...n,deliveryMethod:"async",taskType:"videoInference"},debugKey:"video-inference"});if(e)return s;let a=s?.taskUUID,l=t?.numberResults??1,u=new Map;return await Ae(async({resolve:r,reject:p})=>{try{let d=await this.getResponse({taskUUID:a});for(let c of d||[])c.videoUUID&&u.set(c.videoUUID,c);return u.size===l?(r(Array.from(u.values())),!0):!1}catch(d){return p(d),!0}},{debugKey:"async-response",pollingInterval:2*1e3,timeoutDuration:10*60*1e3}),Array.from(u.values())}catch(s){throw s}};this.getResponse=async t=>{let e=t.taskUUID;return this.baseSingleRequest({payload:{...t,customTaskUUID:e,taskType:"getResponse"},isMultiple:!0,debugKey:"async-results"})};this.upscaleGan=async({inputImage:t,upscaleFactor:e,outputType:n,outputFormat:s,includeCost:a,outputQuality:l,customTaskUUID:u,retry:r,includeGenerationTime:p,includePayload:d})=>{let m=r||this._globalMaxRetries,c,g=Date.now();try{return await v(async()=>{await this.ensureConnection();let i;i=await this.uploadImage(t);let y=u||k(),I={taskUUID:y,inputImage:i?.imageUUID,taskType:"imageUpscale",upscaleFactor:e,...T({key:"includeCost",value:a}),...n?{outputType:n}:{},...l?{outputQuality:l}:{},...s?{outputFormat:s}:{}};this.send(I),c=this.globalListener({taskUUID:y});let b=await w(({resolve:_,reject:R})=>{let U=this.getSingleMessage({taskUUID:y});if(U){if(U?.error)return R(U),!0;if(U)return delete this._globalMessages[y],_(U),!0}},{debugKey:"upscale-gan",timeoutDuration:this._timeoutDuration});return c.destroy(),this.insertAdditionalResponse({response:b,payload:d?I:void 0,startTime:p?g:void 0}),b},{maxRetries:m,callback:()=>{c?.destroy()}})}catch(i){throw i}};this.enhancePrompt=async({prompt:t,promptMaxLength:e=380,promptVersions:n=1,includeCost:s,customTaskUUID:a,retry:l,includeGenerationTime:u,includePayload:r})=>{let p=l||this._globalMaxRetries,d,m=Date.now();try{return await v(async()=>{await this.ensureConnection();let c=a||k(),g={prompt:t,taskUUID:c,promptMaxLength:e,promptVersions:n,...T({key:"includeCost",value:s}),taskType:"promptEnhance"};this.send(g),d=this.globalListener({taskUUID:c});let i=await w(({resolve:y,reject:I})=>{let b=this._globalMessages[c];if(b?.error)return I(b),!0;if(b?.length>=n)return delete this._globalMessages[c],y(b),!0},{debugKey:"enhance-prompt",timeoutDuration:this._timeoutDuration});return d.destroy(),this.insertAdditionalResponse({response:i,payload:r?g:void 0,startTime:u?m:void 0}),i},{maxRetries:p,callback:()=>{d?.destroy()}})}catch(c){throw c}};this.modelUpload=async t=>{let{onUploadStream:e,retry:n,customTaskUUID:s,...a}=t,l=n||this._globalMaxRetries,u;try{return await v(async()=>{await this.ensureConnection();let r=s||k();this.send({...a,taskUUID:r,taskType:"modelUpload"});let p,d;return u=this.listenToUpload({taskUUID:r,onUploadStream:(c,g)=>{e?.(c,g),c?.status==="ready"?p=c:g&&(d=g)}}),await w(({resolve:c,reject:g})=>{if(p)return c(p),!0;if(d)return g(d),!1},{shouldThrowError:!1,timeoutDuration:60*60*1e3})},{maxRetries:l,callback:()=>{u?.destroy()}})}catch(r){throw r}};this.photoMaker=async(t,e)=>{let{onPartialImages:n,retry:s,customTaskUUID:a,numberResults:l,includeGenerationTime:u,includePayload:r,...p}=t,d=s||this._globalMaxRetries,m,c=[],g=0,i=Date.now();try{return await v(async()=>{await this.ensureConnection(),g++;let y=this._globalImages.filter(U=>c.includes(U.taskUUID)),I=a||k();c.push(I);let b=l-y.length,_={...p,...p.seed?{seed:p.seed}:{seed:se()},...e??{},taskUUID:I,taskType:"photoMaker",numberResults:l};this.send({..._,numberResults:b}),m=this.listenToImages({onPartialImages:n,taskUUID:I,groupKey:"REQUEST_IMAGES",requestPayload:r?_:void 0,startTime:u?i:void 0});let R=await this.getSimilarImages({taskUUID:c,numberResults:l,lis:m});return m.destroy(),R},{maxRetries:d,callback:()=>{m?.destroy()}})}catch(y){if(y.taskUUID)throw y;if(g>=d)return this.handleIncompleteImages({taskUUIDs:c,error:y})}};this.modelSearch=async t=>this.baseSingleRequest({payload:{...t,taskType:"modelSearch"},debugKey:"model-search"});this.imageMasking=async t=>this.baseSingleRequest({payload:{...t,taskType:"imageMasking"},debugKey:"image-masking"});this.imageUpload=async t=>this.baseSingleRequest({payload:{...t,taskType:"imageUpload"},debugKey:"image-upload"});this.baseSingleRequest=async({payload:t,debugKey:e,mockResponse:n,isMultiple:s})=>{let{retry:a,customTaskUUID:l,includePayload:u,includeGenerationTime:r,...p}=t,d=a||this._globalMaxRetries,m,c=Date.now();try{return await v(async()=>{await this.ensureConnection();let g=l||k(),i={...p,taskUUID:g};n?setTimeout(()=>{this._globalMessages[g]=n},1e3):this.send(i),m=this.globalListener({taskUUID:g});let y=await w(({resolve:I,reject:b})=>{let _=s?this.getMultipleMessages({taskUUID:g}):this.getSingleMessage({taskUUID:g});if(_){if(_?.error)return b(_),!0;if(_)return delete this._globalMessages[g],I(_),!0}},{debugKey:e,timeoutDuration:this._timeoutDuration});return this.insertAdditionalResponse({response:y,payload:u?i:void 0,startTime:r?c:void 0}),m.destroy(),y},{maxRetries:d,callback:()=>{m?.destroy()}})}catch(g){throw g}};this.getSingleMessage=({taskUUID:t})=>{let e=this._globalMessages[t]?.[0],n=this._globalMessages[t];return!e&&!n?null:n?.error?n:e};this.getMultipleMessages=({taskUUID:t})=>{let e=this._globalMessages[t]?.[0],n=this._globalMessages[t];return!e&&!n?null:n};this.insertAdditionalResponse=({response:t,payload:e,startTime:n})=>{if(!e&&!n)return;let s=t;s.additionalResponse={},e&&(t.additionalResponse.payload=e),n&&(t.additionalResponse.generationTime=Date.now()-n)};this.disconnect=async()=>{this._shouldReconnect=!1,this._ws?.terminate?.(),this._ws?.close?.()};this.connected=()=>this.isWebsocketReadyState()&&!!this._connectionSessionUUID;this._apiKey=t,this._url=e,this._sdkType="CLIENT",this._shouldReconnect=n,this._globalMaxRetries=s,this._timeoutDuration=a}static async initialize(t){try{let e=new this(t);return await e.ensureConnection(),e}catch(e){throw e}}addListener({lis:t,groupKey:e,taskUUID:n}){let s=u=>{let r=Array.isArray(u?.data)?u.data:[u.data],p=u?.[0]?.errors?u?.[0]?.errors:Array.isArray(u?.errors)?u.errors:[u.errors],d=r.filter(c=>(c?.taskUUID||c?.taskType)===n);if(p.filter(c=>(c?.taskUUID||c?.taskType)===n).length){t({error:{...p[0]??{}}});return}if(d.length){t({[n]:r});return}},a={key:n||k(),listener:s,groupKey:e};return this._listeners.push(a),{destroy:()=>{this._listeners=Se(this._listeners,a)}}}connect(){this._ws.onopen=t=>{this._connectionSessionUUID?this.send({taskType:"authentication",apiKey:this._apiKey,connectionSessionUUID:this._connectionSessionUUID}):this.send({apiKey:this._apiKey,taskType:"authentication"}),this.addListener({taskUUID:"authentication",lis:e=>{if(e?.error){this._connectionError=e;return}this._connectionSessionUUID=e?.authentication?.[0]?.connectionSessionUUID,this._connectionError=void 0}})},this._ws.onmessage=t=>{let e=JSON.parse(t.data);for(let n of this._listeners)if(n?.listener?.(e))return},this._ws.onclose=t=>{this.isInvalidAPIKey()}}destroy(t){ke(this._listeners,t)}listenToImages({onPartialImages:t,taskUUID:e,groupKey:n,requestPayload:s,startTime:a}){return this.addListener({taskUUID:e,lis:l=>{let u=l?.[e]?.filter(r=>r.taskUUID===e);l.error?(t?.(u,l?.error&&l),this._globalError=l):(u=u.map(r=>(this.insertAdditionalResponse({response:r,payload:s||void 0,startTime:a||void 0}),{...r})),t?.(u,l?.error&&l),this._sdkType==="CLIENT"?this._globalImages=[...this._globalImages,...(l?.[e]??[]).map(r=>(this.insertAdditionalResponse({response:r,payload:s||void 0,startTime:a||void 0}),{...r}))]:this._globalImages=[...this._globalImages,...u])},groupKey:n})}listenToUpload({onUploadStream:t,taskUUID:e}){return this.addListener({taskUUID:e,lis:n=>{let s=n?.error,a=n?.[e]?.[0],l=a?.taskUUID===e?a:null;(l||s)&&t?.(l||void 0,s)}})}globalListener({taskUUID:t}){return this.addListener({taskUUID:t,lis:e=>{if(e.error){this._globalMessages[t]=e;return}let n=xe({key:t,data:e,useZero:!1});Array.isArray(n)?n.forEach(s=>{this._globalMessages[s.taskUUID]=[...this._globalMessages[s.taskUUID]??[],s]}):this._globalMessages[n.taskUUID]=n}})}async requestImages({outputType:t,outputFormat:e,uploadEndpoint:n,checkNSFW:s,positivePrompt:a,negativePrompt:l,seedImage:u,maskImage:r,strength:p,height:d,width:m,model:c,steps:g,scheduler:i,seed:y,CFGScale:I,clipSkip:b,usePromptWeighting:_,promptWeighting:R,numberResults:U=1,onPartialImages:f,includeCost:N,customTaskUUID:H,retry:j,refiner:x,maskMargin:Ke,outputQuality:h,controlNet:Q,lora:ae,embeddings:oe,ipAdapters:ie,outpaint:le,acceleratorOptions:ce,advancedFeatures:ue,referenceImages:de,includeGenerationTime:We,includePayload:Fe},Ge){let C,pe,L=[],ge=0,me=j||this._globalMaxRetries;try{await this.ensureConnection();let S=null,J=null,z=[];if(u){let D=await this.uploadImage(u);if(!D)return[];S=D.imageUUID}if(r){let D=await this.uploadImage(r);if(!D)return[];J=D.imageUUID}if(Q?.length)for(let D=0;D<Q.length;D++){let E=Q[D],{endStep:Y,startStep:P,weight:$,guideImage:K,controlMode:qe,startStepPercentage:Ve,endStepPercentage:He,model:je}=E,Qe=K?await this.uploadImage(K):null;z.push({guideImage:Qe?.imageUUID,model:je,endStep:Y,startStep:P,weight:$,...T({key:"startStepPercentage",value:Ve}),...T({key:"endStepPercentage",value:He}),controlMode:qe||"controlnet"})}pe={taskType:"imageInference",model:c,positivePrompt:a,...l?{negativePrompt:l}:{},...d?{height:d}:{},...m?{width:m}:{},numberResults:U,...t?{outputType:t}:{},...e?{outputFormat:e}:{},...n?{uploadEndpoint:n}:{},...T({key:"checkNSFW",value:s}),...T({key:"strength",value:p}),...T({key:"CFGScale",value:I}),...T({key:"clipSkip",value:b}),...T({key:"maskMargin",value:Ke}),...T({key:"usePromptWeighting",value:_}),...T({key:"steps",value:g}),...R?{promptWeighting:R}:{},...y?{seed:y}:{seed:se()},...i?{scheduler:i}:{},...x?{refiner:x}:{},...le?{outpaint:le}:{},...T({key:"includeCost",value:N}),...S?{seedImage:S}:{},...J?{maskImage:J}:{},...h?{outputQuality:h}:{},...z.length?{controlNet:z}:{},...ae?.length?{lora:ae}:{},...oe?.length?{embeddings:oe}:{},...ie?.length?{ipAdapters:ie}:{},...ce?{acceleratorOptions:ce}:{},...ue?{advancedFeatures:ue}:{},...de?.length?{referenceImages:de}:{},...Ge??{}};let Be=Date.now();return await v(async()=>{ge++,C?.destroy();let D=this._globalImages.filter(K=>L.includes(K.taskUUID)),E=H||k();L.push(E);let Y=U-D.length,P={...pe,taskUUID:E,numberResults:Y};this.send(P),C=this.listenToImages({onPartialImages:f,taskUUID:E,groupKey:"REQUEST_IMAGES",requestPayload:Fe?P:void 0,startTime:We?Be:void 0});let $=await this.getSimilarImages({taskUUID:L,numberResults:U,lis:C});return C.destroy(),$},{maxRetries:me,callback:()=>{C?.destroy()}})}catch(S){if(ge>=me)return this.handleIncompleteImages({taskUUIDs:L,error:S});throw S}}async ensureConnection(){if(this.connected()||this._url===ne.TEST)return;let e=2e3,n=200;try{if(this.isInvalidAPIKey())throw this._connectionError;return new Promise((s,a)=>{let l=0,u=30,r=k(),p,d,m=()=>{this.ensureConnectionUUID=null,clearInterval(p),clearInterval(d)};this._sdkType==="SERVER"&&(p=setInterval(async()=>{try{let c=this.connected(),g=!1;(!this.ensureConnectionUUID||r===this.ensureConnectionUUID)&&(this.ensureConnectionUUID||(this.ensureConnectionUUID=r),g=!0);let i=l%10===0&&g;c?(m(),s(!0)):l>=u?(m(),a(new Error("Retry timed out"))):(i&&this.connect(),l++)}catch(c){m(),a(c)}},e)),d=setInterval(async()=>{if(this.connected()){m(),s(!0);return}if(this.isInvalidAPIKey()){m(),a(this._connectionError);return}},n)})}catch{throw this.ensureConnectionUUID=null,this._connectionError=void 0,this._connectionError??"Could not connect to server. Ensure your API key is correct"}}async getSimilarImages({taskUUID:t,numberResults:e,shouldThrowError:n,lis:s}){return await w(({resolve:a,reject:l,intervalId:u})=>{let r=Array.isArray(t)?t:[t],p=this._globalImages.filter(d=>r.includes(d.taskUUID));if(this._globalError){let d=this._globalError;return this._globalError=void 0,clearInterval(u),l?.(d),!0}else if(p.length>=e)return clearInterval(u),this._globalImages=this._globalImages.filter(d=>!r.includes(d.taskUUID)),a([...p].slice(0,e)),!0},{debugKey:"getting images",shouldThrowError:n,timeoutDuration:this._timeoutDuration})}handleIncompleteImages({taskUUIDs:t,error:e}){let n=this._globalImages.filter(s=>t.includes(s.taskUUID));if(n.length>1)return this._globalImages=this._globalImages.filter(s=>!t.includes(s.taskUUID)),n;throw e}};var Le=Ie(Ne(),1),M=class extends A{constructor(t){let{shouldReconnect:e,...n}=t;super(n),this._ws=new Le.default(this._url),this.connect()}};var Pe=Ie(require("ws"),1);var O=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 Pe.default(this._url,{perMessageDeflate:!1}),this._ws.on("error",()=>{}),this._ws.on("close",()=>{this.handleClose()}),this._ws.on("open",()=>{this._reconnectingIntervalId&&clearInterval(this._reconnectingIntervalId),this._connectionSessionUUID&&this.isWebsocketReadyState()?this.send({taskType:"authentication",apiKey:this._apiKey,connectionSessionUUID:this._connectionSessionUUID}):this.isWebsocketReadyState()&&this.send({apiKey:this._apiKey,taskType:"authentication"}),this.addListener({taskUUID:"authentication",lis:e=>{if(e?.error){this._connectionError=e;return}this._connectionSessionUUID=e?.authentication?.[0]?.connectionSessionUUID,this._connectionError=void 0}})}),this._ws.on("message",(e,n)=>{let s=n?e:e?.toString();if(!s)return;let a=JSON.parse(s);this._listeners.forEach(l=>{l.listener(a)})}))}handleClose(){this.isInvalidAPIKey()||(this._reconnectingIntervalId&&clearInterval(this._reconnectingIntervalId),this._shouldReconnect&&setTimeout(()=>this.connect(),1e3))}heartBeat(){clearTimeout(this._pingTimeout),this._pingTimeout=setTimeout(()=>{this.isWebsocketReadyState()&&this.send({ping:!0})},5e3)}};var re;typeof window>"u"?re=O:re=M;0&&(module.exports={EControlMode,EModelArchitecture,EModelConditioning,EModelFormat,EModelType,EOpenPosePreProcessor,EPhotoMakerEnum,EPreProcessor,EPreProcessorGroup,ETaskType,Environment,Runware,RunwareClient,RunwareServer,SdkType});
2
2
  //# sourceMappingURL=index.cjs.map