@runware/sdk-js 1.1.35-beta.1 → 1.1.35-beta.2

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