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