@runware/sdk-js 1.0.27

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