@pear-protocol/hyperliquid-sdk 0.0.45 → 0.0.47-alpha

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,2432 +1,23 @@
1
- import React, { useState, useEffect, useMemo, useRef, useCallback, useContext, createContext } from 'react';
2
- import require$$1 from 'react-dom';
1
+ import { jsx } from 'react/jsx-runtime';
2
+ import { useState, useRef, useCallback, useEffect, useMemo, useContext, createContext } from 'react';
3
3
  import { create } from 'zustand';
4
4
 
5
- var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
6
-
7
- function getDefaultExportFromCjs (x) {
8
- return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
9
- }
10
-
11
- var jsxRuntime = {exports: {}};
12
-
13
- var reactJsxRuntime_production_min = {};
14
-
15
- /**
16
- * @license React
17
- * react-jsx-runtime.production.min.js
18
- *
19
- * Copyright (c) Facebook, Inc. and its affiliates.
20
- *
21
- * This source code is licensed under the MIT license found in the
22
- * LICENSE file in the root directory of this source tree.
23
- */
24
-
25
- var hasRequiredReactJsxRuntime_production_min;
26
-
27
- function requireReactJsxRuntime_production_min () {
28
- if (hasRequiredReactJsxRuntime_production_min) return reactJsxRuntime_production_min;
29
- hasRequiredReactJsxRuntime_production_min = 1;
30
- var f=React,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};
31
- 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;
32
- return reactJsxRuntime_production_min;
33
- }
34
-
35
- var reactJsxRuntime_development = {};
36
-
37
- /**
38
- * @license React
39
- * react-jsx-runtime.development.js
40
- *
41
- * Copyright (c) Facebook, Inc. and its affiliates.
42
- *
43
- * This source code is licensed under the MIT license found in the
44
- * LICENSE file in the root directory of this source tree.
45
- */
46
-
47
- var hasRequiredReactJsxRuntime_development;
48
-
49
- function requireReactJsxRuntime_development () {
50
- if (hasRequiredReactJsxRuntime_development) return reactJsxRuntime_development;
51
- hasRequiredReactJsxRuntime_development = 1;
52
-
53
- if (process.env.NODE_ENV !== "production") {
54
- (function() {
55
-
56
- var React$1 = React;
57
-
58
- // ATTENTION
59
- // When adding new symbols to this file,
60
- // Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols'
61
- // The Symbol used to tag the ReactElement-like types.
62
- var REACT_ELEMENT_TYPE = Symbol.for('react.element');
63
- var REACT_PORTAL_TYPE = Symbol.for('react.portal');
64
- var REACT_FRAGMENT_TYPE = Symbol.for('react.fragment');
65
- var REACT_STRICT_MODE_TYPE = Symbol.for('react.strict_mode');
66
- var REACT_PROFILER_TYPE = Symbol.for('react.profiler');
67
- var REACT_PROVIDER_TYPE = Symbol.for('react.provider');
68
- var REACT_CONTEXT_TYPE = Symbol.for('react.context');
69
- var REACT_FORWARD_REF_TYPE = Symbol.for('react.forward_ref');
70
- var REACT_SUSPENSE_TYPE = Symbol.for('react.suspense');
71
- var REACT_SUSPENSE_LIST_TYPE = Symbol.for('react.suspense_list');
72
- var REACT_MEMO_TYPE = Symbol.for('react.memo');
73
- var REACT_LAZY_TYPE = Symbol.for('react.lazy');
74
- var REACT_OFFSCREEN_TYPE = Symbol.for('react.offscreen');
75
- var MAYBE_ITERATOR_SYMBOL = Symbol.iterator;
76
- var FAUX_ITERATOR_SYMBOL = '@@iterator';
77
- function getIteratorFn(maybeIterable) {
78
- if (maybeIterable === null || typeof maybeIterable !== 'object') {
79
- return null;
80
- }
81
-
82
- var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL];
83
-
84
- if (typeof maybeIterator === 'function') {
85
- return maybeIterator;
86
- }
87
-
88
- return null;
89
- }
90
-
91
- var ReactSharedInternals = React$1.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
92
-
93
- function error(format) {
94
- {
95
- {
96
- for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
97
- args[_key2 - 1] = arguments[_key2];
98
- }
99
-
100
- printWarning('error', format, args);
101
- }
102
- }
103
- }
104
-
105
- function printWarning(level, format, args) {
106
- // When changing this logic, you might want to also
107
- // update consoleWithStackDev.www.js as well.
108
- {
109
- var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
110
- var stack = ReactDebugCurrentFrame.getStackAddendum();
111
-
112
- if (stack !== '') {
113
- format += '%s';
114
- args = args.concat([stack]);
115
- } // eslint-disable-next-line react-internal/safe-string-coercion
116
-
117
-
118
- var argsWithFormat = args.map(function (item) {
119
- return String(item);
120
- }); // Careful: RN currently depends on this prefix
121
-
122
- argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it
123
- // breaks IE9: https://github.com/facebook/react/issues/13610
124
- // eslint-disable-next-line react-internal/no-production-logging
125
-
126
- Function.prototype.apply.call(console[level], console, argsWithFormat);
127
- }
128
- }
129
-
130
- // -----------------------------------------------------------------------------
131
-
132
- var enableScopeAPI = false; // Experimental Create Event Handle API.
133
- var enableCacheElement = false;
134
- var enableTransitionTracing = false; // No known bugs, but needs performance testing
135
-
136
- var enableLegacyHidden = false; // Enables unstable_avoidThisFallback feature in Fiber
137
- // stuff. Intended to enable React core members to more easily debug scheduling
138
- // issues in DEV builds.
139
-
140
- var enableDebugTracing = false; // Track which Fiber(s) schedule render work.
141
-
142
- var REACT_MODULE_REFERENCE;
143
-
144
- {
145
- REACT_MODULE_REFERENCE = Symbol.for('react.module.reference');
146
- }
147
-
148
- function isValidElementType(type) {
149
- if (typeof type === 'string' || typeof type === 'function') {
150
- return true;
151
- } // Note: typeof might be other than 'symbol' or 'number' (e.g. if it's a polyfill).
152
-
153
-
154
- 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 ) {
155
- return true;
156
- }
157
-
158
- if (typeof type === 'object' && type !== null) {
159
- 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
160
- // types supported by any Flight configuration anywhere since
161
- // we don't know which Flight build this will end up being used
162
- // with.
163
- type.$$typeof === REACT_MODULE_REFERENCE || type.getModuleId !== undefined) {
164
- return true;
165
- }
166
- }
167
-
168
- return false;
169
- }
170
-
171
- function getWrappedName(outerType, innerType, wrapperName) {
172
- var displayName = outerType.displayName;
173
-
174
- if (displayName) {
175
- return displayName;
176
- }
177
-
178
- var functionName = innerType.displayName || innerType.name || '';
179
- return functionName !== '' ? wrapperName + "(" + functionName + ")" : wrapperName;
180
- } // Keep in sync with react-reconciler/getComponentNameFromFiber
181
-
182
-
183
- function getContextName(type) {
184
- return type.displayName || 'Context';
185
- } // Note that the reconciler package should generally prefer to use getComponentNameFromFiber() instead.
186
-
187
-
188
- function getComponentNameFromType(type) {
189
- if (type == null) {
190
- // Host root, text node or just invalid type.
191
- return null;
192
- }
193
-
194
- {
195
- if (typeof type.tag === 'number') {
196
- error('Received an unexpected object in getComponentNameFromType(). ' + 'This is likely a bug in React. Please file an issue.');
197
- }
198
- }
199
-
200
- if (typeof type === 'function') {
201
- return type.displayName || type.name || null;
202
- }
203
-
204
- if (typeof type === 'string') {
205
- return type;
206
- }
207
-
208
- switch (type) {
209
- case REACT_FRAGMENT_TYPE:
210
- return 'Fragment';
211
-
212
- case REACT_PORTAL_TYPE:
213
- return 'Portal';
214
-
215
- case REACT_PROFILER_TYPE:
216
- return 'Profiler';
217
-
218
- case REACT_STRICT_MODE_TYPE:
219
- return 'StrictMode';
220
-
221
- case REACT_SUSPENSE_TYPE:
222
- return 'Suspense';
223
-
224
- case REACT_SUSPENSE_LIST_TYPE:
225
- return 'SuspenseList';
226
-
227
- }
228
-
229
- if (typeof type === 'object') {
230
- switch (type.$$typeof) {
231
- case REACT_CONTEXT_TYPE:
232
- var context = type;
233
- return getContextName(context) + '.Consumer';
234
-
235
- case REACT_PROVIDER_TYPE:
236
- var provider = type;
237
- return getContextName(provider._context) + '.Provider';
238
-
239
- case REACT_FORWARD_REF_TYPE:
240
- return getWrappedName(type, type.render, 'ForwardRef');
241
-
242
- case REACT_MEMO_TYPE:
243
- var outerName = type.displayName || null;
244
-
245
- if (outerName !== null) {
246
- return outerName;
247
- }
248
-
249
- return getComponentNameFromType(type.type) || 'Memo';
250
-
251
- case REACT_LAZY_TYPE:
252
- {
253
- var lazyComponent = type;
254
- var payload = lazyComponent._payload;
255
- var init = lazyComponent._init;
256
-
257
- try {
258
- return getComponentNameFromType(init(payload));
259
- } catch (x) {
260
- return null;
261
- }
262
- }
263
-
264
- // eslint-disable-next-line no-fallthrough
265
- }
266
- }
267
-
268
- return null;
269
- }
270
-
271
- var assign = Object.assign;
272
-
273
- // Helpers to patch console.logs to avoid logging during side-effect free
274
- // replaying on render function. This currently only patches the object
275
- // lazily which won't cover if the log function was extracted eagerly.
276
- // We could also eagerly patch the method.
277
- var disabledDepth = 0;
278
- var prevLog;
279
- var prevInfo;
280
- var prevWarn;
281
- var prevError;
282
- var prevGroup;
283
- var prevGroupCollapsed;
284
- var prevGroupEnd;
285
-
286
- function disabledLog() {}
287
-
288
- disabledLog.__reactDisabledLog = true;
289
- function disableLogs() {
290
- {
291
- if (disabledDepth === 0) {
292
- /* eslint-disable react-internal/no-production-logging */
293
- prevLog = console.log;
294
- prevInfo = console.info;
295
- prevWarn = console.warn;
296
- prevError = console.error;
297
- prevGroup = console.group;
298
- prevGroupCollapsed = console.groupCollapsed;
299
- prevGroupEnd = console.groupEnd; // https://github.com/facebook/react/issues/19099
300
-
301
- var props = {
302
- configurable: true,
303
- enumerable: true,
304
- value: disabledLog,
305
- writable: true
306
- }; // $FlowFixMe Flow thinks console is immutable.
307
-
308
- Object.defineProperties(console, {
309
- info: props,
310
- log: props,
311
- warn: props,
312
- error: props,
313
- group: props,
314
- groupCollapsed: props,
315
- groupEnd: props
316
- });
317
- /* eslint-enable react-internal/no-production-logging */
318
- }
319
-
320
- disabledDepth++;
321
- }
322
- }
323
- function reenableLogs() {
324
- {
325
- disabledDepth--;
326
-
327
- if (disabledDepth === 0) {
328
- /* eslint-disable react-internal/no-production-logging */
329
- var props = {
330
- configurable: true,
331
- enumerable: true,
332
- writable: true
333
- }; // $FlowFixMe Flow thinks console is immutable.
334
-
335
- Object.defineProperties(console, {
336
- log: assign({}, props, {
337
- value: prevLog
338
- }),
339
- info: assign({}, props, {
340
- value: prevInfo
341
- }),
342
- warn: assign({}, props, {
343
- value: prevWarn
344
- }),
345
- error: assign({}, props, {
346
- value: prevError
347
- }),
348
- group: assign({}, props, {
349
- value: prevGroup
350
- }),
351
- groupCollapsed: assign({}, props, {
352
- value: prevGroupCollapsed
353
- }),
354
- groupEnd: assign({}, props, {
355
- value: prevGroupEnd
356
- })
357
- });
358
- /* eslint-enable react-internal/no-production-logging */
359
- }
360
-
361
- if (disabledDepth < 0) {
362
- error('disabledDepth fell below zero. ' + 'This is a bug in React. Please file an issue.');
363
- }
364
- }
365
- }
366
-
367
- var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher;
368
- var prefix;
369
- function describeBuiltInComponentFrame(name, source, ownerFn) {
370
- {
371
- if (prefix === undefined) {
372
- // Extract the VM specific prefix used by each line.
373
- try {
374
- throw Error();
375
- } catch (x) {
376
- var match = x.stack.trim().match(/\n( *(at )?)/);
377
- prefix = match && match[1] || '';
378
- }
379
- } // We use the prefix to ensure our stacks line up with native stack frames.
380
-
381
-
382
- return '\n' + prefix + name;
383
- }
384
- }
385
- var reentry = false;
386
- var componentFrameCache;
387
-
388
- {
389
- var PossiblyWeakMap = typeof WeakMap === 'function' ? WeakMap : Map;
390
- componentFrameCache = new PossiblyWeakMap();
391
- }
392
-
393
- function describeNativeComponentFrame(fn, construct) {
394
- // If something asked for a stack inside a fake render, it should get ignored.
395
- if ( !fn || reentry) {
396
- return '';
397
- }
398
-
399
- {
400
- var frame = componentFrameCache.get(fn);
401
-
402
- if (frame !== undefined) {
403
- return frame;
404
- }
405
- }
406
-
407
- var control;
408
- reentry = true;
409
- var previousPrepareStackTrace = Error.prepareStackTrace; // $FlowFixMe It does accept undefined.
410
-
411
- Error.prepareStackTrace = undefined;
412
- var previousDispatcher;
413
-
414
- {
415
- previousDispatcher = ReactCurrentDispatcher.current; // Set the dispatcher in DEV because this might be call in the render function
416
- // for warnings.
417
-
418
- ReactCurrentDispatcher.current = null;
419
- disableLogs();
420
- }
421
-
422
- try {
423
- // This should throw.
424
- if (construct) {
425
- // Something should be setting the props in the constructor.
426
- var Fake = function () {
427
- throw Error();
428
- }; // $FlowFixMe
429
-
430
-
431
- Object.defineProperty(Fake.prototype, 'props', {
432
- set: function () {
433
- // We use a throwing setter instead of frozen or non-writable props
434
- // because that won't throw in a non-strict mode function.
435
- throw Error();
436
- }
437
- });
438
-
439
- if (typeof Reflect === 'object' && Reflect.construct) {
440
- // We construct a different control for this case to include any extra
441
- // frames added by the construct call.
442
- try {
443
- Reflect.construct(Fake, []);
444
- } catch (x) {
445
- control = x;
446
- }
447
-
448
- Reflect.construct(fn, [], Fake);
449
- } else {
450
- try {
451
- Fake.call();
452
- } catch (x) {
453
- control = x;
454
- }
455
-
456
- fn.call(Fake.prototype);
457
- }
458
- } else {
459
- try {
460
- throw Error();
461
- } catch (x) {
462
- control = x;
463
- }
464
-
465
- fn();
466
- }
467
- } catch (sample) {
468
- // This is inlined manually because closure doesn't do it for us.
469
- if (sample && control && typeof sample.stack === 'string') {
470
- // This extracts the first frame from the sample that isn't also in the control.
471
- // Skipping one frame that we assume is the frame that calls the two.
472
- var sampleLines = sample.stack.split('\n');
473
- var controlLines = control.stack.split('\n');
474
- var s = sampleLines.length - 1;
475
- var c = controlLines.length - 1;
476
-
477
- while (s >= 1 && c >= 0 && sampleLines[s] !== controlLines[c]) {
478
- // We expect at least one stack frame to be shared.
479
- // Typically this will be the root most one. However, stack frames may be
480
- // cut off due to maximum stack limits. In this case, one maybe cut off
481
- // earlier than the other. We assume that the sample is longer or the same
482
- // and there for cut off earlier. So we should find the root most frame in
483
- // the sample somewhere in the control.
484
- c--;
485
- }
486
-
487
- for (; s >= 1 && c >= 0; s--, c--) {
488
- // Next we find the first one that isn't the same which should be the
489
- // frame that called our sample function and the control.
490
- if (sampleLines[s] !== controlLines[c]) {
491
- // In V8, the first line is describing the message but other VMs don't.
492
- // If we're about to return the first line, and the control is also on the same
493
- // line, that's a pretty good indicator that our sample threw at same line as
494
- // the control. I.e. before we entered the sample frame. So we ignore this result.
495
- // This can happen if you passed a class to function component, or non-function.
496
- if (s !== 1 || c !== 1) {
497
- do {
498
- s--;
499
- c--; // We may still have similar intermediate frames from the construct call.
500
- // The next one that isn't the same should be our match though.
501
-
502
- if (c < 0 || sampleLines[s] !== controlLines[c]) {
503
- // V8 adds a "new" prefix for native classes. Let's remove it to make it prettier.
504
- var _frame = '\n' + sampleLines[s].replace(' at new ', ' at '); // If our component frame is labeled "<anonymous>"
505
- // but we have a user-provided "displayName"
506
- // splice it in to make the stack more readable.
507
-
508
-
509
- if (fn.displayName && _frame.includes('<anonymous>')) {
510
- _frame = _frame.replace('<anonymous>', fn.displayName);
511
- }
512
-
513
- {
514
- if (typeof fn === 'function') {
515
- componentFrameCache.set(fn, _frame);
516
- }
517
- } // Return the line we found.
518
-
519
-
520
- return _frame;
521
- }
522
- } while (s >= 1 && c >= 0);
523
- }
524
-
525
- break;
526
- }
527
- }
528
- }
529
- } finally {
530
- reentry = false;
531
-
532
- {
533
- ReactCurrentDispatcher.current = previousDispatcher;
534
- reenableLogs();
535
- }
536
-
537
- Error.prepareStackTrace = previousPrepareStackTrace;
538
- } // Fallback to just using the name if we couldn't make it throw.
539
-
540
-
541
- var name = fn ? fn.displayName || fn.name : '';
542
- var syntheticFrame = name ? describeBuiltInComponentFrame(name) : '';
543
-
544
- {
545
- if (typeof fn === 'function') {
546
- componentFrameCache.set(fn, syntheticFrame);
547
- }
548
- }
549
-
550
- return syntheticFrame;
551
- }
552
- function describeFunctionComponentFrame(fn, source, ownerFn) {
553
- {
554
- return describeNativeComponentFrame(fn, false);
555
- }
556
- }
557
-
558
- function shouldConstruct(Component) {
559
- var prototype = Component.prototype;
560
- return !!(prototype && prototype.isReactComponent);
561
- }
562
-
563
- function describeUnknownElementTypeFrameInDEV(type, source, ownerFn) {
564
-
565
- if (type == null) {
566
- return '';
567
- }
568
-
569
- if (typeof type === 'function') {
570
- {
571
- return describeNativeComponentFrame(type, shouldConstruct(type));
572
- }
573
- }
574
-
575
- if (typeof type === 'string') {
576
- return describeBuiltInComponentFrame(type);
577
- }
578
-
579
- switch (type) {
580
- case REACT_SUSPENSE_TYPE:
581
- return describeBuiltInComponentFrame('Suspense');
582
-
583
- case REACT_SUSPENSE_LIST_TYPE:
584
- return describeBuiltInComponentFrame('SuspenseList');
585
- }
586
-
587
- if (typeof type === 'object') {
588
- switch (type.$$typeof) {
589
- case REACT_FORWARD_REF_TYPE:
590
- return describeFunctionComponentFrame(type.render);
591
-
592
- case REACT_MEMO_TYPE:
593
- // Memo may contain any component type so we recursively resolve it.
594
- return describeUnknownElementTypeFrameInDEV(type.type, source, ownerFn);
595
-
596
- case REACT_LAZY_TYPE:
597
- {
598
- var lazyComponent = type;
599
- var payload = lazyComponent._payload;
600
- var init = lazyComponent._init;
601
-
602
- try {
603
- // Lazy may contain any component type so we recursively resolve it.
604
- return describeUnknownElementTypeFrameInDEV(init(payload), source, ownerFn);
605
- } catch (x) {}
606
- }
607
- }
608
- }
609
-
610
- return '';
611
- }
612
-
613
- var hasOwnProperty = Object.prototype.hasOwnProperty;
614
-
615
- var loggedTypeFailures = {};
616
- var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
617
-
618
- function setCurrentlyValidatingElement(element) {
619
- {
620
- if (element) {
621
- var owner = element._owner;
622
- var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null);
623
- ReactDebugCurrentFrame.setExtraStackFrame(stack);
624
- } else {
625
- ReactDebugCurrentFrame.setExtraStackFrame(null);
626
- }
627
- }
628
- }
629
-
630
- function checkPropTypes(typeSpecs, values, location, componentName, element) {
631
- {
632
- // $FlowFixMe This is okay but Flow doesn't know it.
633
- var has = Function.call.bind(hasOwnProperty);
634
-
635
- for (var typeSpecName in typeSpecs) {
636
- if (has(typeSpecs, typeSpecName)) {
637
- var error$1 = void 0; // Prop type validation may throw. In case they do, we don't want to
638
- // fail the render phase where it didn't fail before. So we log it.
639
- // After these have been cleaned up, we'll let them throw.
640
-
641
- try {
642
- // This is intentionally an invariant that gets caught. It's the same
643
- // behavior as without this statement except with a better message.
644
- if (typeof typeSpecs[typeSpecName] !== 'function') {
645
- // eslint-disable-next-line react-internal/prod-error-codes
646
- 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`.');
647
- err.name = 'Invariant Violation';
648
- throw err;
649
- }
650
-
651
- error$1 = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED');
652
- } catch (ex) {
653
- error$1 = ex;
654
- }
655
-
656
- if (error$1 && !(error$1 instanceof Error)) {
657
- setCurrentlyValidatingElement(element);
658
-
659
- 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);
660
-
661
- setCurrentlyValidatingElement(null);
662
- }
663
-
664
- if (error$1 instanceof Error && !(error$1.message in loggedTypeFailures)) {
665
- // Only monitor this failure once because there tends to be a lot of the
666
- // same error.
667
- loggedTypeFailures[error$1.message] = true;
668
- setCurrentlyValidatingElement(element);
669
-
670
- error('Failed %s type: %s', location, error$1.message);
671
-
672
- setCurrentlyValidatingElement(null);
673
- }
674
- }
675
- }
676
- }
677
- }
678
-
679
- var isArrayImpl = Array.isArray; // eslint-disable-next-line no-redeclare
680
-
681
- function isArray(a) {
682
- return isArrayImpl(a);
683
- }
684
-
685
- /*
686
- * The `'' + value` pattern (used in in perf-sensitive code) throws for Symbol
687
- * and Temporal.* types. See https://github.com/facebook/react/pull/22064.
688
- *
689
- * The functions in this module will throw an easier-to-understand,
690
- * easier-to-debug exception with a clear errors message message explaining the
691
- * problem. (Instead of a confusing exception thrown inside the implementation
692
- * of the `value` object).
693
- */
694
- // $FlowFixMe only called in DEV, so void return is not possible.
695
- function typeName(value) {
696
- {
697
- // toStringTag is needed for namespaced types like Temporal.Instant
698
- var hasToStringTag = typeof Symbol === 'function' && Symbol.toStringTag;
699
- var type = hasToStringTag && value[Symbol.toStringTag] || value.constructor.name || 'Object';
700
- return type;
701
- }
702
- } // $FlowFixMe only called in DEV, so void return is not possible.
703
-
704
-
705
- function willCoercionThrow(value) {
706
- {
707
- try {
708
- testStringCoercion(value);
709
- return false;
710
- } catch (e) {
711
- return true;
712
- }
713
- }
714
- }
715
-
716
- function testStringCoercion(value) {
717
- // If you ended up here by following an exception call stack, here's what's
718
- // happened: you supplied an object or symbol value to React (as a prop, key,
719
- // DOM attribute, CSS property, string ref, etc.) and when React tried to
720
- // coerce it to a string using `'' + value`, an exception was thrown.
721
- //
722
- // The most common types that will cause this exception are `Symbol` instances
723
- // and Temporal objects like `Temporal.Instant`. But any object that has a
724
- // `valueOf` or `[Symbol.toPrimitive]` method that throws will also cause this
725
- // exception. (Library authors do this to prevent users from using built-in
726
- // numeric operators like `+` or comparison operators like `>=` because custom
727
- // methods are needed to perform accurate arithmetic or comparison.)
728
- //
729
- // To fix the problem, coerce this object or symbol value to a string before
730
- // passing it to React. The most reliable way is usually `String(value)`.
731
- //
732
- // To find which value is throwing, check the browser or debugger console.
733
- // Before this exception was thrown, there should be `console.error` output
734
- // that shows the type (Symbol, Temporal.PlainDate, etc.) that caused the
735
- // problem and how that type was used: key, atrribute, input value prop, etc.
736
- // In most cases, this console output also shows the component and its
737
- // ancestor components where the exception happened.
738
- //
739
- // eslint-disable-next-line react-internal/safe-string-coercion
740
- return '' + value;
741
- }
742
- function checkKeyStringCoercion(value) {
743
- {
744
- if (willCoercionThrow(value)) {
745
- error('The provided key is an unsupported type %s.' + ' This value must be coerced to a string before before using it here.', typeName(value));
746
-
747
- return testStringCoercion(value); // throw (to help callers find troubleshooting comments)
748
- }
749
- }
750
- }
751
-
752
- var ReactCurrentOwner = ReactSharedInternals.ReactCurrentOwner;
753
- var RESERVED_PROPS = {
754
- key: true,
755
- ref: true,
756
- __self: true,
757
- __source: true
758
- };
759
- var specialPropKeyWarningShown;
760
- var specialPropRefWarningShown;
761
- var didWarnAboutStringRefs;
762
-
763
- {
764
- didWarnAboutStringRefs = {};
765
- }
766
-
767
- function hasValidRef(config) {
768
- {
769
- if (hasOwnProperty.call(config, 'ref')) {
770
- var getter = Object.getOwnPropertyDescriptor(config, 'ref').get;
771
-
772
- if (getter && getter.isReactWarning) {
773
- return false;
774
- }
775
- }
776
- }
777
-
778
- return config.ref !== undefined;
779
- }
780
-
781
- function hasValidKey(config) {
782
- {
783
- if (hasOwnProperty.call(config, 'key')) {
784
- var getter = Object.getOwnPropertyDescriptor(config, 'key').get;
785
-
786
- if (getter && getter.isReactWarning) {
787
- return false;
788
- }
789
- }
790
- }
791
-
792
- return config.key !== undefined;
793
- }
794
-
795
- function warnIfStringRefCannotBeAutoConverted(config, self) {
796
- {
797
- if (typeof config.ref === 'string' && ReactCurrentOwner.current && self && ReactCurrentOwner.current.stateNode !== self) {
798
- var componentName = getComponentNameFromType(ReactCurrentOwner.current.type);
799
-
800
- if (!didWarnAboutStringRefs[componentName]) {
801
- 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);
802
-
803
- didWarnAboutStringRefs[componentName] = true;
804
- }
805
- }
806
- }
807
- }
808
-
809
- function defineKeyPropWarningGetter(props, displayName) {
810
- {
811
- var warnAboutAccessingKey = function () {
812
- if (!specialPropKeyWarningShown) {
813
- specialPropKeyWarningShown = true;
814
-
815
- 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);
816
- }
817
- };
818
-
819
- warnAboutAccessingKey.isReactWarning = true;
820
- Object.defineProperty(props, 'key', {
821
- get: warnAboutAccessingKey,
822
- configurable: true
823
- });
824
- }
825
- }
826
-
827
- function defineRefPropWarningGetter(props, displayName) {
828
- {
829
- var warnAboutAccessingRef = function () {
830
- if (!specialPropRefWarningShown) {
831
- specialPropRefWarningShown = true;
832
-
833
- 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);
834
- }
835
- };
836
-
837
- warnAboutAccessingRef.isReactWarning = true;
838
- Object.defineProperty(props, 'ref', {
839
- get: warnAboutAccessingRef,
840
- configurable: true
841
- });
842
- }
843
- }
844
- /**
845
- * Factory method to create a new React element. This no longer adheres to
846
- * the class pattern, so do not use new to call it. Also, instanceof check
847
- * will not work. Instead test $$typeof field against Symbol.for('react.element') to check
848
- * if something is a React Element.
849
- *
850
- * @param {*} type
851
- * @param {*} props
852
- * @param {*} key
853
- * @param {string|object} ref
854
- * @param {*} owner
855
- * @param {*} self A *temporary* helper to detect places where `this` is
856
- * different from the `owner` when React.createElement is called, so that we
857
- * can warn. We want to get rid of owner and replace string `ref`s with arrow
858
- * functions, and as long as `this` and owner are the same, there will be no
859
- * change in behavior.
860
- * @param {*} source An annotation object (added by a transpiler or otherwise)
861
- * indicating filename, line number, and/or other information.
862
- * @internal
863
- */
864
-
865
-
866
- var ReactElement = function (type, key, ref, self, source, owner, props) {
867
- var element = {
868
- // This tag allows us to uniquely identify this as a React Element
869
- $$typeof: REACT_ELEMENT_TYPE,
870
- // Built-in properties that belong on the element
871
- type: type,
872
- key: key,
873
- ref: ref,
874
- props: props,
875
- // Record the component responsible for creating this element.
876
- _owner: owner
877
- };
878
-
879
- {
880
- // The validation flag is currently mutative. We put it on
881
- // an external backing store so that we can freeze the whole object.
882
- // This can be replaced with a WeakMap once they are implemented in
883
- // commonly used development environments.
884
- element._store = {}; // To make comparing ReactElements easier for testing purposes, we make
885
- // the validation flag non-enumerable (where possible, which should
886
- // include every environment we run tests in), so the test framework
887
- // ignores it.
888
-
889
- Object.defineProperty(element._store, 'validated', {
890
- configurable: false,
891
- enumerable: false,
892
- writable: true,
893
- value: false
894
- }); // self and source are DEV only properties.
895
-
896
- Object.defineProperty(element, '_self', {
897
- configurable: false,
898
- enumerable: false,
899
- writable: false,
900
- value: self
901
- }); // Two elements created in two different places should be considered
902
- // equal for testing purposes and therefore we hide it from enumeration.
903
-
904
- Object.defineProperty(element, '_source', {
905
- configurable: false,
906
- enumerable: false,
907
- writable: false,
908
- value: source
909
- });
910
-
911
- if (Object.freeze) {
912
- Object.freeze(element.props);
913
- Object.freeze(element);
914
- }
915
- }
916
-
917
- return element;
918
- };
919
- /**
920
- * https://github.com/reactjs/rfcs/pull/107
921
- * @param {*} type
922
- * @param {object} props
923
- * @param {string} key
924
- */
925
-
926
- function jsxDEV(type, config, maybeKey, source, self) {
927
- {
928
- var propName; // Reserved names are extracted
929
-
930
- var props = {};
931
- var key = null;
932
- var ref = null; // Currently, key can be spread in as a prop. This causes a potential
933
- // issue if key is also explicitly declared (ie. <div {...props} key="Hi" />
934
- // or <div key="Hi" {...props} /> ). We want to deprecate key spread,
935
- // but as an intermediary step, we will use jsxDEV for everything except
936
- // <div {...props} key="Hi" />, because we aren't currently able to tell if
937
- // key is explicitly declared to be undefined or not.
938
-
939
- if (maybeKey !== undefined) {
940
- {
941
- checkKeyStringCoercion(maybeKey);
942
- }
943
-
944
- key = '' + maybeKey;
945
- }
946
-
947
- if (hasValidKey(config)) {
948
- {
949
- checkKeyStringCoercion(config.key);
950
- }
951
-
952
- key = '' + config.key;
953
- }
954
-
955
- if (hasValidRef(config)) {
956
- ref = config.ref;
957
- warnIfStringRefCannotBeAutoConverted(config, self);
958
- } // Remaining properties are added to a new props object
959
-
960
-
961
- for (propName in config) {
962
- if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) {
963
- props[propName] = config[propName];
964
- }
965
- } // Resolve default props
966
-
967
-
968
- if (type && type.defaultProps) {
969
- var defaultProps = type.defaultProps;
970
-
971
- for (propName in defaultProps) {
972
- if (props[propName] === undefined) {
973
- props[propName] = defaultProps[propName];
974
- }
975
- }
976
- }
977
-
978
- if (key || ref) {
979
- var displayName = typeof type === 'function' ? type.displayName || type.name || 'Unknown' : type;
980
-
981
- if (key) {
982
- defineKeyPropWarningGetter(props, displayName);
983
- }
984
-
985
- if (ref) {
986
- defineRefPropWarningGetter(props, displayName);
987
- }
988
- }
989
-
990
- return ReactElement(type, key, ref, self, source, ReactCurrentOwner.current, props);
991
- }
992
- }
993
-
994
- var ReactCurrentOwner$1 = ReactSharedInternals.ReactCurrentOwner;
995
- var ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame;
996
-
997
- function setCurrentlyValidatingElement$1(element) {
998
- {
999
- if (element) {
1000
- var owner = element._owner;
1001
- var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null);
1002
- ReactDebugCurrentFrame$1.setExtraStackFrame(stack);
1003
- } else {
1004
- ReactDebugCurrentFrame$1.setExtraStackFrame(null);
1005
- }
1006
- }
1007
- }
1008
-
1009
- var propTypesMisspellWarningShown;
1010
-
1011
- {
1012
- propTypesMisspellWarningShown = false;
1013
- }
1014
- /**
1015
- * Verifies the object is a ReactElement.
1016
- * See https://reactjs.org/docs/react-api.html#isvalidelement
1017
- * @param {?object} object
1018
- * @return {boolean} True if `object` is a ReactElement.
1019
- * @final
1020
- */
1021
-
1022
-
1023
- function isValidElement(object) {
1024
- {
1025
- return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE;
1026
- }
1027
- }
1028
-
1029
- function getDeclarationErrorAddendum() {
1030
- {
1031
- if (ReactCurrentOwner$1.current) {
1032
- var name = getComponentNameFromType(ReactCurrentOwner$1.current.type);
1033
-
1034
- if (name) {
1035
- return '\n\nCheck the render method of `' + name + '`.';
1036
- }
1037
- }
1038
-
1039
- return '';
1040
- }
1041
- }
1042
-
1043
- function getSourceInfoErrorAddendum(source) {
1044
- {
1045
- if (source !== undefined) {
1046
- var fileName = source.fileName.replace(/^.*[\\\/]/, '');
1047
- var lineNumber = source.lineNumber;
1048
- return '\n\nCheck your code at ' + fileName + ':' + lineNumber + '.';
1049
- }
1050
-
1051
- return '';
1052
- }
1053
- }
1054
- /**
1055
- * Warn if there's no key explicitly set on dynamic arrays of children or
1056
- * object keys are not valid. This allows us to keep track of children between
1057
- * updates.
1058
- */
1059
-
1060
-
1061
- var ownerHasKeyUseWarning = {};
1062
-
1063
- function getCurrentComponentErrorInfo(parentType) {
1064
- {
1065
- var info = getDeclarationErrorAddendum();
1066
-
1067
- if (!info) {
1068
- var parentName = typeof parentType === 'string' ? parentType : parentType.displayName || parentType.name;
1069
-
1070
- if (parentName) {
1071
- info = "\n\nCheck the top-level render call using <" + parentName + ">.";
1072
- }
1073
- }
1074
-
1075
- return info;
1076
- }
1077
- }
1078
- /**
1079
- * Warn if the element doesn't have an explicit key assigned to it.
1080
- * This element is in an array. The array could grow and shrink or be
1081
- * reordered. All children that haven't already been validated are required to
1082
- * have a "key" property assigned to it. Error statuses are cached so a warning
1083
- * will only be shown once.
1084
- *
1085
- * @internal
1086
- * @param {ReactElement} element Element that requires a key.
1087
- * @param {*} parentType element's parent's type.
1088
- */
1089
-
1090
-
1091
- function validateExplicitKey(element, parentType) {
1092
- {
1093
- if (!element._store || element._store.validated || element.key != null) {
1094
- return;
1095
- }
1096
-
1097
- element._store.validated = true;
1098
- var currentComponentErrorInfo = getCurrentComponentErrorInfo(parentType);
1099
-
1100
- if (ownerHasKeyUseWarning[currentComponentErrorInfo]) {
1101
- return;
1102
- }
1103
-
1104
- ownerHasKeyUseWarning[currentComponentErrorInfo] = true; // Usually the current owner is the offender, but if it accepts children as a
1105
- // property, it may be the creator of the child that's responsible for
1106
- // assigning it a key.
1107
-
1108
- var childOwner = '';
1109
-
1110
- if (element && element._owner && element._owner !== ReactCurrentOwner$1.current) {
1111
- // Give the component that originally created this child.
1112
- childOwner = " It was passed a child from " + getComponentNameFromType(element._owner.type) + ".";
1113
- }
1114
-
1115
- setCurrentlyValidatingElement$1(element);
1116
-
1117
- 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);
1118
-
1119
- setCurrentlyValidatingElement$1(null);
1120
- }
1121
- }
1122
- /**
1123
- * Ensure that every element either is passed in a static location, in an
1124
- * array with an explicit keys property defined, or in an object literal
1125
- * with valid key property.
1126
- *
1127
- * @internal
1128
- * @param {ReactNode} node Statically passed child of any type.
1129
- * @param {*} parentType node's parent's type.
1130
- */
1131
-
1132
-
1133
- function validateChildKeys(node, parentType) {
1134
- {
1135
- if (typeof node !== 'object') {
1136
- return;
1137
- }
1138
-
1139
- if (isArray(node)) {
1140
- for (var i = 0; i < node.length; i++) {
1141
- var child = node[i];
1142
-
1143
- if (isValidElement(child)) {
1144
- validateExplicitKey(child, parentType);
1145
- }
1146
- }
1147
- } else if (isValidElement(node)) {
1148
- // This element was passed in a valid location.
1149
- if (node._store) {
1150
- node._store.validated = true;
1151
- }
1152
- } else if (node) {
1153
- var iteratorFn = getIteratorFn(node);
1154
-
1155
- if (typeof iteratorFn === 'function') {
1156
- // Entry iterators used to provide implicit keys,
1157
- // but now we print a separate warning for them later.
1158
- if (iteratorFn !== node.entries) {
1159
- var iterator = iteratorFn.call(node);
1160
- var step;
1161
-
1162
- while (!(step = iterator.next()).done) {
1163
- if (isValidElement(step.value)) {
1164
- validateExplicitKey(step.value, parentType);
1165
- }
1166
- }
1167
- }
1168
- }
1169
- }
1170
- }
1171
- }
1172
- /**
1173
- * Given an element, validate that its props follow the propTypes definition,
1174
- * provided by the type.
1175
- *
1176
- * @param {ReactElement} element
1177
- */
1178
-
1179
-
1180
- function validatePropTypes(element) {
1181
- {
1182
- var type = element.type;
1183
-
1184
- if (type === null || type === undefined || typeof type === 'string') {
1185
- return;
1186
- }
1187
-
1188
- var propTypes;
1189
-
1190
- if (typeof type === 'function') {
1191
- propTypes = type.propTypes;
1192
- } else if (typeof type === 'object' && (type.$$typeof === REACT_FORWARD_REF_TYPE || // Note: Memo only checks outer props here.
1193
- // Inner props are checked in the reconciler.
1194
- type.$$typeof === REACT_MEMO_TYPE)) {
1195
- propTypes = type.propTypes;
1196
- } else {
1197
- return;
1198
- }
1199
-
1200
- if (propTypes) {
1201
- // Intentionally inside to avoid triggering lazy initializers:
1202
- var name = getComponentNameFromType(type);
1203
- checkPropTypes(propTypes, element.props, 'prop', name, element);
1204
- } else if (type.PropTypes !== undefined && !propTypesMisspellWarningShown) {
1205
- propTypesMisspellWarningShown = true; // Intentionally inside to avoid triggering lazy initializers:
1206
-
1207
- var _name = getComponentNameFromType(type);
1208
-
1209
- error('Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?', _name || 'Unknown');
1210
- }
1211
-
1212
- if (typeof type.getDefaultProps === 'function' && !type.getDefaultProps.isReactClassApproved) {
1213
- error('getDefaultProps is only used on classic React.createClass ' + 'definitions. Use a static property named `defaultProps` instead.');
1214
- }
1215
- }
1216
- }
1217
- /**
1218
- * Given a fragment, validate that it can only be provided with fragment props
1219
- * @param {ReactElement} fragment
1220
- */
1221
-
1222
-
1223
- function validateFragmentProps(fragment) {
1224
- {
1225
- var keys = Object.keys(fragment.props);
1226
-
1227
- for (var i = 0; i < keys.length; i++) {
1228
- var key = keys[i];
1229
-
1230
- if (key !== 'children' && key !== 'key') {
1231
- setCurrentlyValidatingElement$1(fragment);
1232
-
1233
- error('Invalid prop `%s` supplied to `React.Fragment`. ' + 'React.Fragment can only have `key` and `children` props.', key);
1234
-
1235
- setCurrentlyValidatingElement$1(null);
1236
- break;
1237
- }
1238
- }
1239
-
1240
- if (fragment.ref !== null) {
1241
- setCurrentlyValidatingElement$1(fragment);
1242
-
1243
- error('Invalid attribute `ref` supplied to `React.Fragment`.');
1244
-
1245
- setCurrentlyValidatingElement$1(null);
1246
- }
1247
- }
1248
- }
1249
-
1250
- var didWarnAboutKeySpread = {};
1251
- function jsxWithValidation(type, props, key, isStaticChildren, source, self) {
1252
- {
1253
- var validType = isValidElementType(type); // We warn in this case but don't throw. We expect the element creation to
1254
- // succeed and there will likely be errors in render.
1255
-
1256
- if (!validType) {
1257
- var info = '';
1258
-
1259
- if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) {
1260
- 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.";
1261
- }
1262
-
1263
- var sourceInfo = getSourceInfoErrorAddendum(source);
1264
-
1265
- if (sourceInfo) {
1266
- info += sourceInfo;
1267
- } else {
1268
- info += getDeclarationErrorAddendum();
1269
- }
1270
-
1271
- var typeString;
1272
-
1273
- if (type === null) {
1274
- typeString = 'null';
1275
- } else if (isArray(type)) {
1276
- typeString = 'array';
1277
- } else if (type !== undefined && type.$$typeof === REACT_ELEMENT_TYPE) {
1278
- typeString = "<" + (getComponentNameFromType(type.type) || 'Unknown') + " />";
1279
- info = ' Did you accidentally export a JSX literal instead of a component?';
1280
- } else {
1281
- typeString = typeof type;
1282
- }
1283
-
1284
- 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);
1285
- }
1286
-
1287
- var element = jsxDEV(type, props, key, source, self); // The result can be nullish if a mock or a custom function is used.
1288
- // TODO: Drop this when these are no longer allowed as the type argument.
1289
-
1290
- if (element == null) {
1291
- return element;
1292
- } // Skip key warning if the type isn't valid since our key validation logic
1293
- // doesn't expect a non-string/function type and can throw confusing errors.
1294
- // We don't want exception behavior to differ between dev and prod.
1295
- // (Rendering will throw with a helpful message and as soon as the type is
1296
- // fixed, the key warnings will appear.)
1297
-
1298
-
1299
- if (validType) {
1300
- var children = props.children;
1301
-
1302
- if (children !== undefined) {
1303
- if (isStaticChildren) {
1304
- if (isArray(children)) {
1305
- for (var i = 0; i < children.length; i++) {
1306
- validateChildKeys(children[i], type);
1307
- }
1308
-
1309
- if (Object.freeze) {
1310
- Object.freeze(children);
1311
- }
1312
- } else {
1313
- 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.');
1314
- }
1315
- } else {
1316
- validateChildKeys(children, type);
1317
- }
1318
- }
1319
- }
1320
-
1321
- {
1322
- if (hasOwnProperty.call(props, 'key')) {
1323
- var componentName = getComponentNameFromType(type);
1324
- var keys = Object.keys(props).filter(function (k) {
1325
- return k !== 'key';
1326
- });
1327
- var beforeExample = keys.length > 0 ? '{key: someKey, ' + keys.join(': ..., ') + ': ...}' : '{key: someKey}';
1328
-
1329
- if (!didWarnAboutKeySpread[componentName + beforeExample]) {
1330
- var afterExample = keys.length > 0 ? '{' + keys.join(': ..., ') + ': ...}' : '{}';
1331
-
1332
- 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);
1333
-
1334
- didWarnAboutKeySpread[componentName + beforeExample] = true;
1335
- }
1336
- }
1337
- }
1338
-
1339
- if (type === REACT_FRAGMENT_TYPE) {
1340
- validateFragmentProps(element);
1341
- } else {
1342
- validatePropTypes(element);
1343
- }
1344
-
1345
- return element;
1346
- }
1347
- } // These two functions exist to still get child warnings in dev
1348
- // even with the prod transform. This means that jsxDEV is purely
1349
- // opt-in behavior for better messages but that we won't stop
1350
- // giving you warnings if you use production apis.
1351
-
1352
- function jsxWithValidationStatic(type, props, key) {
1353
- {
1354
- return jsxWithValidation(type, props, key, true);
1355
- }
1356
- }
1357
- function jsxWithValidationDynamic(type, props, key) {
1358
- {
1359
- return jsxWithValidation(type, props, key, false);
1360
- }
1361
- }
1362
-
1363
- var jsx = jsxWithValidationDynamic ; // we may want to special case jsxs internally to take advantage of static children.
1364
- // for now we can ship identical prod functions
1365
-
1366
- var jsxs = jsxWithValidationStatic ;
1367
-
1368
- reactJsxRuntime_development.Fragment = REACT_FRAGMENT_TYPE;
1369
- reactJsxRuntime_development.jsx = jsx;
1370
- reactJsxRuntime_development.jsxs = jsxs;
1371
- })();
1372
- }
1373
- return reactJsxRuntime_development;
1374
- }
1375
-
1376
- if (process.env.NODE_ENV === 'production') {
1377
- jsxRuntime.exports = requireReactJsxRuntime_production_min();
1378
- } else {
1379
- jsxRuntime.exports = requireReactJsxRuntime_development();
1380
- }
1381
-
1382
- var jsxRuntimeExports = jsxRuntime.exports;
1383
-
1384
- var dist = {};
1385
-
1386
- var useWebsocket = {};
1387
-
1388
- var constants = {};
1389
-
1390
- (function (exports) {
1391
- Object.defineProperty(exports, "__esModule", { value: true });
1392
- 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;
1393
- var MILLISECONDS = 1;
1394
- var SECONDS = 1000 * MILLISECONDS;
1395
- exports.DEFAULT_OPTIONS = {};
1396
- exports.EMPTY_EVENT_HANDLERS = {};
1397
- exports.DEFAULT_EVENT_SOURCE_OPTIONS = {
1398
- withCredentials: false,
1399
- events: exports.EMPTY_EVENT_HANDLERS,
1400
- };
1401
- exports.SOCKET_IO_PING_INTERVAL = 25 * SECONDS;
1402
- exports.SOCKET_IO_PATH = '/socket.io/?EIO=3&transport=websocket';
1403
- exports.SOCKET_IO_PING_CODE = '2';
1404
- exports.DEFAULT_RECONNECT_LIMIT = 20;
1405
- exports.DEFAULT_RECONNECT_INTERVAL_MS = 5000;
1406
- exports.UNPARSABLE_JSON_OBJECT = {};
1407
- exports.DEFAULT_HEARTBEAT = {
1408
- message: 'ping',
1409
- timeout: 60000,
1410
- interval: 25000,
1411
- };
1412
- var ReadyState;
1413
- (function (ReadyState) {
1414
- ReadyState[ReadyState["UNINSTANTIATED"] = -1] = "UNINSTANTIATED";
1415
- ReadyState[ReadyState["CONNECTING"] = 0] = "CONNECTING";
1416
- ReadyState[ReadyState["OPEN"] = 1] = "OPEN";
1417
- ReadyState[ReadyState["CLOSING"] = 2] = "CLOSING";
1418
- ReadyState[ReadyState["CLOSED"] = 3] = "CLOSED";
1419
- })(ReadyState || (exports.ReadyState = ReadyState = {}));
1420
- var eventSourceSupported = function () {
1421
- try {
1422
- return 'EventSource' in globalThis;
1423
- }
1424
- catch (e) {
1425
- return false;
1426
- }
1427
- };
1428
- exports.isReactNative = typeof navigator !== 'undefined' && navigator.product === 'ReactNative';
1429
- exports.isEventSourceSupported = !exports.isReactNative && eventSourceSupported();
1430
-
1431
- } (constants));
1432
-
1433
- var createOrJoin = {};
1434
-
1435
- var globals = {};
1436
-
1437
- (function (exports) {
1438
- Object.defineProperty(exports, "__esModule", { value: true });
1439
- exports.resetWebSockets = exports.sharedWebSockets = void 0;
1440
- exports.sharedWebSockets = {};
1441
- var resetWebSockets = function (url) {
1442
- if (url && exports.sharedWebSockets.hasOwnProperty(url)) {
1443
- delete exports.sharedWebSockets[url];
1444
- }
1445
- else {
1446
- for (var url_1 in exports.sharedWebSockets) {
1447
- if (exports.sharedWebSockets.hasOwnProperty(url_1)) {
1448
- delete exports.sharedWebSockets[url_1];
1449
- }
1450
- }
1451
- }
1452
- };
1453
- exports.resetWebSockets = resetWebSockets;
1454
-
1455
- } (globals));
1456
-
1457
- var attachListener = {};
1458
-
1459
- var socketIo = {};
1460
-
1461
- Object.defineProperty(socketIo, "__esModule", { value: true });
1462
- socketIo.setUpSocketIOPing = socketIo.appendQueryParams = socketIo.parseSocketIOUrl = void 0;
1463
- var constants_1$7 = constants;
1464
- var parseSocketIOUrl = function (url) {
1465
- if (url) {
1466
- var isSecure = /^https|wss/.test(url);
1467
- var strippedProtocol = url.replace(/^(https?|wss?)(:\/\/)?/, '');
1468
- var removedFinalBackSlack = strippedProtocol.replace(/\/$/, '');
1469
- var protocol = isSecure ? 'wss' : 'ws';
1470
- return "".concat(protocol, "://").concat(removedFinalBackSlack).concat(constants_1$7.SOCKET_IO_PATH);
1471
- }
1472
- else if (url === '') {
1473
- var isSecure = /^https/.test(window.location.protocol);
1474
- var protocol = isSecure ? 'wss' : 'ws';
1475
- var port = window.location.port ? ":".concat(window.location.port) : '';
1476
- return "".concat(protocol, "://").concat(window.location.hostname).concat(port).concat(constants_1$7.SOCKET_IO_PATH);
1477
- }
1478
- return url;
1479
- };
1480
- socketIo.parseSocketIOUrl = parseSocketIOUrl;
1481
- var appendQueryParams = function (url, params) {
1482
- if (params === void 0) { params = {}; }
1483
- var hasParamsRegex = /\?([\w]+=[\w]+)/;
1484
- var alreadyHasParams = hasParamsRegex.test(url);
1485
- var stringified = "".concat(Object.entries(params).reduce(function (next, _a) {
1486
- var key = _a[0], value = _a[1];
1487
- return next + "".concat(key, "=").concat(value, "&");
1488
- }, '').slice(0, -1));
1489
- return "".concat(url).concat(alreadyHasParams ? '&' : '?').concat(stringified);
1490
- };
1491
- socketIo.appendQueryParams = appendQueryParams;
1492
- var setUpSocketIOPing = function (sendMessage, interval) {
1493
- if (interval === void 0) { interval = constants_1$7.SOCKET_IO_PING_INTERVAL; }
1494
- var ping = function () { return sendMessage(constants_1$7.SOCKET_IO_PING_CODE); };
1495
- return window.setInterval(ping, interval);
1496
- };
1497
- socketIo.setUpSocketIOPing = setUpSocketIOPing;
1498
-
1499
- var heartbeat$1 = {};
1500
-
1501
- Object.defineProperty(heartbeat$1, "__esModule", { value: true });
1502
- heartbeat$1.heartbeat = heartbeat;
1503
- var constants_1$6 = constants;
1504
- function getLastMessageTime(lastMessageTime) {
1505
- if (Array.isArray(lastMessageTime)) {
1506
- return lastMessageTime.reduce(function (p, c) { return (p.current > c.current) ? p : c; }).current;
1507
- }
1508
- return lastMessageTime.current;
1509
- }
1510
- function heartbeat(ws, lastMessageTime, options) {
1511
- 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;
1512
- // how often check interval between ping messages
1513
- // minimum is 100ms
1514
- // maximum is ${interval / 10}ms
1515
- var intervalCheck = Math.max(100, interval / 10);
1516
- var lastPingSentAt = Date.now();
1517
- var heartbeatInterval = setInterval(function () {
1518
- var timeNow = Date.now();
1519
- var lastMessageReceivedAt = getLastMessageTime(lastMessageTime);
1520
- if (lastMessageReceivedAt + timeout <= timeNow) {
1521
- console.warn("Heartbeat timed out, closing connection, last message received ".concat(timeNow - lastMessageReceivedAt, "ms ago, last ping sent ").concat(timeNow - lastPingSentAt, "ms ago"));
1522
- ws.close();
1523
- }
1524
- else {
1525
- if (lastMessageReceivedAt + interval <= timeNow && lastPingSentAt + interval <= timeNow) {
1526
- try {
1527
- if (typeof message === 'function') {
1528
- ws.send(message());
1529
- }
1530
- else {
1531
- ws.send(message);
1532
- }
1533
- lastPingSentAt = timeNow;
1534
- }
1535
- catch (err) {
1536
- console.error("Heartbeat failed, closing connection", err instanceof Error ? err.message : err);
1537
- ws.close();
1538
- }
1539
- }
1540
- }
1541
- }, intervalCheck);
1542
- ws.addEventListener("close", function () {
1543
- clearInterval(heartbeatInterval);
1544
- });
1545
- return function () { };
1546
- }
1547
-
1548
- var util = {};
1549
-
1550
- var manageSubscribers = {};
1551
-
1552
- (function (exports) {
1553
- Object.defineProperty(exports, "__esModule", { value: true });
1554
- exports.resetSubscribers = exports.removeSubscriber = exports.addSubscriber = exports.hasSubscribers = exports.getSubscribers = void 0;
1555
- var subscribers = {};
1556
- var EMPTY_LIST = [];
1557
- var getSubscribers = function (url) {
1558
- if ((0, exports.hasSubscribers)(url)) {
1559
- return Array.from(subscribers[url]);
1560
- }
1561
- return EMPTY_LIST;
1562
- };
1563
- exports.getSubscribers = getSubscribers;
1564
- var hasSubscribers = function (url) {
1565
- var _a;
1566
- return ((_a = subscribers[url]) === null || _a === void 0 ? void 0 : _a.size) > 0;
1567
- };
1568
- exports.hasSubscribers = hasSubscribers;
1569
- var addSubscriber = function (url, subscriber) {
1570
- subscribers[url] = subscribers[url] || new Set();
1571
- subscribers[url].add(subscriber);
1572
- };
1573
- exports.addSubscriber = addSubscriber;
1574
- var removeSubscriber = function (url, subscriber) {
1575
- subscribers[url].delete(subscriber);
1576
- };
1577
- exports.removeSubscriber = removeSubscriber;
1578
- var resetSubscribers = function (url) {
1579
- if (url && subscribers.hasOwnProperty(url)) {
1580
- delete subscribers[url];
1581
- }
1582
- else {
1583
- for (var url_1 in subscribers) {
1584
- if (subscribers.hasOwnProperty(url_1)) {
1585
- delete subscribers[url_1];
1586
- }
1587
- }
1588
- }
1589
- };
1590
- exports.resetSubscribers = resetSubscribers;
1591
-
1592
- } (manageSubscribers));
1593
-
1594
- Object.defineProperty(util, "__esModule", { value: true });
1595
- util.assertIsWebSocket = assertIsWebSocket;
1596
- util.resetGlobalState = resetGlobalState;
1597
- var globals_1$2 = globals;
1598
- var manage_subscribers_1$2 = manageSubscribers;
1599
- function assertIsWebSocket(webSocketInstance, skip) {
1600
- if (!skip && webSocketInstance instanceof WebSocket === false)
1601
- throw new Error('');
1602
- }
1603
- function resetGlobalState(url) {
1604
- (0, manage_subscribers_1$2.resetSubscribers)(url);
1605
- (0, globals_1$2.resetWebSockets)(url);
1606
- }
1607
-
1608
- var __assign$4 = (commonjsGlobal && commonjsGlobal.__assign) || function () {
1609
- __assign$4 = Object.assign || function(t) {
1610
- for (var s, i = 1, n = arguments.length; i < n; i++) {
1611
- s = arguments[i];
1612
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
1613
- t[p] = s[p];
1614
- }
1615
- return t;
1616
- };
1617
- return __assign$4.apply(this, arguments);
1618
- };
1619
- Object.defineProperty(attachListener, "__esModule", { value: true });
1620
- attachListener.attachListeners = void 0;
1621
- var socket_io_1$1 = socketIo;
1622
- var heartbeat_1$1 = heartbeat$1;
1623
- var constants_1$5 = constants;
1624
- var util_1$1 = util;
1625
- var bindMessageHandler$1 = function (webSocketInstance, optionsRef, setLastMessage, lastMessageTime) {
1626
- webSocketInstance.onmessage = function (message) {
1627
- var _a;
1628
- optionsRef.current.onMessage && optionsRef.current.onMessage(message);
1629
- if (typeof (lastMessageTime === null || lastMessageTime === void 0 ? void 0 : lastMessageTime.current) === 'number') {
1630
- lastMessageTime.current = Date.now();
1631
- }
1632
- if (typeof optionsRef.current.filter === 'function' && optionsRef.current.filter(message) !== true) {
1633
- return;
1634
- }
1635
- if (optionsRef.current.heartbeat &&
1636
- typeof optionsRef.current.heartbeat !== "boolean" &&
1637
- ((_a = optionsRef.current.heartbeat) === null || _a === void 0 ? void 0 : _a.returnMessage) === message.data) {
1638
- return;
1639
- }
1640
- setLastMessage(message);
1641
- };
1642
- };
1643
- var bindOpenHandler$1 = function (webSocketInstance, optionsRef, setReadyState, reconnectCount, lastMessageTime) {
1644
- webSocketInstance.onopen = function (event) {
1645
- optionsRef.current.onOpen && optionsRef.current.onOpen(event);
1646
- reconnectCount.current = 0;
1647
- setReadyState(constants_1$5.ReadyState.OPEN);
1648
- //start heart beat here
1649
- if (optionsRef.current.heartbeat && webSocketInstance instanceof WebSocket) {
1650
- var heartbeatOptions = typeof optionsRef.current.heartbeat === "boolean"
1651
- ? undefined
1652
- : optionsRef.current.heartbeat;
1653
- lastMessageTime.current = Date.now();
1654
- (0, heartbeat_1$1.heartbeat)(webSocketInstance, lastMessageTime, heartbeatOptions);
1655
- }
1656
- };
1657
- };
1658
- var bindCloseHandler$1 = function (webSocketInstance, optionsRef, setReadyState, reconnect, reconnectCount) {
1659
- if (constants_1$5.isEventSourceSupported && webSocketInstance instanceof EventSource) {
1660
- return function () { };
1661
- }
1662
- (0, util_1$1.assertIsWebSocket)(webSocketInstance, optionsRef.current.skipAssert);
1663
- var reconnectTimeout;
1664
- webSocketInstance.onclose = function (event) {
1665
- var _a;
1666
- optionsRef.current.onClose && optionsRef.current.onClose(event);
1667
- setReadyState(constants_1$5.ReadyState.CLOSED);
1668
- if (optionsRef.current.shouldReconnect && optionsRef.current.shouldReconnect(event)) {
1669
- var reconnectAttempts = (_a = optionsRef.current.reconnectAttempts) !== null && _a !== void 0 ? _a : constants_1$5.DEFAULT_RECONNECT_LIMIT;
1670
- if (reconnectCount.current < reconnectAttempts) {
1671
- var nextReconnectInterval = typeof optionsRef.current.reconnectInterval === 'function' ?
1672
- optionsRef.current.reconnectInterval(reconnectCount.current) :
1673
- optionsRef.current.reconnectInterval;
1674
- reconnectTimeout = window.setTimeout(function () {
1675
- reconnectCount.current++;
1676
- reconnect();
1677
- }, nextReconnectInterval !== null && nextReconnectInterval !== void 0 ? nextReconnectInterval : constants_1$5.DEFAULT_RECONNECT_INTERVAL_MS);
1678
- }
1679
- else {
1680
- optionsRef.current.onReconnectStop && optionsRef.current.onReconnectStop(reconnectAttempts);
1681
- console.warn("Max reconnect attempts of ".concat(reconnectAttempts, " exceeded"));
1682
- }
1683
- }
1684
- };
1685
- return function () { return reconnectTimeout && window.clearTimeout(reconnectTimeout); };
1686
- };
1687
- var bindErrorHandler$1 = function (webSocketInstance, optionsRef, setReadyState, reconnect, reconnectCount) {
1688
- var reconnectTimeout;
1689
- webSocketInstance.onerror = function (error) {
1690
- var _a;
1691
- optionsRef.current.onError && optionsRef.current.onError(error);
1692
- if (constants_1$5.isEventSourceSupported && webSocketInstance instanceof EventSource) {
1693
- optionsRef.current.onClose && optionsRef.current.onClose(__assign$4(__assign$4({}, error), { code: 1006, reason: "An error occurred with the EventSource: ".concat(error), wasClean: false }));
1694
- setReadyState(constants_1$5.ReadyState.CLOSED);
1695
- webSocketInstance.close();
1696
- }
1697
- if (optionsRef.current.retryOnError) {
1698
- if (reconnectCount.current < ((_a = optionsRef.current.reconnectAttempts) !== null && _a !== void 0 ? _a : constants_1$5.DEFAULT_RECONNECT_LIMIT)) {
1699
- var nextReconnectInterval = typeof optionsRef.current.reconnectInterval === 'function' ?
1700
- optionsRef.current.reconnectInterval(reconnectCount.current) :
1701
- optionsRef.current.reconnectInterval;
1702
- reconnectTimeout = window.setTimeout(function () {
1703
- reconnectCount.current++;
1704
- reconnect();
1705
- }, nextReconnectInterval !== null && nextReconnectInterval !== void 0 ? nextReconnectInterval : constants_1$5.DEFAULT_RECONNECT_INTERVAL_MS);
1706
- }
1707
- else {
1708
- optionsRef.current.onReconnectStop && optionsRef.current.onReconnectStop(optionsRef.current.reconnectAttempts);
1709
- console.warn("Max reconnect attempts of ".concat(optionsRef.current.reconnectAttempts, " exceeded"));
1710
- }
1711
- }
1712
- };
1713
- return function () { return reconnectTimeout && window.clearTimeout(reconnectTimeout); };
1714
- };
1715
- var attachListeners = function (webSocketInstance, setters, optionsRef, reconnect, reconnectCount, lastMessageTime, sendMessage) {
1716
- var setLastMessage = setters.setLastMessage, setReadyState = setters.setReadyState;
1717
- var interval;
1718
- var cancelReconnectOnClose;
1719
- var cancelReconnectOnError;
1720
- if (optionsRef.current.fromSocketIO) {
1721
- interval = (0, socket_io_1$1.setUpSocketIOPing)(sendMessage);
1722
- }
1723
- bindMessageHandler$1(webSocketInstance, optionsRef, setLastMessage, lastMessageTime);
1724
- bindOpenHandler$1(webSocketInstance, optionsRef, setReadyState, reconnectCount, lastMessageTime);
1725
- cancelReconnectOnClose = bindCloseHandler$1(webSocketInstance, optionsRef, setReadyState, reconnect, reconnectCount);
1726
- cancelReconnectOnError = bindErrorHandler$1(webSocketInstance, optionsRef, setReadyState, reconnect, reconnectCount);
1727
- return function () {
1728
- setReadyState(constants_1$5.ReadyState.CLOSING);
1729
- cancelReconnectOnClose();
1730
- cancelReconnectOnError();
1731
- webSocketInstance.close();
1732
- if (interval)
1733
- clearInterval(interval);
1734
- };
1735
- };
1736
- attachListener.attachListeners = attachListeners;
1737
-
1738
- var attachSharedListeners$1 = {};
1739
-
1740
- var __assign$3 = (commonjsGlobal && commonjsGlobal.__assign) || function () {
1741
- __assign$3 = Object.assign || function(t) {
1742
- for (var s, i = 1, n = arguments.length; i < n; i++) {
1743
- s = arguments[i];
1744
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
1745
- t[p] = s[p];
1746
- }
1747
- return t;
1748
- };
1749
- return __assign$3.apply(this, arguments);
1750
- };
1751
- Object.defineProperty(attachSharedListeners$1, "__esModule", { value: true });
1752
- attachSharedListeners$1.attachSharedListeners = void 0;
1753
- var globals_1$1 = globals;
1754
- var constants_1$4 = constants;
1755
- var manage_subscribers_1$1 = manageSubscribers;
1756
- var socket_io_1 = socketIo;
1757
- var heartbeat_1 = heartbeat$1;
1758
- var bindMessageHandler = function (webSocketInstance, url, heartbeatOptions) {
1759
- webSocketInstance.onmessage = function (message) {
1760
- (0, manage_subscribers_1$1.getSubscribers)(url).forEach(function (subscriber) {
1761
- var _a;
1762
- if (subscriber.optionsRef.current.onMessage) {
1763
- subscriber.optionsRef.current.onMessage(message);
1764
- }
1765
- if (typeof ((_a = subscriber === null || subscriber === void 0 ? void 0 : subscriber.lastMessageTime) === null || _a === void 0 ? void 0 : _a.current) === 'number') {
1766
- subscriber.lastMessageTime.current = Date.now();
1767
- }
1768
- if (typeof subscriber.optionsRef.current.filter === 'function' &&
1769
- subscriber.optionsRef.current.filter(message) !== true) {
1770
- return;
1771
- }
1772
- if (heartbeatOptions &&
1773
- typeof heartbeatOptions !== "boolean" &&
1774
- (heartbeatOptions === null || heartbeatOptions === void 0 ? void 0 : heartbeatOptions.returnMessage) === message.data)
1775
- return;
1776
- subscriber.setLastMessage(message);
1777
- });
1778
- };
1779
- };
1780
- var bindOpenHandler = function (webSocketInstance, url, heartbeatOptions) {
1781
- webSocketInstance.onopen = function (event) {
1782
- var subscribers = (0, manage_subscribers_1$1.getSubscribers)(url);
1783
- subscribers.forEach(function (subscriber) {
1784
- subscriber.reconnectCount.current = 0;
1785
- if (subscriber.optionsRef.current.onOpen) {
1786
- subscriber.optionsRef.current.onOpen(event);
1787
- }
1788
- subscriber.setReadyState(constants_1$4.ReadyState.OPEN);
1789
- if (heartbeatOptions && webSocketInstance instanceof WebSocket) {
1790
- subscriber.lastMessageTime.current = Date.now();
1791
- }
1792
- });
1793
- if (heartbeatOptions && webSocketInstance instanceof WebSocket) {
1794
- (0, heartbeat_1.heartbeat)(webSocketInstance, subscribers.map(function (subscriber) { return subscriber.lastMessageTime; }), typeof heartbeatOptions === 'boolean' ? undefined : heartbeatOptions);
1795
- }
1796
- };
1797
- };
1798
- var bindCloseHandler = function (webSocketInstance, url) {
1799
- if (webSocketInstance instanceof WebSocket) {
1800
- webSocketInstance.onclose = function (event) {
1801
- (0, manage_subscribers_1$1.getSubscribers)(url).forEach(function (subscriber) {
1802
- if (subscriber.optionsRef.current.onClose) {
1803
- subscriber.optionsRef.current.onClose(event);
1804
- }
1805
- subscriber.setReadyState(constants_1$4.ReadyState.CLOSED);
1806
- });
1807
- delete globals_1$1.sharedWebSockets[url];
1808
- (0, manage_subscribers_1$1.getSubscribers)(url).forEach(function (subscriber) {
1809
- var _a;
1810
- if (subscriber.optionsRef.current.shouldReconnect &&
1811
- subscriber.optionsRef.current.shouldReconnect(event)) {
1812
- var reconnectAttempts = (_a = subscriber.optionsRef.current.reconnectAttempts) !== null && _a !== void 0 ? _a : constants_1$4.DEFAULT_RECONNECT_LIMIT;
1813
- if (subscriber.reconnectCount.current < reconnectAttempts) {
1814
- var nextReconnectInterval = typeof subscriber.optionsRef.current.reconnectInterval === 'function' ?
1815
- subscriber.optionsRef.current.reconnectInterval(subscriber.reconnectCount.current) :
1816
- subscriber.optionsRef.current.reconnectInterval;
1817
- setTimeout(function () {
1818
- subscriber.reconnectCount.current++;
1819
- subscriber.reconnect.current();
1820
- }, nextReconnectInterval !== null && nextReconnectInterval !== void 0 ? nextReconnectInterval : constants_1$4.DEFAULT_RECONNECT_INTERVAL_MS);
1821
- }
1822
- else {
1823
- subscriber.optionsRef.current.onReconnectStop && subscriber.optionsRef.current.onReconnectStop(subscriber.optionsRef.current.reconnectAttempts);
1824
- console.warn("Max reconnect attempts of ".concat(reconnectAttempts, " exceeded"));
1825
- }
1826
- }
1827
- });
1828
- };
1829
- }
1830
- };
1831
- var bindErrorHandler = function (webSocketInstance, url) {
1832
- webSocketInstance.onerror = function (error) {
1833
- (0, manage_subscribers_1$1.getSubscribers)(url).forEach(function (subscriber) {
1834
- if (subscriber.optionsRef.current.onError) {
1835
- subscriber.optionsRef.current.onError(error);
1836
- }
1837
- if (constants_1$4.isEventSourceSupported && webSocketInstance instanceof EventSource) {
1838
- 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 }));
1839
- subscriber.setReadyState(constants_1$4.ReadyState.CLOSED);
1840
- }
1841
- });
1842
- if (constants_1$4.isEventSourceSupported && webSocketInstance instanceof EventSource) {
1843
- webSocketInstance.close();
1844
- }
1845
- };
1846
- };
1847
- var attachSharedListeners = function (webSocketInstance, url, optionsRef, sendMessage) {
1848
- var interval;
1849
- if (optionsRef.current.fromSocketIO) {
1850
- interval = (0, socket_io_1.setUpSocketIOPing)(sendMessage);
1851
- }
1852
- bindMessageHandler(webSocketInstance, url, optionsRef.current.heartbeat);
1853
- bindCloseHandler(webSocketInstance, url);
1854
- bindOpenHandler(webSocketInstance, url, optionsRef.current.heartbeat);
1855
- bindErrorHandler(webSocketInstance, url);
1856
- return function () {
1857
- if (interval)
1858
- clearInterval(interval);
1859
- };
1860
- };
1861
- attachSharedListeners$1.attachSharedListeners = attachSharedListeners;
1862
-
1863
- Object.defineProperty(createOrJoin, "__esModule", { value: true });
1864
- createOrJoin.createOrJoinSocket = void 0;
1865
- var globals_1 = globals;
1866
- var constants_1$3 = constants;
1867
- var attach_listener_1 = attachListener;
1868
- var attach_shared_listeners_1 = attachSharedListeners$1;
1869
- var manage_subscribers_1 = manageSubscribers;
1870
- //TODO ensure that all onClose callbacks are called
1871
- var cleanSubscribers = function (url, subscriber, optionsRef, setReadyState, clearSocketIoPingInterval) {
1872
- return function () {
1873
- (0, manage_subscribers_1.removeSubscriber)(url, subscriber);
1874
- if (!(0, manage_subscribers_1.hasSubscribers)(url)) {
1875
- try {
1876
- var socketLike = globals_1.sharedWebSockets[url];
1877
- if (socketLike instanceof WebSocket) {
1878
- socketLike.onclose = function (event) {
1879
- if (optionsRef.current.onClose) {
1880
- optionsRef.current.onClose(event);
1881
- }
1882
- setReadyState(constants_1$3.ReadyState.CLOSED);
1883
- };
1884
- }
1885
- socketLike.close();
1886
- }
1887
- catch (e) {
1888
- }
1889
- if (clearSocketIoPingInterval)
1890
- clearSocketIoPingInterval();
1891
- delete globals_1.sharedWebSockets[url];
1892
- }
1893
- };
1894
- };
1895
- var createOrJoinSocket = function (webSocketRef, url, setReadyState, optionsRef, setLastMessage, startRef, reconnectCount, lastMessageTime, sendMessage) {
1896
- if (!constants_1$3.isEventSourceSupported && optionsRef.current.eventSourceOptions) {
1897
- if (constants_1$3.isReactNative) {
1898
- throw new Error('EventSource is not supported in ReactNative');
1899
- }
1900
- else {
1901
- throw new Error('EventSource is not supported');
1902
- }
1903
- }
1904
- if (optionsRef.current.share) {
1905
- var clearSocketIoPingInterval = null;
1906
- if (globals_1.sharedWebSockets[url] === undefined) {
1907
- globals_1.sharedWebSockets[url] = optionsRef.current.eventSourceOptions ?
1908
- new EventSource(url, optionsRef.current.eventSourceOptions) :
1909
- new WebSocket(url, optionsRef.current.protocols);
1910
- webSocketRef.current = globals_1.sharedWebSockets[url];
1911
- setReadyState(constants_1$3.ReadyState.CONNECTING);
1912
- clearSocketIoPingInterval = (0, attach_shared_listeners_1.attachSharedListeners)(globals_1.sharedWebSockets[url], url, optionsRef, sendMessage);
1913
- }
1914
- else {
1915
- webSocketRef.current = globals_1.sharedWebSockets[url];
1916
- setReadyState(globals_1.sharedWebSockets[url].readyState);
1917
- }
1918
- var subscriber = {
1919
- setLastMessage: setLastMessage,
1920
- setReadyState: setReadyState,
1921
- optionsRef: optionsRef,
1922
- reconnectCount: reconnectCount,
1923
- lastMessageTime: lastMessageTime,
1924
- reconnect: startRef,
1925
- };
1926
- (0, manage_subscribers_1.addSubscriber)(url, subscriber);
1927
- return cleanSubscribers(url, subscriber, optionsRef, setReadyState, clearSocketIoPingInterval);
1928
- }
1929
- else {
1930
- webSocketRef.current = optionsRef.current.eventSourceOptions ?
1931
- new EventSource(url, optionsRef.current.eventSourceOptions) :
1932
- new WebSocket(url, optionsRef.current.protocols);
1933
- setReadyState(constants_1$3.ReadyState.CONNECTING);
1934
- if (!webSocketRef.current) {
1935
- throw new Error('WebSocket failed to be created');
1936
- }
1937
- return (0, attach_listener_1.attachListeners)(webSocketRef.current, {
1938
- setLastMessage: setLastMessage,
1939
- setReadyState: setReadyState
1940
- }, optionsRef, startRef.current, reconnectCount, lastMessageTime, sendMessage);
1941
- }
1942
- };
1943
- createOrJoin.createOrJoinSocket = createOrJoinSocket;
1944
-
1945
- var getUrl = {};
1946
-
1947
- (function (exports) {
1948
- var __awaiter = (commonjsGlobal && commonjsGlobal.__awaiter) || function (thisArg, _arguments, P, generator) {
1949
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
1950
- return new (P || (P = Promise))(function (resolve, reject) {
1951
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
1952
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
1953
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
1954
- step((generator = generator.apply(thisArg, _arguments || [])).next());
1955
- });
1956
- };
1957
- var __generator = (commonjsGlobal && commonjsGlobal.__generator) || function (thisArg, body) {
1958
- 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);
1959
- return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
1960
- function verb(n) { return function (v) { return step([n, v]); }; }
1961
- function step(op) {
1962
- if (f) throw new TypeError("Generator is already executing.");
1963
- while (g && (g = 0, op[0] && (_ = 0)), _) try {
1964
- 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;
1965
- if (y = 0, t) op = [op[0] & 2, t.value];
1966
- switch (op[0]) {
1967
- case 0: case 1: t = op; break;
1968
- case 4: _.label++; return { value: op[1], done: false };
1969
- case 5: _.label++; y = op[1]; op = [0]; continue;
1970
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
1971
- default:
1972
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
1973
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
1974
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
1975
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
1976
- if (t[2]) _.ops.pop();
1977
- _.trys.pop(); continue;
1978
- }
1979
- op = body.call(thisArg, _);
1980
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
1981
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
1982
- }
1983
- };
1984
- var __spreadArray = (commonjsGlobal && commonjsGlobal.__spreadArray) || function (to, from, pack) {
1985
- if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
1986
- if (ar || !(i in from)) {
1987
- if (!ar) ar = Array.prototype.slice.call(from, 0, i);
1988
- ar[i] = from[i];
1989
- }
1990
- }
1991
- return to.concat(ar || Array.prototype.slice.call(from));
1992
- };
1993
- Object.defineProperty(exports, "__esModule", { value: true });
1994
- exports.getUrl = void 0;
1995
- var socket_io_1 = socketIo;
1996
- var constants_1 = constants;
1997
- var waitFor = function (duration) { return new Promise(function (resolve) { return window.setTimeout(resolve, duration); }); };
1998
- var getUrl = function (url_1, optionsRef_1) {
1999
- var args_1 = [];
2000
- for (var _i = 2; _i < arguments.length; _i++) {
2001
- args_1[_i - 2] = arguments[_i];
2002
- }
2003
- return __awaiter(void 0, __spreadArray([url_1, optionsRef_1], args_1, true), void 0, function (url, optionsRef, retriedAttempts) {
2004
- var convertedUrl, reconnectLimit, nextReconnectInterval, parsedUrl, parsedWithQueryParams;
2005
- var _a, _b, _c;
2006
- if (retriedAttempts === void 0) { retriedAttempts = 0; }
2007
- return __generator(this, function (_d) {
2008
- switch (_d.label) {
2009
- case 0:
2010
- if (!(typeof url === 'function')) return [3 /*break*/, 10];
2011
- _d.label = 1;
2012
- case 1:
2013
- _d.trys.push([1, 3, , 9]);
2014
- return [4 /*yield*/, url()];
2015
- case 2:
2016
- convertedUrl = _d.sent();
2017
- return [3 /*break*/, 9];
2018
- case 3:
2019
- _d.sent();
2020
- if (!optionsRef.current.retryOnError) return [3 /*break*/, 7];
2021
- reconnectLimit = (_a = optionsRef.current.reconnectAttempts) !== null && _a !== void 0 ? _a : constants_1.DEFAULT_RECONNECT_LIMIT;
2022
- if (!(retriedAttempts < reconnectLimit)) return [3 /*break*/, 5];
2023
- nextReconnectInterval = typeof optionsRef.current.reconnectInterval === 'function' ?
2024
- optionsRef.current.reconnectInterval(retriedAttempts) :
2025
- optionsRef.current.reconnectInterval;
2026
- return [4 /*yield*/, waitFor(nextReconnectInterval !== null && nextReconnectInterval !== void 0 ? nextReconnectInterval : constants_1.DEFAULT_RECONNECT_INTERVAL_MS)];
2027
- case 4:
2028
- _d.sent();
2029
- return [2 /*return*/, (0, exports.getUrl)(url, optionsRef, retriedAttempts + 1)];
2030
- case 5:
2031
- (_c = (_b = optionsRef.current).onReconnectStop) === null || _c === void 0 ? void 0 : _c.call(_b, retriedAttempts);
2032
- return [2 /*return*/, null];
2033
- case 6: return [3 /*break*/, 8];
2034
- case 7: return [2 /*return*/, null];
2035
- case 8: return [3 /*break*/, 9];
2036
- case 9: return [3 /*break*/, 11];
2037
- case 10:
2038
- convertedUrl = url;
2039
- _d.label = 11;
2040
- case 11:
2041
- parsedUrl = optionsRef.current.fromSocketIO ?
2042
- (0, socket_io_1.parseSocketIOUrl)(convertedUrl) :
2043
- convertedUrl;
2044
- parsedWithQueryParams = optionsRef.current.queryParams ?
2045
- (0, socket_io_1.appendQueryParams)(parsedUrl, optionsRef.current.queryParams) :
2046
- parsedUrl;
2047
- return [2 /*return*/, parsedWithQueryParams];
2048
- }
2049
- });
2050
- });
2051
- };
2052
- exports.getUrl = getUrl;
2053
-
2054
- } (getUrl));
2055
-
2056
- var proxy = {};
2057
-
2058
- (function (exports) {
2059
- Object.defineProperty(exports, "__esModule", { value: true });
2060
- exports.websocketWrapper = void 0;
2061
- var websocketWrapper = function (webSocket, start) {
2062
- return new Proxy(webSocket, {
2063
- get: function (obj, key) {
2064
- var val = obj[key];
2065
- if (key === 'reconnect')
2066
- return start;
2067
- if (typeof val === 'function') {
2068
- console.error('Calling methods directly on the websocket is not supported at this moment. You must use the methods returned by useWebSocket.');
2069
- //Prevent error thrown by invoking a non-function
2070
- return function () { };
2071
- }
2072
- else {
2073
- return val;
2074
- }
2075
- },
2076
- set: function (obj, key, val) {
2077
- if (/^on/.test(key)) {
2078
- console.warn('The websocket\'s event handlers should be defined through the options object passed into useWebSocket.');
2079
- return false;
2080
- }
2081
- else {
2082
- obj[key] = val;
2083
- return true;
2084
- }
2085
- },
2086
- });
2087
- };
2088
- exports.websocketWrapper = websocketWrapper;
2089
- exports.default = exports.websocketWrapper;
2090
-
2091
- } (proxy));
2092
-
2093
- var __assign$2 = (commonjsGlobal && commonjsGlobal.__assign) || function () {
2094
- __assign$2 = Object.assign || function(t) {
2095
- for (var s, i = 1, n = arguments.length; i < n; i++) {
2096
- s = arguments[i];
2097
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
2098
- t[p] = s[p];
2099
- }
2100
- return t;
2101
- };
2102
- return __assign$2.apply(this, arguments);
2103
- };
2104
- var __awaiter = (commonjsGlobal && commonjsGlobal.__awaiter) || function (thisArg, _arguments, P, generator) {
2105
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
2106
- return new (P || (P = Promise))(function (resolve, reject) {
2107
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
2108
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
2109
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
2110
- step((generator = generator.apply(thisArg, _arguments || [])).next());
2111
- });
2112
- };
2113
- var __generator = (commonjsGlobal && commonjsGlobal.__generator) || function (thisArg, body) {
2114
- 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);
2115
- return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
2116
- function verb(n) { return function (v) { return step([n, v]); }; }
2117
- function step(op) {
2118
- if (f) throw new TypeError("Generator is already executing.");
2119
- while (g && (g = 0, op[0] && (_ = 0)), _) try {
2120
- 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;
2121
- if (y = 0, t) op = [op[0] & 2, t.value];
2122
- switch (op[0]) {
2123
- case 0: case 1: t = op; break;
2124
- case 4: _.label++; return { value: op[1], done: false };
2125
- case 5: _.label++; y = op[1]; op = [0]; continue;
2126
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
2127
- default:
2128
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
2129
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
2130
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
2131
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
2132
- if (t[2]) _.ops.pop();
2133
- _.trys.pop(); continue;
2134
- }
2135
- op = body.call(thisArg, _);
2136
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
2137
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
2138
- }
2139
- };
2140
- var __importDefault = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
2141
- return (mod && mod.__esModule) ? mod : { "default": mod };
2142
- };
2143
- Object.defineProperty(useWebsocket, "__esModule", { value: true });
2144
- useWebsocket.useWebSocket = void 0;
2145
- var react_1$2 = React;
2146
- var react_dom_1 = require$$1;
2147
- var constants_1$2 = constants;
2148
- var create_or_join_1 = createOrJoin;
2149
- var get_url_1 = getUrl;
2150
- var proxy_1 = __importDefault(proxy);
2151
- var util_1 = util;
2152
- var useWebSocket$1 = function (url, options, connect) {
2153
- if (options === void 0) { options = constants_1$2.DEFAULT_OPTIONS; }
2154
- if (connect === void 0) { connect = true; }
2155
- var _a = (0, react_1$2.useState)(null), lastMessage = _a[0], setLastMessage = _a[1];
2156
- var _b = (0, react_1$2.useState)({}), readyState = _b[0], setReadyState = _b[1];
2157
- var lastJsonMessage = (0, react_1$2.useMemo)(function () {
2158
- if (!options.disableJson && lastMessage) {
2159
- try {
2160
- return JSON.parse(lastMessage.data);
2161
- }
2162
- catch (e) {
2163
- return constants_1$2.UNPARSABLE_JSON_OBJECT;
2164
- }
2165
- }
2166
- return null;
2167
- }, [lastMessage, options.disableJson]);
2168
- var convertedUrl = (0, react_1$2.useRef)(null);
2169
- var webSocketRef = (0, react_1$2.useRef)(null);
2170
- var startRef = (0, react_1$2.useRef)(function () { return void 0; });
2171
- var reconnectCount = (0, react_1$2.useRef)(0);
2172
- var lastMessageTime = (0, react_1$2.useRef)(Date.now());
2173
- var messageQueue = (0, react_1$2.useRef)([]);
2174
- var webSocketProxy = (0, react_1$2.useRef)(null);
2175
- var optionsCache = (0, react_1$2.useRef)(options);
2176
- optionsCache.current = options;
2177
- var readyStateFromUrl = convertedUrl.current && readyState[convertedUrl.current] !== undefined ?
2178
- readyState[convertedUrl.current] :
2179
- url !== null && connect === true ?
2180
- constants_1$2.ReadyState.CONNECTING :
2181
- constants_1$2.ReadyState.UNINSTANTIATED;
2182
- var stringifiedQueryParams = options.queryParams ? JSON.stringify(options.queryParams) : null;
2183
- var sendMessage = (0, react_1$2.useCallback)(function (message, keep) {
2184
- var _a;
2185
- if (keep === void 0) { keep = true; }
2186
- if (constants_1$2.isEventSourceSupported && webSocketRef.current instanceof EventSource) {
2187
- console.warn('Unable to send a message from an eventSource');
2188
- return;
2189
- }
2190
- if (((_a = webSocketRef.current) === null || _a === void 0 ? void 0 : _a.readyState) === constants_1$2.ReadyState.OPEN) {
2191
- (0, util_1.assertIsWebSocket)(webSocketRef.current, optionsCache.current.skipAssert);
2192
- webSocketRef.current.send(message);
2193
- }
2194
- else if (keep) {
2195
- messageQueue.current.push(message);
2196
- }
2197
- }, []);
2198
- var sendJsonMessage = (0, react_1$2.useCallback)(function (message, keep) {
2199
- if (keep === void 0) { keep = true; }
2200
- sendMessage(JSON.stringify(message), keep);
2201
- }, [sendMessage]);
2202
- var getWebSocket = (0, react_1$2.useCallback)(function () {
2203
- if (optionsCache.current.share !== true || (constants_1$2.isEventSourceSupported && webSocketRef.current instanceof EventSource)) {
2204
- return webSocketRef.current;
2205
- }
2206
- if (webSocketProxy.current === null && webSocketRef.current) {
2207
- (0, util_1.assertIsWebSocket)(webSocketRef.current, optionsCache.current.skipAssert);
2208
- webSocketProxy.current = (0, proxy_1.default)(webSocketRef.current, startRef);
2209
- }
2210
- return webSocketProxy.current;
2211
- }, []);
2212
- (0, react_1$2.useEffect)(function () {
2213
- if (url !== null && connect === true) {
2214
- var removeListeners_1;
2215
- var expectClose_1 = false;
2216
- var createOrJoin_1 = true;
2217
- var start_1 = function () { return __awaiter(void 0, void 0, void 0, function () {
2218
- var _a, protectedSetLastMessage, protectedSetReadyState;
2219
- return __generator(this, function (_b) {
2220
- switch (_b.label) {
2221
- case 0:
2222
- _a = convertedUrl;
2223
- return [4 /*yield*/, (0, get_url_1.getUrl)(url, optionsCache)];
2224
- case 1:
2225
- _a.current = _b.sent();
2226
- if (convertedUrl.current === null) {
2227
- console.error('Failed to get a valid URL. WebSocket connection aborted.');
2228
- convertedUrl.current = 'ABORTED';
2229
- (0, react_dom_1.flushSync)(function () { return setReadyState(function (prev) { return (__assign$2(__assign$2({}, prev), { ABORTED: constants_1$2.ReadyState.CLOSED })); }); });
2230
- return [2 /*return*/];
2231
- }
2232
- protectedSetLastMessage = function (message) {
2233
- if (!expectClose_1) {
2234
- (0, react_dom_1.flushSync)(function () { return setLastMessage(message); });
2235
- }
2236
- };
2237
- protectedSetReadyState = function (state) {
2238
- if (!expectClose_1) {
2239
- (0, react_dom_1.flushSync)(function () { return setReadyState(function (prev) {
2240
- var _a;
2241
- return (__assign$2(__assign$2({}, prev), (convertedUrl.current && (_a = {}, _a[convertedUrl.current] = state, _a))));
2242
- }); });
2243
- }
2244
- };
2245
- if (createOrJoin_1) {
2246
- removeListeners_1 = (0, create_or_join_1.createOrJoinSocket)(webSocketRef, convertedUrl.current, protectedSetReadyState, optionsCache, protectedSetLastMessage, startRef, reconnectCount, lastMessageTime, sendMessage);
2247
- }
2248
- return [2 /*return*/];
2249
- }
2250
- });
2251
- }); };
2252
- startRef.current = function () {
2253
- if (!expectClose_1) {
2254
- if (webSocketProxy.current)
2255
- webSocketProxy.current = null;
2256
- removeListeners_1 === null || removeListeners_1 === void 0 ? void 0 : removeListeners_1();
2257
- start_1();
2258
- }
2259
- };
2260
- start_1();
2261
- return function () {
2262
- expectClose_1 = true;
2263
- createOrJoin_1 = false;
2264
- if (webSocketProxy.current)
2265
- webSocketProxy.current = null;
2266
- removeListeners_1 === null || removeListeners_1 === void 0 ? void 0 : removeListeners_1();
2267
- setLastMessage(null);
2268
- };
2269
- }
2270
- else if (url === null || connect === false) {
2271
- reconnectCount.current = 0; // reset reconnection attempts
2272
- setReadyState(function (prev) {
2273
- var _a;
2274
- return (__assign$2(__assign$2({}, prev), (convertedUrl.current && (_a = {}, _a[convertedUrl.current] = constants_1$2.ReadyState.CLOSED, _a))));
2275
- });
2276
- }
2277
- }, [url, connect, stringifiedQueryParams, sendMessage]);
2278
- (0, react_1$2.useEffect)(function () {
2279
- if (readyStateFromUrl === constants_1$2.ReadyState.OPEN) {
2280
- messageQueue.current.splice(0).forEach(function (message) {
2281
- sendMessage(message);
2282
- });
2283
- }
2284
- }, [readyStateFromUrl]);
2285
- return {
2286
- sendMessage: sendMessage,
2287
- sendJsonMessage: sendJsonMessage,
2288
- lastMessage: lastMessage,
2289
- lastJsonMessage: lastJsonMessage,
2290
- readyState: readyStateFromUrl,
2291
- getWebSocket: getWebSocket,
2292
- };
2293
- };
2294
- useWebsocket.useWebSocket = useWebSocket$1;
2295
-
2296
- var useSocketIo = {};
2297
-
2298
- var __assign$1 = (commonjsGlobal && commonjsGlobal.__assign) || function () {
2299
- __assign$1 = Object.assign || function(t) {
2300
- for (var s, i = 1, n = arguments.length; i < n; i++) {
2301
- s = arguments[i];
2302
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
2303
- t[p] = s[p];
2304
- }
2305
- return t;
2306
- };
2307
- return __assign$1.apply(this, arguments);
2308
- };
2309
- Object.defineProperty(useSocketIo, "__esModule", { value: true });
2310
- useSocketIo.useSocketIO = void 0;
2311
- var react_1$1 = React;
2312
- var use_websocket_1$1 = useWebsocket;
2313
- var constants_1$1 = constants;
2314
- var emptyEvent = {
2315
- type: 'empty',
2316
- payload: null,
2317
- };
2318
- var getSocketData = function (event) {
2319
- if (!event || !event.data) {
2320
- return emptyEvent;
2321
- }
2322
- var match = event.data.match(/\[.*]/);
2323
- if (!match) {
2324
- return emptyEvent;
2325
- }
2326
- var data = JSON.parse(match);
2327
- if (!Array.isArray(data) || !data[1]) {
2328
- return emptyEvent;
2329
- }
2330
- return {
2331
- type: data[0],
2332
- payload: data[1],
2333
- };
2334
- };
2335
- var useSocketIO = function (url, options, connect) {
2336
- if (options === void 0) { options = constants_1$1.DEFAULT_OPTIONS; }
2337
- if (connect === void 0) { connect = true; }
2338
- var optionsWithSocketIO = (0, react_1$1.useMemo)(function () { return (__assign$1(__assign$1({}, options), { fromSocketIO: true })); }, []);
2339
- 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;
2340
- var socketIOLastMessage = (0, react_1$1.useMemo)(function () {
2341
- return getSocketData(lastMessage);
2342
- }, [lastMessage]);
2343
- return {
2344
- sendMessage: sendMessage,
2345
- sendJsonMessage: sendJsonMessage,
2346
- lastMessage: socketIOLastMessage,
2347
- lastJsonMessage: socketIOLastMessage,
2348
- readyState: readyState,
2349
- getWebSocket: getWebSocket,
2350
- };
2351
- };
2352
- useSocketIo.useSocketIO = useSocketIO;
2353
-
2354
- var useEventSource$1 = {};
2355
-
2356
- var __assign = (commonjsGlobal && commonjsGlobal.__assign) || function () {
2357
- __assign = Object.assign || function(t) {
2358
- for (var s, i = 1, n = arguments.length; i < n; i++) {
2359
- s = arguments[i];
2360
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
2361
- t[p] = s[p];
2362
- }
2363
- return t;
2364
- };
2365
- return __assign.apply(this, arguments);
2366
- };
2367
- var __rest = (commonjsGlobal && commonjsGlobal.__rest) || function (s, e) {
2368
- var t = {};
2369
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
2370
- t[p] = s[p];
2371
- if (s != null && typeof Object.getOwnPropertySymbols === "function")
2372
- for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
2373
- if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
2374
- t[p[i]] = s[p[i]];
2375
- }
2376
- return t;
2377
- };
2378
- Object.defineProperty(useEventSource$1, "__esModule", { value: true });
2379
- useEventSource$1.useEventSource = void 0;
2380
- var react_1 = React;
2381
- var use_websocket_1 = useWebsocket;
2382
- var constants_1 = constants;
2383
- var useEventSource = function (url, _a, connect) {
2384
- if (_a === void 0) { _a = constants_1.DEFAULT_EVENT_SOURCE_OPTIONS; }
2385
- var withCredentials = _a.withCredentials, events = _a.events, options = __rest(_a, ["withCredentials", "events"]);
2386
- if (connect === void 0) { connect = true; }
2387
- var optionsWithEventSource = __assign(__assign({}, options), { eventSourceOptions: {
2388
- withCredentials: withCredentials,
2389
- } });
2390
- var eventsRef = (0, react_1.useRef)(constants_1.EMPTY_EVENT_HANDLERS);
2391
- if (events) {
2392
- eventsRef.current = events;
2393
- }
2394
- var _b = (0, use_websocket_1.useWebSocket)(url, optionsWithEventSource, connect), lastMessage = _b.lastMessage, readyState = _b.readyState, getWebSocket = _b.getWebSocket;
2395
- (0, react_1.useEffect)(function () {
2396
- if (lastMessage === null || lastMessage === void 0 ? void 0 : lastMessage.type) {
2397
- Object.entries(eventsRef.current).forEach(function (_a) {
2398
- var type = _a[0], handler = _a[1];
2399
- if (type === lastMessage.type) {
2400
- handler(lastMessage);
2401
- }
2402
- });
2403
- }
2404
- }, [lastMessage]);
2405
- return {
2406
- lastEvent: lastMessage,
2407
- readyState: readyState,
2408
- getEventSource: getWebSocket,
2409
- };
2410
- };
2411
- useEventSource$1.useEventSource = useEventSource;
2412
-
2413
- (function (exports) {
2414
- Object.defineProperty(exports, "__esModule", { value: true });
2415
- exports.resetGlobalState = exports.useEventSource = exports.ReadyState = exports.useSocketIO = exports.default = void 0;
2416
- var use_websocket_1 = useWebsocket;
2417
- Object.defineProperty(exports, "default", { enumerable: true, get: function () { return use_websocket_1.useWebSocket; } });
2418
- var use_socket_io_1 = useSocketIo;
2419
- Object.defineProperty(exports, "useSocketIO", { enumerable: true, get: function () { return use_socket_io_1.useSocketIO; } });
2420
- var constants_1 = constants;
2421
- Object.defineProperty(exports, "ReadyState", { enumerable: true, get: function () { return constants_1.ReadyState; } });
2422
- var use_event_source_1 = useEventSource$1;
2423
- Object.defineProperty(exports, "useEventSource", { enumerable: true, get: function () { return use_event_source_1.useEventSource; } });
2424
- var util_1 = util;
2425
- Object.defineProperty(exports, "resetGlobalState", { enumerable: true, get: function () { return util_1.resetGlobalState; } });
2426
-
2427
- } (dist));
2428
-
2429
- var useWebSocket = /*@__PURE__*/getDefaultExportFromCjs(dist);
5
+ // Browser-compatible WebSocket ready state enum (mirrors native values)
6
+ var ReadyState;
7
+ (function (ReadyState) {
8
+ ReadyState[ReadyState["CONNECTING"] = 0] = "CONNECTING";
9
+ ReadyState[ReadyState["OPEN"] = 1] = "OPEN";
10
+ ReadyState[ReadyState["CLOSING"] = 2] = "CLOSING";
11
+ ReadyState[ReadyState["CLOSED"] = 3] = "CLOSED";
12
+ })(ReadyState || (ReadyState = {}));
13
+ // Auth API Types
14
+ var AuthStatus;
15
+ (function (AuthStatus) {
16
+ AuthStatus["Idle"] = "idle";
17
+ AuthStatus["Authenticating"] = "authenticating";
18
+ AuthStatus["Authenticated"] = "authenticated";
19
+ AuthStatus["Error"] = "error";
20
+ })(AuthStatus || (AuthStatus = {}));
2430
21
 
2431
22
  const useUserData = create((set) => ({
2432
23
  tradeHistories: null,
@@ -2462,63 +53,109 @@ const useHyperliquidWebSocket = ({ wsUrl, address }) => {
2462
53
  const { setMarketData } = useMarketData();
2463
54
  const [lastError, setLastError] = useState(null);
2464
55
  const [lastSubscribedAddress, setLastSubscribedAddress] = useState(null);
2465
- // WebSocket connection
2466
- const { readyState, sendMessage } = useWebSocket(wsUrl, {
2467
- shouldReconnect: () => true,
2468
- reconnectAttempts: 5,
2469
- reconnectInterval: 3000,
2470
- onMessage: (event) => {
2471
- try {
2472
- const message = JSON.parse(event.data);
2473
- // Handle subscription responses (only if they don't have channel data)
2474
- if (('success' in message || 'error' in message) && !('channel' in message)) {
2475
- if (message.error) {
2476
- setLastError(message.error);
2477
- }
2478
- else {
2479
- setLastError(null);
2480
- }
56
+ // Native WebSocket connection with basic reconnection
57
+ const wsRef = useRef(null);
58
+ const reconnectAttemptsRef = useRef(0);
59
+ const manualCloseRef = useRef(false);
60
+ const [readyState, setReadyState] = useState(ReadyState.CONNECTING);
61
+ const handleMessage = useCallback((event) => {
62
+ try {
63
+ const message = JSON.parse(event.data);
64
+ // Handle subscription responses (only if they don't have channel data)
65
+ if (('success' in message || 'error' in message) && !('channel' in message)) {
66
+ if (message.error) {
67
+ setLastError(message.error);
68
+ }
69
+ else {
70
+ setLastError(null);
71
+ }
72
+ return;
73
+ }
74
+ // Handle channel data messages
75
+ if ('channel' in message && 'data' in message) {
76
+ const dataMessage = message;
77
+ // Validate data exists and is not null/undefined
78
+ if (dataMessage.data === null || dataMessage.data === undefined) {
2481
79
  return;
2482
80
  }
2483
- // Handle channel data messages
2484
- if ('channel' in message && 'data' in message) {
2485
- const dataMessage = message;
2486
- // Validate data exists and is not null/undefined
2487
- if (dataMessage.data === null || dataMessage.data === undefined) {
2488
- return;
2489
- }
2490
- switch (dataMessage.channel) {
2491
- case 'trade-histories':
2492
- setTradeHistories(dataMessage.data);
2493
- break;
2494
- case 'open-positions':
2495
- setRawOpenPositions(dataMessage.data);
2496
- break;
2497
- case 'open-orders':
2498
- setOpenOrders(dataMessage.data);
2499
- break;
2500
- case 'account-summary':
2501
- setAccountSummary(dataMessage.data);
2502
- break;
2503
- case 'twap-details':
2504
- setTwapDetails(dataMessage.data);
2505
- break;
2506
- case 'notifications':
2507
- setNotifications(dataMessage.data);
2508
- break;
2509
- case 'market-data':
2510
- setMarketData(dataMessage.data);
2511
- break;
2512
- // 'fills-checkpoint' is intentionally ignored here
2513
- }
81
+ switch (dataMessage.channel) {
82
+ case 'trade-histories':
83
+ setTradeHistories(dataMessage.data);
84
+ break;
85
+ case 'open-positions':
86
+ setRawOpenPositions(dataMessage.data);
87
+ break;
88
+ case 'open-orders':
89
+ setOpenOrders(dataMessage.data);
90
+ break;
91
+ case 'account-summary':
92
+ setAccountSummary(dataMessage.data);
93
+ break;
94
+ case 'twap-details':
95
+ setTwapDetails(dataMessage.data);
96
+ break;
97
+ case 'notifications':
98
+ setNotifications(dataMessage.data);
99
+ break;
100
+ case 'market-data':
101
+ setMarketData(dataMessage.data);
102
+ break;
103
+ // 'fills-checkpoint' is intentionally ignored here
2514
104
  }
2515
105
  }
2516
- catch (error) {
2517
- setLastError(`Failed to parse message: ${error instanceof Error ? error.message : String(error)}`);
106
+ }
107
+ catch (error) {
108
+ setLastError(`Failed to parse message: ${error instanceof Error ? error.message : String(error)}`);
109
+ }
110
+ }, [setTradeHistories, setRawOpenPositions, setOpenOrders, setAccountSummary, setTwapDetails, setNotifications, setMarketData]);
111
+ const connect = useCallback(() => {
112
+ if (!wsUrl)
113
+ return;
114
+ try {
115
+ manualCloseRef.current = false;
116
+ setReadyState(ReadyState.CONNECTING);
117
+ const ws = new WebSocket(wsUrl);
118
+ wsRef.current = ws;
119
+ ws.onopen = () => {
120
+ reconnectAttemptsRef.current = 0;
121
+ setReadyState(ReadyState.OPEN);
122
+ setLastError(null);
123
+ };
124
+ ws.onmessage = handleMessage;
125
+ ws.onerror = () => {
126
+ setLastError('WebSocket error');
127
+ };
128
+ ws.onclose = () => {
129
+ setReadyState(ReadyState.CLOSED);
130
+ if (!manualCloseRef.current && reconnectAttemptsRef.current < 5) {
131
+ reconnectAttemptsRef.current += 1;
132
+ setTimeout(() => connect(), 3000);
133
+ }
134
+ };
135
+ }
136
+ catch (e) {
137
+ setLastError(`WebSocket connection failed: ${e instanceof Error ? e.message : String(e)}`);
138
+ }
139
+ }, [wsUrl, handleMessage]);
140
+ useEffect(() => {
141
+ connect();
142
+ return () => {
143
+ manualCloseRef.current = true;
144
+ if (wsRef.current) {
145
+ try {
146
+ wsRef.current.close();
147
+ }
148
+ catch (_a) { }
2518
149
  }
150
+ wsRef.current = null;
151
+ };
152
+ }, [connect]);
153
+ const sendMessage = useCallback((data) => {
154
+ if (wsRef.current && wsRef.current.readyState === WebSocket.OPEN) {
155
+ wsRef.current.send(data);
2519
156
  }
2520
- });
2521
- const isConnected = readyState === dist.ReadyState.OPEN;
157
+ }, []);
158
+ const isConnected = readyState === ReadyState.OPEN;
2522
159
  // Handle subscription management
2523
160
  useEffect(() => {
2524
161
  if (!isConnected)
@@ -2577,7 +214,6 @@ const useHyperliquidWebSocket = ({ wsUrl, address }) => {
2577
214
  }
2578
215
  }, [address, lastSubscribedAddress, clean]);
2579
216
  return {
2580
- connectionStatus: readyState,
2581
217
  isConnected,
2582
218
  lastError,
2583
219
  };
@@ -2779,59 +415,103 @@ const useHyperliquidNativeWebSocket = ({ address, }) => {
2779
415
  const [subscribedCandleTokens, setSubscribedCandleTokens] = useState([]);
2780
416
  const prevCandleIntervalRef = useRef(null);
2781
417
  const pingIntervalRef = useRef(null);
2782
- const { readyState, sendJsonMessage } = useWebSocket('wss://api.hyperliquid.xyz/ws', {
2783
- shouldReconnect: () => true,
2784
- reconnectAttempts: 5,
2785
- reconnectInterval: 3000,
2786
- onOpen: () => { },
2787
- onClose: () => { },
2788
- onError: (event) => console.error('[HyperLiquid WS] Connection error:', event),
2789
- onReconnectStop: () => console.error('[HyperLiquid WS] Reconnection stopped after 5 attempts'),
2790
- onMessage: (event) => {
2791
- try {
2792
- const message = JSON.parse(event.data);
2793
- // Handle subscription responses
2794
- if ('success' in message || 'error' in message) {
2795
- if (message.error) {
2796
- console.error('[HyperLiquid WS] Subscription error:', message.error);
2797
- setLastError(message.error);
2798
- }
2799
- else {
2800
- setLastError(null);
2801
- }
2802
- return;
418
+ const wsRef = useRef(null);
419
+ const reconnectAttemptsRef = useRef(0);
420
+ const manualCloseRef = useRef(false);
421
+ const [readyState, setReadyState] = useState(ReadyState.CONNECTING);
422
+ const handleMessage = useCallback((event) => {
423
+ try {
424
+ const message = JSON.parse(event.data);
425
+ // Handle subscription responses
426
+ if ('success' in message || 'error' in message) {
427
+ if (message.error) {
428
+ console.error('[HyperLiquid WS] Subscription error:', message.error);
429
+ setLastError(message.error);
2803
430
  }
2804
- // Handle channel data messages
2805
- if ('channel' in message && 'data' in message) {
2806
- const response = message;
2807
- switch (response.channel) {
2808
- case 'webData2':
2809
- setWebData2(response.data);
2810
- break;
2811
- case 'allMids':
2812
- setAllMids(response.data);
2813
- break;
2814
- case 'activeAssetData':
2815
- const assetData = response.data;
2816
- upsertActiveAssetData(assetData.coin, assetData);
2817
- break;
2818
- case 'candle':
2819
- const candleDataItem = response.data;
2820
- addCandleData(candleDataItem.s, candleDataItem);
2821
- break;
2822
- default:
2823
- console.warn(`[HyperLiquid WS] Unknown channel: ${response.channel}`);
2824
- }
431
+ else {
432
+ setLastError(null);
2825
433
  }
434
+ return;
2826
435
  }
2827
- catch (error) {
2828
- const errorMessage = `Failed to parse message: ${error instanceof Error ? error.message : String(error)}`;
2829
- console.error('[HyperLiquid WS] Parse error:', errorMessage, 'Raw message:', event.data);
2830
- setLastError(errorMessage);
436
+ // Handle channel data messages
437
+ if ('channel' in message && 'data' in message) {
438
+ const response = message;
439
+ switch (response.channel) {
440
+ case 'webData2':
441
+ setWebData2(response.data);
442
+ break;
443
+ case 'allMids':
444
+ setAllMids(response.data);
445
+ break;
446
+ case 'activeAssetData':
447
+ const assetData = response.data;
448
+ upsertActiveAssetData(assetData.coin, assetData);
449
+ break;
450
+ case 'candle':
451
+ const candleDataItem = response.data;
452
+ addCandleData(candleDataItem.s, candleDataItem);
453
+ break;
454
+ default:
455
+ console.warn(`[HyperLiquid WS] Unknown channel: ${response.channel}`);
456
+ }
2831
457
  }
2832
458
  }
2833
- });
2834
- const isConnected = readyState === dist.ReadyState.OPEN;
459
+ catch (error) {
460
+ const errorMessage = `Failed to parse message: ${error instanceof Error ? error.message : String(error)}`;
461
+ console.error('[HyperLiquid WS] Parse error:', errorMessage, 'Raw message:', event.data);
462
+ setLastError(errorMessage);
463
+ }
464
+ }, [setWebData2, setAllMids, upsertActiveAssetData, addCandleData]);
465
+ const connect = useCallback(() => {
466
+ try {
467
+ manualCloseRef.current = false;
468
+ setReadyState(ReadyState.CONNECTING);
469
+ const ws = new WebSocket('wss://api.hyperliquid.xyz/ws');
470
+ wsRef.current = ws;
471
+ ws.onopen = () => {
472
+ reconnectAttemptsRef.current = 0;
473
+ setReadyState(ReadyState.OPEN);
474
+ setLastError(null);
475
+ };
476
+ ws.onmessage = handleMessage;
477
+ ws.onerror = (event) => {
478
+ console.error('[HyperLiquid WS] Connection error:', event);
479
+ setLastError('WebSocket error');
480
+ };
481
+ ws.onclose = () => {
482
+ setReadyState(ReadyState.CLOSED);
483
+ if (!manualCloseRef.current && reconnectAttemptsRef.current < 5) {
484
+ reconnectAttemptsRef.current += 1;
485
+ if (reconnectAttemptsRef.current === 5) {
486
+ console.error('[HyperLiquid WS] Reconnection stopped after 5 attempts');
487
+ }
488
+ setTimeout(() => connect(), 3000);
489
+ }
490
+ };
491
+ }
492
+ catch (e) {
493
+ setLastError(`WebSocket connection failed: ${e instanceof Error ? e.message : String(e)}`);
494
+ }
495
+ }, [handleMessage]);
496
+ useEffect(() => {
497
+ connect();
498
+ return () => {
499
+ manualCloseRef.current = true;
500
+ if (wsRef.current) {
501
+ try {
502
+ wsRef.current.close();
503
+ }
504
+ catch (_a) { }
505
+ }
506
+ wsRef.current = null;
507
+ };
508
+ }, [connect]);
509
+ const sendJsonMessage = useCallback((data) => {
510
+ if (wsRef.current && wsRef.current.readyState === WebSocket.OPEN) {
511
+ wsRef.current.send(JSON.stringify(data));
512
+ }
513
+ }, []);
514
+ const isConnected = readyState === ReadyState.OPEN;
2835
515
  // Setup ping mechanism
2836
516
  useEffect(() => {
2837
517
  if (isConnected) {
@@ -2987,7 +667,6 @@ const useHyperliquidNativeWebSocket = ({ address, }) => {
2987
667
  }
2988
668
  }, [isConnected, selectedTokenSymbols, candleInterval, subscribedCandleTokens, sendJsonMessage, setCandleData]);
2989
669
  return {
2990
- connectionStatus: readyState,
2991
670
  isConnected,
2992
671
  lastError,
2993
672
  };
@@ -4352,12 +2031,12 @@ const hasStandardBrowserWebWorkerEnv = (() => {
4352
2031
  const origin = hasBrowserEnv && window.location.href || 'http://localhost';
4353
2032
 
4354
2033
  var utils = /*#__PURE__*/Object.freeze({
4355
- __proto__: null,
4356
- hasBrowserEnv: hasBrowserEnv,
4357
- hasStandardBrowserEnv: hasStandardBrowserEnv,
4358
- hasStandardBrowserWebWorkerEnv: hasStandardBrowserWebWorkerEnv,
4359
- navigator: _navigator,
4360
- origin: origin
2034
+ __proto__: null,
2035
+ hasBrowserEnv: hasBrowserEnv,
2036
+ hasStandardBrowserEnv: hasStandardBrowserEnv,
2037
+ hasStandardBrowserWebWorkerEnv: hasStandardBrowserWebWorkerEnv,
2038
+ navigator: _navigator,
2039
+ origin: origin
4361
2040
  });
4362
2041
 
4363
2042
  var platform = {
@@ -6906,15 +4585,6 @@ async function logout(baseUrl, refreshTokenVal) {
6906
4585
  }
6907
4586
  }
6908
4587
 
6909
- // Auth API Types
6910
- var AuthStatus;
6911
- (function (AuthStatus) {
6912
- AuthStatus["Idle"] = "idle";
6913
- AuthStatus["Authenticating"] = "authenticating";
6914
- AuthStatus["Authenticated"] = "authenticated";
6915
- AuthStatus["Error"] = "error";
6916
- })(AuthStatus || (AuthStatus = {}));
6917
-
6918
4588
  async function getAgentWallet(baseUrl, accessToken) {
6919
4589
  const url = joinUrl(baseUrl, '/agentWallet');
6920
4590
  try {
@@ -7185,7 +4855,6 @@ const useWebData = () => {
7185
4855
  perpsAtOpenInterestCap: webData2 === null || webData2 === void 0 ? void 0 : webData2.perpsAtOpenInterestCap,
7186
4856
  marketDataBySymbol,
7187
4857
  isConnected: context.nativeIsConnected,
7188
- connectionStatus: context.nativeConnectionStatus,
7189
4858
  error: context.nativeLastError,
7190
4859
  };
7191
4860
  };
@@ -8234,23 +5903,6 @@ const usePerformanceOverlays = () => {
8234
5903
  };
8235
5904
  };
8236
5905
 
8237
- // Refactored to read auth state/actions from Provider context
8238
- function useAuth() {
8239
- const ctx = usePearHyperliquid();
8240
- return {
8241
- status: ctx.authStatus,
8242
- isAuthenticated: ctx.isAuthenticated,
8243
- accessToken: ctx.accessToken,
8244
- user: ctx.user,
8245
- error: ctx.authError,
8246
- getEip712: ctx.getEip712,
8247
- loginWithSignedMessage: ctx.loginWithSignedMessage,
8248
- loginWithPrivyToken: ctx.loginWithPrivyToken,
8249
- refreshTokens: ctx.refreshTokens,
8250
- logout: ctx.logout,
8251
- };
8252
- }
8253
-
8254
5906
  /**
8255
5907
  * Sync external fills into Pear Hyperliquid service (POST /sync/fills)
8256
5908
  */
@@ -8971,6 +6623,63 @@ function useWatchlist() {
8971
6623
  return { watchlists: watchlists !== null && watchlists !== void 0 ? watchlists : null, isLoading, toggle };
8972
6624
  }
8973
6625
 
6626
+ /**
6627
+ * Get portfolio summary buckets and overall metrics
6628
+ * Returns bucketed volume, open interest snapshot, win/loss trade counts, and overall metrics filtered to PEAR fills (cloid LIKE 0x50454152%)
6629
+ * Caller should supply an accessToken from localStorage.getItem('accessToken')
6630
+ */
6631
+ async function getPortfolio(baseUrl, accessToken) {
6632
+ const url = joinUrl(baseUrl, '/portfolio');
6633
+ try {
6634
+ const resp = await axios$1.get(url, { headers: { Authorization: `Bearer ${accessToken}` }, timeout: 60000 });
6635
+ return { data: resp.data, status: resp.status, headers: resp.headers };
6636
+ }
6637
+ catch (error) {
6638
+ throw toApiError(error);
6639
+ }
6640
+ }
6641
+
6642
+ /**
6643
+ * Hook to fetch and manage portfolio data
6644
+ * Returns bucketed volume, open interest snapshot, win/loss trade counts,
6645
+ * and overall metrics filtered to PEAR fills (cloid LIKE 0x50454152%)
6646
+ */
6647
+ function usePortfolio() {
6648
+ const context = useContext(PearHyperliquidContext);
6649
+ if (!context) {
6650
+ throw new Error('usePortfolio must be used within a PearHyperliquidProvider');
6651
+ }
6652
+ const { apiBaseUrl, accessToken, isAuthenticated } = context;
6653
+ const [data, setData] = useState(null);
6654
+ const [isLoading, setIsLoading] = useState(false);
6655
+ const [error, setError] = useState(null);
6656
+ const fetchPortfolio = useCallback(async () => {
6657
+ if (!isAuthenticated || !accessToken) {
6658
+ setError(new Error('Not authenticated'));
6659
+ return;
6660
+ }
6661
+ setIsLoading(true);
6662
+ setError(null);
6663
+ try {
6664
+ const response = await getPortfolio(apiBaseUrl, accessToken);
6665
+ setData(response.data);
6666
+ }
6667
+ catch (err) {
6668
+ setError(err instanceof Error ? err : new Error('Failed to fetch portfolio'));
6669
+ setData(null);
6670
+ }
6671
+ finally {
6672
+ setIsLoading(false);
6673
+ }
6674
+ }, [apiBaseUrl, accessToken, isAuthenticated]);
6675
+ return {
6676
+ data,
6677
+ isLoading,
6678
+ error,
6679
+ refetch: fetchPortfolio,
6680
+ };
6681
+ }
6682
+
8974
6683
  const PearHyperliquidContext = createContext(undefined);
8975
6684
  /**
8976
6685
  * React Provider for PearHyperliquidClient
@@ -8978,12 +6687,12 @@ const PearHyperliquidContext = createContext(undefined);
8978
6687
  const PearHyperliquidProvider = ({ children, apiBaseUrl = 'https://hl-v2.pearprotocol.io', clientId = 'PEARPROTOCOLUI', wsUrl = 'wss://hl-v2.pearprotocol.io/ws', }) => {
8979
6688
  const [address, setAddress] = useState(null);
8980
6689
  // WebSocket connection and data (Pear API)
8981
- const { connectionStatus, isConnected, lastError } = useHyperliquidWebSocket({
6690
+ const { isConnected, lastError } = useHyperliquidWebSocket({
8982
6691
  wsUrl,
8983
6692
  address,
8984
6693
  });
8985
6694
  // HyperLiquid native WebSocket connection
8986
- const { connectionStatus: nativeConnectionStatus, isConnected: nativeIsConnected, lastError: nativeLastError } = useHyperliquidNativeWebSocket({
6695
+ const { isConnected: nativeIsConnected, lastError: nativeLastError } = useHyperliquidNativeWebSocket({
8987
6696
  address,
8988
6697
  });
8989
6698
  // Auth hook
@@ -8994,7 +6703,7 @@ const PearHyperliquidProvider = ({ children, apiBaseUrl = 'https://hl-v2.pearpro
8994
6703
  const [accessToken, setAccessToken] = useState(null);
8995
6704
  const isAuthenticated = useMemo(() => !!accessToken, [accessToken]);
8996
6705
  // Hydrate from existing token
8997
- React.useEffect(() => {
6706
+ useEffect(() => {
8998
6707
  const access = localStorage.getItem('accessToken');
8999
6708
  if (access) {
9000
6709
  try {
@@ -9011,11 +6720,11 @@ const PearHyperliquidProvider = ({ children, apiBaseUrl = 'https://hl-v2.pearpro
9011
6720
  }
9012
6721
  }
9013
6722
  }, [clientId]);
9014
- const getEip712 = React.useCallback(async (address) => {
6723
+ const getEip712 = useCallback(async (address) => {
9015
6724
  const { data } = await getEIP712Message(apiBaseUrl, address, clientId);
9016
6725
  return data;
9017
6726
  }, [apiBaseUrl, clientId]);
9018
- const loginWithSignedMessage = React.useCallback(async (address, signature, timestamp) => {
6727
+ const loginWithSignedMessage = useCallback(async (address, signature, timestamp) => {
9019
6728
  setAuthError(null);
9020
6729
  setAuthStatus(AuthStatus.Authenticating);
9021
6730
  try {
@@ -9031,6 +6740,7 @@ const PearHyperliquidProvider = ({ children, apiBaseUrl = 'https://hl-v2.pearpro
9031
6740
  const lower = data.address.toLowerCase();
9032
6741
  setUser({ userId: lower, address: lower, appId: clientId });
9033
6742
  setAuthStatus(AuthStatus.Authenticated);
6743
+ setAddress(lower);
9034
6744
  }
9035
6745
  catch (e) {
9036
6746
  setAuthError((e === null || e === void 0 ? void 0 : e.message) || 'Authentication failed');
@@ -9038,7 +6748,7 @@ const PearHyperliquidProvider = ({ children, apiBaseUrl = 'https://hl-v2.pearpro
9038
6748
  throw e;
9039
6749
  }
9040
6750
  }, [apiBaseUrl, clientId]);
9041
- const refreshTokens = React.useCallback(async () => {
6751
+ const refreshTokens = useCallback(async () => {
9042
6752
  const refresh = localStorage.getItem('refreshToken');
9043
6753
  if (!refresh)
9044
6754
  throw new Error('No refresh token');
@@ -9048,7 +6758,7 @@ const PearHyperliquidProvider = ({ children, apiBaseUrl = 'https://hl-v2.pearpro
9048
6758
  setAccessToken(data.accessToken);
9049
6759
  return data;
9050
6760
  }, [apiBaseUrl]);
9051
- const loginWithPrivyToken = React.useCallback(async (address, appId, privyAccessToken) => {
6761
+ const loginWithPrivyToken = useCallback(async (address, appId, privyAccessToken) => {
9052
6762
  setAuthError(null);
9053
6763
  setAuthStatus(AuthStatus.Authenticating);
9054
6764
  try {
@@ -9059,6 +6769,7 @@ const PearHyperliquidProvider = ({ children, apiBaseUrl = 'https://hl-v2.pearpro
9059
6769
  const lower = data.address.toLowerCase();
9060
6770
  setUser({ userId: lower, address: lower, appId: clientId });
9061
6771
  setAuthStatus(AuthStatus.Authenticated);
6772
+ setAddress(lower);
9062
6773
  }
9063
6774
  catch (e) {
9064
6775
  setAuthError((e === null || e === void 0 ? void 0 : e.message) || 'Authentication failed');
@@ -9066,7 +6777,7 @@ const PearHyperliquidProvider = ({ children, apiBaseUrl = 'https://hl-v2.pearpro
9066
6777
  throw e;
9067
6778
  }
9068
6779
  }, [apiBaseUrl, clientId]);
9069
- const logout$1 = React.useCallback(async () => {
6780
+ const logout$1 = useCallback(async () => {
9070
6781
  const refresh = localStorage.getItem('refreshToken');
9071
6782
  if (refresh) {
9072
6783
  try {
@@ -9080,6 +6791,7 @@ const PearHyperliquidProvider = ({ children, apiBaseUrl = 'https://hl-v2.pearpro
9080
6791
  setUser(null);
9081
6792
  setAuthStatus(AuthStatus.Idle);
9082
6793
  setAuthError(null);
6794
+ setAddress(null);
9083
6795
  }, [apiBaseUrl]);
9084
6796
  // Agent wallet hook
9085
6797
  const { agentWallet, isReady: isAgentWalletReady, loading: agentWalletLoading, error: agentWalletError, refreshAgentWalletStatus, createAgentWallet, notifyAgentWalletApproved, } = useAgentWallet({ baseUrl: apiBaseUrl });
@@ -9099,12 +6811,10 @@ const PearHyperliquidProvider = ({ children, apiBaseUrl = 'https://hl-v2.pearpro
9099
6811
  address,
9100
6812
  setAddress,
9101
6813
  // WebSocket state (Pear API)
9102
- connectionStatus,
9103
6814
  isConnected,
9104
6815
  // WebSocket data (Pear API)
9105
6816
  lastError,
9106
6817
  // HyperLiquid native WebSocket state
9107
- nativeConnectionStatus,
9108
6818
  nativeIsConnected,
9109
6819
  nativeLastError,
9110
6820
  // Auth
@@ -9129,14 +6839,14 @@ const PearHyperliquidProvider = ({ children, apiBaseUrl = 'https://hl-v2.pearpro
9129
6839
  }), [
9130
6840
  apiBaseUrl, wsUrl,
9131
6841
  address, setAddress,
9132
- connectionStatus, isConnected, lastError,
9133
- nativeConnectionStatus, nativeIsConnected, nativeLastError,
6842
+ isConnected, lastError,
6843
+ nativeIsConnected, nativeLastError,
9134
6844
  authStatus, isAuthenticated, user, authError,
9135
6845
  agentWallet, isAgentWalletReady, agentWalletError, agentWalletLoading,
9136
6846
  getEip712, loginWithSignedMessage, refreshTokens, logout$1,
9137
6847
  refreshAgentWalletStatus, createAgentWallet, notifyAgentWalletApproved,
9138
6848
  ]);
9139
- return (jsxRuntimeExports.jsx(PearHyperliquidContext.Provider, { value: contextValue, children: children }));
6849
+ return (jsx(PearHyperliquidContext.Provider, { value: contextValue, children: children }));
9140
6850
  };
9141
6851
  /**
9142
6852
  * Hook to access the entire Pear Hyperliquid context.
@@ -9269,4 +6979,4 @@ function mapCandleIntervalToTradingViewInterval(interval) {
9269
6979
  }
9270
6980
  }
9271
6981
 
9272
- export { AccountSummaryCalculator, AuthStatus, ConflictDetector, MINIMUM_ASSET_USD_VALUE, MinimumPositionSizeError, PearHyperliquidProvider, TokenMetadataExtractor, adjustOrder, adjustPosition, calculateMinimumPositionValue, calculateWeightedRatio, cancelOrder, cancelTwap, cancelTwapOrder, closeAllPositions, closePosition, computeBasketCandles, createCandleLookups, createPosition, getCompleteTimestamps, mapCandleIntervalToTradingViewInterval, mapTradingViewIntervalToCandleInterval, markNotificationReadById, markNotificationsRead, toggleWatchlist, updateRiskParameters, useAccountSummary, useActiveBaskets, useAddress, useAgentWallet, useAuth, useAutoSyncFills, useBasketCandles, useFindBasket, useHighlightedBaskets, useHistoricalPriceData, useHistoricalPriceDataStore, useHyperliquidNativeWebSocket, useHyperliquidWebSocket, useMarketData, useMarketDataPayload, useNotifications, useOpenOrders, useOrders, usePearAgentWallet, usePearAuth, usePearHyperliquid, usePerformanceOverlays, usePosition, useTokenSelectionMetadata, useTopGainers, useTopLosers, useTradeHistories, useTwap, useUserSelection, useWatchlist, useWatchlistBaskets, useWebData, validateMinimumAssetSize, validatePositionSize };
6982
+ export { AccountSummaryCalculator, AuthStatus, ConflictDetector, MINIMUM_ASSET_USD_VALUE, MinimumPositionSizeError, PearHyperliquidProvider, TokenMetadataExtractor, adjustOrder, adjustPosition, calculateMinimumPositionValue, calculateWeightedRatio, cancelOrder, cancelTwap, cancelTwapOrder, closeAllPositions, closePosition, computeBasketCandles, createCandleLookups, createPosition, getCompleteTimestamps, getPortfolio, mapCandleIntervalToTradingViewInterval, mapTradingViewIntervalToCandleInterval, markNotificationReadById, markNotificationsRead, toggleWatchlist, updateRiskParameters, useAccountSummary, useActiveBaskets, useAddress, useAgentWallet, useAutoSyncFills, useBasketCandles, useFindBasket, useHighlightedBaskets, useHistoricalPriceData, useHistoricalPriceDataStore, useHyperliquidNativeWebSocket, useHyperliquidWebSocket, useMarketData, useMarketDataPayload, useNotifications, useOpenOrders, useOrders, usePearAgentWallet, usePearAuth, usePearHyperliquid, usePerformanceOverlays, usePortfolio, usePosition, useTokenSelectionMetadata, useTopGainers, useTopLosers, useTradeHistories, useTwap, useUserSelection, useWatchlist, useWatchlistBaskets, useWebData, validateMinimumAssetSize, validatePositionSize };