@pear-protocol/hyperliquid-sdk 0.0.11 → 0.0.13

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.esm.js DELETED
@@ -1,3908 +0,0 @@
1
- import axios from 'axios';
2
- import require$$0, { useState, useEffect, useRef, createContext, useMemo, useContext, useCallback } from 'react';
3
- import require$$1 from 'react-dom';
4
-
5
- /**
6
- * Main SDK client for Pear Protocol Hyperliquid API integration
7
- */
8
- class PearHyperliquidClient {
9
- constructor(config) {
10
- this.baseUrl = config.baseUrl.replace(/\/$/, ''); // Remove trailing slash
11
- this.httpClient = axios.create({
12
- baseURL: this.baseUrl,
13
- timeout: config.timeout || 30000,
14
- headers: {
15
- 'Content-Type': 'application/json',
16
- ...config.headers,
17
- },
18
- });
19
- // Add response interceptor for error handling
20
- this.httpClient.interceptors.response.use((response) => response, (error) => {
21
- var _a, _b, _c, _d, _e;
22
- const apiError = {
23
- statusCode: ((_a = error.response) === null || _a === void 0 ? void 0 : _a.status) || 500,
24
- message: ((_c = (_b = error.response) === null || _b === void 0 ? void 0 : _b.data) === null || _c === void 0 ? void 0 : _c.message) || error.message,
25
- error: (_e = (_d = error.response) === null || _d === void 0 ? void 0 : _d.data) === null || _e === void 0 ? void 0 : _e.error,
26
- };
27
- return Promise.reject(apiError);
28
- });
29
- }
30
- /**
31
- * Get the configured base URL
32
- */
33
- getBaseUrl() {
34
- return this.baseUrl;
35
- }
36
- /**
37
- * Update request headers
38
- */
39
- setHeaders(headers) {
40
- this.httpClient.defaults.headers = {
41
- ...this.httpClient.defaults.headers,
42
- ...headers,
43
- };
44
- }
45
- /**
46
- * Set authorization header
47
- */
48
- setAuthToken(token) {
49
- this.setHeaders({ Authorization: `Bearer ${token}` });
50
- }
51
- /**
52
- * Make a generic HTTP request
53
- */
54
- async makeRequest(method, endpoint, data) {
55
- const response = await this.httpClient.request({
56
- method,
57
- url: endpoint,
58
- data,
59
- });
60
- return {
61
- data: response.data,
62
- status: response.status,
63
- headers: response.headers,
64
- };
65
- }
66
- /**
67
- * Sync trade history data from old database structure to new database format
68
- * @param payload - Trade history data with user address
69
- * @returns Promise with sync result
70
- */
71
- async syncTradeHistory(payload) {
72
- return this.makeRequest('POST', '/syncer/trade-histories', payload);
73
- }
74
- /**
75
- * Sync open positions data from old database structure to new database format
76
- * @param payload - Open positions data with user address
77
- * @returns Promise with sync result
78
- */
79
- async syncOpenPositions(payload) {
80
- return this.makeRequest('POST', '/syncer/open-positions', payload);
81
- }
82
- /**
83
- * Sync open orders data from old database structure to new database format
84
- * @param payload - Open orders data with user address
85
- * @returns Promise with sync result
86
- */
87
- async syncOpenOrders(payload) {
88
- return this.makeRequest('POST', '/syncer/open-orders', payload);
89
- }
90
- }
91
-
92
- /**
93
- * Main Migration SDK Class - Simple request/response pattern
94
- */
95
- class PearMigrationSDK {
96
- constructor(client) {
97
- this.isTradeHistorySyncRunning = false;
98
- this.isOpenPositionsSyncRunning = false;
99
- this.isOpenOrdersSyncRunning = false;
100
- this.client = client;
101
- }
102
- /**
103
- * Sync trade history data - can only run one at a time
104
- * If called while already running, returns immediately without making request
105
- */
106
- async syncTradeHistory(payload) {
107
- // If sync is already running, return immediately
108
- if (this.isTradeHistorySyncRunning) {
109
- return null;
110
- }
111
- try {
112
- this.isTradeHistorySyncRunning = true;
113
- const response = await this.client.syncTradeHistory(payload);
114
- return response;
115
- }
116
- finally {
117
- this.isTradeHistorySyncRunning = false;
118
- }
119
- }
120
- /**
121
- * Sync open positions data - can only run one at a time
122
- * If called while already running, returns immediately without making request
123
- */
124
- async syncOpenPositions(payload) {
125
- // If sync is already running, return immediately
126
- if (this.isOpenPositionsSyncRunning) {
127
- return null;
128
- }
129
- try {
130
- this.isOpenPositionsSyncRunning = true;
131
- const response = await this.client.syncOpenPositions(payload);
132
- return response;
133
- }
134
- finally {
135
- this.isOpenPositionsSyncRunning = false;
136
- }
137
- }
138
- /**
139
- * Sync open orders data - can only run one at a time
140
- * If called while already running, returns immediately without making request
141
- */
142
- async syncOpenOrders(payload) {
143
- // If sync is already running, return immediately
144
- if (this.isOpenOrdersSyncRunning) {
145
- return null;
146
- }
147
- try {
148
- this.isOpenOrdersSyncRunning = true;
149
- const response = await this.client.syncOpenOrders(payload);
150
- return response;
151
- }
152
- finally {
153
- this.isOpenOrdersSyncRunning = false;
154
- }
155
- }
156
- /**
157
- * Check if any sync is currently running
158
- */
159
- isSyncInProgress() {
160
- return this.isTradeHistorySyncRunning || this.isOpenPositionsSyncRunning || this.isOpenOrdersSyncRunning;
161
- }
162
- /**
163
- * Check if trade history sync is currently running
164
- */
165
- isTradeHistorySyncInProgress() {
166
- return this.isTradeHistorySyncRunning;
167
- }
168
- /**
169
- * Check if open positions sync is currently running
170
- */
171
- isOpenPositionsSyncInProgress() {
172
- return this.isOpenPositionsSyncRunning;
173
- }
174
- /**
175
- * Check if open orders sync is currently running
176
- */
177
- isOpenOrdersSyncInProgress() {
178
- return this.isOpenOrdersSyncRunning;
179
- }
180
- /**
181
- * Get the underlying client instance
182
- */
183
- getClient() {
184
- return this.client;
185
- }
186
- /**
187
- * Set authorization token on the client
188
- */
189
- setAuthToken(token) {
190
- this.client.setAuthToken(token);
191
- }
192
- /**
193
- * Set custom headers on the client
194
- */
195
- setHeaders(headers) {
196
- this.client.setHeaders(headers);
197
- }
198
- /**
199
- * Get base URL from client
200
- */
201
- getBaseUrl() {
202
- return this.client.getBaseUrl();
203
- }
204
- }
205
-
206
- var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
207
-
208
- function getDefaultExportFromCjs (x) {
209
- return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
210
- }
211
-
212
- var jsxRuntime = {exports: {}};
213
-
214
- var reactJsxRuntime_production_min = {};
215
-
216
- /**
217
- * @license React
218
- * react-jsx-runtime.production.min.js
219
- *
220
- * Copyright (c) Facebook, Inc. and its affiliates.
221
- *
222
- * This source code is licensed under the MIT license found in the
223
- * LICENSE file in the root directory of this source tree.
224
- */
225
-
226
- var hasRequiredReactJsxRuntime_production_min;
227
-
228
- function requireReactJsxRuntime_production_min () {
229
- if (hasRequiredReactJsxRuntime_production_min) return reactJsxRuntime_production_min;
230
- hasRequiredReactJsxRuntime_production_min = 1;
231
- var f=require$$0,k=Symbol.for("react.element"),l=Symbol.for("react.fragment"),m=Object.prototype.hasOwnProperty,n=f.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,p={key:!0,ref:!0,__self:!0,__source:!0};
232
- function q(c,a,g){var b,d={},e=null,h=null;void 0!==g&&(e=""+g);void 0!==a.key&&(e=""+a.key);void 0!==a.ref&&(h=a.ref);for(b in a)m.call(a,b)&&!p.hasOwnProperty(b)&&(d[b]=a[b]);if(c&&c.defaultProps)for(b in a=c.defaultProps,a)void 0===d[b]&&(d[b]=a[b]);return {$$typeof:k,type:c,key:e,ref:h,props:d,_owner:n.current}}reactJsxRuntime_production_min.Fragment=l;reactJsxRuntime_production_min.jsx=q;reactJsxRuntime_production_min.jsxs=q;
233
- return reactJsxRuntime_production_min;
234
- }
235
-
236
- var reactJsxRuntime_development = {};
237
-
238
- /**
239
- * @license React
240
- * react-jsx-runtime.development.js
241
- *
242
- * Copyright (c) Facebook, Inc. and its affiliates.
243
- *
244
- * This source code is licensed under the MIT license found in the
245
- * LICENSE file in the root directory of this source tree.
246
- */
247
-
248
- var hasRequiredReactJsxRuntime_development;
249
-
250
- function requireReactJsxRuntime_development () {
251
- if (hasRequiredReactJsxRuntime_development) return reactJsxRuntime_development;
252
- hasRequiredReactJsxRuntime_development = 1;
253
-
254
- if (process.env.NODE_ENV !== "production") {
255
- (function() {
256
-
257
- var React = require$$0;
258
-
259
- // ATTENTION
260
- // When adding new symbols to this file,
261
- // Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols'
262
- // The Symbol used to tag the ReactElement-like types.
263
- var REACT_ELEMENT_TYPE = Symbol.for('react.element');
264
- var REACT_PORTAL_TYPE = Symbol.for('react.portal');
265
- var REACT_FRAGMENT_TYPE = Symbol.for('react.fragment');
266
- var REACT_STRICT_MODE_TYPE = Symbol.for('react.strict_mode');
267
- var REACT_PROFILER_TYPE = Symbol.for('react.profiler');
268
- var REACT_PROVIDER_TYPE = Symbol.for('react.provider');
269
- var REACT_CONTEXT_TYPE = Symbol.for('react.context');
270
- var REACT_FORWARD_REF_TYPE = Symbol.for('react.forward_ref');
271
- var REACT_SUSPENSE_TYPE = Symbol.for('react.suspense');
272
- var REACT_SUSPENSE_LIST_TYPE = Symbol.for('react.suspense_list');
273
- var REACT_MEMO_TYPE = Symbol.for('react.memo');
274
- var REACT_LAZY_TYPE = Symbol.for('react.lazy');
275
- var REACT_OFFSCREEN_TYPE = Symbol.for('react.offscreen');
276
- var MAYBE_ITERATOR_SYMBOL = Symbol.iterator;
277
- var FAUX_ITERATOR_SYMBOL = '@@iterator';
278
- function getIteratorFn(maybeIterable) {
279
- if (maybeIterable === null || typeof maybeIterable !== 'object') {
280
- return null;
281
- }
282
-
283
- var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL];
284
-
285
- if (typeof maybeIterator === 'function') {
286
- return maybeIterator;
287
- }
288
-
289
- return null;
290
- }
291
-
292
- var ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
293
-
294
- function error(format) {
295
- {
296
- {
297
- for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
298
- args[_key2 - 1] = arguments[_key2];
299
- }
300
-
301
- printWarning('error', format, args);
302
- }
303
- }
304
- }
305
-
306
- function printWarning(level, format, args) {
307
- // When changing this logic, you might want to also
308
- // update consoleWithStackDev.www.js as well.
309
- {
310
- var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
311
- var stack = ReactDebugCurrentFrame.getStackAddendum();
312
-
313
- if (stack !== '') {
314
- format += '%s';
315
- args = args.concat([stack]);
316
- } // eslint-disable-next-line react-internal/safe-string-coercion
317
-
318
-
319
- var argsWithFormat = args.map(function (item) {
320
- return String(item);
321
- }); // Careful: RN currently depends on this prefix
322
-
323
- argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it
324
- // breaks IE9: https://github.com/facebook/react/issues/13610
325
- // eslint-disable-next-line react-internal/no-production-logging
326
-
327
- Function.prototype.apply.call(console[level], console, argsWithFormat);
328
- }
329
- }
330
-
331
- // -----------------------------------------------------------------------------
332
-
333
- var enableScopeAPI = false; // Experimental Create Event Handle API.
334
- var enableCacheElement = false;
335
- var enableTransitionTracing = false; // No known bugs, but needs performance testing
336
-
337
- var enableLegacyHidden = false; // Enables unstable_avoidThisFallback feature in Fiber
338
- // stuff. Intended to enable React core members to more easily debug scheduling
339
- // issues in DEV builds.
340
-
341
- var enableDebugTracing = false; // Track which Fiber(s) schedule render work.
342
-
343
- var REACT_MODULE_REFERENCE;
344
-
345
- {
346
- REACT_MODULE_REFERENCE = Symbol.for('react.module.reference');
347
- }
348
-
349
- function isValidElementType(type) {
350
- if (typeof type === 'string' || typeof type === 'function') {
351
- return true;
352
- } // Note: typeof might be other than 'symbol' or 'number' (e.g. if it's a polyfill).
353
-
354
-
355
- if (type === REACT_FRAGMENT_TYPE || type === REACT_PROFILER_TYPE || enableDebugTracing || type === REACT_STRICT_MODE_TYPE || type === REACT_SUSPENSE_TYPE || type === REACT_SUSPENSE_LIST_TYPE || enableLegacyHidden || type === REACT_OFFSCREEN_TYPE || enableScopeAPI || enableCacheElement || enableTransitionTracing ) {
356
- return true;
357
- }
358
-
359
- if (typeof type === 'object' && type !== null) {
360
- if (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE || // This needs to include all possible module reference object
361
- // types supported by any Flight configuration anywhere since
362
- // we don't know which Flight build this will end up being used
363
- // with.
364
- type.$$typeof === REACT_MODULE_REFERENCE || type.getModuleId !== undefined) {
365
- return true;
366
- }
367
- }
368
-
369
- return false;
370
- }
371
-
372
- function getWrappedName(outerType, innerType, wrapperName) {
373
- var displayName = outerType.displayName;
374
-
375
- if (displayName) {
376
- return displayName;
377
- }
378
-
379
- var functionName = innerType.displayName || innerType.name || '';
380
- return functionName !== '' ? wrapperName + "(" + functionName + ")" : wrapperName;
381
- } // Keep in sync with react-reconciler/getComponentNameFromFiber
382
-
383
-
384
- function getContextName(type) {
385
- return type.displayName || 'Context';
386
- } // Note that the reconciler package should generally prefer to use getComponentNameFromFiber() instead.
387
-
388
-
389
- function getComponentNameFromType(type) {
390
- if (type == null) {
391
- // Host root, text node or just invalid type.
392
- return null;
393
- }
394
-
395
- {
396
- if (typeof type.tag === 'number') {
397
- error('Received an unexpected object in getComponentNameFromType(). ' + 'This is likely a bug in React. Please file an issue.');
398
- }
399
- }
400
-
401
- if (typeof type === 'function') {
402
- return type.displayName || type.name || null;
403
- }
404
-
405
- if (typeof type === 'string') {
406
- return type;
407
- }
408
-
409
- switch (type) {
410
- case REACT_FRAGMENT_TYPE:
411
- return 'Fragment';
412
-
413
- case REACT_PORTAL_TYPE:
414
- return 'Portal';
415
-
416
- case REACT_PROFILER_TYPE:
417
- return 'Profiler';
418
-
419
- case REACT_STRICT_MODE_TYPE:
420
- return 'StrictMode';
421
-
422
- case REACT_SUSPENSE_TYPE:
423
- return 'Suspense';
424
-
425
- case REACT_SUSPENSE_LIST_TYPE:
426
- return 'SuspenseList';
427
-
428
- }
429
-
430
- if (typeof type === 'object') {
431
- switch (type.$$typeof) {
432
- case REACT_CONTEXT_TYPE:
433
- var context = type;
434
- return getContextName(context) + '.Consumer';
435
-
436
- case REACT_PROVIDER_TYPE:
437
- var provider = type;
438
- return getContextName(provider._context) + '.Provider';
439
-
440
- case REACT_FORWARD_REF_TYPE:
441
- return getWrappedName(type, type.render, 'ForwardRef');
442
-
443
- case REACT_MEMO_TYPE:
444
- var outerName = type.displayName || null;
445
-
446
- if (outerName !== null) {
447
- return outerName;
448
- }
449
-
450
- return getComponentNameFromType(type.type) || 'Memo';
451
-
452
- case REACT_LAZY_TYPE:
453
- {
454
- var lazyComponent = type;
455
- var payload = lazyComponent._payload;
456
- var init = lazyComponent._init;
457
-
458
- try {
459
- return getComponentNameFromType(init(payload));
460
- } catch (x) {
461
- return null;
462
- }
463
- }
464
-
465
- // eslint-disable-next-line no-fallthrough
466
- }
467
- }
468
-
469
- return null;
470
- }
471
-
472
- var assign = Object.assign;
473
-
474
- // Helpers to patch console.logs to avoid logging during side-effect free
475
- // replaying on render function. This currently only patches the object
476
- // lazily which won't cover if the log function was extracted eagerly.
477
- // We could also eagerly patch the method.
478
- var disabledDepth = 0;
479
- var prevLog;
480
- var prevInfo;
481
- var prevWarn;
482
- var prevError;
483
- var prevGroup;
484
- var prevGroupCollapsed;
485
- var prevGroupEnd;
486
-
487
- function disabledLog() {}
488
-
489
- disabledLog.__reactDisabledLog = true;
490
- function disableLogs() {
491
- {
492
- if (disabledDepth === 0) {
493
- /* eslint-disable react-internal/no-production-logging */
494
- prevLog = console.log;
495
- prevInfo = console.info;
496
- prevWarn = console.warn;
497
- prevError = console.error;
498
- prevGroup = console.group;
499
- prevGroupCollapsed = console.groupCollapsed;
500
- prevGroupEnd = console.groupEnd; // https://github.com/facebook/react/issues/19099
501
-
502
- var props = {
503
- configurable: true,
504
- enumerable: true,
505
- value: disabledLog,
506
- writable: true
507
- }; // $FlowFixMe Flow thinks console is immutable.
508
-
509
- Object.defineProperties(console, {
510
- info: props,
511
- log: props,
512
- warn: props,
513
- error: props,
514
- group: props,
515
- groupCollapsed: props,
516
- groupEnd: props
517
- });
518
- /* eslint-enable react-internal/no-production-logging */
519
- }
520
-
521
- disabledDepth++;
522
- }
523
- }
524
- function reenableLogs() {
525
- {
526
- disabledDepth--;
527
-
528
- if (disabledDepth === 0) {
529
- /* eslint-disable react-internal/no-production-logging */
530
- var props = {
531
- configurable: true,
532
- enumerable: true,
533
- writable: true
534
- }; // $FlowFixMe Flow thinks console is immutable.
535
-
536
- Object.defineProperties(console, {
537
- log: assign({}, props, {
538
- value: prevLog
539
- }),
540
- info: assign({}, props, {
541
- value: prevInfo
542
- }),
543
- warn: assign({}, props, {
544
- value: prevWarn
545
- }),
546
- error: assign({}, props, {
547
- value: prevError
548
- }),
549
- group: assign({}, props, {
550
- value: prevGroup
551
- }),
552
- groupCollapsed: assign({}, props, {
553
- value: prevGroupCollapsed
554
- }),
555
- groupEnd: assign({}, props, {
556
- value: prevGroupEnd
557
- })
558
- });
559
- /* eslint-enable react-internal/no-production-logging */
560
- }
561
-
562
- if (disabledDepth < 0) {
563
- error('disabledDepth fell below zero. ' + 'This is a bug in React. Please file an issue.');
564
- }
565
- }
566
- }
567
-
568
- var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher;
569
- var prefix;
570
- function describeBuiltInComponentFrame(name, source, ownerFn) {
571
- {
572
- if (prefix === undefined) {
573
- // Extract the VM specific prefix used by each line.
574
- try {
575
- throw Error();
576
- } catch (x) {
577
- var match = x.stack.trim().match(/\n( *(at )?)/);
578
- prefix = match && match[1] || '';
579
- }
580
- } // We use the prefix to ensure our stacks line up with native stack frames.
581
-
582
-
583
- return '\n' + prefix + name;
584
- }
585
- }
586
- var reentry = false;
587
- var componentFrameCache;
588
-
589
- {
590
- var PossiblyWeakMap = typeof WeakMap === 'function' ? WeakMap : Map;
591
- componentFrameCache = new PossiblyWeakMap();
592
- }
593
-
594
- function describeNativeComponentFrame(fn, construct) {
595
- // If something asked for a stack inside a fake render, it should get ignored.
596
- if ( !fn || reentry) {
597
- return '';
598
- }
599
-
600
- {
601
- var frame = componentFrameCache.get(fn);
602
-
603
- if (frame !== undefined) {
604
- return frame;
605
- }
606
- }
607
-
608
- var control;
609
- reentry = true;
610
- var previousPrepareStackTrace = Error.prepareStackTrace; // $FlowFixMe It does accept undefined.
611
-
612
- Error.prepareStackTrace = undefined;
613
- var previousDispatcher;
614
-
615
- {
616
- previousDispatcher = ReactCurrentDispatcher.current; // Set the dispatcher in DEV because this might be call in the render function
617
- // for warnings.
618
-
619
- ReactCurrentDispatcher.current = null;
620
- disableLogs();
621
- }
622
-
623
- try {
624
- // This should throw.
625
- if (construct) {
626
- // Something should be setting the props in the constructor.
627
- var Fake = function () {
628
- throw Error();
629
- }; // $FlowFixMe
630
-
631
-
632
- Object.defineProperty(Fake.prototype, 'props', {
633
- set: function () {
634
- // We use a throwing setter instead of frozen or non-writable props
635
- // because that won't throw in a non-strict mode function.
636
- throw Error();
637
- }
638
- });
639
-
640
- if (typeof Reflect === 'object' && Reflect.construct) {
641
- // We construct a different control for this case to include any extra
642
- // frames added by the construct call.
643
- try {
644
- Reflect.construct(Fake, []);
645
- } catch (x) {
646
- control = x;
647
- }
648
-
649
- Reflect.construct(fn, [], Fake);
650
- } else {
651
- try {
652
- Fake.call();
653
- } catch (x) {
654
- control = x;
655
- }
656
-
657
- fn.call(Fake.prototype);
658
- }
659
- } else {
660
- try {
661
- throw Error();
662
- } catch (x) {
663
- control = x;
664
- }
665
-
666
- fn();
667
- }
668
- } catch (sample) {
669
- // This is inlined manually because closure doesn't do it for us.
670
- if (sample && control && typeof sample.stack === 'string') {
671
- // This extracts the first frame from the sample that isn't also in the control.
672
- // Skipping one frame that we assume is the frame that calls the two.
673
- var sampleLines = sample.stack.split('\n');
674
- var controlLines = control.stack.split('\n');
675
- var s = sampleLines.length - 1;
676
- var c = controlLines.length - 1;
677
-
678
- while (s >= 1 && c >= 0 && sampleLines[s] !== controlLines[c]) {
679
- // We expect at least one stack frame to be shared.
680
- // Typically this will be the root most one. However, stack frames may be
681
- // cut off due to maximum stack limits. In this case, one maybe cut off
682
- // earlier than the other. We assume that the sample is longer or the same
683
- // and there for cut off earlier. So we should find the root most frame in
684
- // the sample somewhere in the control.
685
- c--;
686
- }
687
-
688
- for (; s >= 1 && c >= 0; s--, c--) {
689
- // Next we find the first one that isn't the same which should be the
690
- // frame that called our sample function and the control.
691
- if (sampleLines[s] !== controlLines[c]) {
692
- // In V8, the first line is describing the message but other VMs don't.
693
- // If we're about to return the first line, and the control is also on the same
694
- // line, that's a pretty good indicator that our sample threw at same line as
695
- // the control. I.e. before we entered the sample frame. So we ignore this result.
696
- // This can happen if you passed a class to function component, or non-function.
697
- if (s !== 1 || c !== 1) {
698
- do {
699
- s--;
700
- c--; // We may still have similar intermediate frames from the construct call.
701
- // The next one that isn't the same should be our match though.
702
-
703
- if (c < 0 || sampleLines[s] !== controlLines[c]) {
704
- // V8 adds a "new" prefix for native classes. Let's remove it to make it prettier.
705
- var _frame = '\n' + sampleLines[s].replace(' at new ', ' at '); // If our component frame is labeled "<anonymous>"
706
- // but we have a user-provided "displayName"
707
- // splice it in to make the stack more readable.
708
-
709
-
710
- if (fn.displayName && _frame.includes('<anonymous>')) {
711
- _frame = _frame.replace('<anonymous>', fn.displayName);
712
- }
713
-
714
- {
715
- if (typeof fn === 'function') {
716
- componentFrameCache.set(fn, _frame);
717
- }
718
- } // Return the line we found.
719
-
720
-
721
- return _frame;
722
- }
723
- } while (s >= 1 && c >= 0);
724
- }
725
-
726
- break;
727
- }
728
- }
729
- }
730
- } finally {
731
- reentry = false;
732
-
733
- {
734
- ReactCurrentDispatcher.current = previousDispatcher;
735
- reenableLogs();
736
- }
737
-
738
- Error.prepareStackTrace = previousPrepareStackTrace;
739
- } // Fallback to just using the name if we couldn't make it throw.
740
-
741
-
742
- var name = fn ? fn.displayName || fn.name : '';
743
- var syntheticFrame = name ? describeBuiltInComponentFrame(name) : '';
744
-
745
- {
746
- if (typeof fn === 'function') {
747
- componentFrameCache.set(fn, syntheticFrame);
748
- }
749
- }
750
-
751
- return syntheticFrame;
752
- }
753
- function describeFunctionComponentFrame(fn, source, ownerFn) {
754
- {
755
- return describeNativeComponentFrame(fn, false);
756
- }
757
- }
758
-
759
- function shouldConstruct(Component) {
760
- var prototype = Component.prototype;
761
- return !!(prototype && prototype.isReactComponent);
762
- }
763
-
764
- function describeUnknownElementTypeFrameInDEV(type, source, ownerFn) {
765
-
766
- if (type == null) {
767
- return '';
768
- }
769
-
770
- if (typeof type === 'function') {
771
- {
772
- return describeNativeComponentFrame(type, shouldConstruct(type));
773
- }
774
- }
775
-
776
- if (typeof type === 'string') {
777
- return describeBuiltInComponentFrame(type);
778
- }
779
-
780
- switch (type) {
781
- case REACT_SUSPENSE_TYPE:
782
- return describeBuiltInComponentFrame('Suspense');
783
-
784
- case REACT_SUSPENSE_LIST_TYPE:
785
- return describeBuiltInComponentFrame('SuspenseList');
786
- }
787
-
788
- if (typeof type === 'object') {
789
- switch (type.$$typeof) {
790
- case REACT_FORWARD_REF_TYPE:
791
- return describeFunctionComponentFrame(type.render);
792
-
793
- case REACT_MEMO_TYPE:
794
- // Memo may contain any component type so we recursively resolve it.
795
- return describeUnknownElementTypeFrameInDEV(type.type, source, ownerFn);
796
-
797
- case REACT_LAZY_TYPE:
798
- {
799
- var lazyComponent = type;
800
- var payload = lazyComponent._payload;
801
- var init = lazyComponent._init;
802
-
803
- try {
804
- // Lazy may contain any component type so we recursively resolve it.
805
- return describeUnknownElementTypeFrameInDEV(init(payload), source, ownerFn);
806
- } catch (x) {}
807
- }
808
- }
809
- }
810
-
811
- return '';
812
- }
813
-
814
- var hasOwnProperty = Object.prototype.hasOwnProperty;
815
-
816
- var loggedTypeFailures = {};
817
- var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
818
-
819
- function setCurrentlyValidatingElement(element) {
820
- {
821
- if (element) {
822
- var owner = element._owner;
823
- var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null);
824
- ReactDebugCurrentFrame.setExtraStackFrame(stack);
825
- } else {
826
- ReactDebugCurrentFrame.setExtraStackFrame(null);
827
- }
828
- }
829
- }
830
-
831
- function checkPropTypes(typeSpecs, values, location, componentName, element) {
832
- {
833
- // $FlowFixMe This is okay but Flow doesn't know it.
834
- var has = Function.call.bind(hasOwnProperty);
835
-
836
- for (var typeSpecName in typeSpecs) {
837
- if (has(typeSpecs, typeSpecName)) {
838
- var error$1 = void 0; // Prop type validation may throw. In case they do, we don't want to
839
- // fail the render phase where it didn't fail before. So we log it.
840
- // After these have been cleaned up, we'll let them throw.
841
-
842
- try {
843
- // This is intentionally an invariant that gets caught. It's the same
844
- // behavior as without this statement except with a better message.
845
- if (typeof typeSpecs[typeSpecName] !== 'function') {
846
- // eslint-disable-next-line react-internal/prod-error-codes
847
- var err = Error((componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' + 'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.' + 'This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.');
848
- err.name = 'Invariant Violation';
849
- throw err;
850
- }
851
-
852
- error$1 = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED');
853
- } catch (ex) {
854
- error$1 = ex;
855
- }
856
-
857
- if (error$1 && !(error$1 instanceof Error)) {
858
- setCurrentlyValidatingElement(element);
859
-
860
- error('%s: type specification of %s' + ' `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', location, typeSpecName, typeof error$1);
861
-
862
- setCurrentlyValidatingElement(null);
863
- }
864
-
865
- if (error$1 instanceof Error && !(error$1.message in loggedTypeFailures)) {
866
- // Only monitor this failure once because there tends to be a lot of the
867
- // same error.
868
- loggedTypeFailures[error$1.message] = true;
869
- setCurrentlyValidatingElement(element);
870
-
871
- error('Failed %s type: %s', location, error$1.message);
872
-
873
- setCurrentlyValidatingElement(null);
874
- }
875
- }
876
- }
877
- }
878
- }
879
-
880
- var isArrayImpl = Array.isArray; // eslint-disable-next-line no-redeclare
881
-
882
- function isArray(a) {
883
- return isArrayImpl(a);
884
- }
885
-
886
- /*
887
- * The `'' + value` pattern (used in in perf-sensitive code) throws for Symbol
888
- * and Temporal.* types. See https://github.com/facebook/react/pull/22064.
889
- *
890
- * The functions in this module will throw an easier-to-understand,
891
- * easier-to-debug exception with a clear errors message message explaining the
892
- * problem. (Instead of a confusing exception thrown inside the implementation
893
- * of the `value` object).
894
- */
895
- // $FlowFixMe only called in DEV, so void return is not possible.
896
- function typeName(value) {
897
- {
898
- // toStringTag is needed for namespaced types like Temporal.Instant
899
- var hasToStringTag = typeof Symbol === 'function' && Symbol.toStringTag;
900
- var type = hasToStringTag && value[Symbol.toStringTag] || value.constructor.name || 'Object';
901
- return type;
902
- }
903
- } // $FlowFixMe only called in DEV, so void return is not possible.
904
-
905
-
906
- function willCoercionThrow(value) {
907
- {
908
- try {
909
- testStringCoercion(value);
910
- return false;
911
- } catch (e) {
912
- return true;
913
- }
914
- }
915
- }
916
-
917
- function testStringCoercion(value) {
918
- // If you ended up here by following an exception call stack, here's what's
919
- // happened: you supplied an object or symbol value to React (as a prop, key,
920
- // DOM attribute, CSS property, string ref, etc.) and when React tried to
921
- // coerce it to a string using `'' + value`, an exception was thrown.
922
- //
923
- // The most common types that will cause this exception are `Symbol` instances
924
- // and Temporal objects like `Temporal.Instant`. But any object that has a
925
- // `valueOf` or `[Symbol.toPrimitive]` method that throws will also cause this
926
- // exception. (Library authors do this to prevent users from using built-in
927
- // numeric operators like `+` or comparison operators like `>=` because custom
928
- // methods are needed to perform accurate arithmetic or comparison.)
929
- //
930
- // To fix the problem, coerce this object or symbol value to a string before
931
- // passing it to React. The most reliable way is usually `String(value)`.
932
- //
933
- // To find which value is throwing, check the browser or debugger console.
934
- // Before this exception was thrown, there should be `console.error` output
935
- // that shows the type (Symbol, Temporal.PlainDate, etc.) that caused the
936
- // problem and how that type was used: key, atrribute, input value prop, etc.
937
- // In most cases, this console output also shows the component and its
938
- // ancestor components where the exception happened.
939
- //
940
- // eslint-disable-next-line react-internal/safe-string-coercion
941
- return '' + value;
942
- }
943
- function checkKeyStringCoercion(value) {
944
- {
945
- if (willCoercionThrow(value)) {
946
- error('The provided key is an unsupported type %s.' + ' This value must be coerced to a string before before using it here.', typeName(value));
947
-
948
- return testStringCoercion(value); // throw (to help callers find troubleshooting comments)
949
- }
950
- }
951
- }
952
-
953
- var ReactCurrentOwner = ReactSharedInternals.ReactCurrentOwner;
954
- var RESERVED_PROPS = {
955
- key: true,
956
- ref: true,
957
- __self: true,
958
- __source: true
959
- };
960
- var specialPropKeyWarningShown;
961
- var specialPropRefWarningShown;
962
- var didWarnAboutStringRefs;
963
-
964
- {
965
- didWarnAboutStringRefs = {};
966
- }
967
-
968
- function hasValidRef(config) {
969
- {
970
- if (hasOwnProperty.call(config, 'ref')) {
971
- var getter = Object.getOwnPropertyDescriptor(config, 'ref').get;
972
-
973
- if (getter && getter.isReactWarning) {
974
- return false;
975
- }
976
- }
977
- }
978
-
979
- return config.ref !== undefined;
980
- }
981
-
982
- function hasValidKey(config) {
983
- {
984
- if (hasOwnProperty.call(config, 'key')) {
985
- var getter = Object.getOwnPropertyDescriptor(config, 'key').get;
986
-
987
- if (getter && getter.isReactWarning) {
988
- return false;
989
- }
990
- }
991
- }
992
-
993
- return config.key !== undefined;
994
- }
995
-
996
- function warnIfStringRefCannotBeAutoConverted(config, self) {
997
- {
998
- if (typeof config.ref === 'string' && ReactCurrentOwner.current && self && ReactCurrentOwner.current.stateNode !== self) {
999
- var componentName = getComponentNameFromType(ReactCurrentOwner.current.type);
1000
-
1001
- if (!didWarnAboutStringRefs[componentName]) {
1002
- error('Component "%s" contains the string ref "%s". ' + 'Support for string refs will be removed in a future major release. ' + 'This case cannot be automatically converted to an arrow function. ' + 'We ask you to manually fix this case by using useRef() or createRef() instead. ' + 'Learn more about using refs safely here: ' + 'https://reactjs.org/link/strict-mode-string-ref', getComponentNameFromType(ReactCurrentOwner.current.type), config.ref);
1003
-
1004
- didWarnAboutStringRefs[componentName] = true;
1005
- }
1006
- }
1007
- }
1008
- }
1009
-
1010
- function defineKeyPropWarningGetter(props, displayName) {
1011
- {
1012
- var warnAboutAccessingKey = function () {
1013
- if (!specialPropKeyWarningShown) {
1014
- specialPropKeyWarningShown = true;
1015
-
1016
- error('%s: `key` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://reactjs.org/link/special-props)', displayName);
1017
- }
1018
- };
1019
-
1020
- warnAboutAccessingKey.isReactWarning = true;
1021
- Object.defineProperty(props, 'key', {
1022
- get: warnAboutAccessingKey,
1023
- configurable: true
1024
- });
1025
- }
1026
- }
1027
-
1028
- function defineRefPropWarningGetter(props, displayName) {
1029
- {
1030
- var warnAboutAccessingRef = function () {
1031
- if (!specialPropRefWarningShown) {
1032
- specialPropRefWarningShown = true;
1033
-
1034
- error('%s: `ref` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://reactjs.org/link/special-props)', displayName);
1035
- }
1036
- };
1037
-
1038
- warnAboutAccessingRef.isReactWarning = true;
1039
- Object.defineProperty(props, 'ref', {
1040
- get: warnAboutAccessingRef,
1041
- configurable: true
1042
- });
1043
- }
1044
- }
1045
- /**
1046
- * Factory method to create a new React element. This no longer adheres to
1047
- * the class pattern, so do not use new to call it. Also, instanceof check
1048
- * will not work. Instead test $$typeof field against Symbol.for('react.element') to check
1049
- * if something is a React Element.
1050
- *
1051
- * @param {*} type
1052
- * @param {*} props
1053
- * @param {*} key
1054
- * @param {string|object} ref
1055
- * @param {*} owner
1056
- * @param {*} self A *temporary* helper to detect places where `this` is
1057
- * different from the `owner` when React.createElement is called, so that we
1058
- * can warn. We want to get rid of owner and replace string `ref`s with arrow
1059
- * functions, and as long as `this` and owner are the same, there will be no
1060
- * change in behavior.
1061
- * @param {*} source An annotation object (added by a transpiler or otherwise)
1062
- * indicating filename, line number, and/or other information.
1063
- * @internal
1064
- */
1065
-
1066
-
1067
- var ReactElement = function (type, key, ref, self, source, owner, props) {
1068
- var element = {
1069
- // This tag allows us to uniquely identify this as a React Element
1070
- $$typeof: REACT_ELEMENT_TYPE,
1071
- // Built-in properties that belong on the element
1072
- type: type,
1073
- key: key,
1074
- ref: ref,
1075
- props: props,
1076
- // Record the component responsible for creating this element.
1077
- _owner: owner
1078
- };
1079
-
1080
- {
1081
- // The validation flag is currently mutative. We put it on
1082
- // an external backing store so that we can freeze the whole object.
1083
- // This can be replaced with a WeakMap once they are implemented in
1084
- // commonly used development environments.
1085
- element._store = {}; // To make comparing ReactElements easier for testing purposes, we make
1086
- // the validation flag non-enumerable (where possible, which should
1087
- // include every environment we run tests in), so the test framework
1088
- // ignores it.
1089
-
1090
- Object.defineProperty(element._store, 'validated', {
1091
- configurable: false,
1092
- enumerable: false,
1093
- writable: true,
1094
- value: false
1095
- }); // self and source are DEV only properties.
1096
-
1097
- Object.defineProperty(element, '_self', {
1098
- configurable: false,
1099
- enumerable: false,
1100
- writable: false,
1101
- value: self
1102
- }); // Two elements created in two different places should be considered
1103
- // equal for testing purposes and therefore we hide it from enumeration.
1104
-
1105
- Object.defineProperty(element, '_source', {
1106
- configurable: false,
1107
- enumerable: false,
1108
- writable: false,
1109
- value: source
1110
- });
1111
-
1112
- if (Object.freeze) {
1113
- Object.freeze(element.props);
1114
- Object.freeze(element);
1115
- }
1116
- }
1117
-
1118
- return element;
1119
- };
1120
- /**
1121
- * https://github.com/reactjs/rfcs/pull/107
1122
- * @param {*} type
1123
- * @param {object} props
1124
- * @param {string} key
1125
- */
1126
-
1127
- function jsxDEV(type, config, maybeKey, source, self) {
1128
- {
1129
- var propName; // Reserved names are extracted
1130
-
1131
- var props = {};
1132
- var key = null;
1133
- var ref = null; // Currently, key can be spread in as a prop. This causes a potential
1134
- // issue if key is also explicitly declared (ie. <div {...props} key="Hi" />
1135
- // or <div key="Hi" {...props} /> ). We want to deprecate key spread,
1136
- // but as an intermediary step, we will use jsxDEV for everything except
1137
- // <div {...props} key="Hi" />, because we aren't currently able to tell if
1138
- // key is explicitly declared to be undefined or not.
1139
-
1140
- if (maybeKey !== undefined) {
1141
- {
1142
- checkKeyStringCoercion(maybeKey);
1143
- }
1144
-
1145
- key = '' + maybeKey;
1146
- }
1147
-
1148
- if (hasValidKey(config)) {
1149
- {
1150
- checkKeyStringCoercion(config.key);
1151
- }
1152
-
1153
- key = '' + config.key;
1154
- }
1155
-
1156
- if (hasValidRef(config)) {
1157
- ref = config.ref;
1158
- warnIfStringRefCannotBeAutoConverted(config, self);
1159
- } // Remaining properties are added to a new props object
1160
-
1161
-
1162
- for (propName in config) {
1163
- if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) {
1164
- props[propName] = config[propName];
1165
- }
1166
- } // Resolve default props
1167
-
1168
-
1169
- if (type && type.defaultProps) {
1170
- var defaultProps = type.defaultProps;
1171
-
1172
- for (propName in defaultProps) {
1173
- if (props[propName] === undefined) {
1174
- props[propName] = defaultProps[propName];
1175
- }
1176
- }
1177
- }
1178
-
1179
- if (key || ref) {
1180
- var displayName = typeof type === 'function' ? type.displayName || type.name || 'Unknown' : type;
1181
-
1182
- if (key) {
1183
- defineKeyPropWarningGetter(props, displayName);
1184
- }
1185
-
1186
- if (ref) {
1187
- defineRefPropWarningGetter(props, displayName);
1188
- }
1189
- }
1190
-
1191
- return ReactElement(type, key, ref, self, source, ReactCurrentOwner.current, props);
1192
- }
1193
- }
1194
-
1195
- var ReactCurrentOwner$1 = ReactSharedInternals.ReactCurrentOwner;
1196
- var ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame;
1197
-
1198
- function setCurrentlyValidatingElement$1(element) {
1199
- {
1200
- if (element) {
1201
- var owner = element._owner;
1202
- var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null);
1203
- ReactDebugCurrentFrame$1.setExtraStackFrame(stack);
1204
- } else {
1205
- ReactDebugCurrentFrame$1.setExtraStackFrame(null);
1206
- }
1207
- }
1208
- }
1209
-
1210
- var propTypesMisspellWarningShown;
1211
-
1212
- {
1213
- propTypesMisspellWarningShown = false;
1214
- }
1215
- /**
1216
- * Verifies the object is a ReactElement.
1217
- * See https://reactjs.org/docs/react-api.html#isvalidelement
1218
- * @param {?object} object
1219
- * @return {boolean} True if `object` is a ReactElement.
1220
- * @final
1221
- */
1222
-
1223
-
1224
- function isValidElement(object) {
1225
- {
1226
- return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE;
1227
- }
1228
- }
1229
-
1230
- function getDeclarationErrorAddendum() {
1231
- {
1232
- if (ReactCurrentOwner$1.current) {
1233
- var name = getComponentNameFromType(ReactCurrentOwner$1.current.type);
1234
-
1235
- if (name) {
1236
- return '\n\nCheck the render method of `' + name + '`.';
1237
- }
1238
- }
1239
-
1240
- return '';
1241
- }
1242
- }
1243
-
1244
- function getSourceInfoErrorAddendum(source) {
1245
- {
1246
- if (source !== undefined) {
1247
- var fileName = source.fileName.replace(/^.*[\\\/]/, '');
1248
- var lineNumber = source.lineNumber;
1249
- return '\n\nCheck your code at ' + fileName + ':' + lineNumber + '.';
1250
- }
1251
-
1252
- return '';
1253
- }
1254
- }
1255
- /**
1256
- * Warn if there's no key explicitly set on dynamic arrays of children or
1257
- * object keys are not valid. This allows us to keep track of children between
1258
- * updates.
1259
- */
1260
-
1261
-
1262
- var ownerHasKeyUseWarning = {};
1263
-
1264
- function getCurrentComponentErrorInfo(parentType) {
1265
- {
1266
- var info = getDeclarationErrorAddendum();
1267
-
1268
- if (!info) {
1269
- var parentName = typeof parentType === 'string' ? parentType : parentType.displayName || parentType.name;
1270
-
1271
- if (parentName) {
1272
- info = "\n\nCheck the top-level render call using <" + parentName + ">.";
1273
- }
1274
- }
1275
-
1276
- return info;
1277
- }
1278
- }
1279
- /**
1280
- * Warn if the element doesn't have an explicit key assigned to it.
1281
- * This element is in an array. The array could grow and shrink or be
1282
- * reordered. All children that haven't already been validated are required to
1283
- * have a "key" property assigned to it. Error statuses are cached so a warning
1284
- * will only be shown once.
1285
- *
1286
- * @internal
1287
- * @param {ReactElement} element Element that requires a key.
1288
- * @param {*} parentType element's parent's type.
1289
- */
1290
-
1291
-
1292
- function validateExplicitKey(element, parentType) {
1293
- {
1294
- if (!element._store || element._store.validated || element.key != null) {
1295
- return;
1296
- }
1297
-
1298
- element._store.validated = true;
1299
- var currentComponentErrorInfo = getCurrentComponentErrorInfo(parentType);
1300
-
1301
- if (ownerHasKeyUseWarning[currentComponentErrorInfo]) {
1302
- return;
1303
- }
1304
-
1305
- ownerHasKeyUseWarning[currentComponentErrorInfo] = true; // Usually the current owner is the offender, but if it accepts children as a
1306
- // property, it may be the creator of the child that's responsible for
1307
- // assigning it a key.
1308
-
1309
- var childOwner = '';
1310
-
1311
- if (element && element._owner && element._owner !== ReactCurrentOwner$1.current) {
1312
- // Give the component that originally created this child.
1313
- childOwner = " It was passed a child from " + getComponentNameFromType(element._owner.type) + ".";
1314
- }
1315
-
1316
- setCurrentlyValidatingElement$1(element);
1317
-
1318
- error('Each child in a list should have a unique "key" prop.' + '%s%s See https://reactjs.org/link/warning-keys for more information.', currentComponentErrorInfo, childOwner);
1319
-
1320
- setCurrentlyValidatingElement$1(null);
1321
- }
1322
- }
1323
- /**
1324
- * Ensure that every element either is passed in a static location, in an
1325
- * array with an explicit keys property defined, or in an object literal
1326
- * with valid key property.
1327
- *
1328
- * @internal
1329
- * @param {ReactNode} node Statically passed child of any type.
1330
- * @param {*} parentType node's parent's type.
1331
- */
1332
-
1333
-
1334
- function validateChildKeys(node, parentType) {
1335
- {
1336
- if (typeof node !== 'object') {
1337
- return;
1338
- }
1339
-
1340
- if (isArray(node)) {
1341
- for (var i = 0; i < node.length; i++) {
1342
- var child = node[i];
1343
-
1344
- if (isValidElement(child)) {
1345
- validateExplicitKey(child, parentType);
1346
- }
1347
- }
1348
- } else if (isValidElement(node)) {
1349
- // This element was passed in a valid location.
1350
- if (node._store) {
1351
- node._store.validated = true;
1352
- }
1353
- } else if (node) {
1354
- var iteratorFn = getIteratorFn(node);
1355
-
1356
- if (typeof iteratorFn === 'function') {
1357
- // Entry iterators used to provide implicit keys,
1358
- // but now we print a separate warning for them later.
1359
- if (iteratorFn !== node.entries) {
1360
- var iterator = iteratorFn.call(node);
1361
- var step;
1362
-
1363
- while (!(step = iterator.next()).done) {
1364
- if (isValidElement(step.value)) {
1365
- validateExplicitKey(step.value, parentType);
1366
- }
1367
- }
1368
- }
1369
- }
1370
- }
1371
- }
1372
- }
1373
- /**
1374
- * Given an element, validate that its props follow the propTypes definition,
1375
- * provided by the type.
1376
- *
1377
- * @param {ReactElement} element
1378
- */
1379
-
1380
-
1381
- function validatePropTypes(element) {
1382
- {
1383
- var type = element.type;
1384
-
1385
- if (type === null || type === undefined || typeof type === 'string') {
1386
- return;
1387
- }
1388
-
1389
- var propTypes;
1390
-
1391
- if (typeof type === 'function') {
1392
- propTypes = type.propTypes;
1393
- } else if (typeof type === 'object' && (type.$$typeof === REACT_FORWARD_REF_TYPE || // Note: Memo only checks outer props here.
1394
- // Inner props are checked in the reconciler.
1395
- type.$$typeof === REACT_MEMO_TYPE)) {
1396
- propTypes = type.propTypes;
1397
- } else {
1398
- return;
1399
- }
1400
-
1401
- if (propTypes) {
1402
- // Intentionally inside to avoid triggering lazy initializers:
1403
- var name = getComponentNameFromType(type);
1404
- checkPropTypes(propTypes, element.props, 'prop', name, element);
1405
- } else if (type.PropTypes !== undefined && !propTypesMisspellWarningShown) {
1406
- propTypesMisspellWarningShown = true; // Intentionally inside to avoid triggering lazy initializers:
1407
-
1408
- var _name = getComponentNameFromType(type);
1409
-
1410
- error('Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?', _name || 'Unknown');
1411
- }
1412
-
1413
- if (typeof type.getDefaultProps === 'function' && !type.getDefaultProps.isReactClassApproved) {
1414
- error('getDefaultProps is only used on classic React.createClass ' + 'definitions. Use a static property named `defaultProps` instead.');
1415
- }
1416
- }
1417
- }
1418
- /**
1419
- * Given a fragment, validate that it can only be provided with fragment props
1420
- * @param {ReactElement} fragment
1421
- */
1422
-
1423
-
1424
- function validateFragmentProps(fragment) {
1425
- {
1426
- var keys = Object.keys(fragment.props);
1427
-
1428
- for (var i = 0; i < keys.length; i++) {
1429
- var key = keys[i];
1430
-
1431
- if (key !== 'children' && key !== 'key') {
1432
- setCurrentlyValidatingElement$1(fragment);
1433
-
1434
- error('Invalid prop `%s` supplied to `React.Fragment`. ' + 'React.Fragment can only have `key` and `children` props.', key);
1435
-
1436
- setCurrentlyValidatingElement$1(null);
1437
- break;
1438
- }
1439
- }
1440
-
1441
- if (fragment.ref !== null) {
1442
- setCurrentlyValidatingElement$1(fragment);
1443
-
1444
- error('Invalid attribute `ref` supplied to `React.Fragment`.');
1445
-
1446
- setCurrentlyValidatingElement$1(null);
1447
- }
1448
- }
1449
- }
1450
-
1451
- var didWarnAboutKeySpread = {};
1452
- function jsxWithValidation(type, props, key, isStaticChildren, source, self) {
1453
- {
1454
- var validType = isValidElementType(type); // We warn in this case but don't throw. We expect the element creation to
1455
- // succeed and there will likely be errors in render.
1456
-
1457
- if (!validType) {
1458
- var info = '';
1459
-
1460
- if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) {
1461
- info += ' You likely forgot to export your component from the file ' + "it's defined in, or you might have mixed up default and named imports.";
1462
- }
1463
-
1464
- var sourceInfo = getSourceInfoErrorAddendum(source);
1465
-
1466
- if (sourceInfo) {
1467
- info += sourceInfo;
1468
- } else {
1469
- info += getDeclarationErrorAddendum();
1470
- }
1471
-
1472
- var typeString;
1473
-
1474
- if (type === null) {
1475
- typeString = 'null';
1476
- } else if (isArray(type)) {
1477
- typeString = 'array';
1478
- } else if (type !== undefined && type.$$typeof === REACT_ELEMENT_TYPE) {
1479
- typeString = "<" + (getComponentNameFromType(type.type) || 'Unknown') + " />";
1480
- info = ' Did you accidentally export a JSX literal instead of a component?';
1481
- } else {
1482
- typeString = typeof type;
1483
- }
1484
-
1485
- error('React.jsx: type is invalid -- expected a string (for ' + 'built-in components) or a class/function (for composite ' + 'components) but got: %s.%s', typeString, info);
1486
- }
1487
-
1488
- var element = jsxDEV(type, props, key, source, self); // The result can be nullish if a mock or a custom function is used.
1489
- // TODO: Drop this when these are no longer allowed as the type argument.
1490
-
1491
- if (element == null) {
1492
- return element;
1493
- } // Skip key warning if the type isn't valid since our key validation logic
1494
- // doesn't expect a non-string/function type and can throw confusing errors.
1495
- // We don't want exception behavior to differ between dev and prod.
1496
- // (Rendering will throw with a helpful message and as soon as the type is
1497
- // fixed, the key warnings will appear.)
1498
-
1499
-
1500
- if (validType) {
1501
- var children = props.children;
1502
-
1503
- if (children !== undefined) {
1504
- if (isStaticChildren) {
1505
- if (isArray(children)) {
1506
- for (var i = 0; i < children.length; i++) {
1507
- validateChildKeys(children[i], type);
1508
- }
1509
-
1510
- if (Object.freeze) {
1511
- Object.freeze(children);
1512
- }
1513
- } else {
1514
- error('React.jsx: Static children should always be an array. ' + 'You are likely explicitly calling React.jsxs or React.jsxDEV. ' + 'Use the Babel transform instead.');
1515
- }
1516
- } else {
1517
- validateChildKeys(children, type);
1518
- }
1519
- }
1520
- }
1521
-
1522
- {
1523
- if (hasOwnProperty.call(props, 'key')) {
1524
- var componentName = getComponentNameFromType(type);
1525
- var keys = Object.keys(props).filter(function (k) {
1526
- return k !== 'key';
1527
- });
1528
- var beforeExample = keys.length > 0 ? '{key: someKey, ' + keys.join(': ..., ') + ': ...}' : '{key: someKey}';
1529
-
1530
- if (!didWarnAboutKeySpread[componentName + beforeExample]) {
1531
- var afterExample = keys.length > 0 ? '{' + keys.join(': ..., ') + ': ...}' : '{}';
1532
-
1533
- error('A props object containing a "key" prop is being spread into JSX:\n' + ' let props = %s;\n' + ' <%s {...props} />\n' + 'React keys must be passed directly to JSX without using spread:\n' + ' let props = %s;\n' + ' <%s key={someKey} {...props} />', beforeExample, componentName, afterExample, componentName);
1534
-
1535
- didWarnAboutKeySpread[componentName + beforeExample] = true;
1536
- }
1537
- }
1538
- }
1539
-
1540
- if (type === REACT_FRAGMENT_TYPE) {
1541
- validateFragmentProps(element);
1542
- } else {
1543
- validatePropTypes(element);
1544
- }
1545
-
1546
- return element;
1547
- }
1548
- } // These two functions exist to still get child warnings in dev
1549
- // even with the prod transform. This means that jsxDEV is purely
1550
- // opt-in behavior for better messages but that we won't stop
1551
- // giving you warnings if you use production apis.
1552
-
1553
- function jsxWithValidationStatic(type, props, key) {
1554
- {
1555
- return jsxWithValidation(type, props, key, true);
1556
- }
1557
- }
1558
- function jsxWithValidationDynamic(type, props, key) {
1559
- {
1560
- return jsxWithValidation(type, props, key, false);
1561
- }
1562
- }
1563
-
1564
- var jsx = jsxWithValidationDynamic ; // we may want to special case jsxs internally to take advantage of static children.
1565
- // for now we can ship identical prod functions
1566
-
1567
- var jsxs = jsxWithValidationStatic ;
1568
-
1569
- reactJsxRuntime_development.Fragment = REACT_FRAGMENT_TYPE;
1570
- reactJsxRuntime_development.jsx = jsx;
1571
- reactJsxRuntime_development.jsxs = jsxs;
1572
- })();
1573
- }
1574
- return reactJsxRuntime_development;
1575
- }
1576
-
1577
- if (process.env.NODE_ENV === 'production') {
1578
- jsxRuntime.exports = requireReactJsxRuntime_production_min();
1579
- } else {
1580
- jsxRuntime.exports = requireReactJsxRuntime_development();
1581
- }
1582
-
1583
- var jsxRuntimeExports = jsxRuntime.exports;
1584
-
1585
- var dist = {};
1586
-
1587
- var useWebsocket = {};
1588
-
1589
- var constants = {};
1590
-
1591
- (function (exports) {
1592
- Object.defineProperty(exports, "__esModule", { value: true });
1593
- exports.isEventSourceSupported = exports.isReactNative = exports.ReadyState = exports.DEFAULT_HEARTBEAT = exports.UNPARSABLE_JSON_OBJECT = exports.DEFAULT_RECONNECT_INTERVAL_MS = exports.DEFAULT_RECONNECT_LIMIT = exports.SOCKET_IO_PING_CODE = exports.SOCKET_IO_PATH = exports.SOCKET_IO_PING_INTERVAL = exports.DEFAULT_EVENT_SOURCE_OPTIONS = exports.EMPTY_EVENT_HANDLERS = exports.DEFAULT_OPTIONS = void 0;
1594
- var MILLISECONDS = 1;
1595
- var SECONDS = 1000 * MILLISECONDS;
1596
- exports.DEFAULT_OPTIONS = {};
1597
- exports.EMPTY_EVENT_HANDLERS = {};
1598
- exports.DEFAULT_EVENT_SOURCE_OPTIONS = {
1599
- withCredentials: false,
1600
- events: exports.EMPTY_EVENT_HANDLERS,
1601
- };
1602
- exports.SOCKET_IO_PING_INTERVAL = 25 * SECONDS;
1603
- exports.SOCKET_IO_PATH = '/socket.io/?EIO=3&transport=websocket';
1604
- exports.SOCKET_IO_PING_CODE = '2';
1605
- exports.DEFAULT_RECONNECT_LIMIT = 20;
1606
- exports.DEFAULT_RECONNECT_INTERVAL_MS = 5000;
1607
- exports.UNPARSABLE_JSON_OBJECT = {};
1608
- exports.DEFAULT_HEARTBEAT = {
1609
- message: 'ping',
1610
- timeout: 60000,
1611
- interval: 25000,
1612
- };
1613
- var ReadyState;
1614
- (function (ReadyState) {
1615
- ReadyState[ReadyState["UNINSTANTIATED"] = -1] = "UNINSTANTIATED";
1616
- ReadyState[ReadyState["CONNECTING"] = 0] = "CONNECTING";
1617
- ReadyState[ReadyState["OPEN"] = 1] = "OPEN";
1618
- ReadyState[ReadyState["CLOSING"] = 2] = "CLOSING";
1619
- ReadyState[ReadyState["CLOSED"] = 3] = "CLOSED";
1620
- })(ReadyState || (exports.ReadyState = ReadyState = {}));
1621
- var eventSourceSupported = function () {
1622
- try {
1623
- return 'EventSource' in globalThis;
1624
- }
1625
- catch (e) {
1626
- return false;
1627
- }
1628
- };
1629
- exports.isReactNative = typeof navigator !== 'undefined' && navigator.product === 'ReactNative';
1630
- exports.isEventSourceSupported = !exports.isReactNative && eventSourceSupported();
1631
-
1632
- } (constants));
1633
-
1634
- var createOrJoin = {};
1635
-
1636
- var globals = {};
1637
-
1638
- (function (exports) {
1639
- Object.defineProperty(exports, "__esModule", { value: true });
1640
- exports.resetWebSockets = exports.sharedWebSockets = void 0;
1641
- exports.sharedWebSockets = {};
1642
- var resetWebSockets = function (url) {
1643
- if (url && exports.sharedWebSockets.hasOwnProperty(url)) {
1644
- delete exports.sharedWebSockets[url];
1645
- }
1646
- else {
1647
- for (var url_1 in exports.sharedWebSockets) {
1648
- if (exports.sharedWebSockets.hasOwnProperty(url_1)) {
1649
- delete exports.sharedWebSockets[url_1];
1650
- }
1651
- }
1652
- }
1653
- };
1654
- exports.resetWebSockets = resetWebSockets;
1655
-
1656
- } (globals));
1657
-
1658
- var attachListener = {};
1659
-
1660
- var socketIo = {};
1661
-
1662
- Object.defineProperty(socketIo, "__esModule", { value: true });
1663
- socketIo.setUpSocketIOPing = socketIo.appendQueryParams = socketIo.parseSocketIOUrl = void 0;
1664
- var constants_1$7 = constants;
1665
- var parseSocketIOUrl = function (url) {
1666
- if (url) {
1667
- var isSecure = /^https|wss/.test(url);
1668
- var strippedProtocol = url.replace(/^(https?|wss?)(:\/\/)?/, '');
1669
- var removedFinalBackSlack = strippedProtocol.replace(/\/$/, '');
1670
- var protocol = isSecure ? 'wss' : 'ws';
1671
- return "".concat(protocol, "://").concat(removedFinalBackSlack).concat(constants_1$7.SOCKET_IO_PATH);
1672
- }
1673
- else if (url === '') {
1674
- var isSecure = /^https/.test(window.location.protocol);
1675
- var protocol = isSecure ? 'wss' : 'ws';
1676
- var port = window.location.port ? ":".concat(window.location.port) : '';
1677
- return "".concat(protocol, "://").concat(window.location.hostname).concat(port).concat(constants_1$7.SOCKET_IO_PATH);
1678
- }
1679
- return url;
1680
- };
1681
- socketIo.parseSocketIOUrl = parseSocketIOUrl;
1682
- var appendQueryParams = function (url, params) {
1683
- if (params === void 0) { params = {}; }
1684
- var hasParamsRegex = /\?([\w]+=[\w]+)/;
1685
- var alreadyHasParams = hasParamsRegex.test(url);
1686
- var stringified = "".concat(Object.entries(params).reduce(function (next, _a) {
1687
- var key = _a[0], value = _a[1];
1688
- return next + "".concat(key, "=").concat(value, "&");
1689
- }, '').slice(0, -1));
1690
- return "".concat(url).concat(alreadyHasParams ? '&' : '?').concat(stringified);
1691
- };
1692
- socketIo.appendQueryParams = appendQueryParams;
1693
- var setUpSocketIOPing = function (sendMessage, interval) {
1694
- if (interval === void 0) { interval = constants_1$7.SOCKET_IO_PING_INTERVAL; }
1695
- var ping = function () { return sendMessage(constants_1$7.SOCKET_IO_PING_CODE); };
1696
- return window.setInterval(ping, interval);
1697
- };
1698
- socketIo.setUpSocketIOPing = setUpSocketIOPing;
1699
-
1700
- var heartbeat$1 = {};
1701
-
1702
- Object.defineProperty(heartbeat$1, "__esModule", { value: true });
1703
- heartbeat$1.heartbeat = heartbeat;
1704
- var constants_1$6 = constants;
1705
- function getLastMessageTime(lastMessageTime) {
1706
- if (Array.isArray(lastMessageTime)) {
1707
- return lastMessageTime.reduce(function (p, c) { return (p.current > c.current) ? p : c; }).current;
1708
- }
1709
- return lastMessageTime.current;
1710
- }
1711
- function heartbeat(ws, lastMessageTime, options) {
1712
- var _a = options || {}, _b = _a.interval, interval = _b === void 0 ? constants_1$6.DEFAULT_HEARTBEAT.interval : _b, _c = _a.timeout, timeout = _c === void 0 ? constants_1$6.DEFAULT_HEARTBEAT.timeout : _c, _d = _a.message, message = _d === void 0 ? constants_1$6.DEFAULT_HEARTBEAT.message : _d;
1713
- // how often check interval between ping messages
1714
- // minimum is 100ms
1715
- // maximum is ${interval / 10}ms
1716
- var intervalCheck = Math.max(100, interval / 10);
1717
- var lastPingSentAt = Date.now();
1718
- var heartbeatInterval = setInterval(function () {
1719
- var timeNow = Date.now();
1720
- var lastMessageReceivedAt = getLastMessageTime(lastMessageTime);
1721
- if (lastMessageReceivedAt + timeout <= timeNow) {
1722
- console.warn("Heartbeat timed out, closing connection, last message received ".concat(timeNow - lastMessageReceivedAt, "ms ago, last ping sent ").concat(timeNow - lastPingSentAt, "ms ago"));
1723
- ws.close();
1724
- }
1725
- else {
1726
- if (lastMessageReceivedAt + interval <= timeNow && lastPingSentAt + interval <= timeNow) {
1727
- try {
1728
- if (typeof message === 'function') {
1729
- ws.send(message());
1730
- }
1731
- else {
1732
- ws.send(message);
1733
- }
1734
- lastPingSentAt = timeNow;
1735
- }
1736
- catch (err) {
1737
- console.error("Heartbeat failed, closing connection", err instanceof Error ? err.message : err);
1738
- ws.close();
1739
- }
1740
- }
1741
- }
1742
- }, intervalCheck);
1743
- ws.addEventListener("close", function () {
1744
- clearInterval(heartbeatInterval);
1745
- });
1746
- return function () { };
1747
- }
1748
-
1749
- var util = {};
1750
-
1751
- var manageSubscribers = {};
1752
-
1753
- (function (exports) {
1754
- Object.defineProperty(exports, "__esModule", { value: true });
1755
- exports.resetSubscribers = exports.removeSubscriber = exports.addSubscriber = exports.hasSubscribers = exports.getSubscribers = void 0;
1756
- var subscribers = {};
1757
- var EMPTY_LIST = [];
1758
- var getSubscribers = function (url) {
1759
- if ((0, exports.hasSubscribers)(url)) {
1760
- return Array.from(subscribers[url]);
1761
- }
1762
- return EMPTY_LIST;
1763
- };
1764
- exports.getSubscribers = getSubscribers;
1765
- var hasSubscribers = function (url) {
1766
- var _a;
1767
- return ((_a = subscribers[url]) === null || _a === void 0 ? void 0 : _a.size) > 0;
1768
- };
1769
- exports.hasSubscribers = hasSubscribers;
1770
- var addSubscriber = function (url, subscriber) {
1771
- subscribers[url] = subscribers[url] || new Set();
1772
- subscribers[url].add(subscriber);
1773
- };
1774
- exports.addSubscriber = addSubscriber;
1775
- var removeSubscriber = function (url, subscriber) {
1776
- subscribers[url].delete(subscriber);
1777
- };
1778
- exports.removeSubscriber = removeSubscriber;
1779
- var resetSubscribers = function (url) {
1780
- if (url && subscribers.hasOwnProperty(url)) {
1781
- delete subscribers[url];
1782
- }
1783
- else {
1784
- for (var url_1 in subscribers) {
1785
- if (subscribers.hasOwnProperty(url_1)) {
1786
- delete subscribers[url_1];
1787
- }
1788
- }
1789
- }
1790
- };
1791
- exports.resetSubscribers = resetSubscribers;
1792
-
1793
- } (manageSubscribers));
1794
-
1795
- Object.defineProperty(util, "__esModule", { value: true });
1796
- util.assertIsWebSocket = assertIsWebSocket;
1797
- util.resetGlobalState = resetGlobalState;
1798
- var globals_1$2 = globals;
1799
- var manage_subscribers_1$2 = manageSubscribers;
1800
- function assertIsWebSocket(webSocketInstance, skip) {
1801
- if (!skip && webSocketInstance instanceof WebSocket === false)
1802
- throw new Error('');
1803
- }
1804
- function resetGlobalState(url) {
1805
- (0, manage_subscribers_1$2.resetSubscribers)(url);
1806
- (0, globals_1$2.resetWebSockets)(url);
1807
- }
1808
-
1809
- var __assign$4 = (commonjsGlobal && commonjsGlobal.__assign) || function () {
1810
- __assign$4 = Object.assign || function(t) {
1811
- for (var s, i = 1, n = arguments.length; i < n; i++) {
1812
- s = arguments[i];
1813
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
1814
- t[p] = s[p];
1815
- }
1816
- return t;
1817
- };
1818
- return __assign$4.apply(this, arguments);
1819
- };
1820
- Object.defineProperty(attachListener, "__esModule", { value: true });
1821
- attachListener.attachListeners = void 0;
1822
- var socket_io_1$1 = socketIo;
1823
- var heartbeat_1$1 = heartbeat$1;
1824
- var constants_1$5 = constants;
1825
- var util_1$1 = util;
1826
- var bindMessageHandler$1 = function (webSocketInstance, optionsRef, setLastMessage, lastMessageTime) {
1827
- webSocketInstance.onmessage = function (message) {
1828
- var _a;
1829
- optionsRef.current.onMessage && optionsRef.current.onMessage(message);
1830
- if (typeof (lastMessageTime === null || lastMessageTime === void 0 ? void 0 : lastMessageTime.current) === 'number') {
1831
- lastMessageTime.current = Date.now();
1832
- }
1833
- if (typeof optionsRef.current.filter === 'function' && optionsRef.current.filter(message) !== true) {
1834
- return;
1835
- }
1836
- if (optionsRef.current.heartbeat &&
1837
- typeof optionsRef.current.heartbeat !== "boolean" &&
1838
- ((_a = optionsRef.current.heartbeat) === null || _a === void 0 ? void 0 : _a.returnMessage) === message.data) {
1839
- return;
1840
- }
1841
- setLastMessage(message);
1842
- };
1843
- };
1844
- var bindOpenHandler$1 = function (webSocketInstance, optionsRef, setReadyState, reconnectCount, lastMessageTime) {
1845
- webSocketInstance.onopen = function (event) {
1846
- optionsRef.current.onOpen && optionsRef.current.onOpen(event);
1847
- reconnectCount.current = 0;
1848
- setReadyState(constants_1$5.ReadyState.OPEN);
1849
- //start heart beat here
1850
- if (optionsRef.current.heartbeat && webSocketInstance instanceof WebSocket) {
1851
- var heartbeatOptions = typeof optionsRef.current.heartbeat === "boolean"
1852
- ? undefined
1853
- : optionsRef.current.heartbeat;
1854
- lastMessageTime.current = Date.now();
1855
- (0, heartbeat_1$1.heartbeat)(webSocketInstance, lastMessageTime, heartbeatOptions);
1856
- }
1857
- };
1858
- };
1859
- var bindCloseHandler$1 = function (webSocketInstance, optionsRef, setReadyState, reconnect, reconnectCount) {
1860
- if (constants_1$5.isEventSourceSupported && webSocketInstance instanceof EventSource) {
1861
- return function () { };
1862
- }
1863
- (0, util_1$1.assertIsWebSocket)(webSocketInstance, optionsRef.current.skipAssert);
1864
- var reconnectTimeout;
1865
- webSocketInstance.onclose = function (event) {
1866
- var _a;
1867
- optionsRef.current.onClose && optionsRef.current.onClose(event);
1868
- setReadyState(constants_1$5.ReadyState.CLOSED);
1869
- if (optionsRef.current.shouldReconnect && optionsRef.current.shouldReconnect(event)) {
1870
- var reconnectAttempts = (_a = optionsRef.current.reconnectAttempts) !== null && _a !== void 0 ? _a : constants_1$5.DEFAULT_RECONNECT_LIMIT;
1871
- if (reconnectCount.current < reconnectAttempts) {
1872
- var nextReconnectInterval = typeof optionsRef.current.reconnectInterval === 'function' ?
1873
- optionsRef.current.reconnectInterval(reconnectCount.current) :
1874
- optionsRef.current.reconnectInterval;
1875
- reconnectTimeout = window.setTimeout(function () {
1876
- reconnectCount.current++;
1877
- reconnect();
1878
- }, nextReconnectInterval !== null && nextReconnectInterval !== void 0 ? nextReconnectInterval : constants_1$5.DEFAULT_RECONNECT_INTERVAL_MS);
1879
- }
1880
- else {
1881
- optionsRef.current.onReconnectStop && optionsRef.current.onReconnectStop(reconnectAttempts);
1882
- console.warn("Max reconnect attempts of ".concat(reconnectAttempts, " exceeded"));
1883
- }
1884
- }
1885
- };
1886
- return function () { return reconnectTimeout && window.clearTimeout(reconnectTimeout); };
1887
- };
1888
- var bindErrorHandler$1 = function (webSocketInstance, optionsRef, setReadyState, reconnect, reconnectCount) {
1889
- var reconnectTimeout;
1890
- webSocketInstance.onerror = function (error) {
1891
- var _a;
1892
- optionsRef.current.onError && optionsRef.current.onError(error);
1893
- if (constants_1$5.isEventSourceSupported && webSocketInstance instanceof EventSource) {
1894
- optionsRef.current.onClose && optionsRef.current.onClose(__assign$4(__assign$4({}, error), { code: 1006, reason: "An error occurred with the EventSource: ".concat(error), wasClean: false }));
1895
- setReadyState(constants_1$5.ReadyState.CLOSED);
1896
- webSocketInstance.close();
1897
- }
1898
- if (optionsRef.current.retryOnError) {
1899
- if (reconnectCount.current < ((_a = optionsRef.current.reconnectAttempts) !== null && _a !== void 0 ? _a : constants_1$5.DEFAULT_RECONNECT_LIMIT)) {
1900
- var nextReconnectInterval = typeof optionsRef.current.reconnectInterval === 'function' ?
1901
- optionsRef.current.reconnectInterval(reconnectCount.current) :
1902
- optionsRef.current.reconnectInterval;
1903
- reconnectTimeout = window.setTimeout(function () {
1904
- reconnectCount.current++;
1905
- reconnect();
1906
- }, nextReconnectInterval !== null && nextReconnectInterval !== void 0 ? nextReconnectInterval : constants_1$5.DEFAULT_RECONNECT_INTERVAL_MS);
1907
- }
1908
- else {
1909
- optionsRef.current.onReconnectStop && optionsRef.current.onReconnectStop(optionsRef.current.reconnectAttempts);
1910
- console.warn("Max reconnect attempts of ".concat(optionsRef.current.reconnectAttempts, " exceeded"));
1911
- }
1912
- }
1913
- };
1914
- return function () { return reconnectTimeout && window.clearTimeout(reconnectTimeout); };
1915
- };
1916
- var attachListeners = function (webSocketInstance, setters, optionsRef, reconnect, reconnectCount, lastMessageTime, sendMessage) {
1917
- var setLastMessage = setters.setLastMessage, setReadyState = setters.setReadyState;
1918
- var interval;
1919
- var cancelReconnectOnClose;
1920
- var cancelReconnectOnError;
1921
- if (optionsRef.current.fromSocketIO) {
1922
- interval = (0, socket_io_1$1.setUpSocketIOPing)(sendMessage);
1923
- }
1924
- bindMessageHandler$1(webSocketInstance, optionsRef, setLastMessage, lastMessageTime);
1925
- bindOpenHandler$1(webSocketInstance, optionsRef, setReadyState, reconnectCount, lastMessageTime);
1926
- cancelReconnectOnClose = bindCloseHandler$1(webSocketInstance, optionsRef, setReadyState, reconnect, reconnectCount);
1927
- cancelReconnectOnError = bindErrorHandler$1(webSocketInstance, optionsRef, setReadyState, reconnect, reconnectCount);
1928
- return function () {
1929
- setReadyState(constants_1$5.ReadyState.CLOSING);
1930
- cancelReconnectOnClose();
1931
- cancelReconnectOnError();
1932
- webSocketInstance.close();
1933
- if (interval)
1934
- clearInterval(interval);
1935
- };
1936
- };
1937
- attachListener.attachListeners = attachListeners;
1938
-
1939
- var attachSharedListeners$1 = {};
1940
-
1941
- var __assign$3 = (commonjsGlobal && commonjsGlobal.__assign) || function () {
1942
- __assign$3 = Object.assign || function(t) {
1943
- for (var s, i = 1, n = arguments.length; i < n; i++) {
1944
- s = arguments[i];
1945
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
1946
- t[p] = s[p];
1947
- }
1948
- return t;
1949
- };
1950
- return __assign$3.apply(this, arguments);
1951
- };
1952
- Object.defineProperty(attachSharedListeners$1, "__esModule", { value: true });
1953
- attachSharedListeners$1.attachSharedListeners = void 0;
1954
- var globals_1$1 = globals;
1955
- var constants_1$4 = constants;
1956
- var manage_subscribers_1$1 = manageSubscribers;
1957
- var socket_io_1 = socketIo;
1958
- var heartbeat_1 = heartbeat$1;
1959
- var bindMessageHandler = function (webSocketInstance, url, heartbeatOptions) {
1960
- webSocketInstance.onmessage = function (message) {
1961
- (0, manage_subscribers_1$1.getSubscribers)(url).forEach(function (subscriber) {
1962
- var _a;
1963
- if (subscriber.optionsRef.current.onMessage) {
1964
- subscriber.optionsRef.current.onMessage(message);
1965
- }
1966
- if (typeof ((_a = subscriber === null || subscriber === void 0 ? void 0 : subscriber.lastMessageTime) === null || _a === void 0 ? void 0 : _a.current) === 'number') {
1967
- subscriber.lastMessageTime.current = Date.now();
1968
- }
1969
- if (typeof subscriber.optionsRef.current.filter === 'function' &&
1970
- subscriber.optionsRef.current.filter(message) !== true) {
1971
- return;
1972
- }
1973
- if (heartbeatOptions &&
1974
- typeof heartbeatOptions !== "boolean" &&
1975
- (heartbeatOptions === null || heartbeatOptions === void 0 ? void 0 : heartbeatOptions.returnMessage) === message.data)
1976
- return;
1977
- subscriber.setLastMessage(message);
1978
- });
1979
- };
1980
- };
1981
- var bindOpenHandler = function (webSocketInstance, url, heartbeatOptions) {
1982
- webSocketInstance.onopen = function (event) {
1983
- var subscribers = (0, manage_subscribers_1$1.getSubscribers)(url);
1984
- subscribers.forEach(function (subscriber) {
1985
- subscriber.reconnectCount.current = 0;
1986
- if (subscriber.optionsRef.current.onOpen) {
1987
- subscriber.optionsRef.current.onOpen(event);
1988
- }
1989
- subscriber.setReadyState(constants_1$4.ReadyState.OPEN);
1990
- if (heartbeatOptions && webSocketInstance instanceof WebSocket) {
1991
- subscriber.lastMessageTime.current = Date.now();
1992
- }
1993
- });
1994
- if (heartbeatOptions && webSocketInstance instanceof WebSocket) {
1995
- (0, heartbeat_1.heartbeat)(webSocketInstance, subscribers.map(function (subscriber) { return subscriber.lastMessageTime; }), typeof heartbeatOptions === 'boolean' ? undefined : heartbeatOptions);
1996
- }
1997
- };
1998
- };
1999
- var bindCloseHandler = function (webSocketInstance, url) {
2000
- if (webSocketInstance instanceof WebSocket) {
2001
- webSocketInstance.onclose = function (event) {
2002
- (0, manage_subscribers_1$1.getSubscribers)(url).forEach(function (subscriber) {
2003
- if (subscriber.optionsRef.current.onClose) {
2004
- subscriber.optionsRef.current.onClose(event);
2005
- }
2006
- subscriber.setReadyState(constants_1$4.ReadyState.CLOSED);
2007
- });
2008
- delete globals_1$1.sharedWebSockets[url];
2009
- (0, manage_subscribers_1$1.getSubscribers)(url).forEach(function (subscriber) {
2010
- var _a;
2011
- if (subscriber.optionsRef.current.shouldReconnect &&
2012
- subscriber.optionsRef.current.shouldReconnect(event)) {
2013
- var reconnectAttempts = (_a = subscriber.optionsRef.current.reconnectAttempts) !== null && _a !== void 0 ? _a : constants_1$4.DEFAULT_RECONNECT_LIMIT;
2014
- if (subscriber.reconnectCount.current < reconnectAttempts) {
2015
- var nextReconnectInterval = typeof subscriber.optionsRef.current.reconnectInterval === 'function' ?
2016
- subscriber.optionsRef.current.reconnectInterval(subscriber.reconnectCount.current) :
2017
- subscriber.optionsRef.current.reconnectInterval;
2018
- setTimeout(function () {
2019
- subscriber.reconnectCount.current++;
2020
- subscriber.reconnect.current();
2021
- }, nextReconnectInterval !== null && nextReconnectInterval !== void 0 ? nextReconnectInterval : constants_1$4.DEFAULT_RECONNECT_INTERVAL_MS);
2022
- }
2023
- else {
2024
- subscriber.optionsRef.current.onReconnectStop && subscriber.optionsRef.current.onReconnectStop(subscriber.optionsRef.current.reconnectAttempts);
2025
- console.warn("Max reconnect attempts of ".concat(reconnectAttempts, " exceeded"));
2026
- }
2027
- }
2028
- });
2029
- };
2030
- }
2031
- };
2032
- var bindErrorHandler = function (webSocketInstance, url) {
2033
- webSocketInstance.onerror = function (error) {
2034
- (0, manage_subscribers_1$1.getSubscribers)(url).forEach(function (subscriber) {
2035
- if (subscriber.optionsRef.current.onError) {
2036
- subscriber.optionsRef.current.onError(error);
2037
- }
2038
- if (constants_1$4.isEventSourceSupported && webSocketInstance instanceof EventSource) {
2039
- subscriber.optionsRef.current.onClose && subscriber.optionsRef.current.onClose(__assign$3(__assign$3({}, error), { code: 1006, reason: "An error occurred with the EventSource: ".concat(error), wasClean: false }));
2040
- subscriber.setReadyState(constants_1$4.ReadyState.CLOSED);
2041
- }
2042
- });
2043
- if (constants_1$4.isEventSourceSupported && webSocketInstance instanceof EventSource) {
2044
- webSocketInstance.close();
2045
- }
2046
- };
2047
- };
2048
- var attachSharedListeners = function (webSocketInstance, url, optionsRef, sendMessage) {
2049
- var interval;
2050
- if (optionsRef.current.fromSocketIO) {
2051
- interval = (0, socket_io_1.setUpSocketIOPing)(sendMessage);
2052
- }
2053
- bindMessageHandler(webSocketInstance, url, optionsRef.current.heartbeat);
2054
- bindCloseHandler(webSocketInstance, url);
2055
- bindOpenHandler(webSocketInstance, url, optionsRef.current.heartbeat);
2056
- bindErrorHandler(webSocketInstance, url);
2057
- return function () {
2058
- if (interval)
2059
- clearInterval(interval);
2060
- };
2061
- };
2062
- attachSharedListeners$1.attachSharedListeners = attachSharedListeners;
2063
-
2064
- Object.defineProperty(createOrJoin, "__esModule", { value: true });
2065
- createOrJoin.createOrJoinSocket = void 0;
2066
- var globals_1 = globals;
2067
- var constants_1$3 = constants;
2068
- var attach_listener_1 = attachListener;
2069
- var attach_shared_listeners_1 = attachSharedListeners$1;
2070
- var manage_subscribers_1 = manageSubscribers;
2071
- //TODO ensure that all onClose callbacks are called
2072
- var cleanSubscribers = function (url, subscriber, optionsRef, setReadyState, clearSocketIoPingInterval) {
2073
- return function () {
2074
- (0, manage_subscribers_1.removeSubscriber)(url, subscriber);
2075
- if (!(0, manage_subscribers_1.hasSubscribers)(url)) {
2076
- try {
2077
- var socketLike = globals_1.sharedWebSockets[url];
2078
- if (socketLike instanceof WebSocket) {
2079
- socketLike.onclose = function (event) {
2080
- if (optionsRef.current.onClose) {
2081
- optionsRef.current.onClose(event);
2082
- }
2083
- setReadyState(constants_1$3.ReadyState.CLOSED);
2084
- };
2085
- }
2086
- socketLike.close();
2087
- }
2088
- catch (e) {
2089
- }
2090
- if (clearSocketIoPingInterval)
2091
- clearSocketIoPingInterval();
2092
- delete globals_1.sharedWebSockets[url];
2093
- }
2094
- };
2095
- };
2096
- var createOrJoinSocket = function (webSocketRef, url, setReadyState, optionsRef, setLastMessage, startRef, reconnectCount, lastMessageTime, sendMessage) {
2097
- if (!constants_1$3.isEventSourceSupported && optionsRef.current.eventSourceOptions) {
2098
- if (constants_1$3.isReactNative) {
2099
- throw new Error('EventSource is not supported in ReactNative');
2100
- }
2101
- else {
2102
- throw new Error('EventSource is not supported');
2103
- }
2104
- }
2105
- if (optionsRef.current.share) {
2106
- var clearSocketIoPingInterval = null;
2107
- if (globals_1.sharedWebSockets[url] === undefined) {
2108
- globals_1.sharedWebSockets[url] = optionsRef.current.eventSourceOptions ?
2109
- new EventSource(url, optionsRef.current.eventSourceOptions) :
2110
- new WebSocket(url, optionsRef.current.protocols);
2111
- webSocketRef.current = globals_1.sharedWebSockets[url];
2112
- setReadyState(constants_1$3.ReadyState.CONNECTING);
2113
- clearSocketIoPingInterval = (0, attach_shared_listeners_1.attachSharedListeners)(globals_1.sharedWebSockets[url], url, optionsRef, sendMessage);
2114
- }
2115
- else {
2116
- webSocketRef.current = globals_1.sharedWebSockets[url];
2117
- setReadyState(globals_1.sharedWebSockets[url].readyState);
2118
- }
2119
- var subscriber = {
2120
- setLastMessage: setLastMessage,
2121
- setReadyState: setReadyState,
2122
- optionsRef: optionsRef,
2123
- reconnectCount: reconnectCount,
2124
- lastMessageTime: lastMessageTime,
2125
- reconnect: startRef,
2126
- };
2127
- (0, manage_subscribers_1.addSubscriber)(url, subscriber);
2128
- return cleanSubscribers(url, subscriber, optionsRef, setReadyState, clearSocketIoPingInterval);
2129
- }
2130
- else {
2131
- webSocketRef.current = optionsRef.current.eventSourceOptions ?
2132
- new EventSource(url, optionsRef.current.eventSourceOptions) :
2133
- new WebSocket(url, optionsRef.current.protocols);
2134
- setReadyState(constants_1$3.ReadyState.CONNECTING);
2135
- if (!webSocketRef.current) {
2136
- throw new Error('WebSocket failed to be created');
2137
- }
2138
- return (0, attach_listener_1.attachListeners)(webSocketRef.current, {
2139
- setLastMessage: setLastMessage,
2140
- setReadyState: setReadyState
2141
- }, optionsRef, startRef.current, reconnectCount, lastMessageTime, sendMessage);
2142
- }
2143
- };
2144
- createOrJoin.createOrJoinSocket = createOrJoinSocket;
2145
-
2146
- var getUrl = {};
2147
-
2148
- (function (exports) {
2149
- var __awaiter = (commonjsGlobal && commonjsGlobal.__awaiter) || function (thisArg, _arguments, P, generator) {
2150
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
2151
- return new (P || (P = Promise))(function (resolve, reject) {
2152
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
2153
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
2154
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
2155
- step((generator = generator.apply(thisArg, _arguments || [])).next());
2156
- });
2157
- };
2158
- var __generator = (commonjsGlobal && commonjsGlobal.__generator) || function (thisArg, body) {
2159
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
2160
- return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
2161
- function verb(n) { return function (v) { return step([n, v]); }; }
2162
- function step(op) {
2163
- if (f) throw new TypeError("Generator is already executing.");
2164
- while (g && (g = 0, op[0] && (_ = 0)), _) try {
2165
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
2166
- if (y = 0, t) op = [op[0] & 2, t.value];
2167
- switch (op[0]) {
2168
- case 0: case 1: t = op; break;
2169
- case 4: _.label++; return { value: op[1], done: false };
2170
- case 5: _.label++; y = op[1]; op = [0]; continue;
2171
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
2172
- default:
2173
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
2174
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
2175
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
2176
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
2177
- if (t[2]) _.ops.pop();
2178
- _.trys.pop(); continue;
2179
- }
2180
- op = body.call(thisArg, _);
2181
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
2182
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
2183
- }
2184
- };
2185
- var __spreadArray = (commonjsGlobal && commonjsGlobal.__spreadArray) || function (to, from, pack) {
2186
- if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
2187
- if (ar || !(i in from)) {
2188
- if (!ar) ar = Array.prototype.slice.call(from, 0, i);
2189
- ar[i] = from[i];
2190
- }
2191
- }
2192
- return to.concat(ar || Array.prototype.slice.call(from));
2193
- };
2194
- Object.defineProperty(exports, "__esModule", { value: true });
2195
- exports.getUrl = void 0;
2196
- var socket_io_1 = socketIo;
2197
- var constants_1 = constants;
2198
- var waitFor = function (duration) { return new Promise(function (resolve) { return window.setTimeout(resolve, duration); }); };
2199
- var getUrl = function (url_1, optionsRef_1) {
2200
- var args_1 = [];
2201
- for (var _i = 2; _i < arguments.length; _i++) {
2202
- args_1[_i - 2] = arguments[_i];
2203
- }
2204
- return __awaiter(void 0, __spreadArray([url_1, optionsRef_1], args_1, true), void 0, function (url, optionsRef, retriedAttempts) {
2205
- var convertedUrl, reconnectLimit, nextReconnectInterval, parsedUrl, parsedWithQueryParams;
2206
- var _a, _b, _c;
2207
- if (retriedAttempts === void 0) { retriedAttempts = 0; }
2208
- return __generator(this, function (_d) {
2209
- switch (_d.label) {
2210
- case 0:
2211
- if (!(typeof url === 'function')) return [3 /*break*/, 10];
2212
- _d.label = 1;
2213
- case 1:
2214
- _d.trys.push([1, 3, , 9]);
2215
- return [4 /*yield*/, url()];
2216
- case 2:
2217
- convertedUrl = _d.sent();
2218
- return [3 /*break*/, 9];
2219
- case 3:
2220
- _d.sent();
2221
- if (!optionsRef.current.retryOnError) return [3 /*break*/, 7];
2222
- reconnectLimit = (_a = optionsRef.current.reconnectAttempts) !== null && _a !== void 0 ? _a : constants_1.DEFAULT_RECONNECT_LIMIT;
2223
- if (!(retriedAttempts < reconnectLimit)) return [3 /*break*/, 5];
2224
- nextReconnectInterval = typeof optionsRef.current.reconnectInterval === 'function' ?
2225
- optionsRef.current.reconnectInterval(retriedAttempts) :
2226
- optionsRef.current.reconnectInterval;
2227
- return [4 /*yield*/, waitFor(nextReconnectInterval !== null && nextReconnectInterval !== void 0 ? nextReconnectInterval : constants_1.DEFAULT_RECONNECT_INTERVAL_MS)];
2228
- case 4:
2229
- _d.sent();
2230
- return [2 /*return*/, (0, exports.getUrl)(url, optionsRef, retriedAttempts + 1)];
2231
- case 5:
2232
- (_c = (_b = optionsRef.current).onReconnectStop) === null || _c === void 0 ? void 0 : _c.call(_b, retriedAttempts);
2233
- return [2 /*return*/, null];
2234
- case 6: return [3 /*break*/, 8];
2235
- case 7: return [2 /*return*/, null];
2236
- case 8: return [3 /*break*/, 9];
2237
- case 9: return [3 /*break*/, 11];
2238
- case 10:
2239
- convertedUrl = url;
2240
- _d.label = 11;
2241
- case 11:
2242
- parsedUrl = optionsRef.current.fromSocketIO ?
2243
- (0, socket_io_1.parseSocketIOUrl)(convertedUrl) :
2244
- convertedUrl;
2245
- parsedWithQueryParams = optionsRef.current.queryParams ?
2246
- (0, socket_io_1.appendQueryParams)(parsedUrl, optionsRef.current.queryParams) :
2247
- parsedUrl;
2248
- return [2 /*return*/, parsedWithQueryParams];
2249
- }
2250
- });
2251
- });
2252
- };
2253
- exports.getUrl = getUrl;
2254
-
2255
- } (getUrl));
2256
-
2257
- var proxy = {};
2258
-
2259
- (function (exports) {
2260
- Object.defineProperty(exports, "__esModule", { value: true });
2261
- exports.websocketWrapper = void 0;
2262
- var websocketWrapper = function (webSocket, start) {
2263
- return new Proxy(webSocket, {
2264
- get: function (obj, key) {
2265
- var val = obj[key];
2266
- if (key === 'reconnect')
2267
- return start;
2268
- if (typeof val === 'function') {
2269
- console.error('Calling methods directly on the websocket is not supported at this moment. You must use the methods returned by useWebSocket.');
2270
- //Prevent error thrown by invoking a non-function
2271
- return function () { };
2272
- }
2273
- else {
2274
- return val;
2275
- }
2276
- },
2277
- set: function (obj, key, val) {
2278
- if (/^on/.test(key)) {
2279
- console.warn('The websocket\'s event handlers should be defined through the options object passed into useWebSocket.');
2280
- return false;
2281
- }
2282
- else {
2283
- obj[key] = val;
2284
- return true;
2285
- }
2286
- },
2287
- });
2288
- };
2289
- exports.websocketWrapper = websocketWrapper;
2290
- exports.default = exports.websocketWrapper;
2291
-
2292
- } (proxy));
2293
-
2294
- var __assign$2 = (commonjsGlobal && commonjsGlobal.__assign) || function () {
2295
- __assign$2 = Object.assign || function(t) {
2296
- for (var s, i = 1, n = arguments.length; i < n; i++) {
2297
- s = arguments[i];
2298
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
2299
- t[p] = s[p];
2300
- }
2301
- return t;
2302
- };
2303
- return __assign$2.apply(this, arguments);
2304
- };
2305
- var __awaiter = (commonjsGlobal && commonjsGlobal.__awaiter) || function (thisArg, _arguments, P, generator) {
2306
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
2307
- return new (P || (P = Promise))(function (resolve, reject) {
2308
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
2309
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
2310
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
2311
- step((generator = generator.apply(thisArg, _arguments || [])).next());
2312
- });
2313
- };
2314
- var __generator = (commonjsGlobal && commonjsGlobal.__generator) || function (thisArg, body) {
2315
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
2316
- return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
2317
- function verb(n) { return function (v) { return step([n, v]); }; }
2318
- function step(op) {
2319
- if (f) throw new TypeError("Generator is already executing.");
2320
- while (g && (g = 0, op[0] && (_ = 0)), _) try {
2321
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
2322
- if (y = 0, t) op = [op[0] & 2, t.value];
2323
- switch (op[0]) {
2324
- case 0: case 1: t = op; break;
2325
- case 4: _.label++; return { value: op[1], done: false };
2326
- case 5: _.label++; y = op[1]; op = [0]; continue;
2327
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
2328
- default:
2329
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
2330
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
2331
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
2332
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
2333
- if (t[2]) _.ops.pop();
2334
- _.trys.pop(); continue;
2335
- }
2336
- op = body.call(thisArg, _);
2337
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
2338
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
2339
- }
2340
- };
2341
- var __importDefault = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
2342
- return (mod && mod.__esModule) ? mod : { "default": mod };
2343
- };
2344
- Object.defineProperty(useWebsocket, "__esModule", { value: true });
2345
- useWebsocket.useWebSocket = void 0;
2346
- var react_1$2 = require$$0;
2347
- var react_dom_1 = require$$1;
2348
- var constants_1$2 = constants;
2349
- var create_or_join_1 = createOrJoin;
2350
- var get_url_1 = getUrl;
2351
- var proxy_1 = __importDefault(proxy);
2352
- var util_1 = util;
2353
- var useWebSocket$1 = function (url, options, connect) {
2354
- if (options === void 0) { options = constants_1$2.DEFAULT_OPTIONS; }
2355
- if (connect === void 0) { connect = true; }
2356
- var _a = (0, react_1$2.useState)(null), lastMessage = _a[0], setLastMessage = _a[1];
2357
- var _b = (0, react_1$2.useState)({}), readyState = _b[0], setReadyState = _b[1];
2358
- var lastJsonMessage = (0, react_1$2.useMemo)(function () {
2359
- if (!options.disableJson && lastMessage) {
2360
- try {
2361
- return JSON.parse(lastMessage.data);
2362
- }
2363
- catch (e) {
2364
- return constants_1$2.UNPARSABLE_JSON_OBJECT;
2365
- }
2366
- }
2367
- return null;
2368
- }, [lastMessage, options.disableJson]);
2369
- var convertedUrl = (0, react_1$2.useRef)(null);
2370
- var webSocketRef = (0, react_1$2.useRef)(null);
2371
- var startRef = (0, react_1$2.useRef)(function () { return void 0; });
2372
- var reconnectCount = (0, react_1$2.useRef)(0);
2373
- var lastMessageTime = (0, react_1$2.useRef)(Date.now());
2374
- var messageQueue = (0, react_1$2.useRef)([]);
2375
- var webSocketProxy = (0, react_1$2.useRef)(null);
2376
- var optionsCache = (0, react_1$2.useRef)(options);
2377
- optionsCache.current = options;
2378
- var readyStateFromUrl = convertedUrl.current && readyState[convertedUrl.current] !== undefined ?
2379
- readyState[convertedUrl.current] :
2380
- url !== null && connect === true ?
2381
- constants_1$2.ReadyState.CONNECTING :
2382
- constants_1$2.ReadyState.UNINSTANTIATED;
2383
- var stringifiedQueryParams = options.queryParams ? JSON.stringify(options.queryParams) : null;
2384
- var sendMessage = (0, react_1$2.useCallback)(function (message, keep) {
2385
- var _a;
2386
- if (keep === void 0) { keep = true; }
2387
- if (constants_1$2.isEventSourceSupported && webSocketRef.current instanceof EventSource) {
2388
- console.warn('Unable to send a message from an eventSource');
2389
- return;
2390
- }
2391
- if (((_a = webSocketRef.current) === null || _a === void 0 ? void 0 : _a.readyState) === constants_1$2.ReadyState.OPEN) {
2392
- (0, util_1.assertIsWebSocket)(webSocketRef.current, optionsCache.current.skipAssert);
2393
- webSocketRef.current.send(message);
2394
- }
2395
- else if (keep) {
2396
- messageQueue.current.push(message);
2397
- }
2398
- }, []);
2399
- var sendJsonMessage = (0, react_1$2.useCallback)(function (message, keep) {
2400
- if (keep === void 0) { keep = true; }
2401
- sendMessage(JSON.stringify(message), keep);
2402
- }, [sendMessage]);
2403
- var getWebSocket = (0, react_1$2.useCallback)(function () {
2404
- if (optionsCache.current.share !== true || (constants_1$2.isEventSourceSupported && webSocketRef.current instanceof EventSource)) {
2405
- return webSocketRef.current;
2406
- }
2407
- if (webSocketProxy.current === null && webSocketRef.current) {
2408
- (0, util_1.assertIsWebSocket)(webSocketRef.current, optionsCache.current.skipAssert);
2409
- webSocketProxy.current = (0, proxy_1.default)(webSocketRef.current, startRef);
2410
- }
2411
- return webSocketProxy.current;
2412
- }, []);
2413
- (0, react_1$2.useEffect)(function () {
2414
- if (url !== null && connect === true) {
2415
- var removeListeners_1;
2416
- var expectClose_1 = false;
2417
- var createOrJoin_1 = true;
2418
- var start_1 = function () { return __awaiter(void 0, void 0, void 0, function () {
2419
- var _a, protectedSetLastMessage, protectedSetReadyState;
2420
- return __generator(this, function (_b) {
2421
- switch (_b.label) {
2422
- case 0:
2423
- _a = convertedUrl;
2424
- return [4 /*yield*/, (0, get_url_1.getUrl)(url, optionsCache)];
2425
- case 1:
2426
- _a.current = _b.sent();
2427
- if (convertedUrl.current === null) {
2428
- console.error('Failed to get a valid URL. WebSocket connection aborted.');
2429
- convertedUrl.current = 'ABORTED';
2430
- (0, react_dom_1.flushSync)(function () { return setReadyState(function (prev) { return (__assign$2(__assign$2({}, prev), { ABORTED: constants_1$2.ReadyState.CLOSED })); }); });
2431
- return [2 /*return*/];
2432
- }
2433
- protectedSetLastMessage = function (message) {
2434
- if (!expectClose_1) {
2435
- (0, react_dom_1.flushSync)(function () { return setLastMessage(message); });
2436
- }
2437
- };
2438
- protectedSetReadyState = function (state) {
2439
- if (!expectClose_1) {
2440
- (0, react_dom_1.flushSync)(function () { return setReadyState(function (prev) {
2441
- var _a;
2442
- return (__assign$2(__assign$2({}, prev), (convertedUrl.current && (_a = {}, _a[convertedUrl.current] = state, _a))));
2443
- }); });
2444
- }
2445
- };
2446
- if (createOrJoin_1) {
2447
- removeListeners_1 = (0, create_or_join_1.createOrJoinSocket)(webSocketRef, convertedUrl.current, protectedSetReadyState, optionsCache, protectedSetLastMessage, startRef, reconnectCount, lastMessageTime, sendMessage);
2448
- }
2449
- return [2 /*return*/];
2450
- }
2451
- });
2452
- }); };
2453
- startRef.current = function () {
2454
- if (!expectClose_1) {
2455
- if (webSocketProxy.current)
2456
- webSocketProxy.current = null;
2457
- removeListeners_1 === null || removeListeners_1 === void 0 ? void 0 : removeListeners_1();
2458
- start_1();
2459
- }
2460
- };
2461
- start_1();
2462
- return function () {
2463
- expectClose_1 = true;
2464
- createOrJoin_1 = false;
2465
- if (webSocketProxy.current)
2466
- webSocketProxy.current = null;
2467
- removeListeners_1 === null || removeListeners_1 === void 0 ? void 0 : removeListeners_1();
2468
- setLastMessage(null);
2469
- };
2470
- }
2471
- else if (url === null || connect === false) {
2472
- reconnectCount.current = 0; // reset reconnection attempts
2473
- setReadyState(function (prev) {
2474
- var _a;
2475
- return (__assign$2(__assign$2({}, prev), (convertedUrl.current && (_a = {}, _a[convertedUrl.current] = constants_1$2.ReadyState.CLOSED, _a))));
2476
- });
2477
- }
2478
- }, [url, connect, stringifiedQueryParams, sendMessage]);
2479
- (0, react_1$2.useEffect)(function () {
2480
- if (readyStateFromUrl === constants_1$2.ReadyState.OPEN) {
2481
- messageQueue.current.splice(0).forEach(function (message) {
2482
- sendMessage(message);
2483
- });
2484
- }
2485
- }, [readyStateFromUrl]);
2486
- return {
2487
- sendMessage: sendMessage,
2488
- sendJsonMessage: sendJsonMessage,
2489
- lastMessage: lastMessage,
2490
- lastJsonMessage: lastJsonMessage,
2491
- readyState: readyStateFromUrl,
2492
- getWebSocket: getWebSocket,
2493
- };
2494
- };
2495
- useWebsocket.useWebSocket = useWebSocket$1;
2496
-
2497
- var useSocketIo = {};
2498
-
2499
- var __assign$1 = (commonjsGlobal && commonjsGlobal.__assign) || function () {
2500
- __assign$1 = Object.assign || function(t) {
2501
- for (var s, i = 1, n = arguments.length; i < n; i++) {
2502
- s = arguments[i];
2503
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
2504
- t[p] = s[p];
2505
- }
2506
- return t;
2507
- };
2508
- return __assign$1.apply(this, arguments);
2509
- };
2510
- Object.defineProperty(useSocketIo, "__esModule", { value: true });
2511
- useSocketIo.useSocketIO = void 0;
2512
- var react_1$1 = require$$0;
2513
- var use_websocket_1$1 = useWebsocket;
2514
- var constants_1$1 = constants;
2515
- var emptyEvent = {
2516
- type: 'empty',
2517
- payload: null,
2518
- };
2519
- var getSocketData = function (event) {
2520
- if (!event || !event.data) {
2521
- return emptyEvent;
2522
- }
2523
- var match = event.data.match(/\[.*]/);
2524
- if (!match) {
2525
- return emptyEvent;
2526
- }
2527
- var data = JSON.parse(match);
2528
- if (!Array.isArray(data) || !data[1]) {
2529
- return emptyEvent;
2530
- }
2531
- return {
2532
- type: data[0],
2533
- payload: data[1],
2534
- };
2535
- };
2536
- var useSocketIO = function (url, options, connect) {
2537
- if (options === void 0) { options = constants_1$1.DEFAULT_OPTIONS; }
2538
- if (connect === void 0) { connect = true; }
2539
- var optionsWithSocketIO = (0, react_1$1.useMemo)(function () { return (__assign$1(__assign$1({}, options), { fromSocketIO: true })); }, []);
2540
- var _a = (0, use_websocket_1$1.useWebSocket)(url, optionsWithSocketIO, connect), sendMessage = _a.sendMessage, sendJsonMessage = _a.sendJsonMessage, lastMessage = _a.lastMessage, readyState = _a.readyState, getWebSocket = _a.getWebSocket;
2541
- var socketIOLastMessage = (0, react_1$1.useMemo)(function () {
2542
- return getSocketData(lastMessage);
2543
- }, [lastMessage]);
2544
- return {
2545
- sendMessage: sendMessage,
2546
- sendJsonMessage: sendJsonMessage,
2547
- lastMessage: socketIOLastMessage,
2548
- lastJsonMessage: socketIOLastMessage,
2549
- readyState: readyState,
2550
- getWebSocket: getWebSocket,
2551
- };
2552
- };
2553
- useSocketIo.useSocketIO = useSocketIO;
2554
-
2555
- var useEventSource$1 = {};
2556
-
2557
- var __assign = (commonjsGlobal && commonjsGlobal.__assign) || function () {
2558
- __assign = Object.assign || function(t) {
2559
- for (var s, i = 1, n = arguments.length; i < n; i++) {
2560
- s = arguments[i];
2561
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
2562
- t[p] = s[p];
2563
- }
2564
- return t;
2565
- };
2566
- return __assign.apply(this, arguments);
2567
- };
2568
- var __rest = (commonjsGlobal && commonjsGlobal.__rest) || function (s, e) {
2569
- var t = {};
2570
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
2571
- t[p] = s[p];
2572
- if (s != null && typeof Object.getOwnPropertySymbols === "function")
2573
- for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
2574
- if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
2575
- t[p[i]] = s[p[i]];
2576
- }
2577
- return t;
2578
- };
2579
- Object.defineProperty(useEventSource$1, "__esModule", { value: true });
2580
- useEventSource$1.useEventSource = void 0;
2581
- var react_1 = require$$0;
2582
- var use_websocket_1 = useWebsocket;
2583
- var constants_1 = constants;
2584
- var useEventSource = function (url, _a, connect) {
2585
- if (_a === void 0) { _a = constants_1.DEFAULT_EVENT_SOURCE_OPTIONS; }
2586
- var withCredentials = _a.withCredentials, events = _a.events, options = __rest(_a, ["withCredentials", "events"]);
2587
- if (connect === void 0) { connect = true; }
2588
- var optionsWithEventSource = __assign(__assign({}, options), { eventSourceOptions: {
2589
- withCredentials: withCredentials,
2590
- } });
2591
- var eventsRef = (0, react_1.useRef)(constants_1.EMPTY_EVENT_HANDLERS);
2592
- if (events) {
2593
- eventsRef.current = events;
2594
- }
2595
- var _b = (0, use_websocket_1.useWebSocket)(url, optionsWithEventSource, connect), lastMessage = _b.lastMessage, readyState = _b.readyState, getWebSocket = _b.getWebSocket;
2596
- (0, react_1.useEffect)(function () {
2597
- if (lastMessage === null || lastMessage === void 0 ? void 0 : lastMessage.type) {
2598
- Object.entries(eventsRef.current).forEach(function (_a) {
2599
- var type = _a[0], handler = _a[1];
2600
- if (type === lastMessage.type) {
2601
- handler(lastMessage);
2602
- }
2603
- });
2604
- }
2605
- }, [lastMessage]);
2606
- return {
2607
- lastEvent: lastMessage,
2608
- readyState: readyState,
2609
- getEventSource: getWebSocket,
2610
- };
2611
- };
2612
- useEventSource$1.useEventSource = useEventSource;
2613
-
2614
- (function (exports) {
2615
- Object.defineProperty(exports, "__esModule", { value: true });
2616
- exports.resetGlobalState = exports.useEventSource = exports.ReadyState = exports.useSocketIO = exports.default = void 0;
2617
- var use_websocket_1 = useWebsocket;
2618
- Object.defineProperty(exports, "default", { enumerable: true, get: function () { return use_websocket_1.useWebSocket; } });
2619
- var use_socket_io_1 = useSocketIo;
2620
- Object.defineProperty(exports, "useSocketIO", { enumerable: true, get: function () { return use_socket_io_1.useSocketIO; } });
2621
- var constants_1 = constants;
2622
- Object.defineProperty(exports, "ReadyState", { enumerable: true, get: function () { return constants_1.ReadyState; } });
2623
- var use_event_source_1 = useEventSource$1;
2624
- Object.defineProperty(exports, "useEventSource", { enumerable: true, get: function () { return use_event_source_1.useEventSource; } });
2625
- var util_1 = util;
2626
- Object.defineProperty(exports, "resetGlobalState", { enumerable: true, get: function () { return util_1.resetGlobalState; } });
2627
-
2628
- } (dist));
2629
-
2630
- var useWebSocket = /*@__PURE__*/getDefaultExportFromCjs(dist);
2631
-
2632
- const useHyperliquidWebSocket = ({ wsUrl, address }) => {
2633
- // WebSocket data state
2634
- const [data, setData] = useState({
2635
- tradeHistories: null,
2636
- openPositions: null,
2637
- openOrders: null,
2638
- accountSummary: null,
2639
- });
2640
- const [lastError, setLastError] = useState(null);
2641
- const [lastSubscribedAddress, setLastSubscribedAddress] = useState(null);
2642
- // WebSocket connection
2643
- const { readyState, sendMessage } = useWebSocket(wsUrl, {
2644
- shouldReconnect: () => true,
2645
- reconnectAttempts: 5,
2646
- reconnectInterval: 3000,
2647
- onMessage: (event) => {
2648
- try {
2649
- const message = JSON.parse(event.data);
2650
- // Handle subscription responses (only if they don't have channel data)
2651
- if (('success' in message || 'error' in message) && !('channel' in message)) {
2652
- if (message.error) {
2653
- setLastError(message.error);
2654
- }
2655
- else {
2656
- setLastError(null);
2657
- }
2658
- return;
2659
- }
2660
- // Handle channel data messages
2661
- if ('channel' in message && 'data' in message) {
2662
- const dataMessage = message;
2663
- // Validate data exists and is not null/undefined
2664
- if (dataMessage.data === null || dataMessage.data === undefined) {
2665
- return;
2666
- }
2667
- switch (dataMessage.channel) {
2668
- case 'trade-histories':
2669
- if (Array.isArray(dataMessage.data)) {
2670
- setData(prev => ({
2671
- ...prev,
2672
- tradeHistories: dataMessage.data
2673
- }));
2674
- }
2675
- break;
2676
- case 'open-positions':
2677
- if (Array.isArray(dataMessage.data)) {
2678
- setData(prev => ({
2679
- ...prev,
2680
- openPositions: dataMessage.data
2681
- }));
2682
- }
2683
- break;
2684
- case 'open-orders':
2685
- if (Array.isArray(dataMessage.data)) {
2686
- setData(prev => ({
2687
- ...prev,
2688
- openOrders: dataMessage.data
2689
- }));
2690
- }
2691
- break;
2692
- case 'account-summary':
2693
- if (typeof dataMessage.data === 'object' && dataMessage.data !== null) {
2694
- setData(prev => ({
2695
- ...prev,
2696
- accountSummary: dataMessage.data
2697
- }));
2698
- }
2699
- break;
2700
- }
2701
- }
2702
- }
2703
- catch (error) {
2704
- setLastError(`Failed to parse message: ${error instanceof Error ? error.message : String(error)}`);
2705
- }
2706
- }
2707
- });
2708
- const isConnected = readyState === dist.ReadyState.OPEN;
2709
- // Handle subscription management
2710
- useEffect(() => {
2711
- if (isConnected && address && address !== lastSubscribedAddress) {
2712
- // Unsubscribe from previous address if exists
2713
- if (lastSubscribedAddress) {
2714
- sendMessage(JSON.stringify({
2715
- action: 'unsubscribe',
2716
- address: lastSubscribedAddress
2717
- }));
2718
- }
2719
- // Subscribe to new address
2720
- sendMessage(JSON.stringify({
2721
- action: 'subscribe',
2722
- address: address
2723
- }));
2724
- setLastSubscribedAddress(address);
2725
- setLastError(null);
2726
- }
2727
- else if (isConnected && !address && lastSubscribedAddress) {
2728
- // Send unsubscribe action when address is removed
2729
- sendMessage(JSON.stringify({
2730
- action: 'unsubscribe',
2731
- address: lastSubscribedAddress
2732
- }));
2733
- setLastSubscribedAddress(null);
2734
- }
2735
- }, [isConnected, address, lastSubscribedAddress, sendMessage]);
2736
- // Clear data when address changes
2737
- useEffect(() => {
2738
- if (address !== lastSubscribedAddress) {
2739
- setData({
2740
- tradeHistories: null,
2741
- openPositions: null,
2742
- openOrders: null,
2743
- accountSummary: null,
2744
- });
2745
- setLastError(null);
2746
- }
2747
- }, [address, lastSubscribedAddress]);
2748
- return {
2749
- data,
2750
- connectionStatus: readyState,
2751
- isConnected,
2752
- lastError,
2753
- };
2754
- };
2755
-
2756
- const useHyperliquidNativeWebSocket = ({ address }) => {
2757
- const [webData2, setWebData2] = useState(null);
2758
- const [allMids, setAllMids] = useState(null);
2759
- const [lastError, setLastError] = useState(null);
2760
- const [subscribedAddress, setSubscribedAddress] = useState(null);
2761
- const pingIntervalRef = useRef(null);
2762
- // WebSocket connection to HyperLiquid native API
2763
- const { readyState, sendJsonMessage } = useWebSocket('wss://api.hyperliquid.xyz/ws', {
2764
- shouldReconnect: () => true,
2765
- reconnectAttempts: 5,
2766
- reconnectInterval: 3000,
2767
- onOpen: () => { },
2768
- onClose: () => { },
2769
- onError: (event) => console.error('[HyperLiquid WS] Connection error:', event),
2770
- onReconnectStop: () => console.error('[HyperLiquid WS] Reconnection stopped after 5 attempts'),
2771
- onMessage: (event) => {
2772
- try {
2773
- const message = JSON.parse(event.data);
2774
- // Handle subscription responses
2775
- if ('success' in message || 'error' in message) {
2776
- if (message.error) {
2777
- console.error('[HyperLiquid WS] Subscription error:', message.error);
2778
- setLastError(message.error);
2779
- }
2780
- else {
2781
- setLastError(null);
2782
- }
2783
- return;
2784
- }
2785
- // Handle channel data messages
2786
- if ('channel' in message && 'data' in message) {
2787
- const response = message;
2788
- switch (response.channel) {
2789
- case 'webData2':
2790
- setWebData2(response.data);
2791
- break;
2792
- case 'allMids':
2793
- setAllMids(response.data);
2794
- break;
2795
- default:
2796
- console.warn(`[HyperLiquid WS] Unknown channel: ${response.channel}`);
2797
- }
2798
- }
2799
- }
2800
- catch (error) {
2801
- const errorMessage = `Failed to parse message: ${error instanceof Error ? error.message : String(error)}`;
2802
- console.error('[HyperLiquid WS] Parse error:', errorMessage, 'Raw message:', event.data);
2803
- setLastError(errorMessage);
2804
- }
2805
- }
2806
- });
2807
- const isConnected = readyState === dist.ReadyState.OPEN;
2808
- // Setup ping mechanism
2809
- useEffect(() => {
2810
- if (isConnected) {
2811
- // Send ping every 30 seconds
2812
- pingIntervalRef.current = setInterval(() => {
2813
- sendJsonMessage({ method: 'ping' });
2814
- }, 30000);
2815
- }
2816
- else {
2817
- if (pingIntervalRef.current) {
2818
- clearInterval(pingIntervalRef.current);
2819
- pingIntervalRef.current = null;
2820
- }
2821
- }
2822
- return () => {
2823
- if (pingIntervalRef.current) {
2824
- clearInterval(pingIntervalRef.current);
2825
- pingIntervalRef.current = null;
2826
- }
2827
- };
2828
- }, [isConnected, sendJsonMessage]);
2829
- // Handle address subscription changes
2830
- useEffect(() => {
2831
- if (!isConnected)
2832
- return;
2833
- const DEFAULT_ADDRESS = '0x0000000000000000000000000000000000000000';
2834
- const userAddress = address || DEFAULT_ADDRESS;
2835
- if (subscribedAddress === userAddress)
2836
- return;
2837
- // Unsubscribe from previous address if exists
2838
- if (subscribedAddress) {
2839
- const unsubscribeMessage = {
2840
- method: 'unsubscribe',
2841
- subscription: {
2842
- type: 'webData2',
2843
- user: subscribedAddress,
2844
- },
2845
- };
2846
- sendJsonMessage(unsubscribeMessage);
2847
- }
2848
- // Subscribe to webData2 with new address
2849
- const subscribeWebData2 = {
2850
- method: 'subscribe',
2851
- subscription: {
2852
- type: 'webData2',
2853
- user: userAddress,
2854
- },
2855
- };
2856
- // Subscribe to allMids
2857
- const subscribeAllMids = {
2858
- method: 'subscribe',
2859
- subscription: {
2860
- type: 'allMids',
2861
- },
2862
- };
2863
- sendJsonMessage(subscribeWebData2);
2864
- sendJsonMessage(subscribeAllMids);
2865
- setSubscribedAddress(userAddress);
2866
- // Clear previous data when address changes
2867
- if (subscribedAddress && subscribedAddress !== userAddress) {
2868
- setWebData2(null);
2869
- }
2870
- }, [isConnected, address, subscribedAddress, sendJsonMessage]);
2871
- return {
2872
- webData2,
2873
- allMids,
2874
- connectionStatus: readyState,
2875
- isConnected,
2876
- lastError,
2877
- };
2878
- };
2879
-
2880
- const DEFAULT_TOKEN_SELECTION_STATE = {
2881
- longTokens: [
2882
- { symbol: 'HYPE', weight: 25 },
2883
- { symbol: 'BTC', weight: 25 }
2884
- ],
2885
- shortTokens: [
2886
- { symbol: 'AVAX', weight: 10 },
2887
- { symbol: 'SEI', weight: 10 },
2888
- { symbol: 'ADA', weight: 10 },
2889
- { symbol: 'TRUMP', weight: 10 },
2890
- { symbol: 'SUI', weight: 10 }
2891
- ],
2892
- openTokenSelector: false,
2893
- selectorConfig: null,
2894
- openConflictModal: false,
2895
- conflicts: [],
2896
- };
2897
- const PearHyperliquidContext = createContext(undefined);
2898
- /**
2899
- * React Provider for PearHyperliquidClient
2900
- */
2901
- const PearHyperliquidProvider = ({ config, wsUrl = 'wss://hl-v2.pearprotocol.io/ws', children, }) => {
2902
- const client = useMemo(() => new PearHyperliquidClient(config), [config]);
2903
- const migrationSDK = useMemo(() => new PearMigrationSDK(client), [client]);
2904
- // Address state
2905
- const [address, setAddress] = useState(null);
2906
- // Token selection state
2907
- const [tokenSelection, setTokenSelection] = useState(DEFAULT_TOKEN_SELECTION_STATE);
2908
- // WebSocket connection and data (Pear API)
2909
- const { data, connectionStatus, isConnected, lastError } = useHyperliquidWebSocket({
2910
- wsUrl,
2911
- address,
2912
- });
2913
- // HyperLiquid native WebSocket connection
2914
- const { webData2, allMids, connectionStatus: nativeConnectionStatus, isConnected: nativeIsConnected, lastError: nativeLastError } = useHyperliquidNativeWebSocket({
2915
- address,
2916
- });
2917
- const contextValue = useMemo(() => ({
2918
- // Existing clients
2919
- client,
2920
- migrationSDK,
2921
- // Address management
2922
- address,
2923
- setAddress,
2924
- // WebSocket state (Pear API)
2925
- connectionStatus,
2926
- isConnected,
2927
- // WebSocket data (Pear API)
2928
- data,
2929
- lastError,
2930
- // HyperLiquid native WebSocket state
2931
- nativeConnectionStatus,
2932
- nativeIsConnected,
2933
- nativeLastError,
2934
- // HyperLiquid native WebSocket data
2935
- webData2,
2936
- allMids,
2937
- // Token selection state
2938
- tokenSelection,
2939
- setTokenSelection,
2940
- }), [client, migrationSDK, address, connectionStatus, isConnected, data, lastError, nativeConnectionStatus, nativeIsConnected, nativeLastError, webData2, allMids, tokenSelection, setTokenSelection]);
2941
- return (jsxRuntimeExports.jsx(PearHyperliquidContext.Provider, { value: contextValue, children: children }));
2942
- };
2943
- /**
2944
- * Hook to use PearHyperliquidClient from context
2945
- */
2946
- const usePearHyperliquidClient = () => {
2947
- const context = useContext(PearHyperliquidContext);
2948
- if (!context) {
2949
- throw new Error('usePearHyperliquidClient must be used within a PearHyperliquidProvider');
2950
- }
2951
- return context.client;
2952
- };
2953
- /**
2954
- * Hook to use migration SDK from context
2955
- */
2956
- const useMigrationSDK = () => {
2957
- const context = useContext(PearHyperliquidContext);
2958
- if (!context) {
2959
- throw new Error('useMigrationSDK must be used within a PearHyperliquidProvider');
2960
- }
2961
- return context.migrationSDK;
2962
- };
2963
-
2964
- /**
2965
- * Hook to manage address (login/logout functionality)
2966
- */
2967
- const useAddress = () => {
2968
- const context = useContext(PearHyperliquidContext);
2969
- if (!context) {
2970
- throw new Error('useAddress must be used within a PearHyperliquidProvider');
2971
- }
2972
- return {
2973
- address: context.address,
2974
- setAddress: context.setAddress,
2975
- clearAddress: () => context.setAddress(null),
2976
- isLoggedIn: !!context.address,
2977
- };
2978
- };
2979
-
2980
- var PositionSide;
2981
- (function (PositionSide) {
2982
- PositionSide["LONG"] = "LONG";
2983
- PositionSide["SHORT"] = "SHORT";
2984
- })(PositionSide || (PositionSide = {}));
2985
- class PositionProcessor {
2986
- constructor(webData2, allMids) {
2987
- this.webData2 = webData2;
2988
- this.allMids = allMids;
2989
- }
2990
- execute(rawPositions) {
2991
- if (!rawPositions || rawPositions.length === 0) {
2992
- return [];
2993
- }
2994
- const userHyperliquidPositions = this.getUserPositions();
2995
- const platformTotalsByAsset = this.calculatePlatformTotalsByAsset(rawPositions);
2996
- const hlPositionsMap = new Map();
2997
- (userHyperliquidPositions || []).forEach(assetPos => {
2998
- var _a;
2999
- if ((_a = assetPos.position) === null || _a === void 0 ? void 0 : _a.coin) {
3000
- hlPositionsMap.set(assetPos.position.coin, assetPos);
3001
- }
3002
- });
3003
- const openPositionDtos = [];
3004
- for (const position of rawPositions) {
3005
- const syncedPositionDto = this.syncPositionWithAggregateData(position, hlPositionsMap, platformTotalsByAsset);
3006
- openPositionDtos.push(syncedPositionDto);
3007
- }
3008
- return openPositionDtos;
3009
- }
3010
- getUserPositions() {
3011
- var _a, _b;
3012
- return ((_b = (_a = this.webData2) === null || _a === void 0 ? void 0 : _a.clearinghouseState) === null || _b === void 0 ? void 0 : _b.assetPositions) || [];
3013
- }
3014
- getMarketPrice(coin) {
3015
- var _a;
3016
- if (!((_a = this.allMids) === null || _a === void 0 ? void 0 : _a.mids))
3017
- return 0;
3018
- const exactPrice = this.allMids.mids[coin];
3019
- if (exactPrice) {
3020
- return Number(exactPrice);
3021
- }
3022
- const baseCurrency = this.extractBaseCurrency(coin);
3023
- const basePrice = this.allMids.mids[baseCurrency];
3024
- if (basePrice) {
3025
- return Number(basePrice);
3026
- }
3027
- return 0;
3028
- }
3029
- calculatePlatformTotalsByAsset(positions) {
3030
- const totalsMap = new Map();
3031
- for (const position of positions) {
3032
- for (const asset of position.longAssets || []) {
3033
- const baseCurrency = this.extractBaseCurrency(asset.coin);
3034
- if (!totalsMap.has(baseCurrency)) {
3035
- totalsMap.set(baseCurrency, {
3036
- totalSize: 0,
3037
- positions: []
3038
- });
3039
- }
3040
- const totals = totalsMap.get(baseCurrency);
3041
- const assetSize = Number(asset.size || 0);
3042
- totals.totalSize += assetSize;
3043
- totals.positions.push({
3044
- positionId: position.positionId,
3045
- asset: asset,
3046
- size: assetSize
3047
- });
3048
- }
3049
- for (const asset of position.shortAssets || []) {
3050
- const baseCurrency = this.extractBaseCurrency(asset.coin);
3051
- if (!totalsMap.has(baseCurrency)) {
3052
- totalsMap.set(baseCurrency, {
3053
- totalSize: 0,
3054
- positions: []
3055
- });
3056
- }
3057
- const totals = totalsMap.get(baseCurrency);
3058
- const assetSize = Number(asset.size || 0);
3059
- totals.totalSize += assetSize;
3060
- totals.positions.push({
3061
- positionId: position.positionId,
3062
- asset: asset,
3063
- size: assetSize
3064
- });
3065
- }
3066
- }
3067
- return totalsMap;
3068
- }
3069
- extractBaseCurrency(assetName) {
3070
- return assetName.split('/')[0] || assetName;
3071
- }
3072
- syncPositionWithAggregateData(position, hlPositionsMap, platformTotalsByAsset) {
3073
- const syncResults = [];
3074
- let hasExternalModification = false;
3075
- let allAssetsClosed = true;
3076
- let longAssetStatuses = { total: 0, closed: 0 };
3077
- let shortAssetStatuses = { total: 0, closed: 0 };
3078
- // Process long assets
3079
- for (const asset of position.longAssets || []) {
3080
- const baseCurrency = this.extractBaseCurrency(asset.coin);
3081
- const hlPosition = hlPositionsMap.get(baseCurrency);
3082
- const platformTotals = platformTotalsByAsset.get(baseCurrency);
3083
- const syncResult = this.syncAssetWithAggregateData({ ...asset, side: PositionSide.LONG }, hlPosition, (platformTotals === null || platformTotals === void 0 ? void 0 : platformTotals.totalSize) || 0);
3084
- syncResults.push(syncResult);
3085
- longAssetStatuses.total++;
3086
- if (syncResult.actualSize === 0) {
3087
- longAssetStatuses.closed++;
3088
- }
3089
- if (syncResult.isExternallyModified) {
3090
- hasExternalModification = true;
3091
- }
3092
- if (syncResult.actualSize !== 0) {
3093
- allAssetsClosed = false;
3094
- }
3095
- }
3096
- // Process short assets
3097
- for (const asset of position.shortAssets || []) {
3098
- const baseCurrency = this.extractBaseCurrency(asset.coin);
3099
- const hlPosition = hlPositionsMap.get(baseCurrency);
3100
- const platformTotals = platformTotalsByAsset.get(baseCurrency);
3101
- const syncResult = this.syncAssetWithAggregateData({ ...asset, side: PositionSide.SHORT }, hlPosition, (platformTotals === null || platformTotals === void 0 ? void 0 : platformTotals.totalSize) || 0);
3102
- syncResults.push(syncResult);
3103
- shortAssetStatuses.total++;
3104
- if (syncResult.actualSize === 0) {
3105
- shortAssetStatuses.closed++;
3106
- }
3107
- if (syncResult.isExternallyModified) {
3108
- hasExternalModification = true;
3109
- }
3110
- if (syncResult.actualSize !== 0) {
3111
- allAssetsClosed = false;
3112
- }
3113
- }
3114
- const syncStatus = this.determineSyncStatus(hasExternalModification, allAssetsClosed, longAssetStatuses, shortAssetStatuses);
3115
- return this.mapPositionToDtoWithSyncData(position, syncResults, syncStatus);
3116
- }
3117
- determineSyncStatus(hasExternalModification, allAssetsClosed, longAssetStatuses, shortAssetStatuses) {
3118
- if (allAssetsClosed) {
3119
- return 'EXTERNALLY_CLOSED';
3120
- }
3121
- const allLongsClosed = longAssetStatuses.total > 0 &&
3122
- longAssetStatuses.closed === longAssetStatuses.total;
3123
- const allShortsClosed = shortAssetStatuses.total > 0 &&
3124
- shortAssetStatuses.closed === shortAssetStatuses.total;
3125
- if ((allLongsClosed && !allShortsClosed) || (!allLongsClosed && allShortsClosed)) {
3126
- return 'PAIR_BROKEN';
3127
- }
3128
- if (hasExternalModification) {
3129
- return 'EXTERNALLY_MODIFIED';
3130
- }
3131
- return 'SYNCED';
3132
- }
3133
- syncAssetWithAggregateData(asset, hlPosition, platformTotal) {
3134
- const platformSize = Number(asset.size || 0);
3135
- if (!hlPosition || !hlPosition.position || !hlPosition.position.szi) {
3136
- return {
3137
- asset,
3138
- actualSize: 0,
3139
- isExternallyModified: true,
3140
- cumFunding: { allTime: 0, sinceChange: 0, sinceOpen: 0 },
3141
- unrealizedPnl: 0,
3142
- liquidationPrice: 0
3143
- };
3144
- }
3145
- const hlTotalSize = Math.abs(Number(hlPosition.position.szi || 0));
3146
- const totalDifference = Math.abs(hlTotalSize - platformTotal);
3147
- const tolerance = platformTotal * 0.001;
3148
- const isExternallyModified = totalDifference > tolerance;
3149
- const proportion = platformTotal > 0 ? platformSize / platformTotal : 0;
3150
- const actualSize = hlTotalSize * proportion;
3151
- // Get cumFunding from hlPosition.position.cumFunding
3152
- const rawCumFunding = hlPosition.position.cumFunding;
3153
- const cumFunding = {
3154
- allTime: Number((rawCumFunding === null || rawCumFunding === void 0 ? void 0 : rawCumFunding.allTime) || 0),
3155
- sinceChange: Number((rawCumFunding === null || rawCumFunding === void 0 ? void 0 : rawCumFunding.sinceChange) || 0) * proportion,
3156
- sinceOpen: Number((rawCumFunding === null || rawCumFunding === void 0 ? void 0 : rawCumFunding.sinceOpen) || 0) * proportion
3157
- };
3158
- const unrealizedPnl = Number(hlPosition.position.unrealizedPnl || 0) * proportion;
3159
- const liquidationPrice = Number(hlPosition.position.liquidationPx || 0);
3160
- return {
3161
- asset,
3162
- actualSize,
3163
- isExternallyModified,
3164
- cumFunding,
3165
- unrealizedPnl,
3166
- liquidationPrice
3167
- };
3168
- }
3169
- mapPositionToDtoWithSyncData(position, syncResults, syncStatus) {
3170
- var _a, _b;
3171
- const longAssets = ((_a = position.longAssets) === null || _a === void 0 ? void 0 : _a.filter(asset => asset)) || [];
3172
- const shortAssets = ((_b = position.shortAssets) === null || _b === void 0 ? void 0 : _b.filter(asset => asset)) || [];
3173
- const syncResultsMap = new Map();
3174
- syncResults.forEach(result => {
3175
- syncResultsMap.set(`${result.asset.coin}-${result.asset.side}`, result);
3176
- });
3177
- const currentTotalPositionValue = this.calculateCurrentTotalPositionValue(syncResults);
3178
- const entryTotalPositionValue = this.calculateEntryTotalPositionValue(syncResults);
3179
- const totalMarginUsed = entryTotalPositionValue / position.leverage;
3180
- return {
3181
- syncStatus: syncStatus,
3182
- positionId: position.positionId,
3183
- address: position.address,
3184
- leverage: position.leverage,
3185
- stopLoss: position.stopLoss,
3186
- takeProfit: position.takeProfit,
3187
- entryRatio: this.calculateEntryRatio(syncResults),
3188
- markRatio: this.calculateMarkRatio(syncResults),
3189
- netFunding: this.calculateNetFundingFromSyncResults(syncResults),
3190
- positionValue: currentTotalPositionValue,
3191
- marginUsed: totalMarginUsed,
3192
- unrealizedPnl: this.calculateTotalUnrealizedPnlFromSyncResults(syncResults),
3193
- lastSyncAt: new Date().toISOString(),
3194
- longAssets: longAssets.map(asset => this.mapAssetToDetailDto(asset, syncResultsMap.get(`${asset.coin}-LONG`))),
3195
- shortAssets: shortAssets.map(asset => this.mapAssetToDetailDto(asset, syncResultsMap.get(`${asset.coin}-SHORT`))),
3196
- createdAt: position.createdAt,
3197
- updatedAt: position.updatedAt
3198
- };
3199
- }
3200
- mapAssetToDetailDto(asset, syncData) {
3201
- const currentPrice = this.getMarketPrice(asset.coin);
3202
- const actualSize = (syncData === null || syncData === void 0 ? void 0 : syncData.actualSize) || Number(asset.size || 0);
3203
- const positionValue = actualSize * currentPrice;
3204
- const entryValue = Number(asset.size || 0) * Number(asset.entryPrice || 0);
3205
- return {
3206
- coin: asset.coin,
3207
- entryPrice: Number(asset.entryPrice || 0),
3208
- platformSize: Number(asset.size || 0),
3209
- actualSize: actualSize,
3210
- isExternallyModified: (syncData === null || syncData === void 0 ? void 0 : syncData.isExternallyModified) || false,
3211
- cumFunding: (syncData === null || syncData === void 0 ? void 0 : syncData.cumFunding) || {
3212
- allTime: 0,
3213
- sinceChange: 0,
3214
- sinceOpen: 0
3215
- },
3216
- marginUsed: entryValue,
3217
- positionValue: positionValue,
3218
- unrealizedPnl: (syncData === null || syncData === void 0 ? void 0 : syncData.unrealizedPnl) || 0,
3219
- liquidationPrice: (syncData === null || syncData === void 0 ? void 0 : syncData.liquidationPrice) || 0
3220
- };
3221
- }
3222
- calculateEntryRatio(syncResults) {
3223
- var _a, _b;
3224
- const longResults = syncResults.filter(result => result.asset.side === PositionSide.LONG);
3225
- const shortResults = syncResults.filter(result => result.asset.side === PositionSide.SHORT);
3226
- if (longResults.length === 0 || shortResults.length === 0)
3227
- return 0;
3228
- const longEntryPrice = ((_a = longResults[0]) === null || _a === void 0 ? void 0 : _a.asset.entryPrice) ? Number(longResults[0].asset.entryPrice) : 0;
3229
- const shortEntryPrice = ((_b = shortResults[0]) === null || _b === void 0 ? void 0 : _b.asset.entryPrice) ? Number(shortResults[0].asset.entryPrice) : 0;
3230
- return shortEntryPrice > 0 ? longEntryPrice / shortEntryPrice : 0;
3231
- }
3232
- calculateMarkRatio(syncResults) {
3233
- var _a, _b;
3234
- const longResults = syncResults.filter(result => result.asset.side === PositionSide.LONG);
3235
- const shortResults = syncResults.filter(result => result.asset.side === PositionSide.SHORT);
3236
- if (longResults.length === 0 || shortResults.length === 0)
3237
- return 0;
3238
- const longMarkPrice = ((_a = longResults[0]) === null || _a === void 0 ? void 0 : _a.asset.coin) ? this.getMarketPrice(longResults[0].asset.coin) : 0;
3239
- const shortMarkPrice = ((_b = shortResults[0]) === null || _b === void 0 ? void 0 : _b.asset.coin) ? this.getMarketPrice(shortResults[0].asset.coin) : 0;
3240
- return shortMarkPrice > 0 ? longMarkPrice / shortMarkPrice : 0;
3241
- }
3242
- calculateNetFundingFromSyncResults(syncResults) {
3243
- const netFunding = syncResults.reduce((sum, result) => {
3244
- const funding = result.cumFunding.sinceOpen;
3245
- return sum + funding;
3246
- }, 0);
3247
- return netFunding;
3248
- }
3249
- calculateTotalUnrealizedPnlFromSyncResults(syncResults) {
3250
- return syncResults.reduce((sum, result) => sum + result.unrealizedPnl, 0);
3251
- }
3252
- calculateCurrentTotalPositionValue(syncResults) {
3253
- return syncResults.reduce((sum, result) => {
3254
- const currentPrice = this.getMarketPrice(result.asset.coin);
3255
- return sum + (result.actualSize * currentPrice);
3256
- }, 0);
3257
- }
3258
- calculateEntryTotalPositionValue(syncResults) {
3259
- return syncResults.reduce((sum, result) => {
3260
- return sum + (Number(result.asset.size || 0) * Number(result.asset.entryPrice || 0));
3261
- }, 0);
3262
- }
3263
- }
3264
-
3265
- /**
3266
- * Hook that calculates open positions by syncing platform positions with HyperLiquid real-time data
3267
- */
3268
- const useCalculatedOpenPositions = (platformPositions, webData2, allMids) => {
3269
- const calculatedPositions = useMemo(() => {
3270
- // Return null if we don't have platform positions yet
3271
- if (!platformPositions) {
3272
- return null;
3273
- }
3274
- // If we don't have real-time data yet, we can't calculate properly, return null
3275
- if (!webData2 || !allMids) {
3276
- return null;
3277
- }
3278
- // Create processor and compute positions
3279
- const processor = new PositionProcessor(webData2, allMids);
3280
- const processed = processor.execute(platformPositions);
3281
- return processed;
3282
- }, [platformPositions, webData2, allMids]);
3283
- return calculatedPositions;
3284
- };
3285
-
3286
- /**
3287
- * Account summary calculation utility class
3288
- */
3289
- class AccountSummaryCalculator {
3290
- constructor(webData2) {
3291
- this.webData2 = webData2;
3292
- }
3293
- /**
3294
- * Calculate account summary from webData2 and platform orders
3295
- */
3296
- calculateAccountSummary(platformAccountSummary, platformOpenOrders, agentWalletAddress, agentWalletStatus) {
3297
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l;
3298
- // If we don't have webData2, return platform data as-is
3299
- if (!((_a = this.webData2) === null || _a === void 0 ? void 0 : _a.clearinghouseState)) {
3300
- return platformAccountSummary;
3301
- }
3302
- const clearinghouseState = this.webData2.clearinghouseState;
3303
- // Calculate total limit order value from platform orders
3304
- const totalLimitOrderValue = this.calculateTotalLimitOrderValue(platformOpenOrders || []);
3305
- // Use real-time data from webData2 clearinghouseState
3306
- const withdrawableAmount = parseFloat(clearinghouseState.withdrawable || '0');
3307
- const adjustedWithdrawable = Math.max(0, withdrawableAmount - totalLimitOrderValue);
3308
- const accountSummary = {
3309
- balanceSummary: {
3310
- crossMaintenanceMarginUsed: clearinghouseState.crossMaintenanceMarginUsed || '0',
3311
- crossMarginSummary: {
3312
- accountValue: ((_b = clearinghouseState.crossMarginSummary) === null || _b === void 0 ? void 0 : _b.accountValue) || '0',
3313
- totalMarginUsed: ((_c = clearinghouseState.crossMarginSummary) === null || _c === void 0 ? void 0 : _c.totalMarginUsed) || '0',
3314
- totalNtlPos: ((_d = clearinghouseState.crossMarginSummary) === null || _d === void 0 ? void 0 : _d.totalNtlPos) || '0',
3315
- totalRawUsd: ((_e = clearinghouseState.crossMarginSummary) === null || _e === void 0 ? void 0 : _e.totalRawUsd) || '0'
3316
- },
3317
- marginSummary: {
3318
- accountValue: ((_f = clearinghouseState.marginSummary) === null || _f === void 0 ? void 0 : _f.accountValue) || '0',
3319
- totalMarginUsed: ((_g = clearinghouseState.marginSummary) === null || _g === void 0 ? void 0 : _g.totalMarginUsed) || '0',
3320
- totalNtlPos: ((_h = clearinghouseState.marginSummary) === null || _h === void 0 ? void 0 : _h.totalNtlPos) || '0',
3321
- totalRawUsd: ((_j = clearinghouseState.marginSummary) === null || _j === void 0 ? void 0 : _j.totalRawUsd) || '0'
3322
- },
3323
- time: clearinghouseState.time || Date.now(),
3324
- withdrawable: adjustedWithdrawable.toString()
3325
- },
3326
- agentWallet: {
3327
- address: agentWalletAddress || ((_k = platformAccountSummary === null || platformAccountSummary === void 0 ? void 0 : platformAccountSummary.agentWallet) === null || _k === void 0 ? void 0 : _k.address) || '',
3328
- status: agentWalletStatus || ((_l = platformAccountSummary === null || platformAccountSummary === void 0 ? void 0 : platformAccountSummary.agentWallet) === null || _l === void 0 ? void 0 : _l.status) || 'UNKNOWN'
3329
- }
3330
- };
3331
- return accountSummary;
3332
- }
3333
- /**
3334
- * Calculate total USD value of open limit orders
3335
- */
3336
- calculateTotalLimitOrderValue(openOrders) {
3337
- if (!(openOrders === null || openOrders === void 0 ? void 0 : openOrders.length)) {
3338
- return 0;
3339
- }
3340
- const totalValue = openOrders
3341
- .filter(order => order.status === 'OPEN' || order.status === 'PROCESSING')
3342
- .reduce((sum, order) => sum + order.usdValue, 0);
3343
- return totalValue;
3344
- }
3345
- /**
3346
- * Get real-time clearinghouse state from webData2
3347
- */
3348
- getClearinghouseState() {
3349
- var _a;
3350
- return ((_a = this.webData2) === null || _a === void 0 ? void 0 : _a.clearinghouseState) || null;
3351
- }
3352
- /**
3353
- * Check if real-time data is available
3354
- */
3355
- hasRealTimeData() {
3356
- var _a;
3357
- return !!((_a = this.webData2) === null || _a === void 0 ? void 0 : _a.clearinghouseState);
3358
- }
3359
- }
3360
-
3361
- /**
3362
- * Hook that calculates account summary by syncing platform data with HyperLiquid real-time data
3363
- */
3364
- const useCalculatedAccountSummary = (platformAccountSummary, platformOpenOrders, webData2, agentWalletAddress, agentWalletStatus) => {
3365
- const calculatedAccountSummary = useMemo(() => {
3366
- // Return null if we don't have platform account summary yet
3367
- if (!platformAccountSummary) {
3368
- return null;
3369
- }
3370
- // If we don't have real-time data yet, return platform summary as-is
3371
- if (!(webData2 === null || webData2 === void 0 ? void 0 : webData2.clearinghouseState)) {
3372
- return platformAccountSummary;
3373
- }
3374
- // Create calculator and compute account summary
3375
- const calculator = new AccountSummaryCalculator(webData2);
3376
- const calculated = calculator.calculateAccountSummary(platformAccountSummary, platformOpenOrders, agentWalletAddress, agentWalletStatus);
3377
- return calculated;
3378
- }, [platformAccountSummary, platformOpenOrders, webData2, agentWalletAddress, agentWalletStatus]);
3379
- return calculatedAccountSummary;
3380
- };
3381
-
3382
- /**
3383
- * Hook to access trade histories with loading state
3384
- */
3385
- const useTradeHistories = () => {
3386
- const context = useContext(PearHyperliquidContext);
3387
- if (!context) {
3388
- throw new Error('useTradeHistories must be used within a PearHyperliquidProvider');
3389
- }
3390
- const isLoading = useMemo(() => {
3391
- // Loading is true initially and becomes false once we get the first data
3392
- return context.data.tradeHistories === null && context.isConnected;
3393
- }, [context.data.tradeHistories, context.isConnected]);
3394
- return {
3395
- data: context.data.tradeHistories,
3396
- isLoading
3397
- };
3398
- };
3399
- /**
3400
- * Hook to access open positions with real-time calculations and loading state
3401
- */
3402
- const useOpenPositions = () => {
3403
- const context = useContext(PearHyperliquidContext);
3404
- if (!context) {
3405
- throw new Error('useOpenPositions must be used within a PearHyperliquidProvider');
3406
- }
3407
- // Use calculated positions that sync platform data with HyperLiquid real-time data
3408
- const calculatedPositions = useCalculatedOpenPositions(context.data.openPositions, context.webData2, context.allMids);
3409
- const isLoading = useMemo(() => {
3410
- // Loading is true initially and becomes false only when:
3411
- // 1. WebSocket has open-positions data
3412
- // 2. webData2 and allMids are ready (required for calculations)
3413
- // 3. Connection is established
3414
- return (context.isConnected &&
3415
- (context.data.openPositions === null || !context.webData2 || !context.allMids));
3416
- }, [context.data.openPositions, context.webData2, context.allMids, context.isConnected]);
3417
- return {
3418
- data: calculatedPositions,
3419
- isLoading
3420
- };
3421
- };
3422
- /**
3423
- * Hook to access open orders with loading state
3424
- */
3425
- const useOpenOrders = () => {
3426
- const context = useContext(PearHyperliquidContext);
3427
- if (!context) {
3428
- throw new Error('useOpenOrders must be used within a PearHyperliquidProvider');
3429
- }
3430
- const isLoading = useMemo(() => {
3431
- // Loading is true initially and becomes false once we get the first data
3432
- return context.data.openOrders === null && context.isConnected;
3433
- }, [context.data.openOrders, context.isConnected]);
3434
- return {
3435
- data: context.data.openOrders,
3436
- isLoading
3437
- };
3438
- };
3439
- /**
3440
- * Hook to access account summary with real-time calculations and loading state
3441
- */
3442
- const useAccountSummary = () => {
3443
- var _a, _b, _c, _d;
3444
- const context = useContext(PearHyperliquidContext);
3445
- if (!context) {
3446
- throw new Error('useAccountSummary must be used within a PearHyperliquidProvider');
3447
- }
3448
- // Use calculated account summary that syncs platform data with HyperLiquid real-time data
3449
- const calculatedAccountSummary = useCalculatedAccountSummary(context.data.accountSummary, context.data.openOrders, context.webData2, (_b = (_a = context.data.accountSummary) === null || _a === void 0 ? void 0 : _a.agentWallet) === null || _b === void 0 ? void 0 : _b.address, (_d = (_c = context.data.accountSummary) === null || _c === void 0 ? void 0 : _c.agentWallet) === null || _d === void 0 ? void 0 : _d.status);
3450
- const isLoading = useMemo(() => {
3451
- // Loading is true initially and becomes false once we get the first data
3452
- return context.data.accountSummary === null && context.isConnected;
3453
- }, [context.data.accountSummary, context.isConnected]);
3454
- return {
3455
- data: calculatedAccountSummary,
3456
- isLoading
3457
- };
3458
- };
3459
-
3460
- /**
3461
- * Extracts token metadata from WebData2 and AllMids data
3462
- */
3463
- class TokenMetadataExtractor {
3464
- /**
3465
- * Extracts comprehensive token metadata
3466
- * @param symbol - Token symbol
3467
- * @param webData2 - WebData2 response containing asset context and universe data
3468
- * @param allMids - AllMids data containing current prices
3469
- * @returns TokenMetadata or null if token not found
3470
- */
3471
- static extractTokenMetadata(symbol, webData2, allMids) {
3472
- if (!webData2 || !allMids) {
3473
- return null;
3474
- }
3475
- // Find token index in universe
3476
- const universeIndex = webData2.meta.universe.findIndex(asset => asset.name === symbol);
3477
- if (universeIndex === -1) {
3478
- return null;
3479
- }
3480
- const universeAsset = webData2.meta.universe[universeIndex];
3481
- const assetCtx = webData2.assetCtxs[universeIndex];
3482
- if (!assetCtx) {
3483
- return null;
3484
- }
3485
- // Get current price from allMids
3486
- const currentPriceStr = allMids.mids[symbol];
3487
- const currentPrice = currentPriceStr ? parseFloat(currentPriceStr) : 0;
3488
- // Get previous day price
3489
- const prevDayPrice = parseFloat(assetCtx.prevDayPx);
3490
- // Calculate 24h price change
3491
- const priceChange24h = currentPrice - prevDayPrice;
3492
- const priceChange24hPercent = prevDayPrice !== 0 ? (priceChange24h / prevDayPrice) * 100 : 0;
3493
- // Parse other metadata
3494
- const netFunding = parseFloat(assetCtx.funding);
3495
- const markPrice = parseFloat(assetCtx.markPx);
3496
- const oraclePrice = parseFloat(assetCtx.oraclePx);
3497
- return {
3498
- currentPrice,
3499
- prevDayPrice,
3500
- priceChange24h,
3501
- priceChange24hPercent,
3502
- netFunding,
3503
- maxLeverage: universeAsset.maxLeverage,
3504
- markPrice,
3505
- oraclePrice,
3506
- openInterest: assetCtx.openInterest,
3507
- dayVolume: assetCtx.dayNtlVlm,
3508
- };
3509
- }
3510
- /**
3511
- * Extracts metadata for multiple tokens
3512
- * @param symbols - Array of token symbols
3513
- * @param webData2 - WebData2 response
3514
- * @param allMids - AllMids data
3515
- * @returns Record of symbol to TokenMetadata
3516
- */
3517
- static extractMultipleTokensMetadata(symbols, webData2, allMids) {
3518
- const result = {};
3519
- for (const symbol of symbols) {
3520
- result[symbol] = this.extractTokenMetadata(symbol, webData2, allMids);
3521
- }
3522
- return result;
3523
- }
3524
- /**
3525
- * Checks if token data is available in WebData2
3526
- * @param symbol - Token symbol
3527
- * @param webData2 - WebData2 response
3528
- * @returns boolean indicating if token exists in universe
3529
- */
3530
- static isTokenAvailable(symbol, webData2) {
3531
- if (!webData2)
3532
- return false;
3533
- return webData2.meta.universe.some(asset => asset.name === symbol);
3534
- }
3535
- }
3536
-
3537
- /**
3538
- * Hook to access token selection state using provider's WebSocket data
3539
- */
3540
- const useTokenSelection = () => {
3541
- var _a;
3542
- const context = useContext(PearHyperliquidContext);
3543
- if (!context) {
3544
- throw new Error('useTokenSelection must be used within PearHyperliquidProvider');
3545
- }
3546
- const { webData2, allMids, tokenSelection, setTokenSelection } = context;
3547
- // Loading states
3548
- const isPriceDataReady = useMemo(() => {
3549
- return !!(webData2 && allMids);
3550
- }, [webData2, allMids]);
3551
- const isLoading = useMemo(() => {
3552
- // Check if any tokens have missing metadata when price data is available
3553
- if (!isPriceDataReady)
3554
- return true;
3555
- const allTokens = [...tokenSelection.longTokens, ...tokenSelection.shortTokens];
3556
- if (allTokens.length === 0)
3557
- return false;
3558
- // Loading if any token is missing metadata
3559
- return allTokens.some(token => !token.metadata);
3560
- }, [isPriceDataReady, tokenSelection.longTokens, tokenSelection.shortTokens]);
3561
- // Auto-update token metadata when WebSocket data changes
3562
- useEffect(() => {
3563
- if (!webData2 || !allMids)
3564
- return;
3565
- const allTokenSymbols = [...tokenSelection.longTokens, ...tokenSelection.shortTokens].map(t => t.symbol);
3566
- if (allTokenSymbols.length === 0)
3567
- return;
3568
- const metadataMap = TokenMetadataExtractor.extractMultipleTokensMetadata(allTokenSymbols, webData2, allMids);
3569
- setTokenSelection(prev => ({
3570
- ...prev,
3571
- longTokens: prev.longTokens.map(token => ({
3572
- ...token,
3573
- metadata: metadataMap[token.symbol] || undefined
3574
- })),
3575
- shortTokens: prev.shortTokens.map(token => ({
3576
- ...token,
3577
- metadata: metadataMap[token.symbol] || undefined
3578
- }))
3579
- }));
3580
- }, [webData2, allMids, setTokenSelection]);
3581
- // Calculate weighted ratio: LONG^WEIGHT * SHORT^-WEIGHT
3582
- const weightedRatio = useMemo(() => {
3583
- let longProduct = 1;
3584
- let shortProduct = 1;
3585
- // Calculate long side product: PRICE^(WEIGHT/100)
3586
- tokenSelection.longTokens.forEach(token => {
3587
- var _a;
3588
- if (((_a = token.metadata) === null || _a === void 0 ? void 0 : _a.currentPrice) && token.weight > 0) {
3589
- const weightFactor = token.weight / 100;
3590
- longProduct *= Math.pow(token.metadata.currentPrice, weightFactor);
3591
- }
3592
- });
3593
- // Calculate short side product: PRICE^-(WEIGHT/100)
3594
- tokenSelection.shortTokens.forEach(token => {
3595
- var _a;
3596
- if (((_a = token.metadata) === null || _a === void 0 ? void 0 : _a.currentPrice) && token.weight > 0) {
3597
- const weightFactor = token.weight / 100;
3598
- shortProduct *= Math.pow(token.metadata.currentPrice, -weightFactor);
3599
- }
3600
- });
3601
- return longProduct * shortProduct;
3602
- }, [tokenSelection.longTokens, tokenSelection.shortTokens]);
3603
- // Calculate 24h weighted ratio using previous day prices
3604
- const weightedRatio24h = useMemo(() => {
3605
- let longProduct = 1;
3606
- let shortProduct = 1;
3607
- // Calculate long side product: PREV_PRICE^(WEIGHT/100)
3608
- tokenSelection.longTokens.forEach(token => {
3609
- var _a;
3610
- if (((_a = token.metadata) === null || _a === void 0 ? void 0 : _a.prevDayPrice) && token.weight > 0) {
3611
- const weightFactor = token.weight / 100;
3612
- longProduct *= Math.pow(token.metadata.prevDayPrice, weightFactor);
3613
- }
3614
- });
3615
- // Calculate short side product: PREV_PRICE^-(WEIGHT/100)
3616
- tokenSelection.shortTokens.forEach(token => {
3617
- var _a;
3618
- if (((_a = token.metadata) === null || _a === void 0 ? void 0 : _a.prevDayPrice) && token.weight > 0) {
3619
- const weightFactor = token.weight / 100;
3620
- shortProduct *= Math.pow(token.metadata.prevDayPrice, -weightFactor);
3621
- }
3622
- });
3623
- return longProduct * shortProduct;
3624
- }, [tokenSelection.longTokens, tokenSelection.shortTokens]);
3625
- // Calculate sum of weighted net funding
3626
- const sumNetFunding = useMemo(() => {
3627
- let totalFunding = 0;
3628
- // Add long funding weighted by allocation
3629
- tokenSelection.longTokens.forEach(token => {
3630
- var _a;
3631
- if (((_a = token.metadata) === null || _a === void 0 ? void 0 : _a.netFunding) && token.weight > 0) {
3632
- const weightFactor = token.weight / 100;
3633
- totalFunding += token.metadata.netFunding * weightFactor;
3634
- }
3635
- });
3636
- // Subtract short funding weighted by allocation (since we're short)
3637
- tokenSelection.shortTokens.forEach(token => {
3638
- var _a;
3639
- if (((_a = token.metadata) === null || _a === void 0 ? void 0 : _a.netFunding) && token.weight > 0) {
3640
- const weightFactor = token.weight / 100;
3641
- totalFunding -= token.metadata.netFunding * weightFactor;
3642
- }
3643
- });
3644
- return totalFunding;
3645
- }, [tokenSelection.longTokens, tokenSelection.shortTokens]);
3646
- // Calculate max leverage (minimum of all token maxLeverages)
3647
- const maxLeverage = useMemo(() => {
3648
- var _a;
3649
- if (!((_a = webData2 === null || webData2 === void 0 ? void 0 : webData2.meta) === null || _a === void 0 ? void 0 : _a.universe))
3650
- return 0;
3651
- const allTokenSymbols = [...tokenSelection.longTokens, ...tokenSelection.shortTokens].map(t => t.symbol);
3652
- if (allTokenSymbols.length === 0)
3653
- return 0;
3654
- let minLeverage = Infinity;
3655
- allTokenSymbols.forEach(symbol => {
3656
- const tokenUniverse = webData2.meta.universe.find(u => u.name === symbol);
3657
- if (tokenUniverse === null || tokenUniverse === void 0 ? void 0 : tokenUniverse.maxLeverage) {
3658
- minLeverage = Math.min(minLeverage, tokenUniverse.maxLeverage);
3659
- }
3660
- });
3661
- return minLeverage === Infinity ? 0 : minLeverage;
3662
- }, [(_a = webData2 === null || webData2 === void 0 ? void 0 : webData2.meta) === null || _a === void 0 ? void 0 : _a.universe, tokenSelection.longTokens, tokenSelection.shortTokens]);
3663
- // Calculate minimum margin (10 * total number of tokens)
3664
- const minMargin = useMemo(() => {
3665
- const totalTokenCount = tokenSelection.longTokens.length + tokenSelection.shortTokens.length;
3666
- return 10 * totalTokenCount;
3667
- }, [tokenSelection.longTokens.length, tokenSelection.shortTokens.length]);
3668
- // Actions
3669
- const setLongTokens = useCallback((tokens) => {
3670
- setTokenSelection(prev => ({ ...prev, longTokens: tokens }));
3671
- }, [setTokenSelection]);
3672
- const setShortTokens = useCallback((tokens) => {
3673
- setTokenSelection(prev => ({ ...prev, shortTokens: tokens }));
3674
- }, [setTokenSelection]);
3675
- const updateTokenWeight = useCallback((isLong, index, newWeight) => {
3676
- const clampedWeight = Math.max(1, Math.min(100, newWeight));
3677
- setTokenSelection(prev => {
3678
- var _a, _b;
3679
- const currentLongTotal = prev.longTokens.reduce((sum, token) => sum + token.weight, 0);
3680
- const currentShortTotal = prev.shortTokens.reduce((sum, token) => sum + token.weight, 0);
3681
- if (isLong) {
3682
- const oldWeight = ((_a = prev.longTokens[index]) === null || _a === void 0 ? void 0 : _a.weight) || 0;
3683
- const weightDiff = clampedWeight - oldWeight;
3684
- const newLongTotal = currentLongTotal + weightDiff;
3685
- if (newLongTotal + currentShortTotal > 100) {
3686
- const maxAllowedWeight = Math.max(1, 100 - currentShortTotal - (currentLongTotal - oldWeight));
3687
- const updated = [...prev.longTokens];
3688
- updated[index] = { ...updated[index], weight: maxAllowedWeight };
3689
- return { ...prev, longTokens: updated };
3690
- }
3691
- else {
3692
- const updated = [...prev.longTokens];
3693
- updated[index] = { ...updated[index], weight: clampedWeight };
3694
- return { ...prev, longTokens: updated };
3695
- }
3696
- }
3697
- else {
3698
- const oldWeight = ((_b = prev.shortTokens[index]) === null || _b === void 0 ? void 0 : _b.weight) || 0;
3699
- const weightDiff = clampedWeight - oldWeight;
3700
- const newShortTotal = currentShortTotal + weightDiff;
3701
- if (currentLongTotal + newShortTotal > 100) {
3702
- const maxAllowedWeight = Math.max(1, 100 - currentLongTotal - (currentShortTotal - oldWeight));
3703
- const updated = [...prev.shortTokens];
3704
- updated[index] = { ...updated[index], weight: maxAllowedWeight };
3705
- return { ...prev, shortTokens: updated };
3706
- }
3707
- else {
3708
- const updated = [...prev.shortTokens];
3709
- updated[index] = { ...updated[index], weight: clampedWeight };
3710
- return { ...prev, shortTokens: updated };
3711
- }
3712
- }
3713
- });
3714
- }, [setTokenSelection]);
3715
- const addToken = useCallback((isLong) => {
3716
- const currentTokens = isLong ? tokenSelection.longTokens : tokenSelection.shortTokens;
3717
- const newIndex = currentTokens.length;
3718
- setTokenSelection(prev => ({
3719
- ...prev,
3720
- selectorConfig: { isLong, index: newIndex },
3721
- openTokenSelector: true,
3722
- }));
3723
- }, [tokenSelection.longTokens, tokenSelection.shortTokens, setTokenSelection]);
3724
- const removeToken = useCallback((isLong, index) => {
3725
- setTokenSelection(prev => {
3726
- if (isLong) {
3727
- const updated = prev.longTokens.filter((_, i) => i !== index);
3728
- return { ...prev, longTokens: updated };
3729
- }
3730
- else {
3731
- const updated = prev.shortTokens.filter((_, i) => i !== index);
3732
- return { ...prev, shortTokens: updated };
3733
- }
3734
- });
3735
- }, [setTokenSelection]);
3736
- const setOpenTokenSelector = useCallback((open) => {
3737
- setTokenSelection(prev => ({ ...prev, openTokenSelector: open }));
3738
- }, [setTokenSelection]);
3739
- const setSelectorConfig = useCallback((config) => {
3740
- setTokenSelection(prev => ({ ...prev, selectorConfig: config }));
3741
- }, [setTokenSelection]);
3742
- const setOpenConflictModal = useCallback((open) => {
3743
- setTokenSelection(prev => ({ ...prev, openConflictModal: open }));
3744
- }, [setTokenSelection]);
3745
- const setConflicts = useCallback((conflicts) => {
3746
- setTokenSelection(prev => ({ ...prev, conflicts }));
3747
- }, [setTokenSelection]);
3748
- const resetToDefaults = useCallback(() => {
3749
- setTokenSelection(prev => ({
3750
- ...prev,
3751
- longTokens: [
3752
- { symbol: 'HYPE', weight: 25 },
3753
- { symbol: 'BTC', weight: 25 }
3754
- ],
3755
- shortTokens: [
3756
- { symbol: 'AVAX', weight: 10 },
3757
- { symbol: 'SEI', weight: 10 },
3758
- { symbol: 'ADA', weight: 10 },
3759
- { symbol: 'TRUMP', weight: 10 },
3760
- { symbol: 'SUI', weight: 10 }
3761
- ],
3762
- openTokenSelector: false,
3763
- selectorConfig: null,
3764
- openConflictModal: false,
3765
- }));
3766
- }, [setTokenSelection]);
3767
- const handleTokenSelect = useCallback((selectedToken) => {
3768
- if (!tokenSelection.selectorConfig)
3769
- return;
3770
- const { isLong, index } = tokenSelection.selectorConfig;
3771
- const existingTokens = isLong ? tokenSelection.longTokens : tokenSelection.shortTokens;
3772
- // Check if token already exists
3773
- if (existingTokens.some(t => t.symbol === selectedToken))
3774
- return;
3775
- // Get metadata for new token
3776
- const metadata = TokenMetadataExtractor.extractTokenMetadata(selectedToken, webData2, allMids);
3777
- setTokenSelection(prev => {
3778
- if (index >= existingTokens.length) {
3779
- // Adding new token - calculate safe weight
3780
- const currentLongTotal = prev.longTokens.reduce((sum, token) => sum + token.weight, 0);
3781
- const currentShortTotal = prev.shortTokens.reduce((sum, token) => sum + token.weight, 0);
3782
- const currentTotal = currentLongTotal + currentShortTotal;
3783
- const maxAvailableWeight = Math.max(1, 100 - currentTotal);
3784
- const safeWeight = Math.min(20, maxAvailableWeight);
3785
- const newToken = {
3786
- symbol: selectedToken,
3787
- weight: safeWeight,
3788
- metadata: metadata || undefined
3789
- };
3790
- if (isLong) {
3791
- return { ...prev, longTokens: [...prev.longTokens, newToken] };
3792
- }
3793
- else {
3794
- return { ...prev, shortTokens: [...prev.shortTokens, newToken] };
3795
- }
3796
- }
3797
- else {
3798
- // Replacing existing token
3799
- if (isLong) {
3800
- const updated = [...prev.longTokens];
3801
- updated[index] = {
3802
- ...updated[index],
3803
- symbol: selectedToken,
3804
- metadata: metadata || undefined
3805
- };
3806
- return { ...prev, longTokens: updated };
3807
- }
3808
- else {
3809
- const updated = [...prev.shortTokens];
3810
- updated[index] = {
3811
- ...updated[index],
3812
- symbol: selectedToken,
3813
- metadata: metadata || undefined
3814
- };
3815
- return { ...prev, shortTokens: updated };
3816
- }
3817
- }
3818
- });
3819
- }, [tokenSelection.selectorConfig, tokenSelection.longTokens, tokenSelection.shortTokens, webData2, allMids, setTokenSelection]);
3820
- // updateTokenMetadata is now handled automatically by the useEffect above
3821
- return {
3822
- // State
3823
- longTokens: tokenSelection.longTokens,
3824
- shortTokens: tokenSelection.shortTokens,
3825
- openTokenSelector: tokenSelection.openTokenSelector,
3826
- selectorConfig: tokenSelection.selectorConfig,
3827
- openConflictModal: tokenSelection.openConflictModal,
3828
- conflicts: tokenSelection.conflicts,
3829
- // Loading states
3830
- isLoading,
3831
- isPriceDataReady,
3832
- // Calculated values
3833
- weightedRatio,
3834
- weightedRatio24h,
3835
- sumNetFunding,
3836
- maxLeverage,
3837
- minMargin,
3838
- // Actions
3839
- setLongTokens,
3840
- setShortTokens,
3841
- updateTokenWeight,
3842
- addToken,
3843
- removeToken,
3844
- handleTokenSelect,
3845
- setOpenTokenSelector,
3846
- setSelectorConfig,
3847
- setOpenConflictModal,
3848
- setConflicts,
3849
- resetToDefaults,
3850
- };
3851
- };
3852
-
3853
- /**
3854
- * Detects conflicts between selected tokens and existing positions
3855
- */
3856
- class ConflictDetector {
3857
- /**
3858
- * Detects conflicts between token selections and open positions
3859
- * @param longTokens - Selected long tokens
3860
- * @param shortTokens - Selected short tokens
3861
- * @param openPositions - Current open positions from API
3862
- * @returns Array of detected conflicts
3863
- */
3864
- static detectConflicts(longTokens, shortTokens, openPositions) {
3865
- const detectedConflicts = [];
3866
- if (!openPositions) {
3867
- return detectedConflicts;
3868
- }
3869
- // Check long tokens against existing short positions
3870
- longTokens.forEach((token) => {
3871
- const existingShortPosition = openPositions.find((pos) => {
3872
- var _a;
3873
- // Check multiple possible property names and side values
3874
- const symbol = pos.coin || pos.symbol || pos.asset;
3875
- const side = (_a = pos.side) === null || _a === void 0 ? void 0 : _a.toLowerCase();
3876
- return symbol === token.symbol && (side === 'short' || side === 'sell');
3877
- });
3878
- if (existingShortPosition) {
3879
- detectedConflicts.push({
3880
- symbol: token.symbol,
3881
- conflictType: 'short',
3882
- conflictMessage: `${token.symbol} Long conflicts with existing ${token.symbol} Short position`
3883
- });
3884
- }
3885
- });
3886
- // Check short tokens against existing long positions
3887
- shortTokens.forEach((token) => {
3888
- const existingLongPosition = openPositions.find((pos) => {
3889
- var _a;
3890
- // Check multiple possible property names and side values
3891
- const symbol = pos.coin || pos.symbol || pos.asset;
3892
- const side = (_a = pos.side) === null || _a === void 0 ? void 0 : _a.toLowerCase();
3893
- return symbol === token.symbol && (side === 'long' || side === 'buy');
3894
- });
3895
- if (existingLongPosition) {
3896
- detectedConflicts.push({
3897
- symbol: token.symbol,
3898
- conflictType: 'long',
3899
- conflictMessage: `${token.symbol} Short conflicts with existing ${token.symbol} Long position`
3900
- });
3901
- }
3902
- });
3903
- return detectedConflicts;
3904
- }
3905
- }
3906
-
3907
- export { AccountSummaryCalculator, ConflictDetector, PearHyperliquidClient, PearHyperliquidProvider, PearMigrationSDK, TokenMetadataExtractor, PearHyperliquidClient as default, useAccountSummary, useAddress, useCalculatedAccountSummary, useCalculatedOpenPositions, useHyperliquidNativeWebSocket, useHyperliquidWebSocket, useMigrationSDK, useOpenOrders, useOpenPositions, usePearHyperliquidClient, useTokenSelection, useTradeHistories };
3908
- //# sourceMappingURL=index.esm.js.map