@runware/sdk-js 1.1.39 → 1.1.41-beta.1
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 +20 -14
- package/dist/index.d.ts +20 -14
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
- package/readme.md +8 -2
package/dist/index.d.cts
CHANGED
|
@@ -30,6 +30,10 @@ type RunwareBaseType = {
|
|
|
30
30
|
};
|
|
31
31
|
type IOutputType = "base64Data" | "dataURI" | "URL";
|
|
32
32
|
type IOutputFormat = "JPG" | "PNG" | "WEBP";
|
|
33
|
+
interface IAdditionalResponsePayload {
|
|
34
|
+
includePayload?: boolean;
|
|
35
|
+
includeGenerationTime?: boolean;
|
|
36
|
+
}
|
|
33
37
|
interface IImage {
|
|
34
38
|
taskType: ETaskType;
|
|
35
39
|
imageUUID: string;
|
|
@@ -88,7 +92,7 @@ type IControlNetPreprocess = {
|
|
|
88
92
|
outputQuality?: number;
|
|
89
93
|
customTaskUUID?: string;
|
|
90
94
|
retry?: number;
|
|
91
|
-
};
|
|
95
|
+
} & IAdditionalResponsePayload;
|
|
92
96
|
type IControlNet = IControlNetGeneral;
|
|
93
97
|
type IControlNetWithUUID = Omit<IControlNet, "guideImage"> & {
|
|
94
98
|
guideImage?: string;
|
|
@@ -99,7 +103,7 @@ interface IError {
|
|
|
99
103
|
taskUUID: string;
|
|
100
104
|
}
|
|
101
105
|
type TPromptWeighting = "compel" | "sdEmbeds";
|
|
102
|
-
interface IRequestImage {
|
|
106
|
+
interface IRequestImage extends IAdditionalResponsePayload {
|
|
103
107
|
outputType?: IOutputType;
|
|
104
108
|
outputFormat?: IOutputFormat;
|
|
105
109
|
uploadEndpoint?: string;
|
|
@@ -136,6 +140,7 @@ interface IRequestImage {
|
|
|
136
140
|
advancedFeatures?: {
|
|
137
141
|
layerDiffuse: boolean;
|
|
138
142
|
};
|
|
143
|
+
referenceImages?: string[];
|
|
139
144
|
customTaskUUID?: string;
|
|
140
145
|
onPartialImages?: (images: IImage[], error?: IError) => void;
|
|
141
146
|
retry?: number;
|
|
@@ -169,7 +174,7 @@ interface IRefiner {
|
|
|
169
174
|
startStep?: number;
|
|
170
175
|
startStepPercentage?: number;
|
|
171
176
|
}
|
|
172
|
-
interface IRequestImageToText {
|
|
177
|
+
interface IRequestImageToText extends IAdditionalResponsePayload {
|
|
173
178
|
inputImage?: File | string;
|
|
174
179
|
includeCost?: boolean;
|
|
175
180
|
customTaskUUID?: string;
|
|
@@ -208,7 +213,7 @@ interface IRemoveImage {
|
|
|
208
213
|
imageDataURI?: string;
|
|
209
214
|
cost?: number;
|
|
210
215
|
}
|
|
211
|
-
interface IPromptEnhancer {
|
|
216
|
+
interface IPromptEnhancer extends IAdditionalResponsePayload {
|
|
212
217
|
promptMaxLength?: number;
|
|
213
218
|
promptVersions?: number;
|
|
214
219
|
prompt: string;
|
|
@@ -218,7 +223,7 @@ interface IPromptEnhancer {
|
|
|
218
223
|
}
|
|
219
224
|
interface IEnhancedPrompt extends IImageToText {
|
|
220
225
|
}
|
|
221
|
-
interface IUpscaleGan {
|
|
226
|
+
interface IUpscaleGan extends IAdditionalResponsePayload {
|
|
222
227
|
inputImage: File | string;
|
|
223
228
|
upscaleFactor: number;
|
|
224
229
|
outputType?: IOutputType;
|
|
@@ -325,12 +330,12 @@ interface IErrorResponse {
|
|
|
325
330
|
type TAddModelBaseType = {
|
|
326
331
|
air: string;
|
|
327
332
|
name: string;
|
|
328
|
-
|
|
333
|
+
downloadURL: string;
|
|
329
334
|
uniqueIdentifier: string;
|
|
330
335
|
version: string;
|
|
331
336
|
format: EModelFormat;
|
|
332
337
|
architecture: EModelArchitecture;
|
|
333
|
-
|
|
338
|
+
heroImageURL?: string;
|
|
334
339
|
tags?: string[];
|
|
335
340
|
shortDescription?: string;
|
|
336
341
|
comment?: string;
|
|
@@ -381,7 +386,7 @@ type TPhotoMaker = {
|
|
|
381
386
|
customTaskUUID?: string;
|
|
382
387
|
retry?: number;
|
|
383
388
|
onPartialImages?: (images: IImage[], error?: IError) => void;
|
|
384
|
-
};
|
|
389
|
+
} & IAdditionalResponsePayload;
|
|
385
390
|
type TPhotoMakerResponse = {
|
|
386
391
|
taskType: string;
|
|
387
392
|
taskUUID: string;
|
|
@@ -580,12 +585,12 @@ declare class RunwareBase {
|
|
|
580
585
|
private listenToImages;
|
|
581
586
|
private listenToUpload;
|
|
582
587
|
private globalListener;
|
|
583
|
-
requestImages({ outputType, outputFormat, uploadEndpoint, checkNSFW, positivePrompt, negativePrompt, seedImage, maskImage, strength, height, width, model, steps, scheduler, seed, CFGScale, clipSkip, usePromptWeighting, promptWeighting, numberResults, onPartialImages, includeCost, customTaskUUID, retry, refiner, maskMargin, outputQuality, controlNet, lora, embeddings, ipAdapters, outpaint, acceleratorOptions, advancedFeatures, }: IRequestImage, moreOptions?: Record<string, any>): Promise<ITextToImage[] | undefined>;
|
|
584
|
-
controlNetPreProcess: ({ inputImage, preProcessorType, height, width, outputType, outputFormat, highThresholdCanny, lowThresholdCanny, includeHandsAndFaceOpenPose, includeCost, outputQuality, customTaskUUID, retry, }: IControlNetPreprocess) => Promise<IControlNetImage | null>;
|
|
585
|
-
requestImageToText: ({ inputImage, includeCost, customTaskUUID, retry, }: IRequestImageToText) => Promise<IImageToText>;
|
|
588
|
+
requestImages({ outputType, outputFormat, uploadEndpoint, checkNSFW, positivePrompt, negativePrompt, seedImage, maskImage, strength, height, width, model, steps, scheduler, seed, CFGScale, clipSkip, usePromptWeighting, promptWeighting, numberResults, onPartialImages, includeCost, customTaskUUID, retry, refiner, maskMargin, outputQuality, controlNet, lora, embeddings, ipAdapters, outpaint, acceleratorOptions, advancedFeatures, referenceImages, includeGenerationTime, includePayload, }: IRequestImage, moreOptions?: Record<string, any>): Promise<ITextToImage[] | undefined>;
|
|
589
|
+
controlNetPreProcess: ({ inputImage, preProcessorType, height, width, outputType, outputFormat, highThresholdCanny, lowThresholdCanny, includeHandsAndFaceOpenPose, includeCost, outputQuality, customTaskUUID, retry, includeGenerationTime, includePayload, }: IControlNetPreprocess) => Promise<IControlNetImage | null>;
|
|
590
|
+
requestImageToText: ({ inputImage, includeCost, customTaskUUID, retry, includePayload, includeGenerationTime, }: IRequestImageToText) => Promise<IImageToText>;
|
|
586
591
|
removeImageBackground: (payload: IRemoveImageBackground) => Promise<IRemoveImage>;
|
|
587
|
-
upscaleGan: ({ inputImage, upscaleFactor, outputType, outputFormat, includeCost, outputQuality, customTaskUUID, retry, }: IUpscaleGan) => Promise<IImage>;
|
|
588
|
-
enhancePrompt: ({ prompt, promptMaxLength, promptVersions, includeCost, customTaskUUID, retry, }: IPromptEnhancer) => Promise<IEnhancedPrompt[]>;
|
|
592
|
+
upscaleGan: ({ inputImage, upscaleFactor, outputType, outputFormat, includeCost, outputQuality, customTaskUUID, retry, includeGenerationTime, includePayload, }: IUpscaleGan) => Promise<IImage>;
|
|
593
|
+
enhancePrompt: ({ prompt, promptMaxLength, promptVersions, includeCost, customTaskUUID, retry, includeGenerationTime, includePayload, }: IPromptEnhancer) => Promise<IEnhancedPrompt[]>;
|
|
589
594
|
modelUpload: (payload: TAddModel) => Promise<any>;
|
|
590
595
|
photoMaker: (payload: TPhotoMaker, moreOptions?: Record<string, any>) => Promise<TPhotoMakerResponse[] | undefined>;
|
|
591
596
|
modelSearch: (payload: TModelSearch) => Promise<TModelSearchResponse>;
|
|
@@ -598,6 +603,7 @@ declare class RunwareBase {
|
|
|
598
603
|
ensureConnection(): Promise<unknown>;
|
|
599
604
|
private getSimilarImages;
|
|
600
605
|
private getSingleMessage;
|
|
606
|
+
private insertAdditionalResponse;
|
|
601
607
|
private handleIncompleteImages;
|
|
602
608
|
disconnect: () => Promise<void>;
|
|
603
609
|
private connected;
|
|
@@ -623,4 +629,4 @@ declare class RunwareServer extends RunwareBase {
|
|
|
623
629
|
|
|
624
630
|
declare let Runware: typeof RunwareClient | typeof RunwareServer;
|
|
625
631
|
|
|
626
|
-
export { EControlMode, EModelArchitecture, EModelConditioning, EModelFormat, EModelType, EOpenPosePreProcessor, EPhotoMakerEnum, EPreProcessor, EPreProcessorGroup, ETaskType, Environment, type GetWithPromiseCallBackType, type IAddModelResponse, type IControlNet, type IControlNetGeneral, type IControlNetImage, type IControlNetPreprocess, type IControlNetWithUUID, type IEmbedding, type IEnhancedPrompt, type IError, type IErrorResponse, type IImage, type IImageToText, type IOutpaint, type IOutputFormat, type IOutputType, type IPromptEnhancer, type IRefiner, type IRemoveImage, type IRemoveImageBackground, type IRequestImage, type IRequestImageToText, type ITextToImage, type IUpscaleGan, type IipAdapter, type ListenerType, type ReconnectingWebsocketProps, type RequireAtLeastOne, type RequireOnlyOne, Runware, type RunwareBaseType, RunwareClient, RunwareServer, SdkType, type TAcceleratorOptions, type TAddModel, type TAddModelBaseType, type TAddModelCheckPoint, type TAddModelControlNet, type TAddModelLora, type TImageMasking, type TImageMaskingResponse, type TImageUpload, type TImageUploadResponse, type TModel, type TModelSearch, type TModelSearchResponse, type TPhotoMaker, type TPhotoMakerResponse, type TPromptWeighting, type TServerError, type UploadImageType };
|
|
632
|
+
export { EControlMode, EModelArchitecture, EModelConditioning, EModelFormat, EModelType, EOpenPosePreProcessor, EPhotoMakerEnum, EPreProcessor, EPreProcessorGroup, ETaskType, Environment, type GetWithPromiseCallBackType, type IAddModelResponse, type IAdditionalResponsePayload, type IControlNet, type IControlNetGeneral, type IControlNetImage, type IControlNetPreprocess, type IControlNetWithUUID, type IEmbedding, type IEnhancedPrompt, type IError, type IErrorResponse, type IImage, type IImageToText, type IOutpaint, type IOutputFormat, type IOutputType, type IPromptEnhancer, type IRefiner, type IRemoveImage, type IRemoveImageBackground, type IRequestImage, type IRequestImageToText, type ITextToImage, type IUpscaleGan, type IipAdapter, type ListenerType, type ReconnectingWebsocketProps, type RequireAtLeastOne, type RequireOnlyOne, Runware, type RunwareBaseType, RunwareClient, RunwareServer, SdkType, type TAcceleratorOptions, type TAddModel, type TAddModelBaseType, type TAddModelCheckPoint, type TAddModelControlNet, type TAddModelLora, type TImageMasking, type TImageMaskingResponse, type TImageUpload, type TImageUploadResponse, type TModel, type TModelSearch, type TModelSearchResponse, type TPhotoMaker, type TPhotoMakerResponse, type TPromptWeighting, type TServerError, type UploadImageType };
|
package/dist/index.d.ts
CHANGED
|
@@ -30,6 +30,10 @@ type RunwareBaseType = {
|
|
|
30
30
|
};
|
|
31
31
|
type IOutputType = "base64Data" | "dataURI" | "URL";
|
|
32
32
|
type IOutputFormat = "JPG" | "PNG" | "WEBP";
|
|
33
|
+
interface IAdditionalResponsePayload {
|
|
34
|
+
includePayload?: boolean;
|
|
35
|
+
includeGenerationTime?: boolean;
|
|
36
|
+
}
|
|
33
37
|
interface IImage {
|
|
34
38
|
taskType: ETaskType;
|
|
35
39
|
imageUUID: string;
|
|
@@ -88,7 +92,7 @@ type IControlNetPreprocess = {
|
|
|
88
92
|
outputQuality?: number;
|
|
89
93
|
customTaskUUID?: string;
|
|
90
94
|
retry?: number;
|
|
91
|
-
};
|
|
95
|
+
} & IAdditionalResponsePayload;
|
|
92
96
|
type IControlNet = IControlNetGeneral;
|
|
93
97
|
type IControlNetWithUUID = Omit<IControlNet, "guideImage"> & {
|
|
94
98
|
guideImage?: string;
|
|
@@ -99,7 +103,7 @@ interface IError {
|
|
|
99
103
|
taskUUID: string;
|
|
100
104
|
}
|
|
101
105
|
type TPromptWeighting = "compel" | "sdEmbeds";
|
|
102
|
-
interface IRequestImage {
|
|
106
|
+
interface IRequestImage extends IAdditionalResponsePayload {
|
|
103
107
|
outputType?: IOutputType;
|
|
104
108
|
outputFormat?: IOutputFormat;
|
|
105
109
|
uploadEndpoint?: string;
|
|
@@ -136,6 +140,7 @@ interface IRequestImage {
|
|
|
136
140
|
advancedFeatures?: {
|
|
137
141
|
layerDiffuse: boolean;
|
|
138
142
|
};
|
|
143
|
+
referenceImages?: string[];
|
|
139
144
|
customTaskUUID?: string;
|
|
140
145
|
onPartialImages?: (images: IImage[], error?: IError) => void;
|
|
141
146
|
retry?: number;
|
|
@@ -169,7 +174,7 @@ interface IRefiner {
|
|
|
169
174
|
startStep?: number;
|
|
170
175
|
startStepPercentage?: number;
|
|
171
176
|
}
|
|
172
|
-
interface IRequestImageToText {
|
|
177
|
+
interface IRequestImageToText extends IAdditionalResponsePayload {
|
|
173
178
|
inputImage?: File | string;
|
|
174
179
|
includeCost?: boolean;
|
|
175
180
|
customTaskUUID?: string;
|
|
@@ -208,7 +213,7 @@ interface IRemoveImage {
|
|
|
208
213
|
imageDataURI?: string;
|
|
209
214
|
cost?: number;
|
|
210
215
|
}
|
|
211
|
-
interface IPromptEnhancer {
|
|
216
|
+
interface IPromptEnhancer extends IAdditionalResponsePayload {
|
|
212
217
|
promptMaxLength?: number;
|
|
213
218
|
promptVersions?: number;
|
|
214
219
|
prompt: string;
|
|
@@ -218,7 +223,7 @@ interface IPromptEnhancer {
|
|
|
218
223
|
}
|
|
219
224
|
interface IEnhancedPrompt extends IImageToText {
|
|
220
225
|
}
|
|
221
|
-
interface IUpscaleGan {
|
|
226
|
+
interface IUpscaleGan extends IAdditionalResponsePayload {
|
|
222
227
|
inputImage: File | string;
|
|
223
228
|
upscaleFactor: number;
|
|
224
229
|
outputType?: IOutputType;
|
|
@@ -325,12 +330,12 @@ interface IErrorResponse {
|
|
|
325
330
|
type TAddModelBaseType = {
|
|
326
331
|
air: string;
|
|
327
332
|
name: string;
|
|
328
|
-
|
|
333
|
+
downloadURL: string;
|
|
329
334
|
uniqueIdentifier: string;
|
|
330
335
|
version: string;
|
|
331
336
|
format: EModelFormat;
|
|
332
337
|
architecture: EModelArchitecture;
|
|
333
|
-
|
|
338
|
+
heroImageURL?: string;
|
|
334
339
|
tags?: string[];
|
|
335
340
|
shortDescription?: string;
|
|
336
341
|
comment?: string;
|
|
@@ -381,7 +386,7 @@ type TPhotoMaker = {
|
|
|
381
386
|
customTaskUUID?: string;
|
|
382
387
|
retry?: number;
|
|
383
388
|
onPartialImages?: (images: IImage[], error?: IError) => void;
|
|
384
|
-
};
|
|
389
|
+
} & IAdditionalResponsePayload;
|
|
385
390
|
type TPhotoMakerResponse = {
|
|
386
391
|
taskType: string;
|
|
387
392
|
taskUUID: string;
|
|
@@ -580,12 +585,12 @@ declare class RunwareBase {
|
|
|
580
585
|
private listenToImages;
|
|
581
586
|
private listenToUpload;
|
|
582
587
|
private globalListener;
|
|
583
|
-
requestImages({ outputType, outputFormat, uploadEndpoint, checkNSFW, positivePrompt, negativePrompt, seedImage, maskImage, strength, height, width, model, steps, scheduler, seed, CFGScale, clipSkip, usePromptWeighting, promptWeighting, numberResults, onPartialImages, includeCost, customTaskUUID, retry, refiner, maskMargin, outputQuality, controlNet, lora, embeddings, ipAdapters, outpaint, acceleratorOptions, advancedFeatures, }: IRequestImage, moreOptions?: Record<string, any>): Promise<ITextToImage[] | undefined>;
|
|
584
|
-
controlNetPreProcess: ({ inputImage, preProcessorType, height, width, outputType, outputFormat, highThresholdCanny, lowThresholdCanny, includeHandsAndFaceOpenPose, includeCost, outputQuality, customTaskUUID, retry, }: IControlNetPreprocess) => Promise<IControlNetImage | null>;
|
|
585
|
-
requestImageToText: ({ inputImage, includeCost, customTaskUUID, retry, }: IRequestImageToText) => Promise<IImageToText>;
|
|
588
|
+
requestImages({ outputType, outputFormat, uploadEndpoint, checkNSFW, positivePrompt, negativePrompt, seedImage, maskImage, strength, height, width, model, steps, scheduler, seed, CFGScale, clipSkip, usePromptWeighting, promptWeighting, numberResults, onPartialImages, includeCost, customTaskUUID, retry, refiner, maskMargin, outputQuality, controlNet, lora, embeddings, ipAdapters, outpaint, acceleratorOptions, advancedFeatures, referenceImages, includeGenerationTime, includePayload, }: IRequestImage, moreOptions?: Record<string, any>): Promise<ITextToImage[] | undefined>;
|
|
589
|
+
controlNetPreProcess: ({ inputImage, preProcessorType, height, width, outputType, outputFormat, highThresholdCanny, lowThresholdCanny, includeHandsAndFaceOpenPose, includeCost, outputQuality, customTaskUUID, retry, includeGenerationTime, includePayload, }: IControlNetPreprocess) => Promise<IControlNetImage | null>;
|
|
590
|
+
requestImageToText: ({ inputImage, includeCost, customTaskUUID, retry, includePayload, includeGenerationTime, }: IRequestImageToText) => Promise<IImageToText>;
|
|
586
591
|
removeImageBackground: (payload: IRemoveImageBackground) => Promise<IRemoveImage>;
|
|
587
|
-
upscaleGan: ({ inputImage, upscaleFactor, outputType, outputFormat, includeCost, outputQuality, customTaskUUID, retry, }: IUpscaleGan) => Promise<IImage>;
|
|
588
|
-
enhancePrompt: ({ prompt, promptMaxLength, promptVersions, includeCost, customTaskUUID, retry, }: IPromptEnhancer) => Promise<IEnhancedPrompt[]>;
|
|
592
|
+
upscaleGan: ({ inputImage, upscaleFactor, outputType, outputFormat, includeCost, outputQuality, customTaskUUID, retry, includeGenerationTime, includePayload, }: IUpscaleGan) => Promise<IImage>;
|
|
593
|
+
enhancePrompt: ({ prompt, promptMaxLength, promptVersions, includeCost, customTaskUUID, retry, includeGenerationTime, includePayload, }: IPromptEnhancer) => Promise<IEnhancedPrompt[]>;
|
|
589
594
|
modelUpload: (payload: TAddModel) => Promise<any>;
|
|
590
595
|
photoMaker: (payload: TPhotoMaker, moreOptions?: Record<string, any>) => Promise<TPhotoMakerResponse[] | undefined>;
|
|
591
596
|
modelSearch: (payload: TModelSearch) => Promise<TModelSearchResponse>;
|
|
@@ -598,6 +603,7 @@ declare class RunwareBase {
|
|
|
598
603
|
ensureConnection(): Promise<unknown>;
|
|
599
604
|
private getSimilarImages;
|
|
600
605
|
private getSingleMessage;
|
|
606
|
+
private insertAdditionalResponse;
|
|
601
607
|
private handleIncompleteImages;
|
|
602
608
|
disconnect: () => Promise<void>;
|
|
603
609
|
private connected;
|
|
@@ -623,4 +629,4 @@ declare class RunwareServer extends RunwareBase {
|
|
|
623
629
|
|
|
624
630
|
declare let Runware: typeof RunwareClient | typeof RunwareServer;
|
|
625
631
|
|
|
626
|
-
export { EControlMode, EModelArchitecture, EModelConditioning, EModelFormat, EModelType, EOpenPosePreProcessor, EPhotoMakerEnum, EPreProcessor, EPreProcessorGroup, ETaskType, Environment, type GetWithPromiseCallBackType, type IAddModelResponse, type IControlNet, type IControlNetGeneral, type IControlNetImage, type IControlNetPreprocess, type IControlNetWithUUID, type IEmbedding, type IEnhancedPrompt, type IError, type IErrorResponse, type IImage, type IImageToText, type IOutpaint, type IOutputFormat, type IOutputType, type IPromptEnhancer, type IRefiner, type IRemoveImage, type IRemoveImageBackground, type IRequestImage, type IRequestImageToText, type ITextToImage, type IUpscaleGan, type IipAdapter, type ListenerType, type ReconnectingWebsocketProps, type RequireAtLeastOne, type RequireOnlyOne, Runware, type RunwareBaseType, RunwareClient, RunwareServer, SdkType, type TAcceleratorOptions, type TAddModel, type TAddModelBaseType, type TAddModelCheckPoint, type TAddModelControlNet, type TAddModelLora, type TImageMasking, type TImageMaskingResponse, type TImageUpload, type TImageUploadResponse, type TModel, type TModelSearch, type TModelSearchResponse, type TPhotoMaker, type TPhotoMakerResponse, type TPromptWeighting, type TServerError, type UploadImageType };
|
|
632
|
+
export { EControlMode, EModelArchitecture, EModelConditioning, EModelFormat, EModelType, EOpenPosePreProcessor, EPhotoMakerEnum, EPreProcessor, EPreProcessorGroup, ETaskType, Environment, type GetWithPromiseCallBackType, type IAddModelResponse, type IAdditionalResponsePayload, type IControlNet, type IControlNetGeneral, type IControlNetImage, type IControlNetPreprocess, type IControlNetWithUUID, type IEmbedding, type IEnhancedPrompt, type IError, type IErrorResponse, type IImage, type IImageToText, type IOutpaint, type IOutputFormat, type IOutputType, type IPromptEnhancer, type IRefiner, type IRemoveImage, type IRemoveImageBackground, type IRequestImage, type IRequestImageToText, type ITextToImage, type IUpscaleGan, type IipAdapter, type ListenerType, type ReconnectingWebsocketProps, type RequireAtLeastOne, type RequireOnlyOne, Runware, type RunwareBaseType, RunwareClient, RunwareServer, SdkType, type TAcceleratorOptions, type TAddModel, type TAddModelBaseType, type TAddModelCheckPoint, type TAddModelControlNet, type TAddModelLora, type TImageMasking, type TImageMaskingResponse, type TImageUpload, type TImageUploadResponse, type TModel, type TModelSearch, type TModelSearchResponse, type TPhotoMaker, type TPhotoMakerResponse, type TPromptWeighting, type TServerError, type UploadImageType };
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var Ee=Object.create;var re=Object.defineProperty;var Oe=Object.getOwnPropertyDescriptor;var Ne=Object.getOwnPropertyNames;var Me=Object.getPrototypeOf,Le=Object.prototype.hasOwnProperty;var Ke=(l,t)=>()=>(t||l((t={exports:{}}).exports,t),t.exports);var We=(l,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of Ne(t))!Le.call(l,a)&&a!==e&&re(l,a,{get:()=>t[a],enumerable:!(n=Oe(t,a))||n.enumerable});return l};var Fe=(l,t,e)=>(e=l!=null?Ee(Me(l)):{},We(t||!l||!l.__esModule?re(e,"default",{value:l,enumerable:!0}):e,l));var fe=Ke((Yt,be)=>{"use strict";var Ie=l=>l&&l.CLOSING===2,ze=()=>typeof WebSocket<"u"&&Ie(WebSocket),Ze=()=>({constructor:ze()?WebSocket:null,maxReconnectionDelay:1e4,minReconnectionDelay:1500,reconnectionDelayGrowFactor:1.3,connectionTimeout:4e3,maxRetries:1/0,debug:!1}),$e=(l,t,e)=>{Object.defineProperty(t,e,{get:()=>l[e],set:n=>{l[e]=n},enumerable:!0,configurable:!0})},ye=l=>l.minReconnectionDelay+Math.random()*l.minReconnectionDelay,Xe=(l,t)=>{let e=t*l.reconnectionDelayGrowFactor;return e>l.maxReconnectionDelay?l.maxReconnectionDelay:e},et=["onopen","onclose","onmessage","onerror"],tt=(l,t,e)=>{Object.keys(e).forEach(n=>{e[n].forEach(([a,o])=>{l.addEventListener(n,a,o)})}),t&&et.forEach(n=>{l[n]=t[n]})},he=function(l,t,e={}){let n,a,o=0,c=0,i=!0,s={};if(!(this instanceof he))throw new TypeError("Failed to construct 'ReconnectingWebSocket': Please use the 'new' operator");let u=Ze();if(Object.keys(u).filter(m=>e.hasOwnProperty(m)).forEach(m=>u[m]=e[m]),!Ie(u.constructor))throw new TypeError("Invalid WebSocket constructor. Set `options.constructor`");let g=u.debug?(...m)=>console.log("RWS:",...m):()=>{},p=(m,h)=>setTimeout(()=>{let b=new Error(h);b.code=m,Array.isArray(s.error)&&s.error.forEach(([U])=>U(b)),n.onerror&&n.onerror(b)},0),r=()=>{if(g("close"),c++,g("retries count:",c),c>u.maxRetries){p("EHOSTDOWN","Too many failed connection attempts");return}o?o=Xe(u,o):o=ye(u),g("reconnectDelay:",o),i&&setTimeout(d,o)},d=()=>{g("connect");let m=n;n=new u.constructor(l,t),a=setTimeout(()=>{g("timeout"),n.close(),p("ETIMEDOUT","Connection timeout")},u.connectionTimeout),g("bypass properties");for(let h in n)["addEventListener","removeEventListener","close","send"].indexOf(h)<0&&$e(n,this,h);n.addEventListener("open",()=>{clearTimeout(a),g("open"),o=ye(u),g("reconnectDelay:",o),c=0}),n.addEventListener("close",r),tt(n,m,s)};g("init"),d(),this.close=(m=1e3,h="",{keepClosed:b=!1,fastClose:U=!0,delay:S=0}={})=>{if(S&&(o=S),i=!b,n.close(m,h),U){let D={code:m,reason:h,wasClean:!0};r(),Array.isArray(s.close)&&s.close.forEach(([k,y])=>{k(D),n.removeEventListener("close",k,y)}),n.onclose&&(n.onclose(D),n.onclose=null)}},this.send=m=>{n.send(m)},this.addEventListener=(m,h,b)=>{Array.isArray(s[m])?s[m].some(([U])=>U===h)||s[m].push([h,b]):s[m]=[[h,b]],n.addEventListener(m,h,b)},this.removeEventListener=(m,h,b)=>{Array.isArray(s[m])&&(s[m]=s[m].filter(([U])=>U!==h)),n.removeEventListener(m,h,b)}};be.exports=he});var se=(n=>(n.PRODUCTION="PRODUCTION",n.DEVELOPMENT="DEVELOPMENT",n.TEST="TEST",n))(se||{}),B=(e=>(e.CLIENT="CLIENT",e.SERVER="SERVER",e))(B||{}),q=(r=>(r.IMAGE_INFERENCE="imageInference",r.IMAGE_UPLOAD="imageUpload",r.IMAGE_UPSCALE="imageUpscale",r.IMAGE_BACKGROUND_REMOVAL="imageBackgroundRemoval",r.PHOTO_MAKER="photoMaker",r.IMAGE_CAPTION="imageCaption",r.IMAGE_CONTROL_NET_PRE_PROCESS="imageControlNetPreProcess",r.IMAGE_MASKING="imageMasking",r.PROMPT_ENHANCE="promptEnhance",r.AUTHENTICATION="authentication",r.MODEL_UPLOAD="modelUpload",r.MODEL_SEARCH="modelSearch",r))(q||{}),ae=(n=>(n.BALANCED="balanced",n.PROMPT="prompt",n.CONTROL_NET="controlnet",n))(ae||{}),oe=(r=>(r.canny="canny",r.depth="depth",r.mlsd="mlsd",r.normalbae="normalbae",r.openpose="openpose",r.tile="tile",r.seg="seg",r.lineart="lineart",r.lineart_anime="lineart_anime",r.shuffle="shuffle",r.scribble="scribble",r.softedge="softedge",r))(oe||{}),ie=(I=>(I.canny="canny",I.depth_leres="depth_leres",I.depth_midas="depth_midas",I.depth_zoe="depth_zoe",I.inpaint_global_harmonious="inpaint_global_harmonious",I.lineart_anime="lineart_anime",I.lineart_coarse="lineart_coarse",I.lineart_realistic="lineart_realistic",I.lineart_standard="lineart_standard",I.mlsd="mlsd",I.normal_bae="normal_bae",I.scribble_hed="scribble_hed",I.scribble_pidinet="scribble_pidinet",I.seg_ofade20k="seg_ofade20k",I.seg_ofcoco="seg_ofcoco",I.seg_ufade20k="seg_ufade20k",I.shuffle="shuffle",I.softedge_hed="softedge_hed",I.softedge_hedsafe="softedge_hedsafe",I.softedge_pidinet="softedge_pidinet",I.softedge_pidisafe="softedge_pidisafe",I.tile_gaussian="tile_gaussian",I.openpose="openpose",I.openpose_face="openpose_face",I.openpose_faceonly="openpose_faceonly",I.openpose_full="openpose_full",I.openpose_hand="openpose_hand",I))(ie||{}),Pe=(o=>(o.openpose="openpose",o.openpose_face="openpose_face",o.openpose_faceonly="openpose_faceonly",o.openpose_full="openpose_full",o.openpose_hand="openpose_hand",o))(Pe||{}),Ge=(e=>(e.safetensors="safetensors",e.pickletensor="pickletensor",e))(Ge||{}),Be=(d=>(d.flux1d="flux1d",d.flux1s="flux1s",d.pony="pony",d.sdhyper="sdhyper",d.sd1x="sd1x",d.sd1xlcm="sd1xlcm",d.sd3="sd3",d.sdxl="sdxl",d.sdxllcm="sdxllcm",d.sdxldistilled="sdxldistilled",d.sdxlhyper="sdxlhyper",d.sdxllightning="sdxllightning",d.sdxlturbo="sdxlturbo",d))(Be||{}),qe=(n=>(n.base="base",n.inpainting="inpainting",n.pix2pix="pix2pix",n))(qe||{}),He=(y=>(y.canny="canny",y.depth="depth",y.qrcode="qrcode",y.hed="hed",y.scrible="scrible",y.openpose="openpose",y.seg="segmentation",y.openmlsd="openmlsd",y.softedge="softedge",y.normal="normal bae",y.shuffle="shuffle",y.pix2pix="pix2pix",y.inpaint="inpaint",y.lineart="line art",y.sketch="sketch",y.inpaintdepth="inpaint depth",y.tile="tile",y.outfit="outfit",y.blur="blur",y.gray="gray",y.lowquality="low quality",y))(He||{}),Ve=(p=>(p.NoStyle="No style",p.Cinematic="Cinematic",p.DisneyCharacter="Disney Character",p.DigitalArt="Digital Art",p.Photographic="Photographic",p.FantasyArt="Fantasy art",p.Neonpunk="Neonpunk",p.Enhance="Enhance",p.ComicBook="Comic book",p.Lowpoly="Lowpoly",p.LineArt="Line art",p))(Ve||{});import{v4 as je,validate as Qe}from"uuid";var H=6e4,le=1e3,Je=100,V={PRODUCTION:"wss://ws-api.runware.ai/v1",TEST:"ws://localhost:8080"},ce=(l,t)=>{if(l==null)return;let e=l.indexOf(t);e!==-1&&l.splice(e,1)},x=(l,{debugKey:t="debugKey",timeoutDuration:e=H,shouldThrowError:n=!0})=>(e=e<le?le:e,new Promise((a,o)=>{let c=setTimeout(()=>{i&&(clearInterval(i),n&&o(`Response could not be received from server for ${t}`)),clearTimeout(c)},e),i=setInterval(async()=>{l({resolve:a,reject:o,intervalId:i})&&(clearInterval(i),clearTimeout(c))},Je)})),ue=l=>new Promise(t=>{let e=new FileReader;e.readAsDataURL(l),e.onload=function(){t(e.result)}}),T=()=>je(),ge=l=>Qe(l);var pe=({key:l,data:t,useZero:e=!0,shouldReturnString:n=!1})=>l.split(/\.|\[/).map(c=>c.replace(/\]$/,"")).reduce((c,i)=>{let s=e?0:void 0,u=c?.[i];if(!u)return s;if(Array.isArray(u)&&/^\d+$/.test(i)){let g=parseInt(i,10);return g>=0&&g<u.length?c[i]=u[g]:c[i]??s}else return c[i]??s},t||{})??{},de=(l,t=1e3)=>new Promise(e=>setTimeout(e,l*t));var me=(l,t)=>l.filter(e=>e.key!==t.key);var f=({key:l,value:t})=>t||t===0||t===!1?{[l]:t}:{},Ye=(l,t)=>Math.floor(Math.random()*(t-l+1))+l,j=()=>Ye(1,Number.MAX_SAFE_INTEGER);var R=async(l,t={})=>{let{delayInSeconds:e=1,callback:n}=t,a=t.maxRetries??1;for(;a;)try{return await l()}catch(o){if(n?.(),a--,a>0)await de(e),await R(l,{...t,maxRetries:a});else throw o}};var w=class{constructor({apiKey:t,url:e=V.PRODUCTION,shouldReconnect:n=!0,globalMaxRetries:a=2,timeoutDuration:o=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=t=>{this._ws.send(JSON.stringify([t]))};this.uploadImage=async t=>{try{return await R(async()=>{let e=T();if(typeof t=="string"&&ge(t))return{imageURL:t,imageUUID:t,taskUUID:e,taskType:"imageUpload"};let n=typeof t=="string"?t:await ue(t);return{imageURL:n,imageUUID:n,taskUUID:e,taskType:"imageUpload"}})}catch(e){throw e}};this.controlNetPreProcess=async({inputImage:t,preProcessorType:e,height:n,width:a,outputType:o,outputFormat:c,highThresholdCanny:i,lowThresholdCanny:s,includeHandsAndFaceOpenPose:u,includeCost:g,outputQuality:p,customTaskUUID:r,retry:d})=>{let m=d||this._globalMaxRetries,h;try{return await R(async()=>{await this.ensureConnection();let b=await this.uploadImage(t);if(!b?.imageUUID)return null;let U=r||T();this.send({inputImage:b.imageUUID,taskType:"imageControlNetPreProcess",taskUUID:U,preProcessorType:e,...f({key:"height",value:n}),...f({key:"width",value:a}),...f({key:"outputType",value:o}),...f({key:"outputFormat",value:c}),...f({key:"includeCost",value:g}),...f({key:"highThresholdCanny",value:i}),...f({key:"lowThresholdCanny",value:s}),...f({key:"includeHandsAndFaceOpenPose",value:u}),...p?{outputQuality:p}:{}}),h=this.globalListener({taskUUID:U});let S=await x(({resolve:D,reject:k})=>{let y=this.getSingleMessage({taskUUID:U});if(y){if(y?.error)return k(y),!0;if(y)return D(y),!0}},{debugKey:"unprocessed-image",timeoutDuration:this._timeoutDuration});return h.destroy(),S},{maxRetries:m,callback:()=>{h?.destroy()}})}catch(b){throw b}};this.requestImageToText=async({inputImage:t,includeCost:e,customTaskUUID:n,retry:a})=>{let o=a||this._globalMaxRetries,c;try{return await R(async()=>{await this.ensureConnection();let i=t?await this.uploadImage(t):null,s=n||T();this.send({taskUUID:s,taskType:"imageCaption",inputImage:i?.imageUUID,...f({key:"includeCost",value:e})}),c=this.globalListener({taskUUID:s});let u=await x(({resolve:g,reject:p})=>{let r=this.getSingleMessage({taskUUID:s});if(r){if(r?.error)return p(r),!0;if(r)return delete this._globalMessages[s],g(r),!0}},{debugKey:"remove-image-background",timeoutDuration:this._timeoutDuration});return c.destroy(),u},{maxRetries:o,callback:()=>{c?.destroy()}})}catch(i){throw i}};this.removeImageBackground=async t=>this.baseSingleRequest({payload:{...t,taskType:"imageBackgroundRemoval"},debugKey:"remove-image-background"});this.upscaleGan=async({inputImage:t,upscaleFactor:e,outputType:n,outputFormat:a,includeCost:o,outputQuality:c,customTaskUUID:i,retry:s})=>{let u=s||this._globalMaxRetries,g;try{return await R(async()=>{await this.ensureConnection();let p;p=await this.uploadImage(t);let r=i||T();this.send({taskUUID:r,inputImage:p?.imageUUID,taskType:"imageUpscale",upscaleFactor:e,...f({key:"includeCost",value:o}),...n?{outputType:n}:{},...c?{outputQuality:c}:{},...a?{outputFormat:a}:{}}),g=this.globalListener({taskUUID:r});let d=await x(({resolve:m,reject:h})=>{let b=this.getSingleMessage({taskUUID:r});if(b){if(b?.error)return h(b),!0;if(b)return delete this._globalMessages[r],m(b),!0}},{debugKey:"upscale-gan",timeoutDuration:this._timeoutDuration});return g.destroy(),d},{maxRetries:u,callback:()=>{g?.destroy()}})}catch(p){throw p}};this.enhancePrompt=async({prompt:t,promptMaxLength:e=380,promptVersions:n=1,includeCost:a,customTaskUUID:o,retry:c})=>{let i=c||this._globalMaxRetries,s;try{return await R(async()=>{await this.ensureConnection();let u=o||T();this.send({prompt:t,taskUUID:u,promptMaxLength:e,promptVersions:n,...f({key:"includeCost",value:a}),taskType:"promptEnhance"}),s=this.globalListener({taskUUID:u});let g=await x(({resolve:p,reject:r})=>{let d=this._globalMessages[u];if(d?.error)return r(d),!0;if(d?.length>=n)return delete this._globalMessages[u],p(d),!0},{debugKey:"enhance-prompt",timeoutDuration:this._timeoutDuration});return s.destroy(),g},{maxRetries:i,callback:()=>{s?.destroy()}})}catch(u){throw u}};this.modelUpload=async t=>{let{onUploadStream:e,retry:n,customTaskUUID:a,...o}=t,c=n||this._globalMaxRetries,i;try{return await R(async()=>{await this.ensureConnection();let s=a||T();this.send({...o,taskUUID:s,taskType:"modelUpload"});let u,g;return i=this.listenToUpload({taskUUID:s,onUploadStream:(r,d)=>{e?.(r,d),r?.status==="ready"?u=r:d&&(g=d)}}),await x(({resolve:r,reject:d})=>{if(u)return r(u),!0;if(g)return d(g),!1},{shouldThrowError:!1,timeoutDuration:60*60*1e3})},{maxRetries:c,callback:()=>{i?.destroy()}})}catch(s){throw s}};this.photoMaker=async(t,e)=>{let{onPartialImages:n,retry:a,customTaskUUID:o,numberResults:c,...i}=t,s=a||this._globalMaxRetries,u,g=[],p=0;try{return await R(async()=>{await this.ensureConnection(),p++;let r=this._globalImages.filter(b=>g.includes(b.taskUUID)),d=o||T();g.push(d);let m=c-r.length;this.send({...i,...i.seed?{seed:i.seed}:{seed:j()},...e??{},numberResults:m,taskUUID:d,taskType:"photoMaker"}),u=this.listenToImages({onPartialImages:n,taskUUID:d,groupKey:"REQUEST_IMAGES",positivePrompt:i.positivePrompt});let h=await this.getSimilarImages({taskUUID:g,numberResults:c,lis:u});return u.destroy(),h},{maxRetries:s,callback:()=>{u?.destroy()}})}catch(r){if(r.taskUUID)throw r;if(p>=s)return this.handleIncompleteImages({taskUUIDs:g,error:r})}};this.modelSearch=async t=>this.baseSingleRequest({payload:{...t,taskType:"modelSearch"},debugKey:"model-search"});this.imageMasking=async t=>this.baseSingleRequest({payload:{...t,taskType:"imageMasking"},debugKey:"image-masking"});this.imageUpload=async t=>this.baseSingleRequest({payload:{...t,taskType:"imageUpload"},debugKey:"image-upload"});this.baseSingleRequest=async({payload:t,debugKey:e})=>{let{retry:n,customTaskUUID:a,...o}=t,c=n||this._globalMaxRetries,i;try{return await R(async()=>{await this.ensureConnection();let s=a||T();this.send({...o,taskUUID:s}),i=this.globalListener({taskUUID:s});let u=await x(({resolve:g,reject:p})=>{let r=this.getSingleMessage({taskUUID:s});if(r){if(r?.error)return p(r),!0;if(r)return delete this._globalMessages[s],g(r),!0}},{debugKey:e,timeoutDuration:this._timeoutDuration});return i.destroy(),u},{maxRetries:c,callback:()=>{i?.destroy()}})}catch(s){throw s}};this.getSingleMessage=({taskUUID:t})=>{let e=this._globalMessages[t]?.[0],n=this._globalMessages[t];return!e&&!n?null:n?.error?n:e};this.disconnect=async()=>{this._shouldReconnect=!1,this._ws?.terminate?.(),this._ws?.close?.()};this.connected=()=>this.isWebsocketReadyState()&&!!this._connectionSessionUUID;this._apiKey=t,this._url=e,this._sdkType="CLIENT",this._shouldReconnect=n,this._globalMaxRetries=a,this._timeoutDuration=o}static async initialize(t){try{let e=new this(t);return await e.ensureConnection(),e}catch(e){throw e}}addListener({lis:t,groupKey:e,taskUUID:n}){let a=i=>{let s=Array.isArray(i?.data)?i.data:[i.data],u=i?.[0]?.errors?i?.[0]?.errors:Array.isArray(i?.errors)?i.errors:[i.errors],g=s.filter(r=>(r?.taskUUID||r?.taskType)===n);if(u.filter(r=>(r?.taskUUID||r?.taskType)===n).length){t({error:{...u[0]??{}}});return}if(g.length){t({[n]:s});return}},o={key:n||T(),listener:a,groupKey:e};return this._listeners.push(o),{destroy:()=>{this._listeners=me(this._listeners,o)}}}connect(){this._ws.onopen=t=>{this._connectionSessionUUID?this.send({taskType:"authentication",apiKey:this._apiKey,connectionSessionUUID:this._connectionSessionUUID}):this.send({apiKey:this._apiKey,taskType:"authentication"}),this.addListener({taskUUID:"authentication",lis:e=>{if(e?.error){this._connectionError=e;return}this._connectionSessionUUID=e?.authentication?.[0]?.connectionSessionUUID,this._connectionError=void 0}})},this._ws.onmessage=t=>{let e=JSON.parse(t.data);for(let n of this._listeners)if(n?.listener?.(e))return},this._ws.onclose=t=>{this.isInvalidAPIKey()}}destroy(t){ce(this._listeners,t)}listenToImages({onPartialImages:t,taskUUID:e,groupKey:n,positivePrompt:a,negativePrompt:o}){return this.addListener({taskUUID:e,lis:c=>{let i=c?.[e]?.filter(s=>s.taskUUID===e);c.error?(t?.(i,c?.error&&c),this._globalError=c):(i=i.map(s=>({...s,positivePrompt:a,negativePrompt:o})),t?.(i,c?.error&&c),this._sdkType==="CLIENT"?this._globalImages=[...this._globalImages,...(c?.[e]??[]).map(s=>({...s,positivePrompt:a,negativePrompt:o}))]:this._globalImages=[...this._globalImages,...i])},groupKey:n})}listenToUpload({onUploadStream:t,taskUUID:e}){return this.addListener({taskUUID:e,lis:n=>{let a=n?.error,o=n?.[e]?.[0],c=o?.taskUUID===e?o:null;(c||a)&&t?.(c||void 0,a)}})}globalListener({taskUUID:t}){return this.addListener({taskUUID:t,lis:e=>{if(e.error){this._globalMessages[t]=e;return}let n=pe({key:t,data:e,useZero:!1});Array.isArray(n)?n.forEach(a=>{this._globalMessages[a.taskUUID]=[...this._globalMessages[a.taskUUID]??[],a]}):this._globalMessages[n.taskUUID]=n}})}async requestImages({outputType:t,outputFormat:e,uploadEndpoint:n,checkNSFW:a,positivePrompt:o,negativePrompt:c,seedImage:i,maskImage:s,strength:u,height:g,width:p,model:r,steps:d,scheduler:m,seed:h,CFGScale:b,clipSkip:U,usePromptWeighting:S,promptWeighting:D,numberResults:k=1,onPartialImages:y,includeCost:_e,customTaskUUID:Re,retry:ke,refiner:Q,maskMargin:xe,outputQuality:I,controlNet:L,lora:J,embeddings:Y,ipAdapters:z,outpaint:Z,acceleratorOptions:$,advancedFeatures:X},De){let A,ee,E=[],te=0,ne=ke||this._globalMaxRetries;try{await this.ensureConnection();let v=null,K=null,W=[];if(i){let _=await this.uploadImage(i);if(!_)return[];v=_.imageUUID}if(s){let _=await this.uploadImage(s);if(!_)return[];K=_.imageUUID}if(L?.length)for(let _=0;_<L.length;_++){let C=L[_],{endStep:F,startStep:P,weight:G,guideImage:O,controlMode:Se,startStepPercentage:ve,endStepPercentage:we,model:Ae}=C,Ce=O?await this.uploadImage(O):null;W.push({guideImage:Ce?.imageUUID,model:Ae,endStep:F,startStep:P,weight:G,...f({key:"startStepPercentage",value:ve}),...f({key:"endStepPercentage",value:we}),controlMode:Se||"controlnet"})}return ee={taskType:"imageInference",model:r,positivePrompt:o,...c?{negativePrompt:c}:{},...g?{height:g}:{},...p?{width:p}:{},numberResults:k,...t?{outputType:t}:{},...e?{outputFormat:e}:{},...n?{uploadEndpoint:n}:{},...f({key:"checkNSFW",value:a}),...f({key:"strength",value:u}),...f({key:"CFGScale",value:b}),...f({key:"clipSkip",value:U}),...f({key:"maskMargin",value:xe}),...f({key:"usePromptWeighting",value:S}),...f({key:"steps",value:d}),...D?{promptWeighting:D}:{},...h?{seed:h}:{seed:j()},...m?{scheduler:m}:{},...Q?{refiner:Q}:{},...Z?{outpaint:Z}:{},...f({key:"includeCost",value:_e}),...v?{seedImage:v}:{},...K?{maskImage:K}:{},...I?{outputQuality:I}:{},...W.length?{controlNet:W}:{},...J?.length?{lora:J}:{},...Y?.length?{embeddings:Y}:{},...z?.length?{ipAdapters:z}:{},...$?{acceleratorOptions:$}:{},...X?{advancedFeatures:X}:{},...De??{}},await R(async()=>{te++,A?.destroy();let _=this._globalImages.filter(O=>E.includes(O.taskUUID)),C=Re||T();E.push(C);let F=k-_.length,P={...ee,taskUUID:C,numberResults:F};this.send(P),A=this.listenToImages({onPartialImages:y,taskUUID:C,groupKey:"REQUEST_IMAGES",positivePrompt:o,negativePrompt:c});let G=await this.getSimilarImages({taskUUID:E,numberResults:k,lis:A});return A.destroy(),G},{maxRetries:ne,callback:()=>{A?.destroy()}})}catch(v){if(te>=ne)return this.handleIncompleteImages({taskUUIDs:E,error:v});throw v}}async ensureConnection(){if(this.connected()||this._url===V.TEST)return;let e=2e3,n=200;try{if(this.isInvalidAPIKey())throw this._connectionError;return new Promise((a,o)=>{let c=0,i=30,s=T(),u,g,p=()=>{this.ensureConnectionUUID=null,clearInterval(u),clearInterval(g)};this._sdkType==="SERVER"&&(u=setInterval(async()=>{try{let r=this.connected(),d=!1;(!this.ensureConnectionUUID||s===this.ensureConnectionUUID)&&(this.ensureConnectionUUID||(this.ensureConnectionUUID=s),d=!0);let m=c%10===0&&d;r?(p(),a(!0)):c>=i?(p(),o(new Error("Retry timed out"))):(m&&this.connect(),c++)}catch(r){p(),o(r)}},e)),g=setInterval(async()=>{if(this.connected()){p(),a(!0);return}if(this.isInvalidAPIKey()){p(),o(this._connectionError);return}},n)})}catch{throw this.ensureConnectionUUID=null,this._connectionError=void 0,this._connectionError??"Could not connect to server. Ensure your API key is correct"}}async getSimilarImages({taskUUID:t,numberResults:e,shouldThrowError:n,lis:a}){return await x(({resolve:o,reject:c,intervalId:i})=>{let s=Array.isArray(t)?t:[t],u=this._globalImages.filter(g=>s.includes(g.taskUUID));if(this._globalError){let g=this._globalError;return this._globalError=void 0,clearInterval(i),c?.(g),!0}else if(u.length>=e)return clearInterval(i),this._globalImages=this._globalImages.filter(g=>!s.includes(g.taskUUID)),o([...u].slice(0,e)),!0},{debugKey:"getting images",shouldThrowError:n,timeoutDuration:this._timeoutDuration})}handleIncompleteImages({taskUUIDs:t,error:e}){let n=this._globalImages.filter(a=>t.includes(a.taskUUID));if(n.length>1)return this._globalImages=this._globalImages.filter(a=>!t.includes(a.taskUUID)),n;throw e}};var Ue=Fe(fe(),1),N=class extends w{constructor(t){let{shouldReconnect:e,...n}=t;super(n),this._ws=new Ue.default(this._url),this.connect()}};import nt from"ws";var M=class extends w{constructor(e){super(e);this._instantiated=!1;this._listeners=[];this._reconnectingIntervalId=null;this.send=e=>{this._ws.send(JSON.stringify([e]))};this.resetConnection=()=>{this._ws&&(this._listeners.forEach(e=>{e?.destroy?.()}),this._ws.removeAllListeners(),this._ws.readyState===1&&(this._ws.terminate(),this._ws.close()),this._ws=null,this._listeners=[])};this._sdkType="SERVER",this.connect()}async connect(){this._url&&(this.resetConnection(),this._ws=new nt(this._url,{perMessageDeflate:!1}),this._ws.on("error",()=>{}),this._ws.on("close",()=>{this.handleClose()}),this._ws.on("open",()=>{this._reconnectingIntervalId&&clearInterval(this._reconnectingIntervalId),this._connectionSessionUUID&&this.isWebsocketReadyState()?this.send({taskType:"authentication",apiKey:this._apiKey,connectionSessionUUID:this._connectionSessionUUID}):this.isWebsocketReadyState()&&this.send({apiKey:this._apiKey,taskType:"authentication"}),this.addListener({taskUUID:"authentication",lis:e=>{if(e?.error){this._connectionError=e;return}this._connectionSessionUUID=e?.authentication?.[0]?.connectionSessionUUID,this._connectionError=void 0}})}),this._ws.on("message",(e,n)=>{let a=n?e:e?.toString();if(!a)return;let o=JSON.parse(a);this._listeners.forEach(c=>{c.listener(o)})}))}handleClose(){this.isInvalidAPIKey()||(this._reconnectingIntervalId&&clearInterval(this._reconnectingIntervalId),this._shouldReconnect&&setTimeout(()=>this.connect(),1e3))}heartBeat(){clearTimeout(this._pingTimeout),this._pingTimeout=setTimeout(()=>{this.isWebsocketReadyState()&&this.send({ping:!0})},5e3)}};var Te;typeof window>"u"?Te=M:Te=N;export{ae as EControlMode,Be as EModelArchitecture,He as EModelConditioning,Ge as EModelFormat,qe as EModelType,Pe as EOpenPosePreProcessor,Ve as EPhotoMakerEnum,ie as EPreProcessor,oe as EPreProcessorGroup,q as ETaskType,se as Environment,Te as Runware,N as RunwareClient,M as RunwareServer,B as SdkType};
|
|
1
|
+
var Le=Object.create;var ie=Object.defineProperty;var Ke=Object.getOwnPropertyDescriptor;var Pe=Object.getOwnPropertyNames;var We=Object.getPrototypeOf,Fe=Object.prototype.hasOwnProperty;var Ge=(o,t)=>()=>(t||o((t={exports:{}}).exports,t),t.exports);var Be=(o,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Pe(t))!Fe.call(o,r)&&r!==e&&ie(o,r,{get:()=>t[r],enumerable:!(n=Ke(t,r))||n.enumerable});return o};var qe=(o,t,e)=>(e=o!=null?Le(We(o)):{},Be(t||!o||!o.__esModule?ie(e,"default",{value:o,enumerable:!0}):e,o));var Re=Ge((Xt,_e)=>{"use strict";var Te=o=>o&&o.CLOSING===2,et=()=>typeof WebSocket<"u"&&Te(WebSocket),tt=()=>({constructor:et()?WebSocket:null,maxReconnectionDelay:1e4,minReconnectionDelay:1500,reconnectionDelayGrowFactor:1.3,connectionTimeout:4e3,maxRetries:1/0,debug:!1}),nt=(o,t,e)=>{Object.defineProperty(t,e,{get:()=>o[e],set:n=>{o[e]=n},enumerable:!0,configurable:!0})},be=o=>o.minReconnectionDelay+Math.random()*o.minReconnectionDelay,st=(o,t)=>{let e=t*o.reconnectionDelayGrowFactor;return e>o.maxReconnectionDelay?o.maxReconnectionDelay:e},rt=["onopen","onclose","onmessage","onerror"],at=(o,t,e)=>{Object.keys(e).forEach(n=>{e[n].forEach(([r,a])=>{o.addEventListener(n,r,a)})}),t&&rt.forEach(n=>{o[n]=t[n]})},Ue=function(o,t,e={}){let n,r,a=0,l=0,c=!0,i={};if(!(this instanceof Ue))throw new TypeError("Failed to construct 'ReconnectingWebSocket': Please use the 'new' operator");let g=tt();if(Object.keys(g).filter(p=>e.hasOwnProperty(p)).forEach(p=>g[p]=e[p]),!Te(g.constructor))throw new TypeError("Invalid WebSocket constructor. Set `options.constructor`");let d=g.debug?(...p)=>console.log("RWS:",...p):()=>{},u=(p,y)=>setTimeout(()=>{let I=new Error(y);I.code=p,Array.isArray(i.error)&&i.error.forEach(([b])=>b(I)),n.onerror&&n.onerror(I)},0),s=()=>{if(d("close"),l++,d("retries count:",l),l>g.maxRetries){u("EHOSTDOWN","Too many failed connection attempts");return}a?a=st(g,a):a=be(g),d("reconnectDelay:",a),c&&setTimeout(m,a)},m=()=>{d("connect");let p=n;n=new g.constructor(o,t),r=setTimeout(()=>{d("timeout"),n.close(),u("ETIMEDOUT","Connection timeout")},g.connectionTimeout),d("bypass properties");for(let y in n)["addEventListener","removeEventListener","close","send"].indexOf(y)<0&&nt(n,this,y);n.addEventListener("open",()=>{clearTimeout(r),d("open"),a=be(g),d("reconnectDelay:",a),l=0}),n.addEventListener("close",s),at(n,p,i)};d("init"),m(),this.close=(p=1e3,y="",{keepClosed:I=!1,fastClose:b=!0,delay:k=0}={})=>{if(k&&(a=k),c=!I,n.close(p,y),b){let _={code:p,reason:y,wasClean:!0};s(),Array.isArray(i.close)&&i.close.forEach(([U,f])=>{U(_),n.removeEventListener("close",U,f)}),n.onclose&&(n.onclose(_),n.onclose=null)}},this.send=p=>{n.send(p)},this.addEventListener=(p,y,I)=>{Array.isArray(i[p])?i[p].some(([b])=>b===y)||i[p].push([y,I]):i[p]=[[y,I]],n.addEventListener(p,y,I)},this.removeEventListener=(p,y,I)=>{Array.isArray(i[p])&&(i[p]=i[p].filter(([b])=>b!==y)),n.removeEventListener(p,y,I)}};_e.exports=Ue});var le=(n=>(n.PRODUCTION="PRODUCTION",n.DEVELOPMENT="DEVELOPMENT",n.TEST="TEST",n))(le||{}),j=(e=>(e.CLIENT="CLIENT",e.SERVER="SERVER",e))(j||{}),Q=(s=>(s.IMAGE_INFERENCE="imageInference",s.IMAGE_UPLOAD="imageUpload",s.IMAGE_UPSCALE="imageUpscale",s.IMAGE_BACKGROUND_REMOVAL="imageBackgroundRemoval",s.PHOTO_MAKER="photoMaker",s.IMAGE_CAPTION="imageCaption",s.IMAGE_CONTROL_NET_PRE_PROCESS="imageControlNetPreProcess",s.IMAGE_MASKING="imageMasking",s.PROMPT_ENHANCE="promptEnhance",s.AUTHENTICATION="authentication",s.MODEL_UPLOAD="modelUpload",s.MODEL_SEARCH="modelSearch",s))(Q||{}),ce=(n=>(n.BALANCED="balanced",n.PROMPT="prompt",n.CONTROL_NET="controlnet",n))(ce||{}),ue=(s=>(s.canny="canny",s.depth="depth",s.mlsd="mlsd",s.normalbae="normalbae",s.openpose="openpose",s.tile="tile",s.seg="seg",s.lineart="lineart",s.lineart_anime="lineart_anime",s.shuffle="shuffle",s.scribble="scribble",s.softedge="softedge",s))(ue||{}),de=(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))(de||{}),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||{}),Ve=(e=>(e.safetensors="safetensors",e.pickletensor="pickletensor",e))(Ve||{}),je=(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))(je||{}),Qe=(n=>(n.base="base",n.inpainting="inpainting",n.pix2pix="pix2pix",n))(Qe||{}),Je=(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))(Je||{}),Ye=(u=>(u.NoStyle="No style",u.Cinematic="Cinematic",u.DisneyCharacter="Disney Character",u.DigitalArt="Digital Art",u.Photographic="Photographic",u.FantasyArt="Fantasy art",u.Neonpunk="Neonpunk",u.Enhance="Enhance",u.ComicBook="Comic book",u.Lowpoly="Lowpoly",u.LineArt="Line art",u))(Ye||{});import{v4 as ze,validate as Ze}from"uuid";var J=6e4,pe=1e3,$e=100,Y={PRODUCTION:"wss://ws-api.runware.ai/v1",TEST:"ws://localhost:8080"},ge=(o,t)=>{if(o==null)return;let e=o.indexOf(t);e!==-1&&o.splice(e,1)},v=(o,{debugKey:t="debugKey",timeoutDuration:e=J,shouldThrowError:n=!0})=>(e=e<pe?pe:e,new Promise((r,a)=>{let l=setTimeout(()=>{c&&(clearInterval(c),n&&a(`Response could not be received from server for ${t}`)),clearTimeout(l)},e),c=setInterval(async()=>{o({resolve:r,reject:a,intervalId:c})&&(clearInterval(c),clearTimeout(l))},$e)})),me=o=>new Promise(t=>{let e=new FileReader;e.readAsDataURL(o),e.onload=function(){t(e.result)}}),R=()=>ze(),ye=o=>Ze(o);var Ie=({key:o,data:t,useZero:e=!0,shouldReturnString:n=!1})=>o.split(/\.|\[/).map(l=>l.replace(/\]$/,"")).reduce((l,c)=>{let i=e?0:void 0,g=l?.[c];if(!g)return i;if(Array.isArray(g)&&/^\d+$/.test(c)){let d=parseInt(c,10);return d>=0&&d<g.length?l[c]=g[d]:l[c]??i}else return l[c]??i},t||{})??{},he=(o,t=1e3)=>new Promise(e=>setTimeout(e,o*t));var fe=(o,t)=>o.filter(e=>e.key!==t.key);var T=({key:o,value:t})=>t||t===0||t===!1?{[o]:t}:{},Xe=(o,t)=>Math.floor(Math.random()*(t-o+1))+o,z=()=>Xe(1,Number.MAX_SAFE_INTEGER);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?.(),r--,r>0)await he(e),await x(o,{...t,maxRetries:r});else throw a}};var A=class{constructor({apiKey:t,url:e=Y.PRODUCTION,shouldReconnect:n=!0,globalMaxRetries:r=2,timeoutDuration:a=J}){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"&&ye(t))return{imageURL:t,imageUUID:t,taskUUID:e,taskType:"imageUpload"};let n=typeof t=="string"?t:await me(t);return{imageURL:n,imageUUID:n,taskUUID:e,taskType:"imageUpload"}})}catch(e){throw e}};this.controlNetPreProcess=async({inputImage:t,preProcessorType:e,height:n,width:r,outputType:a,outputFormat:l,highThresholdCanny:c,lowThresholdCanny:i,includeHandsAndFaceOpenPose:g,includeCost:d,outputQuality:u,customTaskUUID:s,retry:m,includeGenerationTime:p,includePayload:y})=>{let I=m||this._globalMaxRetries,b,k=Date.now();try{return await x(async()=>{await this.ensureConnection();let _=await this.uploadImage(t);if(!_?.imageUUID)return null;let U=s||R(),f={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:l}),...T({key:"includeCost",value:d}),...T({key:"highThresholdCanny",value:c}),...T({key:"lowThresholdCanny",value:i}),...T({key:"includeHandsAndFaceOpenPose",value:g}),...u?{outputQuality:u}:{}};this.send({...f}),b=this.globalListener({taskUUID:U});let O=await v(({resolve:W,reject:F})=>{let S=this.getSingleMessage({taskUUID:U});if(S){if(S?.error)return F(S),!0;if(S)return W(S),!0}},{debugKey:"unprocessed-image",timeoutDuration:this._timeoutDuration});return b.destroy(),this.insertAdditionalResponse({response:O,payload:y?f:void 0,startTime:p?k:void 0}),O},{maxRetries:I,callback:()=>{b?.destroy()}})}catch(_){throw _}};this.requestImageToText=async({inputImage:t,includeCost:e,customTaskUUID:n,retry:r,includePayload:a,includeGenerationTime:l})=>{let c=r||this._globalMaxRetries,i,g=Date.now();try{return await x(async()=>{await this.ensureConnection();let d=t?await this.uploadImage(t):null,u=n||R(),s={taskUUID:u,taskType:"imageCaption",inputImage:d?.imageUUID,...T({key:"includeCost",value:e})};this.send(s),i=this.globalListener({taskUUID:u});let m=await v(({resolve:p,reject:y})=>{let I=this.getSingleMessage({taskUUID:u});if(I){if(I?.error)return y(I),!0;if(I)return delete this._globalMessages[u],p(I),!0}},{debugKey:"remove-image-background",timeoutDuration:this._timeoutDuration});return i.destroy(),this.insertAdditionalResponse({response:m,payload:a?s:void 0,startTime:l?g:void 0}),m},{maxRetries:c,callback:()=>{i?.destroy()}})}catch(d){throw d}};this.removeImageBackground=async t=>this.baseSingleRequest({payload:{...t,taskType:"imageBackgroundRemoval"},debugKey:"remove-image-background"});this.upscaleGan=async({inputImage:t,upscaleFactor:e,outputType:n,outputFormat:r,includeCost:a,outputQuality:l,customTaskUUID:c,retry:i,includeGenerationTime:g,includePayload:d})=>{let u=i||this._globalMaxRetries,s,m=Date.now();try{return await x(async()=>{await this.ensureConnection();let p;p=await this.uploadImage(t);let y=c||R(),I={taskUUID:y,inputImage:p?.imageUUID,taskType:"imageUpscale",upscaleFactor:e,...T({key:"includeCost",value:a}),...n?{outputType:n}:{},...l?{outputQuality:l}:{},...r?{outputFormat:r}:{}};this.send(I),s=this.globalListener({taskUUID:y});let b=await v(({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 s.destroy(),this.insertAdditionalResponse({response:b,payload:d?I:void 0,startTime:g?m:void 0}),b},{maxRetries:u,callback:()=>{s?.destroy()}})}catch(p){throw p}};this.enhancePrompt=async({prompt:t,promptMaxLength:e=380,promptVersions:n=1,includeCost:r,customTaskUUID:a,retry:l,includeGenerationTime:c,includePayload:i})=>{let g=l||this._globalMaxRetries,d,u=Date.now();try{return await x(async()=>{await this.ensureConnection();let s=a||R(),m={prompt:t,taskUUID:s,promptMaxLength:e,promptVersions:n,...T({key:"includeCost",value:r}),taskType:"promptEnhance"};this.send(m),d=this.globalListener({taskUUID:s});let p=await v(({resolve:y,reject:I})=>{let b=this._globalMessages[s];if(b?.error)return I(b),!0;if(b?.length>=n)return delete this._globalMessages[s],y(b),!0},{debugKey:"enhance-prompt",timeoutDuration:this._timeoutDuration});return d.destroy(),this.insertAdditionalResponse({response:p,payload:i?m:void 0,startTime:c?u:void 0}),p},{maxRetries:g,callback:()=>{d?.destroy()}})}catch(s){throw s}};this.modelUpload=async t=>{let{onUploadStream:e,retry:n,customTaskUUID:r,...a}=t,l=n||this._globalMaxRetries,c;try{return await x(async()=>{await this.ensureConnection();let i=r||R();this.send({...a,taskUUID:i,taskType:"modelUpload"});let g,d;return c=this.listenToUpload({taskUUID:i,onUploadStream:(s,m)=>{e?.(s,m),s?.status==="ready"?g=s:m&&(d=m)}}),await v(({resolve:s,reject:m})=>{if(g)return s(g),!0;if(d)return m(d),!1},{shouldThrowError:!1,timeoutDuration:60*60*1e3})},{maxRetries:l,callback:()=>{c?.destroy()}})}catch(i){throw i}};this.photoMaker=async(t,e)=>{let{onPartialImages:n,retry:r,customTaskUUID:a,numberResults:l,includeGenerationTime:c,includePayload:i,...g}=t,d=r||this._globalMaxRetries,u,s=[],m=0,p=Date.now();try{return await x(async()=>{await this.ensureConnection(),m++;let y=this._globalImages.filter(U=>s.includes(U.taskUUID)),I=a||R();s.push(I);let b=l-y.length,k={...g,...g.seed?{seed:g.seed}:{seed:z()},...e??{},taskUUID:I,taskType:"photoMaker",numberResults:l};this.send({...k,numberResults:b}),u=this.listenToImages({onPartialImages:n,taskUUID:I,groupKey:"REQUEST_IMAGES",requestPayload:i?k:void 0,startTime:c?p:void 0});let _=await this.getSimilarImages({taskUUID:s,numberResults:l,lis:u});return u.destroy(),_},{maxRetries:d,callback:()=>{u?.destroy()}})}catch(y){if(y.taskUUID)throw y;if(m>=d)return this.handleIncompleteImages({taskUUIDs:s,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})=>{let{retry:n,customTaskUUID:r,includePayload:a,includeGenerationTime:l,...c}=t,i=n||this._globalMaxRetries,g,d=Date.now();try{return await x(async()=>{await this.ensureConnection();let u=r||R(),s={...c,taskUUID:u};this.send(s),g=this.globalListener({taskUUID:u});let m=await v(({resolve:p,reject:y})=>{let I=this.getSingleMessage({taskUUID:u});if(I){if(I?.error)return y(I),!0;if(I)return delete this._globalMessages[u],p(I),!0}},{debugKey:e,timeoutDuration:this._timeoutDuration});return this.insertAdditionalResponse({response:m,payload:a?s:void 0,startTime:l?d:void 0}),g.destroy(),m},{maxRetries:i,callback:()=>{g?.destroy()}})}catch(u){throw u}};this.getSingleMessage=({taskUUID:t})=>{let e=this._globalMessages[t]?.[0],n=this._globalMessages[t];return!e&&!n?null:n?.error?n:e};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 i=Array.isArray(c?.data)?c.data:[c.data],g=c?.[0]?.errors?c?.[0]?.errors:Array.isArray(c?.errors)?c.errors:[c.errors],d=i.filter(s=>(s?.taskUUID||s?.taskType)===n);if(g.filter(s=>(s?.taskUUID||s?.taskType)===n).length){t({error:{...g[0]??{}}});return}if(d.length){t({[n]:i});return}},a={key:n||R(),listener:r,groupKey:e};return this._listeners.push(a),{destroy:()=>{this._listeners=fe(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){ge(this._listeners,t)}listenToImages({onPartialImages:t,taskUUID:e,groupKey:n,requestPayload:r,startTime:a}){return this.addListener({taskUUID:e,lis:l=>{let c=l?.[e]?.filter(i=>i.taskUUID===e);l.error?(t?.(c,l?.error&&l),this._globalError=l):(c=c.map(i=>(this.insertAdditionalResponse({response:i,payload:r||void 0,startTime:a||void 0}),{...i})),t?.(c,l?.error&&l),this._sdkType==="CLIENT"?this._globalImages=[...this._globalImages,...(l?.[e]??[]).map(i=>(this.insertAdditionalResponse({response:i,payload:r||void 0,startTime:a||void 0}),{...i}))]: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],l=a?.taskUUID===e?a:null;(l||r)&&t?.(l||void 0,r)}})}globalListener({taskUUID:t}){return this.addListener({taskUUID:t,lis:e=>{if(e.error){this._globalMessages[t]=e;return}let n=Ie({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:l,seedImage:c,maskImage:i,strength:g,height:d,width:u,model:s,steps:m,scheduler:p,seed:y,CFGScale:I,clipSkip:b,usePromptWeighting:k,promptWeighting:_,numberResults:U=1,onPartialImages:f,includeCost:O,customTaskUUID:W,retry:F,refiner:S,maskMargin:xe,outputQuality:h,controlNet:G,lora:Z,embeddings:$,ipAdapters:X,outpaint:ee,acceleratorOptions:te,advancedFeatures:ne,referenceImages:se,includeGenerationTime:Se,includePayload:ve},we){let C,re,N=[],ae=0,oe=F||this._globalMaxRetries;try{await this.ensureConnection();let w=null,B=null,q=[];if(c){let D=await this.uploadImage(c);if(!D)return[];w=D.imageUUID}if(i){let D=await this.uploadImage(i);if(!D)return[];B=D.imageUUID}if(G?.length)for(let D=0;D<G.length;D++){let E=G[D],{endStep:H,startStep:M,weight:V,guideImage:L,controlMode:Ce,startStepPercentage:Ee,endStepPercentage:Oe,model:Ne}=E,Me=L?await this.uploadImage(L):null;q.push({guideImage:Me?.imageUUID,model:Ne,endStep:H,startStep:M,weight:V,...T({key:"startStepPercentage",value:Ee}),...T({key:"endStepPercentage",value:Oe}),controlMode:Ce||"controlnet"})}re={taskType:"imageInference",model:s,positivePrompt:a,...l?{negativePrompt:l}:{},...d?{height:d}:{},...u?{width:u}:{},numberResults:U,...t?{outputType:t}:{},...e?{outputFormat:e}:{},...n?{uploadEndpoint:n}:{},...T({key:"checkNSFW",value:r}),...T({key:"strength",value:g}),...T({key:"CFGScale",value:I}),...T({key:"clipSkip",value:b}),...T({key:"maskMargin",value:xe}),...T({key:"usePromptWeighting",value:k}),...T({key:"steps",value:m}),..._?{promptWeighting:_}:{},...y?{seed:y}:{seed:z()},...p?{scheduler:p}:{},...S?{refiner:S}:{},...ee?{outpaint:ee}:{},...T({key:"includeCost",value:O}),...w?{seedImage:w}:{},...B?{maskImage:B}:{},...h?{outputQuality:h}:{},...q.length?{controlNet:q}:{},...Z?.length?{lora:Z}:{},...$?.length?{embeddings:$}:{},...X?.length?{ipAdapters:X}:{},...te?{acceleratorOptions:te}:{},...ne?{advancedFeatures:ne}:{},...se?.length?{referenceImages:se}:{},...we??{}};let Ae=Date.now();return await x(async()=>{ae++,C?.destroy();let D=this._globalImages.filter(L=>N.includes(L.taskUUID)),E=W||R();N.push(E);let H=U-D.length,M={...re,taskUUID:E,numberResults:H};this.send(M),C=this.listenToImages({onPartialImages:f,taskUUID:E,groupKey:"REQUEST_IMAGES",requestPayload:ve?M:void 0,startTime:Se?Ae:void 0});let V=await this.getSimilarImages({taskUUID:N,numberResults:U,lis:C});return C.destroy(),V},{maxRetries:oe,callback:()=>{C?.destroy()}})}catch(w){if(ae>=oe)return this.handleIncompleteImages({taskUUIDs:N,error:w});throw w}}async ensureConnection(){if(this.connected()||this._url===Y.TEST)return;let e=2e3,n=200;try{if(this.isInvalidAPIKey())throw this._connectionError;return new Promise((r,a)=>{let l=0,c=30,i=R(),g,d,u=()=>{this.ensureConnectionUUID=null,clearInterval(g),clearInterval(d)};this._sdkType==="SERVER"&&(g=setInterval(async()=>{try{let s=this.connected(),m=!1;(!this.ensureConnectionUUID||i===this.ensureConnectionUUID)&&(this.ensureConnectionUUID||(this.ensureConnectionUUID=i),m=!0);let p=l%10===0&&m;s?(u(),r(!0)):l>=c?(u(),a(new Error("Retry timed out"))):(p&&this.connect(),l++)}catch(s){u(),a(s)}},e)),d=setInterval(async()=>{if(this.connected()){u(),r(!0);return}if(this.isInvalidAPIKey()){u(),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 v(({resolve:a,reject:l,intervalId:c})=>{let i=Array.isArray(t)?t:[t],g=this._globalImages.filter(d=>i.includes(d.taskUUID));if(this._globalError){let d=this._globalError;return this._globalError=void 0,clearInterval(c),l?.(d),!0}else if(g.length>=e)return clearInterval(c),this._globalImages=this._globalImages.filter(d=>!i.includes(d.taskUUID)),a([...g].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=qe(Re(),1),K=class extends A{constructor(t){let{shouldReconnect:e,...n}=t;super(n),this._ws=new ke.default(this._url),this.connect()}};import ot from"ws";var P=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 ot(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(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 De;typeof window>"u"?De=P:De=K;export{ce as EControlMode,je as EModelArchitecture,Je as EModelConditioning,Ve as EModelFormat,Qe as EModelType,He as EOpenPosePreProcessor,Ye as EPhotoMakerEnum,de as EPreProcessor,ue as EPreProcessorGroup,Q as ETaskType,le as Environment,De as Runware,K as RunwareClient,P as RunwareServer,j as SdkType};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|