@pear-protocol/hyperliquid-sdk 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2810 @@
1
+ import axios from 'axios';
2
+ import require$$0, { createContext, useMemo, useState, useEffect, useContext } 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.isSyncRunning = false;
98
+ this.client = client;
99
+ }
100
+ /**
101
+ * Sync trade history data - can only run one at a time
102
+ * If called while already running, returns immediately without making request
103
+ */
104
+ async syncTradeHistory(payload) {
105
+ // If sync is already running, return immediately
106
+ if (this.isSyncRunning) {
107
+ return null;
108
+ }
109
+ try {
110
+ this.isSyncRunning = true;
111
+ const response = await this.client.syncTradeHistory(payload);
112
+ return response;
113
+ }
114
+ finally {
115
+ this.isSyncRunning = false;
116
+ }
117
+ }
118
+ /**
119
+ * Sync open positions data - can only run one at a time
120
+ * If called while already running, returns immediately without making request
121
+ */
122
+ async syncOpenPositions(payload) {
123
+ // If sync is already running, return immediately
124
+ if (this.isSyncRunning) {
125
+ return null;
126
+ }
127
+ try {
128
+ this.isSyncRunning = true;
129
+ const response = await this.client.syncOpenPositions(payload);
130
+ return response;
131
+ }
132
+ finally {
133
+ this.isSyncRunning = false;
134
+ }
135
+ }
136
+ /**
137
+ * Sync open orders data - can only run one at a time
138
+ * If called while already running, returns immediately without making request
139
+ */
140
+ async syncOpenOrders(payload) {
141
+ // If sync is already running, return immediately
142
+ if (this.isSyncRunning) {
143
+ return null;
144
+ }
145
+ try {
146
+ this.isSyncRunning = true;
147
+ const response = await this.client.syncOpenOrders(payload);
148
+ return response;
149
+ }
150
+ finally {
151
+ this.isSyncRunning = false;
152
+ }
153
+ }
154
+ /**
155
+ * Check if sync is currently running
156
+ */
157
+ isSyncInProgress() {
158
+ return this.isSyncRunning;
159
+ }
160
+ /**
161
+ * Get the underlying client instance
162
+ */
163
+ getClient() {
164
+ return this.client;
165
+ }
166
+ /**
167
+ * Set authorization token on the client
168
+ */
169
+ setAuthToken(token) {
170
+ this.client.setAuthToken(token);
171
+ }
172
+ /**
173
+ * Set custom headers on the client
174
+ */
175
+ setHeaders(headers) {
176
+ this.client.setHeaders(headers);
177
+ }
178
+ /**
179
+ * Get base URL from client
180
+ */
181
+ getBaseUrl() {
182
+ return this.client.getBaseUrl();
183
+ }
184
+ }
185
+
186
+ var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
187
+
188
+ function getDefaultExportFromCjs (x) {
189
+ return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
190
+ }
191
+
192
+ var jsxRuntime = {exports: {}};
193
+
194
+ var reactJsxRuntime_production_min = {};
195
+
196
+ /**
197
+ * @license React
198
+ * react-jsx-runtime.production.min.js
199
+ *
200
+ * Copyright (c) Facebook, Inc. and its affiliates.
201
+ *
202
+ * This source code is licensed under the MIT license found in the
203
+ * LICENSE file in the root directory of this source tree.
204
+ */
205
+
206
+ var hasRequiredReactJsxRuntime_production_min;
207
+
208
+ function requireReactJsxRuntime_production_min () {
209
+ if (hasRequiredReactJsxRuntime_production_min) return reactJsxRuntime_production_min;
210
+ hasRequiredReactJsxRuntime_production_min = 1;
211
+ 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};
212
+ 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;
213
+ return reactJsxRuntime_production_min;
214
+ }
215
+
216
+ var reactJsxRuntime_development = {};
217
+
218
+ /**
219
+ * @license React
220
+ * react-jsx-runtime.development.js
221
+ *
222
+ * Copyright (c) Facebook, Inc. and its affiliates.
223
+ *
224
+ * This source code is licensed under the MIT license found in the
225
+ * LICENSE file in the root directory of this source tree.
226
+ */
227
+
228
+ var hasRequiredReactJsxRuntime_development;
229
+
230
+ function requireReactJsxRuntime_development () {
231
+ if (hasRequiredReactJsxRuntime_development) return reactJsxRuntime_development;
232
+ hasRequiredReactJsxRuntime_development = 1;
233
+
234
+ if (process.env.NODE_ENV !== "production") {
235
+ (function() {
236
+
237
+ var React = require$$0;
238
+
239
+ // ATTENTION
240
+ // When adding new symbols to this file,
241
+ // Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols'
242
+ // The Symbol used to tag the ReactElement-like types.
243
+ var REACT_ELEMENT_TYPE = Symbol.for('react.element');
244
+ var REACT_PORTAL_TYPE = Symbol.for('react.portal');
245
+ var REACT_FRAGMENT_TYPE = Symbol.for('react.fragment');
246
+ var REACT_STRICT_MODE_TYPE = Symbol.for('react.strict_mode');
247
+ var REACT_PROFILER_TYPE = Symbol.for('react.profiler');
248
+ var REACT_PROVIDER_TYPE = Symbol.for('react.provider');
249
+ var REACT_CONTEXT_TYPE = Symbol.for('react.context');
250
+ var REACT_FORWARD_REF_TYPE = Symbol.for('react.forward_ref');
251
+ var REACT_SUSPENSE_TYPE = Symbol.for('react.suspense');
252
+ var REACT_SUSPENSE_LIST_TYPE = Symbol.for('react.suspense_list');
253
+ var REACT_MEMO_TYPE = Symbol.for('react.memo');
254
+ var REACT_LAZY_TYPE = Symbol.for('react.lazy');
255
+ var REACT_OFFSCREEN_TYPE = Symbol.for('react.offscreen');
256
+ var MAYBE_ITERATOR_SYMBOL = Symbol.iterator;
257
+ var FAUX_ITERATOR_SYMBOL = '@@iterator';
258
+ function getIteratorFn(maybeIterable) {
259
+ if (maybeIterable === null || typeof maybeIterable !== 'object') {
260
+ return null;
261
+ }
262
+
263
+ var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL];
264
+
265
+ if (typeof maybeIterator === 'function') {
266
+ return maybeIterator;
267
+ }
268
+
269
+ return null;
270
+ }
271
+
272
+ var ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
273
+
274
+ function error(format) {
275
+ {
276
+ {
277
+ for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
278
+ args[_key2 - 1] = arguments[_key2];
279
+ }
280
+
281
+ printWarning('error', format, args);
282
+ }
283
+ }
284
+ }
285
+
286
+ function printWarning(level, format, args) {
287
+ // When changing this logic, you might want to also
288
+ // update consoleWithStackDev.www.js as well.
289
+ {
290
+ var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
291
+ var stack = ReactDebugCurrentFrame.getStackAddendum();
292
+
293
+ if (stack !== '') {
294
+ format += '%s';
295
+ args = args.concat([stack]);
296
+ } // eslint-disable-next-line react-internal/safe-string-coercion
297
+
298
+
299
+ var argsWithFormat = args.map(function (item) {
300
+ return String(item);
301
+ }); // Careful: RN currently depends on this prefix
302
+
303
+ argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it
304
+ // breaks IE9: https://github.com/facebook/react/issues/13610
305
+ // eslint-disable-next-line react-internal/no-production-logging
306
+
307
+ Function.prototype.apply.call(console[level], console, argsWithFormat);
308
+ }
309
+ }
310
+
311
+ // -----------------------------------------------------------------------------
312
+
313
+ var enableScopeAPI = false; // Experimental Create Event Handle API.
314
+ var enableCacheElement = false;
315
+ var enableTransitionTracing = false; // No known bugs, but needs performance testing
316
+
317
+ var enableLegacyHidden = false; // Enables unstable_avoidThisFallback feature in Fiber
318
+ // stuff. Intended to enable React core members to more easily debug scheduling
319
+ // issues in DEV builds.
320
+
321
+ var enableDebugTracing = false; // Track which Fiber(s) schedule render work.
322
+
323
+ var REACT_MODULE_REFERENCE;
324
+
325
+ {
326
+ REACT_MODULE_REFERENCE = Symbol.for('react.module.reference');
327
+ }
328
+
329
+ function isValidElementType(type) {
330
+ if (typeof type === 'string' || typeof type === 'function') {
331
+ return true;
332
+ } // Note: typeof might be other than 'symbol' or 'number' (e.g. if it's a polyfill).
333
+
334
+
335
+ 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 ) {
336
+ return true;
337
+ }
338
+
339
+ if (typeof type === 'object' && type !== null) {
340
+ 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
341
+ // types supported by any Flight configuration anywhere since
342
+ // we don't know which Flight build this will end up being used
343
+ // with.
344
+ type.$$typeof === REACT_MODULE_REFERENCE || type.getModuleId !== undefined) {
345
+ return true;
346
+ }
347
+ }
348
+
349
+ return false;
350
+ }
351
+
352
+ function getWrappedName(outerType, innerType, wrapperName) {
353
+ var displayName = outerType.displayName;
354
+
355
+ if (displayName) {
356
+ return displayName;
357
+ }
358
+
359
+ var functionName = innerType.displayName || innerType.name || '';
360
+ return functionName !== '' ? wrapperName + "(" + functionName + ")" : wrapperName;
361
+ } // Keep in sync with react-reconciler/getComponentNameFromFiber
362
+
363
+
364
+ function getContextName(type) {
365
+ return type.displayName || 'Context';
366
+ } // Note that the reconciler package should generally prefer to use getComponentNameFromFiber() instead.
367
+
368
+
369
+ function getComponentNameFromType(type) {
370
+ if (type == null) {
371
+ // Host root, text node or just invalid type.
372
+ return null;
373
+ }
374
+
375
+ {
376
+ if (typeof type.tag === 'number') {
377
+ error('Received an unexpected object in getComponentNameFromType(). ' + 'This is likely a bug in React. Please file an issue.');
378
+ }
379
+ }
380
+
381
+ if (typeof type === 'function') {
382
+ return type.displayName || type.name || null;
383
+ }
384
+
385
+ if (typeof type === 'string') {
386
+ return type;
387
+ }
388
+
389
+ switch (type) {
390
+ case REACT_FRAGMENT_TYPE:
391
+ return 'Fragment';
392
+
393
+ case REACT_PORTAL_TYPE:
394
+ return 'Portal';
395
+
396
+ case REACT_PROFILER_TYPE:
397
+ return 'Profiler';
398
+
399
+ case REACT_STRICT_MODE_TYPE:
400
+ return 'StrictMode';
401
+
402
+ case REACT_SUSPENSE_TYPE:
403
+ return 'Suspense';
404
+
405
+ case REACT_SUSPENSE_LIST_TYPE:
406
+ return 'SuspenseList';
407
+
408
+ }
409
+
410
+ if (typeof type === 'object') {
411
+ switch (type.$$typeof) {
412
+ case REACT_CONTEXT_TYPE:
413
+ var context = type;
414
+ return getContextName(context) + '.Consumer';
415
+
416
+ case REACT_PROVIDER_TYPE:
417
+ var provider = type;
418
+ return getContextName(provider._context) + '.Provider';
419
+
420
+ case REACT_FORWARD_REF_TYPE:
421
+ return getWrappedName(type, type.render, 'ForwardRef');
422
+
423
+ case REACT_MEMO_TYPE:
424
+ var outerName = type.displayName || null;
425
+
426
+ if (outerName !== null) {
427
+ return outerName;
428
+ }
429
+
430
+ return getComponentNameFromType(type.type) || 'Memo';
431
+
432
+ case REACT_LAZY_TYPE:
433
+ {
434
+ var lazyComponent = type;
435
+ var payload = lazyComponent._payload;
436
+ var init = lazyComponent._init;
437
+
438
+ try {
439
+ return getComponentNameFromType(init(payload));
440
+ } catch (x) {
441
+ return null;
442
+ }
443
+ }
444
+
445
+ // eslint-disable-next-line no-fallthrough
446
+ }
447
+ }
448
+
449
+ return null;
450
+ }
451
+
452
+ var assign = Object.assign;
453
+
454
+ // Helpers to patch console.logs to avoid logging during side-effect free
455
+ // replaying on render function. This currently only patches the object
456
+ // lazily which won't cover if the log function was extracted eagerly.
457
+ // We could also eagerly patch the method.
458
+ var disabledDepth = 0;
459
+ var prevLog;
460
+ var prevInfo;
461
+ var prevWarn;
462
+ var prevError;
463
+ var prevGroup;
464
+ var prevGroupCollapsed;
465
+ var prevGroupEnd;
466
+
467
+ function disabledLog() {}
468
+
469
+ disabledLog.__reactDisabledLog = true;
470
+ function disableLogs() {
471
+ {
472
+ if (disabledDepth === 0) {
473
+ /* eslint-disable react-internal/no-production-logging */
474
+ prevLog = console.log;
475
+ prevInfo = console.info;
476
+ prevWarn = console.warn;
477
+ prevError = console.error;
478
+ prevGroup = console.group;
479
+ prevGroupCollapsed = console.groupCollapsed;
480
+ prevGroupEnd = console.groupEnd; // https://github.com/facebook/react/issues/19099
481
+
482
+ var props = {
483
+ configurable: true,
484
+ enumerable: true,
485
+ value: disabledLog,
486
+ writable: true
487
+ }; // $FlowFixMe Flow thinks console is immutable.
488
+
489
+ Object.defineProperties(console, {
490
+ info: props,
491
+ log: props,
492
+ warn: props,
493
+ error: props,
494
+ group: props,
495
+ groupCollapsed: props,
496
+ groupEnd: props
497
+ });
498
+ /* eslint-enable react-internal/no-production-logging */
499
+ }
500
+
501
+ disabledDepth++;
502
+ }
503
+ }
504
+ function reenableLogs() {
505
+ {
506
+ disabledDepth--;
507
+
508
+ if (disabledDepth === 0) {
509
+ /* eslint-disable react-internal/no-production-logging */
510
+ var props = {
511
+ configurable: true,
512
+ enumerable: true,
513
+ writable: true
514
+ }; // $FlowFixMe Flow thinks console is immutable.
515
+
516
+ Object.defineProperties(console, {
517
+ log: assign({}, props, {
518
+ value: prevLog
519
+ }),
520
+ info: assign({}, props, {
521
+ value: prevInfo
522
+ }),
523
+ warn: assign({}, props, {
524
+ value: prevWarn
525
+ }),
526
+ error: assign({}, props, {
527
+ value: prevError
528
+ }),
529
+ group: assign({}, props, {
530
+ value: prevGroup
531
+ }),
532
+ groupCollapsed: assign({}, props, {
533
+ value: prevGroupCollapsed
534
+ }),
535
+ groupEnd: assign({}, props, {
536
+ value: prevGroupEnd
537
+ })
538
+ });
539
+ /* eslint-enable react-internal/no-production-logging */
540
+ }
541
+
542
+ if (disabledDepth < 0) {
543
+ error('disabledDepth fell below zero. ' + 'This is a bug in React. Please file an issue.');
544
+ }
545
+ }
546
+ }
547
+
548
+ var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher;
549
+ var prefix;
550
+ function describeBuiltInComponentFrame(name, source, ownerFn) {
551
+ {
552
+ if (prefix === undefined) {
553
+ // Extract the VM specific prefix used by each line.
554
+ try {
555
+ throw Error();
556
+ } catch (x) {
557
+ var match = x.stack.trim().match(/\n( *(at )?)/);
558
+ prefix = match && match[1] || '';
559
+ }
560
+ } // We use the prefix to ensure our stacks line up with native stack frames.
561
+
562
+
563
+ return '\n' + prefix + name;
564
+ }
565
+ }
566
+ var reentry = false;
567
+ var componentFrameCache;
568
+
569
+ {
570
+ var PossiblyWeakMap = typeof WeakMap === 'function' ? WeakMap : Map;
571
+ componentFrameCache = new PossiblyWeakMap();
572
+ }
573
+
574
+ function describeNativeComponentFrame(fn, construct) {
575
+ // If something asked for a stack inside a fake render, it should get ignored.
576
+ if ( !fn || reentry) {
577
+ return '';
578
+ }
579
+
580
+ {
581
+ var frame = componentFrameCache.get(fn);
582
+
583
+ if (frame !== undefined) {
584
+ return frame;
585
+ }
586
+ }
587
+
588
+ var control;
589
+ reentry = true;
590
+ var previousPrepareStackTrace = Error.prepareStackTrace; // $FlowFixMe It does accept undefined.
591
+
592
+ Error.prepareStackTrace = undefined;
593
+ var previousDispatcher;
594
+
595
+ {
596
+ previousDispatcher = ReactCurrentDispatcher.current; // Set the dispatcher in DEV because this might be call in the render function
597
+ // for warnings.
598
+
599
+ ReactCurrentDispatcher.current = null;
600
+ disableLogs();
601
+ }
602
+
603
+ try {
604
+ // This should throw.
605
+ if (construct) {
606
+ // Something should be setting the props in the constructor.
607
+ var Fake = function () {
608
+ throw Error();
609
+ }; // $FlowFixMe
610
+
611
+
612
+ Object.defineProperty(Fake.prototype, 'props', {
613
+ set: function () {
614
+ // We use a throwing setter instead of frozen or non-writable props
615
+ // because that won't throw in a non-strict mode function.
616
+ throw Error();
617
+ }
618
+ });
619
+
620
+ if (typeof Reflect === 'object' && Reflect.construct) {
621
+ // We construct a different control for this case to include any extra
622
+ // frames added by the construct call.
623
+ try {
624
+ Reflect.construct(Fake, []);
625
+ } catch (x) {
626
+ control = x;
627
+ }
628
+
629
+ Reflect.construct(fn, [], Fake);
630
+ } else {
631
+ try {
632
+ Fake.call();
633
+ } catch (x) {
634
+ control = x;
635
+ }
636
+
637
+ fn.call(Fake.prototype);
638
+ }
639
+ } else {
640
+ try {
641
+ throw Error();
642
+ } catch (x) {
643
+ control = x;
644
+ }
645
+
646
+ fn();
647
+ }
648
+ } catch (sample) {
649
+ // This is inlined manually because closure doesn't do it for us.
650
+ if (sample && control && typeof sample.stack === 'string') {
651
+ // This extracts the first frame from the sample that isn't also in the control.
652
+ // Skipping one frame that we assume is the frame that calls the two.
653
+ var sampleLines = sample.stack.split('\n');
654
+ var controlLines = control.stack.split('\n');
655
+ var s = sampleLines.length - 1;
656
+ var c = controlLines.length - 1;
657
+
658
+ while (s >= 1 && c >= 0 && sampleLines[s] !== controlLines[c]) {
659
+ // We expect at least one stack frame to be shared.
660
+ // Typically this will be the root most one. However, stack frames may be
661
+ // cut off due to maximum stack limits. In this case, one maybe cut off
662
+ // earlier than the other. We assume that the sample is longer or the same
663
+ // and there for cut off earlier. So we should find the root most frame in
664
+ // the sample somewhere in the control.
665
+ c--;
666
+ }
667
+
668
+ for (; s >= 1 && c >= 0; s--, c--) {
669
+ // Next we find the first one that isn't the same which should be the
670
+ // frame that called our sample function and the control.
671
+ if (sampleLines[s] !== controlLines[c]) {
672
+ // In V8, the first line is describing the message but other VMs don't.
673
+ // If we're about to return the first line, and the control is also on the same
674
+ // line, that's a pretty good indicator that our sample threw at same line as
675
+ // the control. I.e. before we entered the sample frame. So we ignore this result.
676
+ // This can happen if you passed a class to function component, or non-function.
677
+ if (s !== 1 || c !== 1) {
678
+ do {
679
+ s--;
680
+ c--; // We may still have similar intermediate frames from the construct call.
681
+ // The next one that isn't the same should be our match though.
682
+
683
+ if (c < 0 || sampleLines[s] !== controlLines[c]) {
684
+ // V8 adds a "new" prefix for native classes. Let's remove it to make it prettier.
685
+ var _frame = '\n' + sampleLines[s].replace(' at new ', ' at '); // If our component frame is labeled "<anonymous>"
686
+ // but we have a user-provided "displayName"
687
+ // splice it in to make the stack more readable.
688
+
689
+
690
+ if (fn.displayName && _frame.includes('<anonymous>')) {
691
+ _frame = _frame.replace('<anonymous>', fn.displayName);
692
+ }
693
+
694
+ {
695
+ if (typeof fn === 'function') {
696
+ componentFrameCache.set(fn, _frame);
697
+ }
698
+ } // Return the line we found.
699
+
700
+
701
+ return _frame;
702
+ }
703
+ } while (s >= 1 && c >= 0);
704
+ }
705
+
706
+ break;
707
+ }
708
+ }
709
+ }
710
+ } finally {
711
+ reentry = false;
712
+
713
+ {
714
+ ReactCurrentDispatcher.current = previousDispatcher;
715
+ reenableLogs();
716
+ }
717
+
718
+ Error.prepareStackTrace = previousPrepareStackTrace;
719
+ } // Fallback to just using the name if we couldn't make it throw.
720
+
721
+
722
+ var name = fn ? fn.displayName || fn.name : '';
723
+ var syntheticFrame = name ? describeBuiltInComponentFrame(name) : '';
724
+
725
+ {
726
+ if (typeof fn === 'function') {
727
+ componentFrameCache.set(fn, syntheticFrame);
728
+ }
729
+ }
730
+
731
+ return syntheticFrame;
732
+ }
733
+ function describeFunctionComponentFrame(fn, source, ownerFn) {
734
+ {
735
+ return describeNativeComponentFrame(fn, false);
736
+ }
737
+ }
738
+
739
+ function shouldConstruct(Component) {
740
+ var prototype = Component.prototype;
741
+ return !!(prototype && prototype.isReactComponent);
742
+ }
743
+
744
+ function describeUnknownElementTypeFrameInDEV(type, source, ownerFn) {
745
+
746
+ if (type == null) {
747
+ return '';
748
+ }
749
+
750
+ if (typeof type === 'function') {
751
+ {
752
+ return describeNativeComponentFrame(type, shouldConstruct(type));
753
+ }
754
+ }
755
+
756
+ if (typeof type === 'string') {
757
+ return describeBuiltInComponentFrame(type);
758
+ }
759
+
760
+ switch (type) {
761
+ case REACT_SUSPENSE_TYPE:
762
+ return describeBuiltInComponentFrame('Suspense');
763
+
764
+ case REACT_SUSPENSE_LIST_TYPE:
765
+ return describeBuiltInComponentFrame('SuspenseList');
766
+ }
767
+
768
+ if (typeof type === 'object') {
769
+ switch (type.$$typeof) {
770
+ case REACT_FORWARD_REF_TYPE:
771
+ return describeFunctionComponentFrame(type.render);
772
+
773
+ case REACT_MEMO_TYPE:
774
+ // Memo may contain any component type so we recursively resolve it.
775
+ return describeUnknownElementTypeFrameInDEV(type.type, source, ownerFn);
776
+
777
+ case REACT_LAZY_TYPE:
778
+ {
779
+ var lazyComponent = type;
780
+ var payload = lazyComponent._payload;
781
+ var init = lazyComponent._init;
782
+
783
+ try {
784
+ // Lazy may contain any component type so we recursively resolve it.
785
+ return describeUnknownElementTypeFrameInDEV(init(payload), source, ownerFn);
786
+ } catch (x) {}
787
+ }
788
+ }
789
+ }
790
+
791
+ return '';
792
+ }
793
+
794
+ var hasOwnProperty = Object.prototype.hasOwnProperty;
795
+
796
+ var loggedTypeFailures = {};
797
+ var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
798
+
799
+ function setCurrentlyValidatingElement(element) {
800
+ {
801
+ if (element) {
802
+ var owner = element._owner;
803
+ var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null);
804
+ ReactDebugCurrentFrame.setExtraStackFrame(stack);
805
+ } else {
806
+ ReactDebugCurrentFrame.setExtraStackFrame(null);
807
+ }
808
+ }
809
+ }
810
+
811
+ function checkPropTypes(typeSpecs, values, location, componentName, element) {
812
+ {
813
+ // $FlowFixMe This is okay but Flow doesn't know it.
814
+ var has = Function.call.bind(hasOwnProperty);
815
+
816
+ for (var typeSpecName in typeSpecs) {
817
+ if (has(typeSpecs, typeSpecName)) {
818
+ var error$1 = void 0; // Prop type validation may throw. In case they do, we don't want to
819
+ // fail the render phase where it didn't fail before. So we log it.
820
+ // After these have been cleaned up, we'll let them throw.
821
+
822
+ try {
823
+ // This is intentionally an invariant that gets caught. It's the same
824
+ // behavior as without this statement except with a better message.
825
+ if (typeof typeSpecs[typeSpecName] !== 'function') {
826
+ // eslint-disable-next-line react-internal/prod-error-codes
827
+ 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`.');
828
+ err.name = 'Invariant Violation';
829
+ throw err;
830
+ }
831
+
832
+ error$1 = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED');
833
+ } catch (ex) {
834
+ error$1 = ex;
835
+ }
836
+
837
+ if (error$1 && !(error$1 instanceof Error)) {
838
+ setCurrentlyValidatingElement(element);
839
+
840
+ 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);
841
+
842
+ setCurrentlyValidatingElement(null);
843
+ }
844
+
845
+ if (error$1 instanceof Error && !(error$1.message in loggedTypeFailures)) {
846
+ // Only monitor this failure once because there tends to be a lot of the
847
+ // same error.
848
+ loggedTypeFailures[error$1.message] = true;
849
+ setCurrentlyValidatingElement(element);
850
+
851
+ error('Failed %s type: %s', location, error$1.message);
852
+
853
+ setCurrentlyValidatingElement(null);
854
+ }
855
+ }
856
+ }
857
+ }
858
+ }
859
+
860
+ var isArrayImpl = Array.isArray; // eslint-disable-next-line no-redeclare
861
+
862
+ function isArray(a) {
863
+ return isArrayImpl(a);
864
+ }
865
+
866
+ /*
867
+ * The `'' + value` pattern (used in in perf-sensitive code) throws for Symbol
868
+ * and Temporal.* types. See https://github.com/facebook/react/pull/22064.
869
+ *
870
+ * The functions in this module will throw an easier-to-understand,
871
+ * easier-to-debug exception with a clear errors message message explaining the
872
+ * problem. (Instead of a confusing exception thrown inside the implementation
873
+ * of the `value` object).
874
+ */
875
+ // $FlowFixMe only called in DEV, so void return is not possible.
876
+ function typeName(value) {
877
+ {
878
+ // toStringTag is needed for namespaced types like Temporal.Instant
879
+ var hasToStringTag = typeof Symbol === 'function' && Symbol.toStringTag;
880
+ var type = hasToStringTag && value[Symbol.toStringTag] || value.constructor.name || 'Object';
881
+ return type;
882
+ }
883
+ } // $FlowFixMe only called in DEV, so void return is not possible.
884
+
885
+
886
+ function willCoercionThrow(value) {
887
+ {
888
+ try {
889
+ testStringCoercion(value);
890
+ return false;
891
+ } catch (e) {
892
+ return true;
893
+ }
894
+ }
895
+ }
896
+
897
+ function testStringCoercion(value) {
898
+ // If you ended up here by following an exception call stack, here's what's
899
+ // happened: you supplied an object or symbol value to React (as a prop, key,
900
+ // DOM attribute, CSS property, string ref, etc.) and when React tried to
901
+ // coerce it to a string using `'' + value`, an exception was thrown.
902
+ //
903
+ // The most common types that will cause this exception are `Symbol` instances
904
+ // and Temporal objects like `Temporal.Instant`. But any object that has a
905
+ // `valueOf` or `[Symbol.toPrimitive]` method that throws will also cause this
906
+ // exception. (Library authors do this to prevent users from using built-in
907
+ // numeric operators like `+` or comparison operators like `>=` because custom
908
+ // methods are needed to perform accurate arithmetic or comparison.)
909
+ //
910
+ // To fix the problem, coerce this object or symbol value to a string before
911
+ // passing it to React. The most reliable way is usually `String(value)`.
912
+ //
913
+ // To find which value is throwing, check the browser or debugger console.
914
+ // Before this exception was thrown, there should be `console.error` output
915
+ // that shows the type (Symbol, Temporal.PlainDate, etc.) that caused the
916
+ // problem and how that type was used: key, atrribute, input value prop, etc.
917
+ // In most cases, this console output also shows the component and its
918
+ // ancestor components where the exception happened.
919
+ //
920
+ // eslint-disable-next-line react-internal/safe-string-coercion
921
+ return '' + value;
922
+ }
923
+ function checkKeyStringCoercion(value) {
924
+ {
925
+ if (willCoercionThrow(value)) {
926
+ error('The provided key is an unsupported type %s.' + ' This value must be coerced to a string before before using it here.', typeName(value));
927
+
928
+ return testStringCoercion(value); // throw (to help callers find troubleshooting comments)
929
+ }
930
+ }
931
+ }
932
+
933
+ var ReactCurrentOwner = ReactSharedInternals.ReactCurrentOwner;
934
+ var RESERVED_PROPS = {
935
+ key: true,
936
+ ref: true,
937
+ __self: true,
938
+ __source: true
939
+ };
940
+ var specialPropKeyWarningShown;
941
+ var specialPropRefWarningShown;
942
+ var didWarnAboutStringRefs;
943
+
944
+ {
945
+ didWarnAboutStringRefs = {};
946
+ }
947
+
948
+ function hasValidRef(config) {
949
+ {
950
+ if (hasOwnProperty.call(config, 'ref')) {
951
+ var getter = Object.getOwnPropertyDescriptor(config, 'ref').get;
952
+
953
+ if (getter && getter.isReactWarning) {
954
+ return false;
955
+ }
956
+ }
957
+ }
958
+
959
+ return config.ref !== undefined;
960
+ }
961
+
962
+ function hasValidKey(config) {
963
+ {
964
+ if (hasOwnProperty.call(config, 'key')) {
965
+ var getter = Object.getOwnPropertyDescriptor(config, 'key').get;
966
+
967
+ if (getter && getter.isReactWarning) {
968
+ return false;
969
+ }
970
+ }
971
+ }
972
+
973
+ return config.key !== undefined;
974
+ }
975
+
976
+ function warnIfStringRefCannotBeAutoConverted(config, self) {
977
+ {
978
+ if (typeof config.ref === 'string' && ReactCurrentOwner.current && self && ReactCurrentOwner.current.stateNode !== self) {
979
+ var componentName = getComponentNameFromType(ReactCurrentOwner.current.type);
980
+
981
+ if (!didWarnAboutStringRefs[componentName]) {
982
+ 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);
983
+
984
+ didWarnAboutStringRefs[componentName] = true;
985
+ }
986
+ }
987
+ }
988
+ }
989
+
990
+ function defineKeyPropWarningGetter(props, displayName) {
991
+ {
992
+ var warnAboutAccessingKey = function () {
993
+ if (!specialPropKeyWarningShown) {
994
+ specialPropKeyWarningShown = true;
995
+
996
+ 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);
997
+ }
998
+ };
999
+
1000
+ warnAboutAccessingKey.isReactWarning = true;
1001
+ Object.defineProperty(props, 'key', {
1002
+ get: warnAboutAccessingKey,
1003
+ configurable: true
1004
+ });
1005
+ }
1006
+ }
1007
+
1008
+ function defineRefPropWarningGetter(props, displayName) {
1009
+ {
1010
+ var warnAboutAccessingRef = function () {
1011
+ if (!specialPropRefWarningShown) {
1012
+ specialPropRefWarningShown = true;
1013
+
1014
+ 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);
1015
+ }
1016
+ };
1017
+
1018
+ warnAboutAccessingRef.isReactWarning = true;
1019
+ Object.defineProperty(props, 'ref', {
1020
+ get: warnAboutAccessingRef,
1021
+ configurable: true
1022
+ });
1023
+ }
1024
+ }
1025
+ /**
1026
+ * Factory method to create a new React element. This no longer adheres to
1027
+ * the class pattern, so do not use new to call it. Also, instanceof check
1028
+ * will not work. Instead test $$typeof field against Symbol.for('react.element') to check
1029
+ * if something is a React Element.
1030
+ *
1031
+ * @param {*} type
1032
+ * @param {*} props
1033
+ * @param {*} key
1034
+ * @param {string|object} ref
1035
+ * @param {*} owner
1036
+ * @param {*} self A *temporary* helper to detect places where `this` is
1037
+ * different from the `owner` when React.createElement is called, so that we
1038
+ * can warn. We want to get rid of owner and replace string `ref`s with arrow
1039
+ * functions, and as long as `this` and owner are the same, there will be no
1040
+ * change in behavior.
1041
+ * @param {*} source An annotation object (added by a transpiler or otherwise)
1042
+ * indicating filename, line number, and/or other information.
1043
+ * @internal
1044
+ */
1045
+
1046
+
1047
+ var ReactElement = function (type, key, ref, self, source, owner, props) {
1048
+ var element = {
1049
+ // This tag allows us to uniquely identify this as a React Element
1050
+ $$typeof: REACT_ELEMENT_TYPE,
1051
+ // Built-in properties that belong on the element
1052
+ type: type,
1053
+ key: key,
1054
+ ref: ref,
1055
+ props: props,
1056
+ // Record the component responsible for creating this element.
1057
+ _owner: owner
1058
+ };
1059
+
1060
+ {
1061
+ // The validation flag is currently mutative. We put it on
1062
+ // an external backing store so that we can freeze the whole object.
1063
+ // This can be replaced with a WeakMap once they are implemented in
1064
+ // commonly used development environments.
1065
+ element._store = {}; // To make comparing ReactElements easier for testing purposes, we make
1066
+ // the validation flag non-enumerable (where possible, which should
1067
+ // include every environment we run tests in), so the test framework
1068
+ // ignores it.
1069
+
1070
+ Object.defineProperty(element._store, 'validated', {
1071
+ configurable: false,
1072
+ enumerable: false,
1073
+ writable: true,
1074
+ value: false
1075
+ }); // self and source are DEV only properties.
1076
+
1077
+ Object.defineProperty(element, '_self', {
1078
+ configurable: false,
1079
+ enumerable: false,
1080
+ writable: false,
1081
+ value: self
1082
+ }); // Two elements created in two different places should be considered
1083
+ // equal for testing purposes and therefore we hide it from enumeration.
1084
+
1085
+ Object.defineProperty(element, '_source', {
1086
+ configurable: false,
1087
+ enumerable: false,
1088
+ writable: false,
1089
+ value: source
1090
+ });
1091
+
1092
+ if (Object.freeze) {
1093
+ Object.freeze(element.props);
1094
+ Object.freeze(element);
1095
+ }
1096
+ }
1097
+
1098
+ return element;
1099
+ };
1100
+ /**
1101
+ * https://github.com/reactjs/rfcs/pull/107
1102
+ * @param {*} type
1103
+ * @param {object} props
1104
+ * @param {string} key
1105
+ */
1106
+
1107
+ function jsxDEV(type, config, maybeKey, source, self) {
1108
+ {
1109
+ var propName; // Reserved names are extracted
1110
+
1111
+ var props = {};
1112
+ var key = null;
1113
+ var ref = null; // Currently, key can be spread in as a prop. This causes a potential
1114
+ // issue if key is also explicitly declared (ie. <div {...props} key="Hi" />
1115
+ // or <div key="Hi" {...props} /> ). We want to deprecate key spread,
1116
+ // but as an intermediary step, we will use jsxDEV for everything except
1117
+ // <div {...props} key="Hi" />, because we aren't currently able to tell if
1118
+ // key is explicitly declared to be undefined or not.
1119
+
1120
+ if (maybeKey !== undefined) {
1121
+ {
1122
+ checkKeyStringCoercion(maybeKey);
1123
+ }
1124
+
1125
+ key = '' + maybeKey;
1126
+ }
1127
+
1128
+ if (hasValidKey(config)) {
1129
+ {
1130
+ checkKeyStringCoercion(config.key);
1131
+ }
1132
+
1133
+ key = '' + config.key;
1134
+ }
1135
+
1136
+ if (hasValidRef(config)) {
1137
+ ref = config.ref;
1138
+ warnIfStringRefCannotBeAutoConverted(config, self);
1139
+ } // Remaining properties are added to a new props object
1140
+
1141
+
1142
+ for (propName in config) {
1143
+ if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) {
1144
+ props[propName] = config[propName];
1145
+ }
1146
+ } // Resolve default props
1147
+
1148
+
1149
+ if (type && type.defaultProps) {
1150
+ var defaultProps = type.defaultProps;
1151
+
1152
+ for (propName in defaultProps) {
1153
+ if (props[propName] === undefined) {
1154
+ props[propName] = defaultProps[propName];
1155
+ }
1156
+ }
1157
+ }
1158
+
1159
+ if (key || ref) {
1160
+ var displayName = typeof type === 'function' ? type.displayName || type.name || 'Unknown' : type;
1161
+
1162
+ if (key) {
1163
+ defineKeyPropWarningGetter(props, displayName);
1164
+ }
1165
+
1166
+ if (ref) {
1167
+ defineRefPropWarningGetter(props, displayName);
1168
+ }
1169
+ }
1170
+
1171
+ return ReactElement(type, key, ref, self, source, ReactCurrentOwner.current, props);
1172
+ }
1173
+ }
1174
+
1175
+ var ReactCurrentOwner$1 = ReactSharedInternals.ReactCurrentOwner;
1176
+ var ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame;
1177
+
1178
+ function setCurrentlyValidatingElement$1(element) {
1179
+ {
1180
+ if (element) {
1181
+ var owner = element._owner;
1182
+ var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null);
1183
+ ReactDebugCurrentFrame$1.setExtraStackFrame(stack);
1184
+ } else {
1185
+ ReactDebugCurrentFrame$1.setExtraStackFrame(null);
1186
+ }
1187
+ }
1188
+ }
1189
+
1190
+ var propTypesMisspellWarningShown;
1191
+
1192
+ {
1193
+ propTypesMisspellWarningShown = false;
1194
+ }
1195
+ /**
1196
+ * Verifies the object is a ReactElement.
1197
+ * See https://reactjs.org/docs/react-api.html#isvalidelement
1198
+ * @param {?object} object
1199
+ * @return {boolean} True if `object` is a ReactElement.
1200
+ * @final
1201
+ */
1202
+
1203
+
1204
+ function isValidElement(object) {
1205
+ {
1206
+ return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE;
1207
+ }
1208
+ }
1209
+
1210
+ function getDeclarationErrorAddendum() {
1211
+ {
1212
+ if (ReactCurrentOwner$1.current) {
1213
+ var name = getComponentNameFromType(ReactCurrentOwner$1.current.type);
1214
+
1215
+ if (name) {
1216
+ return '\n\nCheck the render method of `' + name + '`.';
1217
+ }
1218
+ }
1219
+
1220
+ return '';
1221
+ }
1222
+ }
1223
+
1224
+ function getSourceInfoErrorAddendum(source) {
1225
+ {
1226
+ if (source !== undefined) {
1227
+ var fileName = source.fileName.replace(/^.*[\\\/]/, '');
1228
+ var lineNumber = source.lineNumber;
1229
+ return '\n\nCheck your code at ' + fileName + ':' + lineNumber + '.';
1230
+ }
1231
+
1232
+ return '';
1233
+ }
1234
+ }
1235
+ /**
1236
+ * Warn if there's no key explicitly set on dynamic arrays of children or
1237
+ * object keys are not valid. This allows us to keep track of children between
1238
+ * updates.
1239
+ */
1240
+
1241
+
1242
+ var ownerHasKeyUseWarning = {};
1243
+
1244
+ function getCurrentComponentErrorInfo(parentType) {
1245
+ {
1246
+ var info = getDeclarationErrorAddendum();
1247
+
1248
+ if (!info) {
1249
+ var parentName = typeof parentType === 'string' ? parentType : parentType.displayName || parentType.name;
1250
+
1251
+ if (parentName) {
1252
+ info = "\n\nCheck the top-level render call using <" + parentName + ">.";
1253
+ }
1254
+ }
1255
+
1256
+ return info;
1257
+ }
1258
+ }
1259
+ /**
1260
+ * Warn if the element doesn't have an explicit key assigned to it.
1261
+ * This element is in an array. The array could grow and shrink or be
1262
+ * reordered. All children that haven't already been validated are required to
1263
+ * have a "key" property assigned to it. Error statuses are cached so a warning
1264
+ * will only be shown once.
1265
+ *
1266
+ * @internal
1267
+ * @param {ReactElement} element Element that requires a key.
1268
+ * @param {*} parentType element's parent's type.
1269
+ */
1270
+
1271
+
1272
+ function validateExplicitKey(element, parentType) {
1273
+ {
1274
+ if (!element._store || element._store.validated || element.key != null) {
1275
+ return;
1276
+ }
1277
+
1278
+ element._store.validated = true;
1279
+ var currentComponentErrorInfo = getCurrentComponentErrorInfo(parentType);
1280
+
1281
+ if (ownerHasKeyUseWarning[currentComponentErrorInfo]) {
1282
+ return;
1283
+ }
1284
+
1285
+ ownerHasKeyUseWarning[currentComponentErrorInfo] = true; // Usually the current owner is the offender, but if it accepts children as a
1286
+ // property, it may be the creator of the child that's responsible for
1287
+ // assigning it a key.
1288
+
1289
+ var childOwner = '';
1290
+
1291
+ if (element && element._owner && element._owner !== ReactCurrentOwner$1.current) {
1292
+ // Give the component that originally created this child.
1293
+ childOwner = " It was passed a child from " + getComponentNameFromType(element._owner.type) + ".";
1294
+ }
1295
+
1296
+ setCurrentlyValidatingElement$1(element);
1297
+
1298
+ 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);
1299
+
1300
+ setCurrentlyValidatingElement$1(null);
1301
+ }
1302
+ }
1303
+ /**
1304
+ * Ensure that every element either is passed in a static location, in an
1305
+ * array with an explicit keys property defined, or in an object literal
1306
+ * with valid key property.
1307
+ *
1308
+ * @internal
1309
+ * @param {ReactNode} node Statically passed child of any type.
1310
+ * @param {*} parentType node's parent's type.
1311
+ */
1312
+
1313
+
1314
+ function validateChildKeys(node, parentType) {
1315
+ {
1316
+ if (typeof node !== 'object') {
1317
+ return;
1318
+ }
1319
+
1320
+ if (isArray(node)) {
1321
+ for (var i = 0; i < node.length; i++) {
1322
+ var child = node[i];
1323
+
1324
+ if (isValidElement(child)) {
1325
+ validateExplicitKey(child, parentType);
1326
+ }
1327
+ }
1328
+ } else if (isValidElement(node)) {
1329
+ // This element was passed in a valid location.
1330
+ if (node._store) {
1331
+ node._store.validated = true;
1332
+ }
1333
+ } else if (node) {
1334
+ var iteratorFn = getIteratorFn(node);
1335
+
1336
+ if (typeof iteratorFn === 'function') {
1337
+ // Entry iterators used to provide implicit keys,
1338
+ // but now we print a separate warning for them later.
1339
+ if (iteratorFn !== node.entries) {
1340
+ var iterator = iteratorFn.call(node);
1341
+ var step;
1342
+
1343
+ while (!(step = iterator.next()).done) {
1344
+ if (isValidElement(step.value)) {
1345
+ validateExplicitKey(step.value, parentType);
1346
+ }
1347
+ }
1348
+ }
1349
+ }
1350
+ }
1351
+ }
1352
+ }
1353
+ /**
1354
+ * Given an element, validate that its props follow the propTypes definition,
1355
+ * provided by the type.
1356
+ *
1357
+ * @param {ReactElement} element
1358
+ */
1359
+
1360
+
1361
+ function validatePropTypes(element) {
1362
+ {
1363
+ var type = element.type;
1364
+
1365
+ if (type === null || type === undefined || typeof type === 'string') {
1366
+ return;
1367
+ }
1368
+
1369
+ var propTypes;
1370
+
1371
+ if (typeof type === 'function') {
1372
+ propTypes = type.propTypes;
1373
+ } else if (typeof type === 'object' && (type.$$typeof === REACT_FORWARD_REF_TYPE || // Note: Memo only checks outer props here.
1374
+ // Inner props are checked in the reconciler.
1375
+ type.$$typeof === REACT_MEMO_TYPE)) {
1376
+ propTypes = type.propTypes;
1377
+ } else {
1378
+ return;
1379
+ }
1380
+
1381
+ if (propTypes) {
1382
+ // Intentionally inside to avoid triggering lazy initializers:
1383
+ var name = getComponentNameFromType(type);
1384
+ checkPropTypes(propTypes, element.props, 'prop', name, element);
1385
+ } else if (type.PropTypes !== undefined && !propTypesMisspellWarningShown) {
1386
+ propTypesMisspellWarningShown = true; // Intentionally inside to avoid triggering lazy initializers:
1387
+
1388
+ var _name = getComponentNameFromType(type);
1389
+
1390
+ error('Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?', _name || 'Unknown');
1391
+ }
1392
+
1393
+ if (typeof type.getDefaultProps === 'function' && !type.getDefaultProps.isReactClassApproved) {
1394
+ error('getDefaultProps is only used on classic React.createClass ' + 'definitions. Use a static property named `defaultProps` instead.');
1395
+ }
1396
+ }
1397
+ }
1398
+ /**
1399
+ * Given a fragment, validate that it can only be provided with fragment props
1400
+ * @param {ReactElement} fragment
1401
+ */
1402
+
1403
+
1404
+ function validateFragmentProps(fragment) {
1405
+ {
1406
+ var keys = Object.keys(fragment.props);
1407
+
1408
+ for (var i = 0; i < keys.length; i++) {
1409
+ var key = keys[i];
1410
+
1411
+ if (key !== 'children' && key !== 'key') {
1412
+ setCurrentlyValidatingElement$1(fragment);
1413
+
1414
+ error('Invalid prop `%s` supplied to `React.Fragment`. ' + 'React.Fragment can only have `key` and `children` props.', key);
1415
+
1416
+ setCurrentlyValidatingElement$1(null);
1417
+ break;
1418
+ }
1419
+ }
1420
+
1421
+ if (fragment.ref !== null) {
1422
+ setCurrentlyValidatingElement$1(fragment);
1423
+
1424
+ error('Invalid attribute `ref` supplied to `React.Fragment`.');
1425
+
1426
+ setCurrentlyValidatingElement$1(null);
1427
+ }
1428
+ }
1429
+ }
1430
+
1431
+ var didWarnAboutKeySpread = {};
1432
+ function jsxWithValidation(type, props, key, isStaticChildren, source, self) {
1433
+ {
1434
+ var validType = isValidElementType(type); // We warn in this case but don't throw. We expect the element creation to
1435
+ // succeed and there will likely be errors in render.
1436
+
1437
+ if (!validType) {
1438
+ var info = '';
1439
+
1440
+ if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) {
1441
+ 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.";
1442
+ }
1443
+
1444
+ var sourceInfo = getSourceInfoErrorAddendum(source);
1445
+
1446
+ if (sourceInfo) {
1447
+ info += sourceInfo;
1448
+ } else {
1449
+ info += getDeclarationErrorAddendum();
1450
+ }
1451
+
1452
+ var typeString;
1453
+
1454
+ if (type === null) {
1455
+ typeString = 'null';
1456
+ } else if (isArray(type)) {
1457
+ typeString = 'array';
1458
+ } else if (type !== undefined && type.$$typeof === REACT_ELEMENT_TYPE) {
1459
+ typeString = "<" + (getComponentNameFromType(type.type) || 'Unknown') + " />";
1460
+ info = ' Did you accidentally export a JSX literal instead of a component?';
1461
+ } else {
1462
+ typeString = typeof type;
1463
+ }
1464
+
1465
+ 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);
1466
+ }
1467
+
1468
+ var element = jsxDEV(type, props, key, source, self); // The result can be nullish if a mock or a custom function is used.
1469
+ // TODO: Drop this when these are no longer allowed as the type argument.
1470
+
1471
+ if (element == null) {
1472
+ return element;
1473
+ } // Skip key warning if the type isn't valid since our key validation logic
1474
+ // doesn't expect a non-string/function type and can throw confusing errors.
1475
+ // We don't want exception behavior to differ between dev and prod.
1476
+ // (Rendering will throw with a helpful message and as soon as the type is
1477
+ // fixed, the key warnings will appear.)
1478
+
1479
+
1480
+ if (validType) {
1481
+ var children = props.children;
1482
+
1483
+ if (children !== undefined) {
1484
+ if (isStaticChildren) {
1485
+ if (isArray(children)) {
1486
+ for (var i = 0; i < children.length; i++) {
1487
+ validateChildKeys(children[i], type);
1488
+ }
1489
+
1490
+ if (Object.freeze) {
1491
+ Object.freeze(children);
1492
+ }
1493
+ } else {
1494
+ 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.');
1495
+ }
1496
+ } else {
1497
+ validateChildKeys(children, type);
1498
+ }
1499
+ }
1500
+ }
1501
+
1502
+ {
1503
+ if (hasOwnProperty.call(props, 'key')) {
1504
+ var componentName = getComponentNameFromType(type);
1505
+ var keys = Object.keys(props).filter(function (k) {
1506
+ return k !== 'key';
1507
+ });
1508
+ var beforeExample = keys.length > 0 ? '{key: someKey, ' + keys.join(': ..., ') + ': ...}' : '{key: someKey}';
1509
+
1510
+ if (!didWarnAboutKeySpread[componentName + beforeExample]) {
1511
+ var afterExample = keys.length > 0 ? '{' + keys.join(': ..., ') + ': ...}' : '{}';
1512
+
1513
+ 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);
1514
+
1515
+ didWarnAboutKeySpread[componentName + beforeExample] = true;
1516
+ }
1517
+ }
1518
+ }
1519
+
1520
+ if (type === REACT_FRAGMENT_TYPE) {
1521
+ validateFragmentProps(element);
1522
+ } else {
1523
+ validatePropTypes(element);
1524
+ }
1525
+
1526
+ return element;
1527
+ }
1528
+ } // These two functions exist to still get child warnings in dev
1529
+ // even with the prod transform. This means that jsxDEV is purely
1530
+ // opt-in behavior for better messages but that we won't stop
1531
+ // giving you warnings if you use production apis.
1532
+
1533
+ function jsxWithValidationStatic(type, props, key) {
1534
+ {
1535
+ return jsxWithValidation(type, props, key, true);
1536
+ }
1537
+ }
1538
+ function jsxWithValidationDynamic(type, props, key) {
1539
+ {
1540
+ return jsxWithValidation(type, props, key, false);
1541
+ }
1542
+ }
1543
+
1544
+ var jsx = jsxWithValidationDynamic ; // we may want to special case jsxs internally to take advantage of static children.
1545
+ // for now we can ship identical prod functions
1546
+
1547
+ var jsxs = jsxWithValidationStatic ;
1548
+
1549
+ reactJsxRuntime_development.Fragment = REACT_FRAGMENT_TYPE;
1550
+ reactJsxRuntime_development.jsx = jsx;
1551
+ reactJsxRuntime_development.jsxs = jsxs;
1552
+ })();
1553
+ }
1554
+ return reactJsxRuntime_development;
1555
+ }
1556
+
1557
+ if (process.env.NODE_ENV === 'production') {
1558
+ jsxRuntime.exports = requireReactJsxRuntime_production_min();
1559
+ } else {
1560
+ jsxRuntime.exports = requireReactJsxRuntime_development();
1561
+ }
1562
+
1563
+ var jsxRuntimeExports = jsxRuntime.exports;
1564
+
1565
+ var dist = {};
1566
+
1567
+ var useWebsocket = {};
1568
+
1569
+ var constants = {};
1570
+
1571
+ (function (exports) {
1572
+ Object.defineProperty(exports, "__esModule", { value: true });
1573
+ 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;
1574
+ var MILLISECONDS = 1;
1575
+ var SECONDS = 1000 * MILLISECONDS;
1576
+ exports.DEFAULT_OPTIONS = {};
1577
+ exports.EMPTY_EVENT_HANDLERS = {};
1578
+ exports.DEFAULT_EVENT_SOURCE_OPTIONS = {
1579
+ withCredentials: false,
1580
+ events: exports.EMPTY_EVENT_HANDLERS,
1581
+ };
1582
+ exports.SOCKET_IO_PING_INTERVAL = 25 * SECONDS;
1583
+ exports.SOCKET_IO_PATH = '/socket.io/?EIO=3&transport=websocket';
1584
+ exports.SOCKET_IO_PING_CODE = '2';
1585
+ exports.DEFAULT_RECONNECT_LIMIT = 20;
1586
+ exports.DEFAULT_RECONNECT_INTERVAL_MS = 5000;
1587
+ exports.UNPARSABLE_JSON_OBJECT = {};
1588
+ exports.DEFAULT_HEARTBEAT = {
1589
+ message: 'ping',
1590
+ timeout: 60000,
1591
+ interval: 25000,
1592
+ };
1593
+ var ReadyState;
1594
+ (function (ReadyState) {
1595
+ ReadyState[ReadyState["UNINSTANTIATED"] = -1] = "UNINSTANTIATED";
1596
+ ReadyState[ReadyState["CONNECTING"] = 0] = "CONNECTING";
1597
+ ReadyState[ReadyState["OPEN"] = 1] = "OPEN";
1598
+ ReadyState[ReadyState["CLOSING"] = 2] = "CLOSING";
1599
+ ReadyState[ReadyState["CLOSED"] = 3] = "CLOSED";
1600
+ })(ReadyState || (exports.ReadyState = ReadyState = {}));
1601
+ var eventSourceSupported = function () {
1602
+ try {
1603
+ return 'EventSource' in globalThis;
1604
+ }
1605
+ catch (e) {
1606
+ return false;
1607
+ }
1608
+ };
1609
+ exports.isReactNative = typeof navigator !== 'undefined' && navigator.product === 'ReactNative';
1610
+ exports.isEventSourceSupported = !exports.isReactNative && eventSourceSupported();
1611
+
1612
+ } (constants));
1613
+
1614
+ var createOrJoin = {};
1615
+
1616
+ var globals = {};
1617
+
1618
+ (function (exports) {
1619
+ Object.defineProperty(exports, "__esModule", { value: true });
1620
+ exports.resetWebSockets = exports.sharedWebSockets = void 0;
1621
+ exports.sharedWebSockets = {};
1622
+ var resetWebSockets = function (url) {
1623
+ if (url && exports.sharedWebSockets.hasOwnProperty(url)) {
1624
+ delete exports.sharedWebSockets[url];
1625
+ }
1626
+ else {
1627
+ for (var url_1 in exports.sharedWebSockets) {
1628
+ if (exports.sharedWebSockets.hasOwnProperty(url_1)) {
1629
+ delete exports.sharedWebSockets[url_1];
1630
+ }
1631
+ }
1632
+ }
1633
+ };
1634
+ exports.resetWebSockets = resetWebSockets;
1635
+
1636
+ } (globals));
1637
+
1638
+ var attachListener = {};
1639
+
1640
+ var socketIo = {};
1641
+
1642
+ Object.defineProperty(socketIo, "__esModule", { value: true });
1643
+ socketIo.setUpSocketIOPing = socketIo.appendQueryParams = socketIo.parseSocketIOUrl = void 0;
1644
+ var constants_1$7 = constants;
1645
+ var parseSocketIOUrl = function (url) {
1646
+ if (url) {
1647
+ var isSecure = /^https|wss/.test(url);
1648
+ var strippedProtocol = url.replace(/^(https?|wss?)(:\/\/)?/, '');
1649
+ var removedFinalBackSlack = strippedProtocol.replace(/\/$/, '');
1650
+ var protocol = isSecure ? 'wss' : 'ws';
1651
+ return "".concat(protocol, "://").concat(removedFinalBackSlack).concat(constants_1$7.SOCKET_IO_PATH);
1652
+ }
1653
+ else if (url === '') {
1654
+ var isSecure = /^https/.test(window.location.protocol);
1655
+ var protocol = isSecure ? 'wss' : 'ws';
1656
+ var port = window.location.port ? ":".concat(window.location.port) : '';
1657
+ return "".concat(protocol, "://").concat(window.location.hostname).concat(port).concat(constants_1$7.SOCKET_IO_PATH);
1658
+ }
1659
+ return url;
1660
+ };
1661
+ socketIo.parseSocketIOUrl = parseSocketIOUrl;
1662
+ var appendQueryParams = function (url, params) {
1663
+ if (params === void 0) { params = {}; }
1664
+ var hasParamsRegex = /\?([\w]+=[\w]+)/;
1665
+ var alreadyHasParams = hasParamsRegex.test(url);
1666
+ var stringified = "".concat(Object.entries(params).reduce(function (next, _a) {
1667
+ var key = _a[0], value = _a[1];
1668
+ return next + "".concat(key, "=").concat(value, "&");
1669
+ }, '').slice(0, -1));
1670
+ return "".concat(url).concat(alreadyHasParams ? '&' : '?').concat(stringified);
1671
+ };
1672
+ socketIo.appendQueryParams = appendQueryParams;
1673
+ var setUpSocketIOPing = function (sendMessage, interval) {
1674
+ if (interval === void 0) { interval = constants_1$7.SOCKET_IO_PING_INTERVAL; }
1675
+ var ping = function () { return sendMessage(constants_1$7.SOCKET_IO_PING_CODE); };
1676
+ return window.setInterval(ping, interval);
1677
+ };
1678
+ socketIo.setUpSocketIOPing = setUpSocketIOPing;
1679
+
1680
+ var heartbeat$1 = {};
1681
+
1682
+ Object.defineProperty(heartbeat$1, "__esModule", { value: true });
1683
+ heartbeat$1.heartbeat = heartbeat;
1684
+ var constants_1$6 = constants;
1685
+ function getLastMessageTime(lastMessageTime) {
1686
+ if (Array.isArray(lastMessageTime)) {
1687
+ return lastMessageTime.reduce(function (p, c) { return (p.current > c.current) ? p : c; }).current;
1688
+ }
1689
+ return lastMessageTime.current;
1690
+ }
1691
+ function heartbeat(ws, lastMessageTime, options) {
1692
+ 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;
1693
+ // how often check interval between ping messages
1694
+ // minimum is 100ms
1695
+ // maximum is ${interval / 10}ms
1696
+ var intervalCheck = Math.max(100, interval / 10);
1697
+ var lastPingSentAt = Date.now();
1698
+ var heartbeatInterval = setInterval(function () {
1699
+ var timeNow = Date.now();
1700
+ var lastMessageReceivedAt = getLastMessageTime(lastMessageTime);
1701
+ if (lastMessageReceivedAt + timeout <= timeNow) {
1702
+ console.warn("Heartbeat timed out, closing connection, last message received ".concat(timeNow - lastMessageReceivedAt, "ms ago, last ping sent ").concat(timeNow - lastPingSentAt, "ms ago"));
1703
+ ws.close();
1704
+ }
1705
+ else {
1706
+ if (lastMessageReceivedAt + interval <= timeNow && lastPingSentAt + interval <= timeNow) {
1707
+ try {
1708
+ if (typeof message === 'function') {
1709
+ ws.send(message());
1710
+ }
1711
+ else {
1712
+ ws.send(message);
1713
+ }
1714
+ lastPingSentAt = timeNow;
1715
+ }
1716
+ catch (err) {
1717
+ console.error("Heartbeat failed, closing connection", err instanceof Error ? err.message : err);
1718
+ ws.close();
1719
+ }
1720
+ }
1721
+ }
1722
+ }, intervalCheck);
1723
+ ws.addEventListener("close", function () {
1724
+ clearInterval(heartbeatInterval);
1725
+ });
1726
+ return function () { };
1727
+ }
1728
+
1729
+ var util = {};
1730
+
1731
+ var manageSubscribers = {};
1732
+
1733
+ (function (exports) {
1734
+ Object.defineProperty(exports, "__esModule", { value: true });
1735
+ exports.resetSubscribers = exports.removeSubscriber = exports.addSubscriber = exports.hasSubscribers = exports.getSubscribers = void 0;
1736
+ var subscribers = {};
1737
+ var EMPTY_LIST = [];
1738
+ var getSubscribers = function (url) {
1739
+ if ((0, exports.hasSubscribers)(url)) {
1740
+ return Array.from(subscribers[url]);
1741
+ }
1742
+ return EMPTY_LIST;
1743
+ };
1744
+ exports.getSubscribers = getSubscribers;
1745
+ var hasSubscribers = function (url) {
1746
+ var _a;
1747
+ return ((_a = subscribers[url]) === null || _a === void 0 ? void 0 : _a.size) > 0;
1748
+ };
1749
+ exports.hasSubscribers = hasSubscribers;
1750
+ var addSubscriber = function (url, subscriber) {
1751
+ subscribers[url] = subscribers[url] || new Set();
1752
+ subscribers[url].add(subscriber);
1753
+ };
1754
+ exports.addSubscriber = addSubscriber;
1755
+ var removeSubscriber = function (url, subscriber) {
1756
+ subscribers[url].delete(subscriber);
1757
+ };
1758
+ exports.removeSubscriber = removeSubscriber;
1759
+ var resetSubscribers = function (url) {
1760
+ if (url && subscribers.hasOwnProperty(url)) {
1761
+ delete subscribers[url];
1762
+ }
1763
+ else {
1764
+ for (var url_1 in subscribers) {
1765
+ if (subscribers.hasOwnProperty(url_1)) {
1766
+ delete subscribers[url_1];
1767
+ }
1768
+ }
1769
+ }
1770
+ };
1771
+ exports.resetSubscribers = resetSubscribers;
1772
+
1773
+ } (manageSubscribers));
1774
+
1775
+ Object.defineProperty(util, "__esModule", { value: true });
1776
+ util.assertIsWebSocket = assertIsWebSocket;
1777
+ util.resetGlobalState = resetGlobalState;
1778
+ var globals_1$2 = globals;
1779
+ var manage_subscribers_1$2 = manageSubscribers;
1780
+ function assertIsWebSocket(webSocketInstance, skip) {
1781
+ if (!skip && webSocketInstance instanceof WebSocket === false)
1782
+ throw new Error('');
1783
+ }
1784
+ function resetGlobalState(url) {
1785
+ (0, manage_subscribers_1$2.resetSubscribers)(url);
1786
+ (0, globals_1$2.resetWebSockets)(url);
1787
+ }
1788
+
1789
+ var __assign$4 = (commonjsGlobal && commonjsGlobal.__assign) || function () {
1790
+ __assign$4 = Object.assign || function(t) {
1791
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
1792
+ s = arguments[i];
1793
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
1794
+ t[p] = s[p];
1795
+ }
1796
+ return t;
1797
+ };
1798
+ return __assign$4.apply(this, arguments);
1799
+ };
1800
+ Object.defineProperty(attachListener, "__esModule", { value: true });
1801
+ attachListener.attachListeners = void 0;
1802
+ var socket_io_1$1 = socketIo;
1803
+ var heartbeat_1$1 = heartbeat$1;
1804
+ var constants_1$5 = constants;
1805
+ var util_1$1 = util;
1806
+ var bindMessageHandler$1 = function (webSocketInstance, optionsRef, setLastMessage, lastMessageTime) {
1807
+ webSocketInstance.onmessage = function (message) {
1808
+ var _a;
1809
+ optionsRef.current.onMessage && optionsRef.current.onMessage(message);
1810
+ if (typeof (lastMessageTime === null || lastMessageTime === void 0 ? void 0 : lastMessageTime.current) === 'number') {
1811
+ lastMessageTime.current = Date.now();
1812
+ }
1813
+ if (typeof optionsRef.current.filter === 'function' && optionsRef.current.filter(message) !== true) {
1814
+ return;
1815
+ }
1816
+ if (optionsRef.current.heartbeat &&
1817
+ typeof optionsRef.current.heartbeat !== "boolean" &&
1818
+ ((_a = optionsRef.current.heartbeat) === null || _a === void 0 ? void 0 : _a.returnMessage) === message.data) {
1819
+ return;
1820
+ }
1821
+ setLastMessage(message);
1822
+ };
1823
+ };
1824
+ var bindOpenHandler$1 = function (webSocketInstance, optionsRef, setReadyState, reconnectCount, lastMessageTime) {
1825
+ webSocketInstance.onopen = function (event) {
1826
+ optionsRef.current.onOpen && optionsRef.current.onOpen(event);
1827
+ reconnectCount.current = 0;
1828
+ setReadyState(constants_1$5.ReadyState.OPEN);
1829
+ //start heart beat here
1830
+ if (optionsRef.current.heartbeat && webSocketInstance instanceof WebSocket) {
1831
+ var heartbeatOptions = typeof optionsRef.current.heartbeat === "boolean"
1832
+ ? undefined
1833
+ : optionsRef.current.heartbeat;
1834
+ lastMessageTime.current = Date.now();
1835
+ (0, heartbeat_1$1.heartbeat)(webSocketInstance, lastMessageTime, heartbeatOptions);
1836
+ }
1837
+ };
1838
+ };
1839
+ var bindCloseHandler$1 = function (webSocketInstance, optionsRef, setReadyState, reconnect, reconnectCount) {
1840
+ if (constants_1$5.isEventSourceSupported && webSocketInstance instanceof EventSource) {
1841
+ return function () { };
1842
+ }
1843
+ (0, util_1$1.assertIsWebSocket)(webSocketInstance, optionsRef.current.skipAssert);
1844
+ var reconnectTimeout;
1845
+ webSocketInstance.onclose = function (event) {
1846
+ var _a;
1847
+ optionsRef.current.onClose && optionsRef.current.onClose(event);
1848
+ setReadyState(constants_1$5.ReadyState.CLOSED);
1849
+ if (optionsRef.current.shouldReconnect && optionsRef.current.shouldReconnect(event)) {
1850
+ var reconnectAttempts = (_a = optionsRef.current.reconnectAttempts) !== null && _a !== void 0 ? _a : constants_1$5.DEFAULT_RECONNECT_LIMIT;
1851
+ if (reconnectCount.current < reconnectAttempts) {
1852
+ var nextReconnectInterval = typeof optionsRef.current.reconnectInterval === 'function' ?
1853
+ optionsRef.current.reconnectInterval(reconnectCount.current) :
1854
+ optionsRef.current.reconnectInterval;
1855
+ reconnectTimeout = window.setTimeout(function () {
1856
+ reconnectCount.current++;
1857
+ reconnect();
1858
+ }, nextReconnectInterval !== null && nextReconnectInterval !== void 0 ? nextReconnectInterval : constants_1$5.DEFAULT_RECONNECT_INTERVAL_MS);
1859
+ }
1860
+ else {
1861
+ optionsRef.current.onReconnectStop && optionsRef.current.onReconnectStop(reconnectAttempts);
1862
+ console.warn("Max reconnect attempts of ".concat(reconnectAttempts, " exceeded"));
1863
+ }
1864
+ }
1865
+ };
1866
+ return function () { return reconnectTimeout && window.clearTimeout(reconnectTimeout); };
1867
+ };
1868
+ var bindErrorHandler$1 = function (webSocketInstance, optionsRef, setReadyState, reconnect, reconnectCount) {
1869
+ var reconnectTimeout;
1870
+ webSocketInstance.onerror = function (error) {
1871
+ var _a;
1872
+ optionsRef.current.onError && optionsRef.current.onError(error);
1873
+ if (constants_1$5.isEventSourceSupported && webSocketInstance instanceof EventSource) {
1874
+ optionsRef.current.onClose && optionsRef.current.onClose(__assign$4(__assign$4({}, error), { code: 1006, reason: "An error occurred with the EventSource: ".concat(error), wasClean: false }));
1875
+ setReadyState(constants_1$5.ReadyState.CLOSED);
1876
+ webSocketInstance.close();
1877
+ }
1878
+ if (optionsRef.current.retryOnError) {
1879
+ if (reconnectCount.current < ((_a = optionsRef.current.reconnectAttempts) !== null && _a !== void 0 ? _a : constants_1$5.DEFAULT_RECONNECT_LIMIT)) {
1880
+ var nextReconnectInterval = typeof optionsRef.current.reconnectInterval === 'function' ?
1881
+ optionsRef.current.reconnectInterval(reconnectCount.current) :
1882
+ optionsRef.current.reconnectInterval;
1883
+ reconnectTimeout = window.setTimeout(function () {
1884
+ reconnectCount.current++;
1885
+ reconnect();
1886
+ }, nextReconnectInterval !== null && nextReconnectInterval !== void 0 ? nextReconnectInterval : constants_1$5.DEFAULT_RECONNECT_INTERVAL_MS);
1887
+ }
1888
+ else {
1889
+ optionsRef.current.onReconnectStop && optionsRef.current.onReconnectStop(optionsRef.current.reconnectAttempts);
1890
+ console.warn("Max reconnect attempts of ".concat(optionsRef.current.reconnectAttempts, " exceeded"));
1891
+ }
1892
+ }
1893
+ };
1894
+ return function () { return reconnectTimeout && window.clearTimeout(reconnectTimeout); };
1895
+ };
1896
+ var attachListeners = function (webSocketInstance, setters, optionsRef, reconnect, reconnectCount, lastMessageTime, sendMessage) {
1897
+ var setLastMessage = setters.setLastMessage, setReadyState = setters.setReadyState;
1898
+ var interval;
1899
+ var cancelReconnectOnClose;
1900
+ var cancelReconnectOnError;
1901
+ if (optionsRef.current.fromSocketIO) {
1902
+ interval = (0, socket_io_1$1.setUpSocketIOPing)(sendMessage);
1903
+ }
1904
+ bindMessageHandler$1(webSocketInstance, optionsRef, setLastMessage, lastMessageTime);
1905
+ bindOpenHandler$1(webSocketInstance, optionsRef, setReadyState, reconnectCount, lastMessageTime);
1906
+ cancelReconnectOnClose = bindCloseHandler$1(webSocketInstance, optionsRef, setReadyState, reconnect, reconnectCount);
1907
+ cancelReconnectOnError = bindErrorHandler$1(webSocketInstance, optionsRef, setReadyState, reconnect, reconnectCount);
1908
+ return function () {
1909
+ setReadyState(constants_1$5.ReadyState.CLOSING);
1910
+ cancelReconnectOnClose();
1911
+ cancelReconnectOnError();
1912
+ webSocketInstance.close();
1913
+ if (interval)
1914
+ clearInterval(interval);
1915
+ };
1916
+ };
1917
+ attachListener.attachListeners = attachListeners;
1918
+
1919
+ var attachSharedListeners$1 = {};
1920
+
1921
+ var __assign$3 = (commonjsGlobal && commonjsGlobal.__assign) || function () {
1922
+ __assign$3 = Object.assign || function(t) {
1923
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
1924
+ s = arguments[i];
1925
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
1926
+ t[p] = s[p];
1927
+ }
1928
+ return t;
1929
+ };
1930
+ return __assign$3.apply(this, arguments);
1931
+ };
1932
+ Object.defineProperty(attachSharedListeners$1, "__esModule", { value: true });
1933
+ attachSharedListeners$1.attachSharedListeners = void 0;
1934
+ var globals_1$1 = globals;
1935
+ var constants_1$4 = constants;
1936
+ var manage_subscribers_1$1 = manageSubscribers;
1937
+ var socket_io_1 = socketIo;
1938
+ var heartbeat_1 = heartbeat$1;
1939
+ var bindMessageHandler = function (webSocketInstance, url, heartbeatOptions) {
1940
+ webSocketInstance.onmessage = function (message) {
1941
+ (0, manage_subscribers_1$1.getSubscribers)(url).forEach(function (subscriber) {
1942
+ var _a;
1943
+ if (subscriber.optionsRef.current.onMessage) {
1944
+ subscriber.optionsRef.current.onMessage(message);
1945
+ }
1946
+ if (typeof ((_a = subscriber === null || subscriber === void 0 ? void 0 : subscriber.lastMessageTime) === null || _a === void 0 ? void 0 : _a.current) === 'number') {
1947
+ subscriber.lastMessageTime.current = Date.now();
1948
+ }
1949
+ if (typeof subscriber.optionsRef.current.filter === 'function' &&
1950
+ subscriber.optionsRef.current.filter(message) !== true) {
1951
+ return;
1952
+ }
1953
+ if (heartbeatOptions &&
1954
+ typeof heartbeatOptions !== "boolean" &&
1955
+ (heartbeatOptions === null || heartbeatOptions === void 0 ? void 0 : heartbeatOptions.returnMessage) === message.data)
1956
+ return;
1957
+ subscriber.setLastMessage(message);
1958
+ });
1959
+ };
1960
+ };
1961
+ var bindOpenHandler = function (webSocketInstance, url, heartbeatOptions) {
1962
+ webSocketInstance.onopen = function (event) {
1963
+ var subscribers = (0, manage_subscribers_1$1.getSubscribers)(url);
1964
+ subscribers.forEach(function (subscriber) {
1965
+ subscriber.reconnectCount.current = 0;
1966
+ if (subscriber.optionsRef.current.onOpen) {
1967
+ subscriber.optionsRef.current.onOpen(event);
1968
+ }
1969
+ subscriber.setReadyState(constants_1$4.ReadyState.OPEN);
1970
+ if (heartbeatOptions && webSocketInstance instanceof WebSocket) {
1971
+ subscriber.lastMessageTime.current = Date.now();
1972
+ }
1973
+ });
1974
+ if (heartbeatOptions && webSocketInstance instanceof WebSocket) {
1975
+ (0, heartbeat_1.heartbeat)(webSocketInstance, subscribers.map(function (subscriber) { return subscriber.lastMessageTime; }), typeof heartbeatOptions === 'boolean' ? undefined : heartbeatOptions);
1976
+ }
1977
+ };
1978
+ };
1979
+ var bindCloseHandler = function (webSocketInstance, url) {
1980
+ if (webSocketInstance instanceof WebSocket) {
1981
+ webSocketInstance.onclose = function (event) {
1982
+ (0, manage_subscribers_1$1.getSubscribers)(url).forEach(function (subscriber) {
1983
+ if (subscriber.optionsRef.current.onClose) {
1984
+ subscriber.optionsRef.current.onClose(event);
1985
+ }
1986
+ subscriber.setReadyState(constants_1$4.ReadyState.CLOSED);
1987
+ });
1988
+ delete globals_1$1.sharedWebSockets[url];
1989
+ (0, manage_subscribers_1$1.getSubscribers)(url).forEach(function (subscriber) {
1990
+ var _a;
1991
+ if (subscriber.optionsRef.current.shouldReconnect &&
1992
+ subscriber.optionsRef.current.shouldReconnect(event)) {
1993
+ var reconnectAttempts = (_a = subscriber.optionsRef.current.reconnectAttempts) !== null && _a !== void 0 ? _a : constants_1$4.DEFAULT_RECONNECT_LIMIT;
1994
+ if (subscriber.reconnectCount.current < reconnectAttempts) {
1995
+ var nextReconnectInterval = typeof subscriber.optionsRef.current.reconnectInterval === 'function' ?
1996
+ subscriber.optionsRef.current.reconnectInterval(subscriber.reconnectCount.current) :
1997
+ subscriber.optionsRef.current.reconnectInterval;
1998
+ setTimeout(function () {
1999
+ subscriber.reconnectCount.current++;
2000
+ subscriber.reconnect.current();
2001
+ }, nextReconnectInterval !== null && nextReconnectInterval !== void 0 ? nextReconnectInterval : constants_1$4.DEFAULT_RECONNECT_INTERVAL_MS);
2002
+ }
2003
+ else {
2004
+ subscriber.optionsRef.current.onReconnectStop && subscriber.optionsRef.current.onReconnectStop(subscriber.optionsRef.current.reconnectAttempts);
2005
+ console.warn("Max reconnect attempts of ".concat(reconnectAttempts, " exceeded"));
2006
+ }
2007
+ }
2008
+ });
2009
+ };
2010
+ }
2011
+ };
2012
+ var bindErrorHandler = function (webSocketInstance, url) {
2013
+ webSocketInstance.onerror = function (error) {
2014
+ (0, manage_subscribers_1$1.getSubscribers)(url).forEach(function (subscriber) {
2015
+ if (subscriber.optionsRef.current.onError) {
2016
+ subscriber.optionsRef.current.onError(error);
2017
+ }
2018
+ if (constants_1$4.isEventSourceSupported && webSocketInstance instanceof EventSource) {
2019
+ 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 }));
2020
+ subscriber.setReadyState(constants_1$4.ReadyState.CLOSED);
2021
+ }
2022
+ });
2023
+ if (constants_1$4.isEventSourceSupported && webSocketInstance instanceof EventSource) {
2024
+ webSocketInstance.close();
2025
+ }
2026
+ };
2027
+ };
2028
+ var attachSharedListeners = function (webSocketInstance, url, optionsRef, sendMessage) {
2029
+ var interval;
2030
+ if (optionsRef.current.fromSocketIO) {
2031
+ interval = (0, socket_io_1.setUpSocketIOPing)(sendMessage);
2032
+ }
2033
+ bindMessageHandler(webSocketInstance, url, optionsRef.current.heartbeat);
2034
+ bindCloseHandler(webSocketInstance, url);
2035
+ bindOpenHandler(webSocketInstance, url, optionsRef.current.heartbeat);
2036
+ bindErrorHandler(webSocketInstance, url);
2037
+ return function () {
2038
+ if (interval)
2039
+ clearInterval(interval);
2040
+ };
2041
+ };
2042
+ attachSharedListeners$1.attachSharedListeners = attachSharedListeners;
2043
+
2044
+ Object.defineProperty(createOrJoin, "__esModule", { value: true });
2045
+ createOrJoin.createOrJoinSocket = void 0;
2046
+ var globals_1 = globals;
2047
+ var constants_1$3 = constants;
2048
+ var attach_listener_1 = attachListener;
2049
+ var attach_shared_listeners_1 = attachSharedListeners$1;
2050
+ var manage_subscribers_1 = manageSubscribers;
2051
+ //TODO ensure that all onClose callbacks are called
2052
+ var cleanSubscribers = function (url, subscriber, optionsRef, setReadyState, clearSocketIoPingInterval) {
2053
+ return function () {
2054
+ (0, manage_subscribers_1.removeSubscriber)(url, subscriber);
2055
+ if (!(0, manage_subscribers_1.hasSubscribers)(url)) {
2056
+ try {
2057
+ var socketLike = globals_1.sharedWebSockets[url];
2058
+ if (socketLike instanceof WebSocket) {
2059
+ socketLike.onclose = function (event) {
2060
+ if (optionsRef.current.onClose) {
2061
+ optionsRef.current.onClose(event);
2062
+ }
2063
+ setReadyState(constants_1$3.ReadyState.CLOSED);
2064
+ };
2065
+ }
2066
+ socketLike.close();
2067
+ }
2068
+ catch (e) {
2069
+ }
2070
+ if (clearSocketIoPingInterval)
2071
+ clearSocketIoPingInterval();
2072
+ delete globals_1.sharedWebSockets[url];
2073
+ }
2074
+ };
2075
+ };
2076
+ var createOrJoinSocket = function (webSocketRef, url, setReadyState, optionsRef, setLastMessage, startRef, reconnectCount, lastMessageTime, sendMessage) {
2077
+ if (!constants_1$3.isEventSourceSupported && optionsRef.current.eventSourceOptions) {
2078
+ if (constants_1$3.isReactNative) {
2079
+ throw new Error('EventSource is not supported in ReactNative');
2080
+ }
2081
+ else {
2082
+ throw new Error('EventSource is not supported');
2083
+ }
2084
+ }
2085
+ if (optionsRef.current.share) {
2086
+ var clearSocketIoPingInterval = null;
2087
+ if (globals_1.sharedWebSockets[url] === undefined) {
2088
+ globals_1.sharedWebSockets[url] = optionsRef.current.eventSourceOptions ?
2089
+ new EventSource(url, optionsRef.current.eventSourceOptions) :
2090
+ new WebSocket(url, optionsRef.current.protocols);
2091
+ webSocketRef.current = globals_1.sharedWebSockets[url];
2092
+ setReadyState(constants_1$3.ReadyState.CONNECTING);
2093
+ clearSocketIoPingInterval = (0, attach_shared_listeners_1.attachSharedListeners)(globals_1.sharedWebSockets[url], url, optionsRef, sendMessage);
2094
+ }
2095
+ else {
2096
+ webSocketRef.current = globals_1.sharedWebSockets[url];
2097
+ setReadyState(globals_1.sharedWebSockets[url].readyState);
2098
+ }
2099
+ var subscriber = {
2100
+ setLastMessage: setLastMessage,
2101
+ setReadyState: setReadyState,
2102
+ optionsRef: optionsRef,
2103
+ reconnectCount: reconnectCount,
2104
+ lastMessageTime: lastMessageTime,
2105
+ reconnect: startRef,
2106
+ };
2107
+ (0, manage_subscribers_1.addSubscriber)(url, subscriber);
2108
+ return cleanSubscribers(url, subscriber, optionsRef, setReadyState, clearSocketIoPingInterval);
2109
+ }
2110
+ else {
2111
+ webSocketRef.current = optionsRef.current.eventSourceOptions ?
2112
+ new EventSource(url, optionsRef.current.eventSourceOptions) :
2113
+ new WebSocket(url, optionsRef.current.protocols);
2114
+ setReadyState(constants_1$3.ReadyState.CONNECTING);
2115
+ if (!webSocketRef.current) {
2116
+ throw new Error('WebSocket failed to be created');
2117
+ }
2118
+ return (0, attach_listener_1.attachListeners)(webSocketRef.current, {
2119
+ setLastMessage: setLastMessage,
2120
+ setReadyState: setReadyState
2121
+ }, optionsRef, startRef.current, reconnectCount, lastMessageTime, sendMessage);
2122
+ }
2123
+ };
2124
+ createOrJoin.createOrJoinSocket = createOrJoinSocket;
2125
+
2126
+ var getUrl = {};
2127
+
2128
+ (function (exports) {
2129
+ var __awaiter = (commonjsGlobal && commonjsGlobal.__awaiter) || function (thisArg, _arguments, P, generator) {
2130
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
2131
+ return new (P || (P = Promise))(function (resolve, reject) {
2132
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
2133
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
2134
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
2135
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
2136
+ });
2137
+ };
2138
+ var __generator = (commonjsGlobal && commonjsGlobal.__generator) || function (thisArg, body) {
2139
+ 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);
2140
+ return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
2141
+ function verb(n) { return function (v) { return step([n, v]); }; }
2142
+ function step(op) {
2143
+ if (f) throw new TypeError("Generator is already executing.");
2144
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
2145
+ 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;
2146
+ if (y = 0, t) op = [op[0] & 2, t.value];
2147
+ switch (op[0]) {
2148
+ case 0: case 1: t = op; break;
2149
+ case 4: _.label++; return { value: op[1], done: false };
2150
+ case 5: _.label++; y = op[1]; op = [0]; continue;
2151
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
2152
+ default:
2153
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
2154
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
2155
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
2156
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
2157
+ if (t[2]) _.ops.pop();
2158
+ _.trys.pop(); continue;
2159
+ }
2160
+ op = body.call(thisArg, _);
2161
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
2162
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
2163
+ }
2164
+ };
2165
+ var __spreadArray = (commonjsGlobal && commonjsGlobal.__spreadArray) || function (to, from, pack) {
2166
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
2167
+ if (ar || !(i in from)) {
2168
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
2169
+ ar[i] = from[i];
2170
+ }
2171
+ }
2172
+ return to.concat(ar || Array.prototype.slice.call(from));
2173
+ };
2174
+ Object.defineProperty(exports, "__esModule", { value: true });
2175
+ exports.getUrl = void 0;
2176
+ var socket_io_1 = socketIo;
2177
+ var constants_1 = constants;
2178
+ var waitFor = function (duration) { return new Promise(function (resolve) { return window.setTimeout(resolve, duration); }); };
2179
+ var getUrl = function (url_1, optionsRef_1) {
2180
+ var args_1 = [];
2181
+ for (var _i = 2; _i < arguments.length; _i++) {
2182
+ args_1[_i - 2] = arguments[_i];
2183
+ }
2184
+ return __awaiter(void 0, __spreadArray([url_1, optionsRef_1], args_1, true), void 0, function (url, optionsRef, retriedAttempts) {
2185
+ var convertedUrl, reconnectLimit, nextReconnectInterval, parsedUrl, parsedWithQueryParams;
2186
+ var _a, _b, _c;
2187
+ if (retriedAttempts === void 0) { retriedAttempts = 0; }
2188
+ return __generator(this, function (_d) {
2189
+ switch (_d.label) {
2190
+ case 0:
2191
+ if (!(typeof url === 'function')) return [3 /*break*/, 10];
2192
+ _d.label = 1;
2193
+ case 1:
2194
+ _d.trys.push([1, 3, , 9]);
2195
+ return [4 /*yield*/, url()];
2196
+ case 2:
2197
+ convertedUrl = _d.sent();
2198
+ return [3 /*break*/, 9];
2199
+ case 3:
2200
+ _d.sent();
2201
+ if (!optionsRef.current.retryOnError) return [3 /*break*/, 7];
2202
+ reconnectLimit = (_a = optionsRef.current.reconnectAttempts) !== null && _a !== void 0 ? _a : constants_1.DEFAULT_RECONNECT_LIMIT;
2203
+ if (!(retriedAttempts < reconnectLimit)) return [3 /*break*/, 5];
2204
+ nextReconnectInterval = typeof optionsRef.current.reconnectInterval === 'function' ?
2205
+ optionsRef.current.reconnectInterval(retriedAttempts) :
2206
+ optionsRef.current.reconnectInterval;
2207
+ return [4 /*yield*/, waitFor(nextReconnectInterval !== null && nextReconnectInterval !== void 0 ? nextReconnectInterval : constants_1.DEFAULT_RECONNECT_INTERVAL_MS)];
2208
+ case 4:
2209
+ _d.sent();
2210
+ return [2 /*return*/, (0, exports.getUrl)(url, optionsRef, retriedAttempts + 1)];
2211
+ case 5:
2212
+ (_c = (_b = optionsRef.current).onReconnectStop) === null || _c === void 0 ? void 0 : _c.call(_b, retriedAttempts);
2213
+ return [2 /*return*/, null];
2214
+ case 6: return [3 /*break*/, 8];
2215
+ case 7: return [2 /*return*/, null];
2216
+ case 8: return [3 /*break*/, 9];
2217
+ case 9: return [3 /*break*/, 11];
2218
+ case 10:
2219
+ convertedUrl = url;
2220
+ _d.label = 11;
2221
+ case 11:
2222
+ parsedUrl = optionsRef.current.fromSocketIO ?
2223
+ (0, socket_io_1.parseSocketIOUrl)(convertedUrl) :
2224
+ convertedUrl;
2225
+ parsedWithQueryParams = optionsRef.current.queryParams ?
2226
+ (0, socket_io_1.appendQueryParams)(parsedUrl, optionsRef.current.queryParams) :
2227
+ parsedUrl;
2228
+ return [2 /*return*/, parsedWithQueryParams];
2229
+ }
2230
+ });
2231
+ });
2232
+ };
2233
+ exports.getUrl = getUrl;
2234
+
2235
+ } (getUrl));
2236
+
2237
+ var proxy = {};
2238
+
2239
+ (function (exports) {
2240
+ Object.defineProperty(exports, "__esModule", { value: true });
2241
+ exports.websocketWrapper = void 0;
2242
+ var websocketWrapper = function (webSocket, start) {
2243
+ return new Proxy(webSocket, {
2244
+ get: function (obj, key) {
2245
+ var val = obj[key];
2246
+ if (key === 'reconnect')
2247
+ return start;
2248
+ if (typeof val === 'function') {
2249
+ console.error('Calling methods directly on the websocket is not supported at this moment. You must use the methods returned by useWebSocket.');
2250
+ //Prevent error thrown by invoking a non-function
2251
+ return function () { };
2252
+ }
2253
+ else {
2254
+ return val;
2255
+ }
2256
+ },
2257
+ set: function (obj, key, val) {
2258
+ if (/^on/.test(key)) {
2259
+ console.warn('The websocket\'s event handlers should be defined through the options object passed into useWebSocket.');
2260
+ return false;
2261
+ }
2262
+ else {
2263
+ obj[key] = val;
2264
+ return true;
2265
+ }
2266
+ },
2267
+ });
2268
+ };
2269
+ exports.websocketWrapper = websocketWrapper;
2270
+ exports.default = exports.websocketWrapper;
2271
+
2272
+ } (proxy));
2273
+
2274
+ var __assign$2 = (commonjsGlobal && commonjsGlobal.__assign) || function () {
2275
+ __assign$2 = Object.assign || function(t) {
2276
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
2277
+ s = arguments[i];
2278
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
2279
+ t[p] = s[p];
2280
+ }
2281
+ return t;
2282
+ };
2283
+ return __assign$2.apply(this, arguments);
2284
+ };
2285
+ var __awaiter = (commonjsGlobal && commonjsGlobal.__awaiter) || function (thisArg, _arguments, P, generator) {
2286
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
2287
+ return new (P || (P = Promise))(function (resolve, reject) {
2288
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
2289
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
2290
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
2291
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
2292
+ });
2293
+ };
2294
+ var __generator = (commonjsGlobal && commonjsGlobal.__generator) || function (thisArg, body) {
2295
+ 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);
2296
+ return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
2297
+ function verb(n) { return function (v) { return step([n, v]); }; }
2298
+ function step(op) {
2299
+ if (f) throw new TypeError("Generator is already executing.");
2300
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
2301
+ 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;
2302
+ if (y = 0, t) op = [op[0] & 2, t.value];
2303
+ switch (op[0]) {
2304
+ case 0: case 1: t = op; break;
2305
+ case 4: _.label++; return { value: op[1], done: false };
2306
+ case 5: _.label++; y = op[1]; op = [0]; continue;
2307
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
2308
+ default:
2309
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
2310
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
2311
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
2312
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
2313
+ if (t[2]) _.ops.pop();
2314
+ _.trys.pop(); continue;
2315
+ }
2316
+ op = body.call(thisArg, _);
2317
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
2318
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
2319
+ }
2320
+ };
2321
+ var __importDefault = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
2322
+ return (mod && mod.__esModule) ? mod : { "default": mod };
2323
+ };
2324
+ Object.defineProperty(useWebsocket, "__esModule", { value: true });
2325
+ useWebsocket.useWebSocket = void 0;
2326
+ var react_1$2 = require$$0;
2327
+ var react_dom_1 = require$$1;
2328
+ var constants_1$2 = constants;
2329
+ var create_or_join_1 = createOrJoin;
2330
+ var get_url_1 = getUrl;
2331
+ var proxy_1 = __importDefault(proxy);
2332
+ var util_1 = util;
2333
+ var useWebSocket$1 = function (url, options, connect) {
2334
+ if (options === void 0) { options = constants_1$2.DEFAULT_OPTIONS; }
2335
+ if (connect === void 0) { connect = true; }
2336
+ var _a = (0, react_1$2.useState)(null), lastMessage = _a[0], setLastMessage = _a[1];
2337
+ var _b = (0, react_1$2.useState)({}), readyState = _b[0], setReadyState = _b[1];
2338
+ var lastJsonMessage = (0, react_1$2.useMemo)(function () {
2339
+ if (!options.disableJson && lastMessage) {
2340
+ try {
2341
+ return JSON.parse(lastMessage.data);
2342
+ }
2343
+ catch (e) {
2344
+ return constants_1$2.UNPARSABLE_JSON_OBJECT;
2345
+ }
2346
+ }
2347
+ return null;
2348
+ }, [lastMessage, options.disableJson]);
2349
+ var convertedUrl = (0, react_1$2.useRef)(null);
2350
+ var webSocketRef = (0, react_1$2.useRef)(null);
2351
+ var startRef = (0, react_1$2.useRef)(function () { return void 0; });
2352
+ var reconnectCount = (0, react_1$2.useRef)(0);
2353
+ var lastMessageTime = (0, react_1$2.useRef)(Date.now());
2354
+ var messageQueue = (0, react_1$2.useRef)([]);
2355
+ var webSocketProxy = (0, react_1$2.useRef)(null);
2356
+ var optionsCache = (0, react_1$2.useRef)(options);
2357
+ optionsCache.current = options;
2358
+ var readyStateFromUrl = convertedUrl.current && readyState[convertedUrl.current] !== undefined ?
2359
+ readyState[convertedUrl.current] :
2360
+ url !== null && connect === true ?
2361
+ constants_1$2.ReadyState.CONNECTING :
2362
+ constants_1$2.ReadyState.UNINSTANTIATED;
2363
+ var stringifiedQueryParams = options.queryParams ? JSON.stringify(options.queryParams) : null;
2364
+ var sendMessage = (0, react_1$2.useCallback)(function (message, keep) {
2365
+ var _a;
2366
+ if (keep === void 0) { keep = true; }
2367
+ if (constants_1$2.isEventSourceSupported && webSocketRef.current instanceof EventSource) {
2368
+ console.warn('Unable to send a message from an eventSource');
2369
+ return;
2370
+ }
2371
+ if (((_a = webSocketRef.current) === null || _a === void 0 ? void 0 : _a.readyState) === constants_1$2.ReadyState.OPEN) {
2372
+ (0, util_1.assertIsWebSocket)(webSocketRef.current, optionsCache.current.skipAssert);
2373
+ webSocketRef.current.send(message);
2374
+ }
2375
+ else if (keep) {
2376
+ messageQueue.current.push(message);
2377
+ }
2378
+ }, []);
2379
+ var sendJsonMessage = (0, react_1$2.useCallback)(function (message, keep) {
2380
+ if (keep === void 0) { keep = true; }
2381
+ sendMessage(JSON.stringify(message), keep);
2382
+ }, [sendMessage]);
2383
+ var getWebSocket = (0, react_1$2.useCallback)(function () {
2384
+ if (optionsCache.current.share !== true || (constants_1$2.isEventSourceSupported && webSocketRef.current instanceof EventSource)) {
2385
+ return webSocketRef.current;
2386
+ }
2387
+ if (webSocketProxy.current === null && webSocketRef.current) {
2388
+ (0, util_1.assertIsWebSocket)(webSocketRef.current, optionsCache.current.skipAssert);
2389
+ webSocketProxy.current = (0, proxy_1.default)(webSocketRef.current, startRef);
2390
+ }
2391
+ return webSocketProxy.current;
2392
+ }, []);
2393
+ (0, react_1$2.useEffect)(function () {
2394
+ if (url !== null && connect === true) {
2395
+ var removeListeners_1;
2396
+ var expectClose_1 = false;
2397
+ var createOrJoin_1 = true;
2398
+ var start_1 = function () { return __awaiter(void 0, void 0, void 0, function () {
2399
+ var _a, protectedSetLastMessage, protectedSetReadyState;
2400
+ return __generator(this, function (_b) {
2401
+ switch (_b.label) {
2402
+ case 0:
2403
+ _a = convertedUrl;
2404
+ return [4 /*yield*/, (0, get_url_1.getUrl)(url, optionsCache)];
2405
+ case 1:
2406
+ _a.current = _b.sent();
2407
+ if (convertedUrl.current === null) {
2408
+ console.error('Failed to get a valid URL. WebSocket connection aborted.');
2409
+ convertedUrl.current = 'ABORTED';
2410
+ (0, react_dom_1.flushSync)(function () { return setReadyState(function (prev) { return (__assign$2(__assign$2({}, prev), { ABORTED: constants_1$2.ReadyState.CLOSED })); }); });
2411
+ return [2 /*return*/];
2412
+ }
2413
+ protectedSetLastMessage = function (message) {
2414
+ if (!expectClose_1) {
2415
+ (0, react_dom_1.flushSync)(function () { return setLastMessage(message); });
2416
+ }
2417
+ };
2418
+ protectedSetReadyState = function (state) {
2419
+ if (!expectClose_1) {
2420
+ (0, react_dom_1.flushSync)(function () { return setReadyState(function (prev) {
2421
+ var _a;
2422
+ return (__assign$2(__assign$2({}, prev), (convertedUrl.current && (_a = {}, _a[convertedUrl.current] = state, _a))));
2423
+ }); });
2424
+ }
2425
+ };
2426
+ if (createOrJoin_1) {
2427
+ removeListeners_1 = (0, create_or_join_1.createOrJoinSocket)(webSocketRef, convertedUrl.current, protectedSetReadyState, optionsCache, protectedSetLastMessage, startRef, reconnectCount, lastMessageTime, sendMessage);
2428
+ }
2429
+ return [2 /*return*/];
2430
+ }
2431
+ });
2432
+ }); };
2433
+ startRef.current = function () {
2434
+ if (!expectClose_1) {
2435
+ if (webSocketProxy.current)
2436
+ webSocketProxy.current = null;
2437
+ removeListeners_1 === null || removeListeners_1 === void 0 ? void 0 : removeListeners_1();
2438
+ start_1();
2439
+ }
2440
+ };
2441
+ start_1();
2442
+ return function () {
2443
+ expectClose_1 = true;
2444
+ createOrJoin_1 = false;
2445
+ if (webSocketProxy.current)
2446
+ webSocketProxy.current = null;
2447
+ removeListeners_1 === null || removeListeners_1 === void 0 ? void 0 : removeListeners_1();
2448
+ setLastMessage(null);
2449
+ };
2450
+ }
2451
+ else if (url === null || connect === false) {
2452
+ reconnectCount.current = 0; // reset reconnection attempts
2453
+ setReadyState(function (prev) {
2454
+ var _a;
2455
+ return (__assign$2(__assign$2({}, prev), (convertedUrl.current && (_a = {}, _a[convertedUrl.current] = constants_1$2.ReadyState.CLOSED, _a))));
2456
+ });
2457
+ }
2458
+ }, [url, connect, stringifiedQueryParams, sendMessage]);
2459
+ (0, react_1$2.useEffect)(function () {
2460
+ if (readyStateFromUrl === constants_1$2.ReadyState.OPEN) {
2461
+ messageQueue.current.splice(0).forEach(function (message) {
2462
+ sendMessage(message);
2463
+ });
2464
+ }
2465
+ }, [readyStateFromUrl]);
2466
+ return {
2467
+ sendMessage: sendMessage,
2468
+ sendJsonMessage: sendJsonMessage,
2469
+ lastMessage: lastMessage,
2470
+ lastJsonMessage: lastJsonMessage,
2471
+ readyState: readyStateFromUrl,
2472
+ getWebSocket: getWebSocket,
2473
+ };
2474
+ };
2475
+ useWebsocket.useWebSocket = useWebSocket$1;
2476
+
2477
+ var useSocketIo = {};
2478
+
2479
+ var __assign$1 = (commonjsGlobal && commonjsGlobal.__assign) || function () {
2480
+ __assign$1 = Object.assign || function(t) {
2481
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
2482
+ s = arguments[i];
2483
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
2484
+ t[p] = s[p];
2485
+ }
2486
+ return t;
2487
+ };
2488
+ return __assign$1.apply(this, arguments);
2489
+ };
2490
+ Object.defineProperty(useSocketIo, "__esModule", { value: true });
2491
+ useSocketIo.useSocketIO = void 0;
2492
+ var react_1$1 = require$$0;
2493
+ var use_websocket_1$1 = useWebsocket;
2494
+ var constants_1$1 = constants;
2495
+ var emptyEvent = {
2496
+ type: 'empty',
2497
+ payload: null,
2498
+ };
2499
+ var getSocketData = function (event) {
2500
+ if (!event || !event.data) {
2501
+ return emptyEvent;
2502
+ }
2503
+ var match = event.data.match(/\[.*]/);
2504
+ if (!match) {
2505
+ return emptyEvent;
2506
+ }
2507
+ var data = JSON.parse(match);
2508
+ if (!Array.isArray(data) || !data[1]) {
2509
+ return emptyEvent;
2510
+ }
2511
+ return {
2512
+ type: data[0],
2513
+ payload: data[1],
2514
+ };
2515
+ };
2516
+ var useSocketIO = function (url, options, connect) {
2517
+ if (options === void 0) { options = constants_1$1.DEFAULT_OPTIONS; }
2518
+ if (connect === void 0) { connect = true; }
2519
+ var optionsWithSocketIO = (0, react_1$1.useMemo)(function () { return (__assign$1(__assign$1({}, options), { fromSocketIO: true })); }, []);
2520
+ 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;
2521
+ var socketIOLastMessage = (0, react_1$1.useMemo)(function () {
2522
+ return getSocketData(lastMessage);
2523
+ }, [lastMessage]);
2524
+ return {
2525
+ sendMessage: sendMessage,
2526
+ sendJsonMessage: sendJsonMessage,
2527
+ lastMessage: socketIOLastMessage,
2528
+ lastJsonMessage: socketIOLastMessage,
2529
+ readyState: readyState,
2530
+ getWebSocket: getWebSocket,
2531
+ };
2532
+ };
2533
+ useSocketIo.useSocketIO = useSocketIO;
2534
+
2535
+ var useEventSource$1 = {};
2536
+
2537
+ var __assign = (commonjsGlobal && commonjsGlobal.__assign) || function () {
2538
+ __assign = Object.assign || function(t) {
2539
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
2540
+ s = arguments[i];
2541
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
2542
+ t[p] = s[p];
2543
+ }
2544
+ return t;
2545
+ };
2546
+ return __assign.apply(this, arguments);
2547
+ };
2548
+ var __rest = (commonjsGlobal && commonjsGlobal.__rest) || function (s, e) {
2549
+ var t = {};
2550
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
2551
+ t[p] = s[p];
2552
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
2553
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
2554
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
2555
+ t[p[i]] = s[p[i]];
2556
+ }
2557
+ return t;
2558
+ };
2559
+ Object.defineProperty(useEventSource$1, "__esModule", { value: true });
2560
+ useEventSource$1.useEventSource = void 0;
2561
+ var react_1 = require$$0;
2562
+ var use_websocket_1 = useWebsocket;
2563
+ var constants_1 = constants;
2564
+ var useEventSource = function (url, _a, connect) {
2565
+ if (_a === void 0) { _a = constants_1.DEFAULT_EVENT_SOURCE_OPTIONS; }
2566
+ var withCredentials = _a.withCredentials, events = _a.events, options = __rest(_a, ["withCredentials", "events"]);
2567
+ if (connect === void 0) { connect = true; }
2568
+ var optionsWithEventSource = __assign(__assign({}, options), { eventSourceOptions: {
2569
+ withCredentials: withCredentials,
2570
+ } });
2571
+ var eventsRef = (0, react_1.useRef)(constants_1.EMPTY_EVENT_HANDLERS);
2572
+ if (events) {
2573
+ eventsRef.current = events;
2574
+ }
2575
+ var _b = (0, use_websocket_1.useWebSocket)(url, optionsWithEventSource, connect), lastMessage = _b.lastMessage, readyState = _b.readyState, getWebSocket = _b.getWebSocket;
2576
+ (0, react_1.useEffect)(function () {
2577
+ if (lastMessage === null || lastMessage === void 0 ? void 0 : lastMessage.type) {
2578
+ Object.entries(eventsRef.current).forEach(function (_a) {
2579
+ var type = _a[0], handler = _a[1];
2580
+ if (type === lastMessage.type) {
2581
+ handler(lastMessage);
2582
+ }
2583
+ });
2584
+ }
2585
+ }, [lastMessage]);
2586
+ return {
2587
+ lastEvent: lastMessage,
2588
+ readyState: readyState,
2589
+ getEventSource: getWebSocket,
2590
+ };
2591
+ };
2592
+ useEventSource$1.useEventSource = useEventSource;
2593
+
2594
+ (function (exports) {
2595
+ Object.defineProperty(exports, "__esModule", { value: true });
2596
+ exports.resetGlobalState = exports.useEventSource = exports.ReadyState = exports.useSocketIO = exports.default = void 0;
2597
+ var use_websocket_1 = useWebsocket;
2598
+ Object.defineProperty(exports, "default", { enumerable: true, get: function () { return use_websocket_1.useWebSocket; } });
2599
+ var use_socket_io_1 = useSocketIo;
2600
+ Object.defineProperty(exports, "useSocketIO", { enumerable: true, get: function () { return use_socket_io_1.useSocketIO; } });
2601
+ var constants_1 = constants;
2602
+ Object.defineProperty(exports, "ReadyState", { enumerable: true, get: function () { return constants_1.ReadyState; } });
2603
+ var use_event_source_1 = useEventSource$1;
2604
+ Object.defineProperty(exports, "useEventSource", { enumerable: true, get: function () { return use_event_source_1.useEventSource; } });
2605
+ var util_1 = util;
2606
+ Object.defineProperty(exports, "resetGlobalState", { enumerable: true, get: function () { return util_1.resetGlobalState; } });
2607
+
2608
+ } (dist));
2609
+
2610
+ var useWebSocket = /*@__PURE__*/getDefaultExportFromCjs(dist);
2611
+
2612
+ const PearHyperliquidContext = createContext(undefined);
2613
+ /**
2614
+ * React Provider for PearHyperliquidClient
2615
+ */
2616
+ const PearHyperliquidProvider = ({ config, wsUrl = 'wss://hl-v2.pearprotocol.io/ws', children, }) => {
2617
+ const client = useMemo(() => new PearHyperliquidClient(config), [config]);
2618
+ const migrationSDK = useMemo(() => new PearMigrationSDK(client), [client]);
2619
+ // Address state
2620
+ const [address, setAddress] = useState(null);
2621
+ // WebSocket data state
2622
+ const [data, setData] = useState({
2623
+ tradeHistories: null,
2624
+ openPositions: null,
2625
+ openOrders: null,
2626
+ accountSummary: null,
2627
+ });
2628
+ const [lastError, setLastError] = useState(null);
2629
+ // WebSocket connection
2630
+ const { lastMessage, readyState, sendMessage } = useWebSocket(address ? wsUrl : null, // Only connect when address is set
2631
+ {
2632
+ shouldReconnect: () => true,
2633
+ reconnectAttempts: 5,
2634
+ reconnectInterval: 3000,
2635
+ });
2636
+ const isConnected = readyState === dist.ReadyState.OPEN;
2637
+ // Handle incoming WebSocket messages
2638
+ useEffect(() => {
2639
+ if (lastMessage !== null) {
2640
+ try {
2641
+ const message = JSON.parse(lastMessage.data);
2642
+ // Handle subscription responses
2643
+ if ('success' in message || 'error' in message) {
2644
+ if (message.error) {
2645
+ setLastError(message.error);
2646
+ }
2647
+ else {
2648
+ setLastError(null);
2649
+ }
2650
+ return;
2651
+ }
2652
+ // Handle channel data messages
2653
+ if ('channel' in message && 'data' in message) {
2654
+ const dataMessage = message;
2655
+ switch (dataMessage.channel) {
2656
+ case 'trade-histories':
2657
+ setData(prev => ({
2658
+ ...prev,
2659
+ tradeHistories: dataMessage.data
2660
+ }));
2661
+ break;
2662
+ case 'open-positions':
2663
+ setData(prev => ({
2664
+ ...prev,
2665
+ openPositions: dataMessage.data
2666
+ }));
2667
+ break;
2668
+ case 'open-orders':
2669
+ setData(prev => ({
2670
+ ...prev,
2671
+ openOrders: dataMessage.data
2672
+ }));
2673
+ break;
2674
+ case 'account-summary':
2675
+ setData(prev => ({
2676
+ ...prev,
2677
+ accountSummary: dataMessage.data
2678
+ }));
2679
+ break;
2680
+ }
2681
+ }
2682
+ }
2683
+ catch (error) {
2684
+ setLastError(`Failed to parse message: ${error instanceof Error ? error.message : String(error)}`);
2685
+ }
2686
+ }
2687
+ }, [lastMessage]);
2688
+ // Handle address changes - subscribe/unsubscribe
2689
+ useEffect(() => {
2690
+ if (isConnected && address) {
2691
+ // Subscribe to new address
2692
+ sendMessage(JSON.stringify({
2693
+ action: 'subscribe',
2694
+ address: address
2695
+ }));
2696
+ // Clear previous data
2697
+ setData({
2698
+ tradeHistories: null,
2699
+ openPositions: null,
2700
+ openOrders: null,
2701
+ accountSummary: null,
2702
+ });
2703
+ setLastError(null);
2704
+ }
2705
+ else if (isConnected && !address) {
2706
+ // Clear data when address is removed
2707
+ setData({
2708
+ tradeHistories: null,
2709
+ openPositions: null,
2710
+ openOrders: null,
2711
+ accountSummary: null,
2712
+ });
2713
+ }
2714
+ }, [isConnected, address, sendMessage]);
2715
+ const contextValue = useMemo(() => ({
2716
+ // Existing clients
2717
+ client,
2718
+ migrationSDK,
2719
+ // Address management
2720
+ address,
2721
+ setAddress,
2722
+ // WebSocket state
2723
+ connectionStatus: readyState,
2724
+ isConnected,
2725
+ // WebSocket data
2726
+ data,
2727
+ lastError,
2728
+ }), [client, migrationSDK, address, readyState, isConnected, data, lastError]);
2729
+ return (jsxRuntimeExports.jsx(PearHyperliquidContext.Provider, { value: contextValue, children: children }));
2730
+ };
2731
+ /**
2732
+ * Hook to use PearHyperliquidClient from context
2733
+ */
2734
+ const usePearHyperliquidClient = () => {
2735
+ const context = useContext(PearHyperliquidContext);
2736
+ if (!context) {
2737
+ throw new Error('usePearHyperliquidClient must be used within a PearHyperliquidProvider');
2738
+ }
2739
+ return context.client;
2740
+ };
2741
+ /**
2742
+ * Hook to use migration SDK from context
2743
+ */
2744
+ const useMigrationSDK = () => {
2745
+ const context = useContext(PearHyperliquidContext);
2746
+ if (!context) {
2747
+ throw new Error('useMigrationSDK must be used within a PearHyperliquidProvider');
2748
+ }
2749
+ return context.migrationSDK;
2750
+ };
2751
+
2752
+ /**
2753
+ * Hook to manage address (login/logout functionality)
2754
+ */
2755
+ const useAddress = () => {
2756
+ const context = useContext(PearHyperliquidContext);
2757
+ if (!context) {
2758
+ throw new Error('useAddress must be used within a PearHyperliquidProvider');
2759
+ }
2760
+ return {
2761
+ address: context.address,
2762
+ setAddress: context.setAddress,
2763
+ clearAddress: () => context.setAddress(null),
2764
+ isLoggedIn: !!context.address,
2765
+ };
2766
+ };
2767
+
2768
+ /**
2769
+ * Hook to access trade histories
2770
+ */
2771
+ const useTradeHistories = () => {
2772
+ const context = useContext(PearHyperliquidContext);
2773
+ if (!context) {
2774
+ throw new Error('useTradeHistories must be used within a PearHyperliquidProvider');
2775
+ }
2776
+ return context.data.tradeHistories;
2777
+ };
2778
+ /**
2779
+ * Hook to access open positions
2780
+ */
2781
+ const useOpenPositions = () => {
2782
+ const context = useContext(PearHyperliquidContext);
2783
+ if (!context) {
2784
+ throw new Error('useOpenPositions must be used within a PearHyperliquidProvider');
2785
+ }
2786
+ return context.data.openPositions;
2787
+ };
2788
+ /**
2789
+ * Hook to access open orders
2790
+ */
2791
+ const useOpenOrders = () => {
2792
+ const context = useContext(PearHyperliquidContext);
2793
+ if (!context) {
2794
+ throw new Error('useOpenOrders must be used within a PearHyperliquidProvider');
2795
+ }
2796
+ return context.data.openOrders;
2797
+ };
2798
+ /**
2799
+ * Hook to access account summary
2800
+ */
2801
+ const useAccountSummary = () => {
2802
+ const context = useContext(PearHyperliquidContext);
2803
+ if (!context) {
2804
+ throw new Error('useAccountSummary must be used within a PearHyperliquidProvider');
2805
+ }
2806
+ return context.data.accountSummary;
2807
+ };
2808
+
2809
+ export { PearHyperliquidClient, PearHyperliquidProvider, PearMigrationSDK, PearHyperliquidClient as default, useAccountSummary, useAddress, useMigrationSDK, useOpenOrders, useOpenPositions, usePearHyperliquidClient, useTradeHistories };
2810
+ //# sourceMappingURL=index.esm.js.map