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