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