@runware/sdk-js 1.1.10 → 1.1.12

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.
@@ -0,0 +1,1249 @@
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __defProps = Object.defineProperties;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
8
+ var __getProtoOf = Object.getPrototypeOf;
9
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
10
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
11
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
12
+ var __spreadValues = (a, b) => {
13
+ for (var prop in b || (b = {}))
14
+ if (__hasOwnProp.call(b, prop))
15
+ __defNormalProp(a, prop, b[prop]);
16
+ if (__getOwnPropSymbols)
17
+ for (var prop of __getOwnPropSymbols(b)) {
18
+ if (__propIsEnum.call(b, prop))
19
+ __defNormalProp(a, prop, b[prop]);
20
+ }
21
+ return a;
22
+ };
23
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
24
+ var __esm = (fn, res) => function __init() {
25
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
26
+ };
27
+ var __commonJS = (cb, mod) => function __require() {
28
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
29
+ };
30
+ var __export = (target, all) => {
31
+ for (var name in all)
32
+ __defProp(target, name, { get: all[name], enumerable: true });
33
+ };
34
+ var __copyProps = (to, from, except, desc) => {
35
+ if (from && typeof from === "object" || typeof from === "function") {
36
+ for (let key of __getOwnPropNames(from))
37
+ if (!__hasOwnProp.call(to, key) && key !== except)
38
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
39
+ }
40
+ return to;
41
+ };
42
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
43
+ // If the importer is in node compatibility mode or this is not an ESM
44
+ // file that has been converted to a CommonJS file using a Babel-
45
+ // compatible transform (i.e. "__esModule" has not been set), then set
46
+ // "default" to the CommonJS "module.exports" for node compatibility.
47
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
48
+ mod
49
+ ));
50
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
51
+
52
+ // Runware/types.ts
53
+ var Environment, SdkType, ETaskType, EControlMode, EPreProcessorGroup, EPreProcessor, EOpenPosePreProcessor;
54
+ var init_types = __esm({
55
+ "Runware/types.ts"() {
56
+ "use strict";
57
+ Environment = /* @__PURE__ */ ((Environment2) => {
58
+ Environment2["PRODUCTION"] = "PRODUCTION";
59
+ Environment2["DEVELOPMENT"] = "DEVELOPMENT";
60
+ Environment2["TEST"] = "TEST";
61
+ return Environment2;
62
+ })(Environment || {});
63
+ SdkType = /* @__PURE__ */ ((SdkType2) => {
64
+ SdkType2["CLIENT"] = "CLIENT";
65
+ SdkType2["SERVER"] = "SERVER";
66
+ return SdkType2;
67
+ })(SdkType || {});
68
+ ETaskType = /* @__PURE__ */ ((ETaskType2) => {
69
+ ETaskType2["IMAGE_INFERENCE"] = "imageInference";
70
+ ETaskType2["IMAGE_UPLOAD"] = "imageUpload";
71
+ ETaskType2["IMAGE_UPSCALE"] = "imageUpscale";
72
+ ETaskType2["IMAGE_BACKGROUND_REMOVAL"] = "imageBackgroundRemoval";
73
+ ETaskType2["IMAGE_CAPTION"] = "imageCaption";
74
+ ETaskType2["IMAGE_CONTROL_NET_PRE_PROCESS"] = "imageControlNetPreProcess";
75
+ ETaskType2["PROMPT_ENHANCE"] = "promptEnhance";
76
+ ETaskType2["AUTHENTICATION"] = "authentication";
77
+ return ETaskType2;
78
+ })(ETaskType || {});
79
+ EControlMode = /* @__PURE__ */ ((EControlMode2) => {
80
+ EControlMode2["BALANCED"] = "balanced";
81
+ EControlMode2["PROMPT"] = "prompt";
82
+ EControlMode2["CONTROL_NET"] = "controlnet";
83
+ return EControlMode2;
84
+ })(EControlMode || {});
85
+ EPreProcessorGroup = /* @__PURE__ */ ((EPreProcessorGroup3) => {
86
+ EPreProcessorGroup3["canny"] = "canny";
87
+ EPreProcessorGroup3["depth"] = "depth";
88
+ EPreProcessorGroup3["mlsd"] = "mlsd";
89
+ EPreProcessorGroup3["normalbae"] = "normalbae";
90
+ EPreProcessorGroup3["openpose"] = "openpose";
91
+ EPreProcessorGroup3["tile"] = "tile";
92
+ EPreProcessorGroup3["seg"] = "seg";
93
+ EPreProcessorGroup3["lineart"] = "lineart";
94
+ EPreProcessorGroup3["lineart_anime"] = "lineart_anime";
95
+ EPreProcessorGroup3["shuffle"] = "shuffle";
96
+ EPreProcessorGroup3["scribble"] = "scribble";
97
+ EPreProcessorGroup3["softedge"] = "softedge";
98
+ return EPreProcessorGroup3;
99
+ })(EPreProcessorGroup || {});
100
+ EPreProcessor = /* @__PURE__ */ ((EPreProcessor3) => {
101
+ EPreProcessor3["canny"] = "canny";
102
+ EPreProcessor3["depth_leres"] = "depth_leres";
103
+ EPreProcessor3["depth_midas"] = "depth_midas";
104
+ EPreProcessor3["depth_zoe"] = "depth_zoe";
105
+ EPreProcessor3["inpaint_global_harmonious"] = "inpaint_global_harmonious";
106
+ EPreProcessor3["lineart_anime"] = "lineart_anime";
107
+ EPreProcessor3["lineart_coarse"] = "lineart_coarse";
108
+ EPreProcessor3["lineart_realistic"] = "lineart_realistic";
109
+ EPreProcessor3["lineart_standard"] = "lineart_standard";
110
+ EPreProcessor3["mlsd"] = "mlsd";
111
+ EPreProcessor3["normal_bae"] = "normal_bae";
112
+ EPreProcessor3["scribble_hed"] = "scribble_hed";
113
+ EPreProcessor3["scribble_pidinet"] = "scribble_pidinet";
114
+ EPreProcessor3["seg_ofade20k"] = "seg_ofade20k";
115
+ EPreProcessor3["seg_ofcoco"] = "seg_ofcoco";
116
+ EPreProcessor3["seg_ufade20k"] = "seg_ufade20k";
117
+ EPreProcessor3["shuffle"] = "shuffle";
118
+ EPreProcessor3["softedge_hed"] = "softedge_hed";
119
+ EPreProcessor3["softedge_hedsafe"] = "softedge_hedsafe";
120
+ EPreProcessor3["softedge_pidinet"] = "softedge_pidinet";
121
+ EPreProcessor3["softedge_pidisafe"] = "softedge_pidisafe";
122
+ EPreProcessor3["tile_gaussian"] = "tile_gaussian";
123
+ EPreProcessor3["openpose"] = "openpose";
124
+ EPreProcessor3["openpose_face"] = "openpose_face";
125
+ EPreProcessor3["openpose_faceonly"] = "openpose_faceonly";
126
+ EPreProcessor3["openpose_full"] = "openpose_full";
127
+ EPreProcessor3["openpose_hand"] = "openpose_hand";
128
+ return EPreProcessor3;
129
+ })(EPreProcessor || {});
130
+ EOpenPosePreProcessor = /* @__PURE__ */ ((EOpenPosePreProcessor2) => {
131
+ EOpenPosePreProcessor2["openpose"] = "openpose";
132
+ EOpenPosePreProcessor2["openpose_face"] = "openpose_face";
133
+ EOpenPosePreProcessor2["openpose_faceonly"] = "openpose_faceonly";
134
+ EOpenPosePreProcessor2["openpose_full"] = "openpose_full";
135
+ EOpenPosePreProcessor2["openpose_hand"] = "openpose_hand";
136
+ return EOpenPosePreProcessor2;
137
+ })(EOpenPosePreProcessor || {});
138
+ }
139
+ });
140
+
141
+ // Runware/utils.ts
142
+ import { v4 as uuidv4, validate as validateUUID } from "uuid";
143
+ var TIMEOUT_DURATION, POLLING_INTERVAL, BASE_RUNWARE_URLS, removeFromAray, getIntervalWithPromise, fileToBase64, getUUID, isValidUUID, accessDeepObject, delay, removeListener, evaluateNonTrue;
144
+ var init_utils = __esm({
145
+ "Runware/utils.ts"() {
146
+ "use strict";
147
+ init_types();
148
+ TIMEOUT_DURATION = 6e4;
149
+ POLLING_INTERVAL = 100;
150
+ BASE_RUNWARE_URLS = {
151
+ ["PRODUCTION" /* PRODUCTION */]: "wss://ws-api.runware.ai/v1",
152
+ ["TEST" /* TEST */]: "ws://localhost:8080"
153
+ };
154
+ removeFromAray = (col, targetElem) => {
155
+ if (col == null) {
156
+ return;
157
+ }
158
+ let i = col.indexOf(targetElem);
159
+ if (i === -1) {
160
+ return;
161
+ }
162
+ col.splice(i, 1);
163
+ };
164
+ getIntervalWithPromise = (callback, {
165
+ debugKey = "debugKey",
166
+ timeOutDuration = TIMEOUT_DURATION,
167
+ shouldThrowError = true
168
+ }) => {
169
+ return new Promise((resolve, reject) => {
170
+ const timeoutId = setTimeout(() => {
171
+ if (intervalId) {
172
+ clearInterval(intervalId);
173
+ if (shouldThrowError) {
174
+ reject(`Message could not be received for ${debugKey}`);
175
+ console.error("Message could not be received for ", debugKey);
176
+ }
177
+ }
178
+ clearTimeout(timeoutId);
179
+ }, timeOutDuration);
180
+ let intervalId = setInterval(async () => {
181
+ const shouldClear = callback({ resolve, reject, intervalId });
182
+ if (shouldClear) {
183
+ clearInterval(intervalId);
184
+ clearTimeout(timeoutId);
185
+ }
186
+ }, POLLING_INTERVAL);
187
+ });
188
+ };
189
+ fileToBase64 = (file) => new Promise((resolve) => {
190
+ const reader = new FileReader();
191
+ reader.readAsDataURL(file);
192
+ reader.onload = function() {
193
+ resolve(reader.result);
194
+ };
195
+ });
196
+ getUUID = () => uuidv4();
197
+ isValidUUID = (uuid) => validateUUID(uuid);
198
+ accessDeepObject = ({
199
+ key,
200
+ data,
201
+ useZero = true,
202
+ shouldReturnString = false
203
+ }) => {
204
+ const splittedKeys = key.split(/\.|\[/).map((key2) => key2.replace(/\]$/, ""));
205
+ const value = splittedKeys.reduce((acc, curr) => {
206
+ var _a, _b;
207
+ const returnZero = useZero ? 0 : void 0;
208
+ const currentValue = acc == null ? void 0 : acc[curr];
209
+ if (!currentValue) {
210
+ return returnZero;
211
+ }
212
+ if (Array.isArray(currentValue) && /^\d+$/.test(curr)) {
213
+ const index = parseInt(curr, 10);
214
+ if (index >= 0 && index < currentValue.length) {
215
+ return acc[curr] = currentValue[index];
216
+ } else {
217
+ return (_a = acc[curr]) != null ? _a : returnZero;
218
+ }
219
+ } else {
220
+ return (_b = acc[curr]) != null ? _b : returnZero;
221
+ }
222
+ }, data || {});
223
+ return value != null ? value : {};
224
+ };
225
+ delay = (time, milliseconds = 1e3) => {
226
+ return new Promise((resolve) => setTimeout(resolve, time * milliseconds));
227
+ };
228
+ removeListener = (listeners, listener) => {
229
+ return listeners.filter((lis) => lis.key !== listener.key);
230
+ };
231
+ evaluateNonTrue = ({
232
+ key,
233
+ value
234
+ }) => {
235
+ if (!!value || value === 0 || value === false) {
236
+ return { [key]: value };
237
+ } else {
238
+ return {};
239
+ }
240
+ };
241
+ }
242
+ });
243
+
244
+ // Runware/async-retry.ts
245
+ var asyncRetry;
246
+ var init_async_retry = __esm({
247
+ "Runware/async-retry.ts"() {
248
+ "use strict";
249
+ init_utils();
250
+ asyncRetry = async (apiCall, options = {}) => {
251
+ var _a;
252
+ const { delayInSeconds = 1, callback } = options;
253
+ let maxRetries = (_a = options.maxRetries) != null ? _a : 1;
254
+ while (maxRetries) {
255
+ try {
256
+ const result = await apiCall();
257
+ return result;
258
+ } catch (error) {
259
+ callback == null ? void 0 : callback();
260
+ maxRetries--;
261
+ if (maxRetries > 0) {
262
+ await delay(delayInSeconds);
263
+ await asyncRetry(apiCall, __spreadProps(__spreadValues({}, options), { maxRetries }));
264
+ } else {
265
+ throw error;
266
+ }
267
+ }
268
+ }
269
+ };
270
+ }
271
+ });
272
+
273
+ // Runware/Runware-base.ts
274
+ var RunwareBase;
275
+ var init_Runware_base = __esm({
276
+ "Runware/Runware-base.ts"() {
277
+ "use strict";
278
+ init_async_retry();
279
+ init_types();
280
+ init_utils();
281
+ RunwareBase = class {
282
+ constructor({ apiKey, url = BASE_RUNWARE_URLS.PRODUCTION }) {
283
+ this._listeners = [];
284
+ // _globalMessages: any[] = [];
285
+ this._globalMessages = {};
286
+ this._globalImages = [];
287
+ this.isWebsocketReadyState = () => {
288
+ var _a;
289
+ return ((_a = this._ws) == null ? void 0 : _a.readyState) === 1;
290
+ };
291
+ // We moving to an array format, it make sense to consolidate all request to an array here
292
+ this.send = (msg) => {
293
+ this._ws.send(JSON.stringify([msg]));
294
+ };
295
+ this.uploadImage = async (file) => {
296
+ try {
297
+ return await asyncRetry(async () => {
298
+ const taskUUID = getUUID();
299
+ if (typeof file === "string" && isValidUUID(file)) {
300
+ return {
301
+ imageURL: file,
302
+ imageUUID: file,
303
+ taskUUID,
304
+ taskType: "imageUpload" /* IMAGE_UPLOAD */
305
+ };
306
+ }
307
+ const imageBase64 = typeof file === "string" ? file : await fileToBase64(file);
308
+ this.send({
309
+ taskType: "imageUpload" /* IMAGE_UPLOAD */,
310
+ image: imageBase64,
311
+ taskUUID
312
+ });
313
+ const lis = this.globalListener({
314
+ taskUUID
315
+ });
316
+ const image = await getIntervalWithPromise(
317
+ ({ resolve, reject }) => {
318
+ const uploadedImage = this.getSingleMessage({
319
+ taskUUID
320
+ });
321
+ if (!uploadedImage)
322
+ return;
323
+ if (uploadedImage == null ? void 0 : uploadedImage.error) {
324
+ reject(uploadedImage);
325
+ return true;
326
+ }
327
+ if (uploadedImage) {
328
+ delete this._globalMessages[taskUUID];
329
+ resolve(uploadedImage);
330
+ return true;
331
+ }
332
+ },
333
+ { debugKey: "upload-image" }
334
+ );
335
+ lis.destroy();
336
+ return image;
337
+ });
338
+ } catch (e) {
339
+ throw e;
340
+ }
341
+ };
342
+ this.controlNetPreProcess = async ({
343
+ inputImage,
344
+ preProcessor,
345
+ height,
346
+ width,
347
+ outputType,
348
+ outputFormat,
349
+ highThresholdCanny,
350
+ lowThresholdCanny,
351
+ includeHandsAndFaceOpenPose,
352
+ includeCost,
353
+ customTaskUUID
354
+ }) => {
355
+ try {
356
+ const image = await this.uploadImage(inputImage);
357
+ if (!(image == null ? void 0 : image.imageUUID))
358
+ return null;
359
+ const taskUUID = customTaskUUID || getUUID();
360
+ this.send(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues({
361
+ inputImage: image.imageUUID,
362
+ taskType: "imageControlNetPreProcess" /* IMAGE_CONTROL_NET_PRE_PROCESS */,
363
+ taskUUID,
364
+ preProcessor
365
+ }, evaluateNonTrue({ key: "height", value: height })), evaluateNonTrue({ key: "width", value: width })), evaluateNonTrue({ key: "outputType", value: outputType })), evaluateNonTrue({ key: "outputFormat", value: outputFormat })), evaluateNonTrue({ key: "includeCost", value: includeCost })), evaluateNonTrue({
366
+ key: "highThresholdCanny",
367
+ value: highThresholdCanny
368
+ })), evaluateNonTrue({
369
+ key: "lowThresholdCanny",
370
+ value: lowThresholdCanny
371
+ })), evaluateNonTrue({
372
+ key: "includeHandsAndFaceOpenPose",
373
+ value: includeHandsAndFaceOpenPose
374
+ })));
375
+ const lis = this.globalListener({
376
+ taskUUID
377
+ });
378
+ const guideImage = await getIntervalWithPromise(
379
+ ({ resolve, reject }) => {
380
+ const uploadedImage = this.getSingleMessage({
381
+ taskUUID
382
+ });
383
+ if (!uploadedImage)
384
+ return;
385
+ if (uploadedImage == null ? void 0 : uploadedImage.error) {
386
+ reject(uploadedImage);
387
+ return true;
388
+ }
389
+ if (uploadedImage) {
390
+ resolve(uploadedImage);
391
+ return true;
392
+ }
393
+ },
394
+ { debugKey: "unprocessed-image" }
395
+ );
396
+ lis.destroy();
397
+ return guideImage;
398
+ } catch (e) {
399
+ throw e;
400
+ }
401
+ };
402
+ this.requestImageToText = async ({
403
+ inputImage,
404
+ includeCost,
405
+ customTaskUUID
406
+ }) => {
407
+ try {
408
+ await this.ensureConnection();
409
+ return await asyncRetry(async () => {
410
+ const imageUploaded = await this.uploadImage(
411
+ inputImage
412
+ );
413
+ if (!(imageUploaded == null ? void 0 : imageUploaded.imageUUID))
414
+ return null;
415
+ const taskUUID = customTaskUUID || getUUID();
416
+ this.send(__spreadValues({
417
+ taskUUID,
418
+ taskType: "imageCaption" /* IMAGE_CAPTION */,
419
+ inputImage: imageUploaded.imageUUID
420
+ }, evaluateNonTrue({ key: "includeCost", value: includeCost })));
421
+ const lis = this.globalListener({
422
+ taskUUID
423
+ });
424
+ const response = await getIntervalWithPromise(
425
+ ({ resolve, reject }) => {
426
+ const newReverseClip = this.getSingleMessage({
427
+ taskUUID
428
+ });
429
+ if (!newReverseClip)
430
+ return;
431
+ if (newReverseClip == null ? void 0 : newReverseClip.error) {
432
+ reject(newReverseClip);
433
+ return true;
434
+ }
435
+ if (newReverseClip) {
436
+ delete this._globalMessages[taskUUID];
437
+ resolve(newReverseClip);
438
+ return true;
439
+ }
440
+ },
441
+ { debugKey: "remove-image-background" }
442
+ );
443
+ lis.destroy();
444
+ return response;
445
+ });
446
+ } catch (e) {
447
+ throw e;
448
+ }
449
+ };
450
+ this.removeImageBackground = async ({
451
+ inputImage,
452
+ outputType,
453
+ outputFormat,
454
+ rgba,
455
+ postProcessMask,
456
+ returnOnlyMask,
457
+ alphaMatting,
458
+ alphaMattingForegroundThreshold,
459
+ alphaMattingBackgroundThreshold,
460
+ alphaMattingErodeSize,
461
+ includeCost,
462
+ customTaskUUID
463
+ }) => {
464
+ try {
465
+ await this.ensureConnection();
466
+ return await asyncRetry(async () => {
467
+ const imageUploaded = inputImage ? await this.uploadImage(inputImage) : null;
468
+ const taskUUID = customTaskUUID || getUUID();
469
+ this.send(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues({
470
+ taskType: "imageBackgroundRemoval" /* IMAGE_BACKGROUND_REMOVAL */,
471
+ taskUUID,
472
+ inputImage: imageUploaded == null ? void 0 : imageUploaded.imageUUID
473
+ }, evaluateNonTrue({ key: "rgba", value: rgba })), evaluateNonTrue({
474
+ key: "postProcessMask",
475
+ value: postProcessMask
476
+ })), evaluateNonTrue({ key: "returnOnlyMask", value: returnOnlyMask })), evaluateNonTrue({ key: "alphaMatting", value: alphaMatting })), evaluateNonTrue({ key: "includeCost", value: includeCost })), evaluateNonTrue({
477
+ key: "alphaMattingForegroundThreshold",
478
+ value: alphaMattingForegroundThreshold
479
+ })), evaluateNonTrue({
480
+ key: "alphaMattingBackgroundThreshold",
481
+ value: alphaMattingBackgroundThreshold
482
+ })), evaluateNonTrue({
483
+ key: "alphaMattingErodeSize",
484
+ value: alphaMattingErodeSize
485
+ })), evaluateNonTrue({ key: "outputType", value: outputType })), evaluateNonTrue({ key: "outputFormat", value: outputFormat })));
486
+ const lis = this.globalListener({
487
+ taskUUID
488
+ });
489
+ const response = await getIntervalWithPromise(
490
+ ({ resolve, reject }) => {
491
+ const newRemoveBackground = this.getSingleMessage({ taskUUID });
492
+ if (!newRemoveBackground)
493
+ return;
494
+ if (newRemoveBackground == null ? void 0 : newRemoveBackground.error) {
495
+ reject(newRemoveBackground);
496
+ return true;
497
+ }
498
+ if (newRemoveBackground) {
499
+ delete this._globalMessages[taskUUID];
500
+ resolve([newRemoveBackground]);
501
+ return true;
502
+ }
503
+ },
504
+ { debugKey: "remove-image-background" }
505
+ );
506
+ lis.destroy();
507
+ return response;
508
+ });
509
+ } catch (e) {
510
+ throw e;
511
+ }
512
+ };
513
+ this.upscaleGan = async ({
514
+ inputImage,
515
+ upscaleFactor,
516
+ outputType,
517
+ outputFormat,
518
+ includeCost,
519
+ customTaskUUID
520
+ }) => {
521
+ try {
522
+ await this.ensureConnection();
523
+ return await asyncRetry(async () => {
524
+ let imageUploaded;
525
+ imageUploaded = await this.uploadImage(inputImage);
526
+ if (!(imageUploaded == null ? void 0 : imageUploaded.imageUUID))
527
+ return null;
528
+ const taskUUID = customTaskUUID || getUUID();
529
+ this.send(__spreadValues(__spreadValues(__spreadValues({
530
+ taskUUID,
531
+ inputImage: imageUploaded == null ? void 0 : imageUploaded.imageUUID,
532
+ taskType: "imageUpscale" /* IMAGE_UPSCALE */,
533
+ upscaleFactor
534
+ }, evaluateNonTrue({ key: "includeCost", value: includeCost })), outputType ? { outputType } : {}), outputFormat ? { outputFormat } : {}));
535
+ const lis = this.globalListener({
536
+ taskUUID
537
+ });
538
+ const response = await getIntervalWithPromise(
539
+ ({ resolve, reject }) => {
540
+ const newUpscaleGan = this.getSingleMessage({ taskUUID });
541
+ if (!newUpscaleGan)
542
+ return;
543
+ if (newUpscaleGan == null ? void 0 : newUpscaleGan.error) {
544
+ reject(newUpscaleGan);
545
+ return true;
546
+ }
547
+ if (newUpscaleGan) {
548
+ delete this._globalMessages[taskUUID];
549
+ resolve([newUpscaleGan]);
550
+ return true;
551
+ }
552
+ },
553
+ { debugKey: "upscale-gan" }
554
+ );
555
+ lis.destroy();
556
+ return response;
557
+ });
558
+ } catch (e) {
559
+ throw e;
560
+ }
561
+ };
562
+ this.enhancePrompt = async ({
563
+ prompt,
564
+ promptMaxLength = 380,
565
+ promptVersions = 1,
566
+ includeCost,
567
+ customTaskUUID
568
+ }) => {
569
+ try {
570
+ await this.ensureConnection();
571
+ return await asyncRetry(async () => {
572
+ const taskUUID = customTaskUUID || getUUID();
573
+ this.send(__spreadProps(__spreadValues({
574
+ prompt,
575
+ taskUUID,
576
+ promptMaxLength,
577
+ promptVersions
578
+ }, evaluateNonTrue({ key: "includeCost", value: includeCost })), {
579
+ taskType: "promptEnhance" /* PROMPT_ENHANCE */
580
+ }));
581
+ const lis = this.globalListener({
582
+ taskUUID
583
+ });
584
+ const response = await getIntervalWithPromise(
585
+ ({ resolve, reject }) => {
586
+ const reducedPrompt = this._globalMessages[taskUUID];
587
+ if (reducedPrompt == null ? void 0 : reducedPrompt.error) {
588
+ reject(reducedPrompt);
589
+ return true;
590
+ }
591
+ if ((reducedPrompt == null ? void 0 : reducedPrompt.length) >= promptVersions) {
592
+ delete this._globalMessages[taskUUID];
593
+ resolve(reducedPrompt);
594
+ return true;
595
+ }
596
+ },
597
+ { debugKey: "enhance-prompt" }
598
+ );
599
+ lis.destroy();
600
+ return response;
601
+ });
602
+ } catch (e) {
603
+ throw e;
604
+ }
605
+ };
606
+ this.getSingleMessage = ({ taskUUID }) => {
607
+ var _a;
608
+ const value = this._globalMessages[taskUUID] || ((_a = this._globalMessages[taskUUID]) == null ? void 0 : _a[0]);
609
+ if (!value)
610
+ return null;
611
+ return value;
612
+ };
613
+ this.disconnect = () => {
614
+ var _a, _b, _c, _d;
615
+ (_b = (_a = this._ws) == null ? void 0 : _a.terminate) == null ? void 0 : _b.call(_a);
616
+ (_d = (_c = this._ws) == null ? void 0 : _c.close) == null ? void 0 : _d.call(_c);
617
+ };
618
+ this.connected = () => this.isWebsocketReadyState() && !!this._connectionSessionUUID;
619
+ this._apiKey = apiKey;
620
+ this._url = url;
621
+ this._sdkType = "CLIENT" /* CLIENT */;
622
+ }
623
+ // protected addListener({
624
+ // lis,
625
+ // check,
626
+ // }: {
627
+ // lis: (v: any) => any;
628
+ // check: (v: any) => any;
629
+ // groupKey?: string;
630
+ // }): { destroy: Function } {
631
+ // this._ws.onmessage = (e: any) => {
632
+ // const m = JSON.parse(e.data);
633
+ // if (m?.error) {
634
+ // lis(m);
635
+ // } else if (check(m)) {
636
+ // lis(m);
637
+ // }
638
+ // };
639
+ // return {
640
+ // destroy: () => {},
641
+ // };
642
+ // }
643
+ addListener({
644
+ lis,
645
+ // check,
646
+ groupKey,
647
+ taskUUID
648
+ }) {
649
+ const listener = (msg) => {
650
+ var _a;
651
+ const arrayMessage = Array.isArray(msg == null ? void 0 : msg.data) ? msg.data : [msg.data];
652
+ const arrayErrors = Array.isArray(msg == null ? void 0 : msg.errors) ? msg.errors : [msg.errors];
653
+ const filteredMessage = arrayMessage.filter(
654
+ (v) => ((v == null ? void 0 : v.taskUUID) || (v == null ? void 0 : v.taskType)) === taskUUID
655
+ );
656
+ const filteredErrors = arrayErrors.filter(
657
+ (v) => ((v == null ? void 0 : v.taskUUID) || (v == null ? void 0 : v.taskType)) === taskUUID
658
+ );
659
+ if (filteredErrors.length) {
660
+ lis({ error: __spreadValues({}, (_a = arrayErrors[0]) != null ? _a : {}) });
661
+ return;
662
+ }
663
+ if (filteredMessage.length) {
664
+ lis({ [taskUUID]: arrayMessage });
665
+ return;
666
+ }
667
+ };
668
+ const groupListener = { key: getUUID(), listener, groupKey };
669
+ this._listeners.push(groupListener);
670
+ const destroy = () => {
671
+ this._listeners = removeListener(this._listeners, groupListener);
672
+ };
673
+ return {
674
+ destroy
675
+ };
676
+ }
677
+ connect() {
678
+ this._ws.onopen = (e) => {
679
+ if (this._connectionSessionUUID) {
680
+ this.send({
681
+ taskType: "authentication" /* AUTHENTICATION */,
682
+ apiKey: this._apiKey,
683
+ connectionSessionUUID: this._connectionSessionUUID
684
+ });
685
+ } else {
686
+ this.send({ apiKey: this._apiKey, taskType: "authentication" /* AUTHENTICATION */ });
687
+ }
688
+ this.addListener({
689
+ taskUUID: "authentication" /* AUTHENTICATION */,
690
+ lis: (m) => {
691
+ var _a, _b;
692
+ if (m == null ? void 0 : m.error) {
693
+ this._invalidAPIkey = "Invalid API key";
694
+ return;
695
+ }
696
+ this._connectionSessionUUID = (_b = (_a = m == null ? void 0 : m["authentication" /* AUTHENTICATION */]) == null ? void 0 : _a[0]) == null ? void 0 : _b.connectionSessionUUID;
697
+ this._invalidAPIkey = void 0;
698
+ }
699
+ });
700
+ };
701
+ this._ws.onmessage = (e) => {
702
+ var _a;
703
+ const data = JSON.parse(e.data);
704
+ for (const lis of this._listeners) {
705
+ const result = (_a = lis == null ? void 0 : lis.listener) == null ? void 0 : _a.call(lis, data);
706
+ if (result)
707
+ return;
708
+ }
709
+ };
710
+ this._ws.onclose = (e) => {
711
+ if (this._invalidAPIkey) {
712
+ console.error(this._invalidAPIkey);
713
+ return;
714
+ }
715
+ };
716
+ }
717
+ destroy(lis) {
718
+ removeFromAray(this._listeners, lis);
719
+ }
720
+ listenToImages({
721
+ onPartialImages,
722
+ taskUUID,
723
+ groupKey,
724
+ positivePrompt,
725
+ negativePrompt
726
+ }) {
727
+ return this.addListener({
728
+ taskUUID,
729
+ lis: (m) => {
730
+ var _a, _b;
731
+ let images = (_a = m == null ? void 0 : m[taskUUID]) == null ? void 0 : _a.filter(
732
+ (img) => img.taskUUID === taskUUID
733
+ );
734
+ if (m.error) {
735
+ onPartialImages == null ? void 0 : onPartialImages(images, (m == null ? void 0 : m.error) && m);
736
+ this._globalError = m;
737
+ } else {
738
+ images = images.map((image) => __spreadProps(__spreadValues({}, image), {
739
+ positivePrompt,
740
+ negativePrompt
741
+ }));
742
+ onPartialImages == null ? void 0 : onPartialImages(images, (m == null ? void 0 : m.error) && m);
743
+ if (this._sdkType === "CLIENT" /* CLIENT */) {
744
+ this._globalImages = [
745
+ ...this._globalImages,
746
+ ...((_b = m == null ? void 0 : m[taskUUID]) != null ? _b : []).map((image) => __spreadProps(__spreadValues({}, image), {
747
+ positivePrompt,
748
+ negativePrompt
749
+ }))
750
+ ];
751
+ } else {
752
+ this._globalImages = [...this._globalImages, ...images];
753
+ }
754
+ }
755
+ },
756
+ groupKey
757
+ });
758
+ }
759
+ globalListener({ taskUUID }) {
760
+ return this.addListener({
761
+ // check: (m) => {
762
+ // const value = accessDeepObject({
763
+ // key: responseKey,
764
+ // data: m,
765
+ // useZero: false,
766
+ // });
767
+ // return !!value;
768
+ // },
769
+ // check: responseKey,
770
+ taskUUID,
771
+ lis: (m) => {
772
+ console.log("m", m);
773
+ if (m.error) {
774
+ this._globalMessages[taskUUID] = m;
775
+ return;
776
+ }
777
+ const value = accessDeepObject({
778
+ key: taskUUID,
779
+ data: m,
780
+ useZero: false
781
+ });
782
+ if (Array.isArray(value)) {
783
+ value.forEach((v) => {
784
+ var _a;
785
+ this._globalMessages[v.taskUUID] = [
786
+ ...(_a = this._globalMessages[v.taskUUID]) != null ? _a : [],
787
+ v
788
+ ];
789
+ });
790
+ } else {
791
+ this._globalMessages[value.taskUUID] = value;
792
+ }
793
+ }
794
+ });
795
+ }
796
+ async requestImages({
797
+ outputType,
798
+ outputFormat,
799
+ uploadEndpoint,
800
+ checkNsfw,
801
+ positivePrompt,
802
+ negativePrompt,
803
+ seedImage,
804
+ maskImage,
805
+ strength,
806
+ height,
807
+ width,
808
+ model,
809
+ steps,
810
+ scheduler,
811
+ seed,
812
+ CFGScale,
813
+ clipSkip,
814
+ usePromptWeighting,
815
+ numberResults = 1,
816
+ controlNet,
817
+ lora,
818
+ onPartialImages,
819
+ includeCost,
820
+ customTaskUUID,
821
+ retry = 2
822
+ }) {
823
+ await this.ensureConnection();
824
+ let lis = void 0;
825
+ let requestObject = void 0;
826
+ let taskUUIDs = [];
827
+ let retryCount = 0;
828
+ try {
829
+ await this.ensureConnection();
830
+ let seedImageUUID = null;
831
+ let maskImageUUID = null;
832
+ let controlNetData = [];
833
+ if (seedImage) {
834
+ const uploadedImage = await this.uploadImage(seedImage);
835
+ if (!uploadedImage)
836
+ return [];
837
+ seedImageUUID = uploadedImage.imageUUID;
838
+ }
839
+ if (maskImage) {
840
+ const uploadedMaskInitiator = await this.uploadImage(maskImage);
841
+ if (!uploadedMaskInitiator)
842
+ return [];
843
+ maskImageUUID = uploadedMaskInitiator.imageUUID;
844
+ }
845
+ if (controlNet == null ? void 0 : controlNet.length) {
846
+ for (let i = 0; i < controlNet.length; i++) {
847
+ const controlData = controlNet[i];
848
+ const {
849
+ endStep,
850
+ startStep,
851
+ weight,
852
+ guideImage,
853
+ controlMode,
854
+ startStepPercentage,
855
+ endStepPercentage,
856
+ model: controlNetModel
857
+ } = controlData;
858
+ if (!guideImage)
859
+ return;
860
+ const imageUploaded = await this.uploadImage(
861
+ guideImage
862
+ );
863
+ if (!imageUploaded)
864
+ return;
865
+ controlNetData.push(__spreadProps(__spreadValues(__spreadValues({
866
+ guideImage: imageUploaded.imageUUID,
867
+ model: controlNetModel,
868
+ endStep,
869
+ startStep,
870
+ weight
871
+ }, evaluateNonTrue({
872
+ key: "startStepPercentage",
873
+ value: startStepPercentage
874
+ })), evaluateNonTrue({
875
+ key: "endStepPercentage",
876
+ value: endStepPercentage
877
+ })), {
878
+ controlMode: controlMode || "controlnet" /* CONTROL_NET */
879
+ }));
880
+ }
881
+ }
882
+ requestObject = __spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadProps(__spreadValues(__spreadValues(__spreadValues({
883
+ taskType: "imageInference" /* IMAGE_INFERENCE */,
884
+ model,
885
+ positivePrompt
886
+ }, negativePrompt ? { negativePrompt } : {}), height ? { height } : {}), width ? { width } : {}), {
887
+ numberResults
888
+ }), (lora == null ? void 0 : lora.length) ? { lora } : {}), outputType ? { outputType } : {}), outputFormat ? { outputFormat } : {}), uploadEndpoint ? { uploadEndpoint } : {}), evaluateNonTrue({ key: "checkNsfw", value: checkNsfw })), evaluateNonTrue({ key: "strength", value: strength })), evaluateNonTrue({ key: "CFGScale", value: CFGScale })), evaluateNonTrue({ key: "clipSkip", value: clipSkip })), evaluateNonTrue({
889
+ key: "usePromptWeighting",
890
+ value: usePromptWeighting
891
+ })), evaluateNonTrue({ key: "steps", value: steps })), controlNetData.length ? { controlNet: controlNetData } : {}), seed ? { seed } : {}), scheduler ? { scheduler } : {}), evaluateNonTrue({ key: "includeCost", value: includeCost })), seedImageUUID ? { seedImage: seedImageUUID } : {}), maskImageUUID ? { maskImage: maskImageUUID } : {});
892
+ return await asyncRetry(
893
+ async () => {
894
+ retryCount++;
895
+ lis == null ? void 0 : lis.destroy();
896
+ const imagesWithSimilarTask = this._globalImages.filter(
897
+ (img) => taskUUIDs.includes(img.taskUUID)
898
+ );
899
+ const taskUUID = customTaskUUID || getUUID();
900
+ taskUUIDs.push(taskUUID);
901
+ const imageRemaining = numberResults - imagesWithSimilarTask.length;
902
+ const newRequestObject = __spreadProps(__spreadValues({}, requestObject), {
903
+ taskUUID,
904
+ numberResults: imageRemaining
905
+ });
906
+ this.send(newRequestObject);
907
+ lis = this.listenToImages({
908
+ onPartialImages,
909
+ taskUUID,
910
+ groupKey: "REQUEST_IMAGES" /* REQUEST_IMAGES */,
911
+ positivePrompt,
912
+ negativePrompt
913
+ });
914
+ const promise = await this.getSimilarImages({
915
+ taskUUID: taskUUIDs,
916
+ numberResults,
917
+ lis
918
+ });
919
+ lis.destroy();
920
+ return promise;
921
+ },
922
+ {
923
+ maxRetries: retry,
924
+ callback: () => {
925
+ lis == null ? void 0 : lis.destroy();
926
+ }
927
+ }
928
+ );
929
+ } catch (e) {
930
+ if (e.taskUUID) {
931
+ throw e;
932
+ }
933
+ if (retryCount >= retry) {
934
+ return this.handleIncompleteImages({ taskUUIDs, error: e });
935
+ }
936
+ }
937
+ }
938
+ async ensureConnection() {
939
+ var _a;
940
+ let isConnected = this.connected();
941
+ if (isConnected || this._url === BASE_RUNWARE_URLS.TEST)
942
+ return;
943
+ const retryInterval = 2e3;
944
+ const pollingInterval = 200;
945
+ try {
946
+ if (this._invalidAPIkey)
947
+ throw this._invalidAPIkey;
948
+ return new Promise((resolve, reject) => {
949
+ let retry = 0;
950
+ const MAX_RETRY = 10;
951
+ let retryIntervalId;
952
+ let pollingIntervalId;
953
+ const clearAllIntervals = () => {
954
+ clearInterval(retryIntervalId);
955
+ clearInterval(pollingIntervalId);
956
+ };
957
+ if (this._sdkType === "SERVER" /* SERVER */) {
958
+ retryIntervalId = setInterval(async () => {
959
+ try {
960
+ const hasConnected = this.connected();
961
+ if (hasConnected) {
962
+ clearAllIntervals();
963
+ resolve(true);
964
+ } else if (retry >= MAX_RETRY) {
965
+ clearAllIntervals();
966
+ reject(new Error("Retry timed out"));
967
+ } else {
968
+ this.connect();
969
+ retry++;
970
+ }
971
+ } catch (error) {
972
+ clearAllIntervals();
973
+ reject(error);
974
+ }
975
+ }, retryInterval);
976
+ }
977
+ pollingIntervalId = setInterval(async () => {
978
+ const hasConnected = this.connected();
979
+ if (hasConnected) {
980
+ clearAllIntervals();
981
+ resolve(true);
982
+ }
983
+ if (!!this._invalidAPIkey) {
984
+ clearAllIntervals();
985
+ reject(new Error("Invalid API key"));
986
+ return;
987
+ }
988
+ }, pollingInterval);
989
+ });
990
+ if (!isConnected) {
991
+ this.connect();
992
+ await delay(2);
993
+ }
994
+ } catch (e) {
995
+ throw (_a = this._invalidAPIkey) != null ? _a : "Could not connect to server. Ensure your API key is correct";
996
+ }
997
+ }
998
+ async getSimilarImages({
999
+ taskUUID,
1000
+ numberResults,
1001
+ shouldThrowError,
1002
+ lis
1003
+ }) {
1004
+ return await getIntervalWithPromise(
1005
+ ({ resolve, reject, intervalId }) => {
1006
+ const taskUUIDs = Array.isArray(taskUUID) ? taskUUID : [taskUUID];
1007
+ const imagesWithSimilarTask = this._globalImages.filter(
1008
+ (img) => taskUUIDs.includes(img.taskUUID)
1009
+ );
1010
+ if (this._globalError) {
1011
+ const newData = this._globalError;
1012
+ this._globalError = void 0;
1013
+ clearInterval(intervalId);
1014
+ reject == null ? void 0 : reject(newData);
1015
+ return true;
1016
+ } else if (imagesWithSimilarTask.length >= numberResults) {
1017
+ clearInterval(intervalId);
1018
+ this._globalImages = this._globalImages.filter(
1019
+ (img) => !taskUUIDs.includes(img.taskUUID)
1020
+ );
1021
+ resolve([...imagesWithSimilarTask].slice(0, numberResults));
1022
+ return true;
1023
+ }
1024
+ },
1025
+ { debugKey: "getting images", shouldThrowError }
1026
+ );
1027
+ }
1028
+ handleIncompleteImages({
1029
+ taskUUIDs,
1030
+ error
1031
+ }) {
1032
+ const imagesWithSimilarTask = this._globalImages.filter(
1033
+ (img) => taskUUIDs.includes(img.taskUUID)
1034
+ );
1035
+ if (imagesWithSimilarTask.length > 1) {
1036
+ this._globalImages = this._globalImages.filter(
1037
+ (img) => !taskUUIDs.includes(img.taskUUID)
1038
+ );
1039
+ return imagesWithSimilarTask;
1040
+ } else {
1041
+ throw error;
1042
+ }
1043
+ }
1044
+ //end of data
1045
+ };
1046
+ }
1047
+ });
1048
+
1049
+ // Runware/reconnect.ts
1050
+ var require_reconnect = __commonJS({
1051
+ "Runware/reconnect.ts"(exports, module) {
1052
+ "use strict";
1053
+ var isWebSocket = (constructor) => constructor && constructor.CLOSING === 2;
1054
+ var isGlobalWebSocket = () => typeof WebSocket !== "undefined" && isWebSocket(WebSocket);
1055
+ var getDefaultOptions = () => ({
1056
+ constructor: isGlobalWebSocket() ? WebSocket : null,
1057
+ maxReconnectionDelay: 1e4,
1058
+ minReconnectionDelay: 1500,
1059
+ reconnectionDelayGrowFactor: 1.3,
1060
+ connectionTimeout: 4e3,
1061
+ maxRetries: Infinity,
1062
+ debug: false
1063
+ });
1064
+ var bypassProperty = (src, dst, name) => {
1065
+ Object.defineProperty(dst, name, {
1066
+ get: () => src[name],
1067
+ set: (value) => {
1068
+ src[name] = value;
1069
+ },
1070
+ enumerable: true,
1071
+ configurable: true
1072
+ });
1073
+ };
1074
+ var initReconnectionDelay = (config) => config.minReconnectionDelay + Math.random() * config.minReconnectionDelay;
1075
+ var updateReconnectionDelay = (config, previousDelay) => {
1076
+ const newDelay = previousDelay * config.reconnectionDelayGrowFactor;
1077
+ return newDelay > config.maxReconnectionDelay ? config.maxReconnectionDelay : newDelay;
1078
+ };
1079
+ var LEVEL_0_EVENTS = ["onopen", "onclose", "onmessage", "onerror"];
1080
+ var reassignEventListeners = (ws, oldWs, listeners) => {
1081
+ Object.keys(listeners).forEach((type) => {
1082
+ listeners[type].forEach(([listener, options]) => {
1083
+ ws.addEventListener(type, listener, options);
1084
+ });
1085
+ });
1086
+ if (oldWs) {
1087
+ LEVEL_0_EVENTS.forEach((name) => {
1088
+ ws[name] = oldWs[name];
1089
+ });
1090
+ }
1091
+ };
1092
+ var ReconnectingWebsocket2 = function(url, protocols, options = {}) {
1093
+ let ws;
1094
+ let connectingTimeout;
1095
+ let reconnectDelay = 0;
1096
+ let retriesCount = 0;
1097
+ let shouldRetry = true;
1098
+ const listeners = {};
1099
+ if (!(this instanceof ReconnectingWebsocket2)) {
1100
+ throw new TypeError(
1101
+ "Failed to construct 'ReconnectingWebSocket': Please use the 'new' operator"
1102
+ );
1103
+ }
1104
+ const config = getDefaultOptions();
1105
+ Object.keys(config).filter((key) => options.hasOwnProperty(key)).forEach((key) => config[key] = options[key]);
1106
+ if (!isWebSocket(config.constructor)) {
1107
+ throw new TypeError(
1108
+ "Invalid WebSocket constructor. Set `options.constructor`"
1109
+ );
1110
+ }
1111
+ const log = config.debug ? (...params) => console.log("RWS:", ...params) : () => {
1112
+ };
1113
+ const emitError = (code, msg) => setTimeout(() => {
1114
+ const err = new Error(msg);
1115
+ err.code = code;
1116
+ if (Array.isArray(listeners.error)) {
1117
+ listeners.error.forEach(([fn]) => fn(err));
1118
+ }
1119
+ if (ws.onerror) {
1120
+ ws.onerror(err);
1121
+ }
1122
+ }, 0);
1123
+ const handleClose = () => {
1124
+ log("close");
1125
+ retriesCount++;
1126
+ log("retries count:", retriesCount);
1127
+ if (retriesCount > config.maxRetries) {
1128
+ emitError("EHOSTDOWN", "Too many failed connection attempts");
1129
+ return;
1130
+ }
1131
+ if (!reconnectDelay) {
1132
+ reconnectDelay = initReconnectionDelay(config);
1133
+ } else {
1134
+ reconnectDelay = updateReconnectionDelay(config, reconnectDelay);
1135
+ }
1136
+ log("reconnectDelay:", reconnectDelay);
1137
+ if (shouldRetry) {
1138
+ setTimeout(connect, reconnectDelay);
1139
+ }
1140
+ };
1141
+ const connect = () => {
1142
+ log("connect");
1143
+ const oldWs = ws;
1144
+ ws = new config.constructor(url, protocols);
1145
+ connectingTimeout = setTimeout(() => {
1146
+ log("timeout");
1147
+ ws.close();
1148
+ emitError("ETIMEDOUT", "Connection timeout");
1149
+ }, config.connectionTimeout);
1150
+ log("bypass properties");
1151
+ for (let key in ws) {
1152
+ if (["addEventListener", "removeEventListener", "close", "send"].indexOf(
1153
+ key
1154
+ ) < 0) {
1155
+ bypassProperty(ws, this, key);
1156
+ }
1157
+ }
1158
+ ws.addEventListener("open", () => {
1159
+ clearTimeout(connectingTimeout);
1160
+ log("open");
1161
+ reconnectDelay = initReconnectionDelay(config);
1162
+ log("reconnectDelay:", reconnectDelay);
1163
+ retriesCount = 0;
1164
+ });
1165
+ ws.addEventListener("close", handleClose);
1166
+ reassignEventListeners(ws, oldWs, listeners);
1167
+ };
1168
+ log("init");
1169
+ connect();
1170
+ this.close = (code = 1e3, reason = "", { keepClosed = false, fastClose = true, delay: delay2 = 0 } = {}) => {
1171
+ if (delay2) {
1172
+ reconnectDelay = delay2;
1173
+ }
1174
+ shouldRetry = !keepClosed;
1175
+ ws.close(code, reason);
1176
+ if (fastClose) {
1177
+ const fakeCloseEvent = {
1178
+ code,
1179
+ reason,
1180
+ wasClean: true
1181
+ };
1182
+ handleClose();
1183
+ if (Array.isArray(listeners.close)) {
1184
+ listeners.close.forEach(([listener, options2]) => {
1185
+ listener(fakeCloseEvent);
1186
+ ws.removeEventListener("close", listener, options2);
1187
+ });
1188
+ }
1189
+ if (ws.onclose) {
1190
+ ws.onclose(fakeCloseEvent);
1191
+ ws.onclose = null;
1192
+ }
1193
+ }
1194
+ };
1195
+ this.send = (data) => {
1196
+ ws.send(data);
1197
+ };
1198
+ this.addEventListener = (type, listener, options2) => {
1199
+ if (Array.isArray(listeners[type])) {
1200
+ if (!listeners[type].some(([l]) => l === listener)) {
1201
+ listeners[type].push([listener, options2]);
1202
+ }
1203
+ } else {
1204
+ listeners[type] = [[listener, options2]];
1205
+ }
1206
+ ws.addEventListener(type, listener, options2);
1207
+ };
1208
+ this.removeEventListener = (type, listener, options2) => {
1209
+ if (Array.isArray(listeners[type])) {
1210
+ listeners[type] = listeners[type].filter(([l]) => l !== listener);
1211
+ }
1212
+ ws.removeEventListener(type, listener, options2);
1213
+ };
1214
+ };
1215
+ module.exports = ReconnectingWebsocket2;
1216
+ }
1217
+ });
1218
+
1219
+ // Runware/Runware-client.ts
1220
+ init_Runware_base();
1221
+ var import_reconnect = __toESM(require_reconnect());
1222
+ var RunwareClient = class extends RunwareBase {
1223
+ constructor({ apiKey, url }) {
1224
+ super({ apiKey, url });
1225
+ if (apiKey) {
1226
+ this._ws = new import_reconnect.default(
1227
+ this._url
1228
+ );
1229
+ this.connect();
1230
+ }
1231
+ }
1232
+ };
1233
+
1234
+ export {
1235
+ __esm,
1236
+ __export,
1237
+ __toCommonJS,
1238
+ Environment,
1239
+ SdkType,
1240
+ ETaskType,
1241
+ EControlMode,
1242
+ EPreProcessorGroup,
1243
+ EPreProcessor,
1244
+ EOpenPosePreProcessor,
1245
+ init_types,
1246
+ RunwareBase,
1247
+ init_Runware_base,
1248
+ RunwareClient
1249
+ };