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