@shiva004/surveys 0.1.3 → 0.1.5

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.
Files changed (38) hide show
  1. package/dist/index.cjs +109 -0
  2. package/dist/index.cjs.map +1 -0
  3. package/dist/index.d.ts +403 -0
  4. package/dist/index.js +8716 -0
  5. package/dist/index.js.map +1 -0
  6. package/dist/style.css +1 -0
  7. package/package.json +33 -27
  8. package/src/Pages/Allsurvey/Allsurvey.tsx +0 -157
  9. package/src/Pages/Allsurvey/SurveyGridCard.tsx +0 -125
  10. package/src/Pages/Allsurvey/index.ts +0 -1
  11. package/src/Pages/Allsurvey/surveysTable.config.ts +0 -15
  12. package/src/Pages/Createsurvey/Createsurvey.tsx +0 -318
  13. package/src/Pages/Createsurvey/index.ts +0 -1
  14. package/src/Pages/NPStracker/NPStracker.tsx +0 -78
  15. package/src/Pages/NPStracker/index.ts +0 -1
  16. package/src/Pages/Responses/Responses.tsx +0 -61
  17. package/src/Pages/Responses/index.ts +0 -1
  18. package/src/Pages/Responses/responsesTable.config.ts +0 -74
  19. package/src/Pages/Surveyanalytics/Surveyanalytics.tsx +0 -154
  20. package/src/Pages/Surveyanalytics/analyticsTable.config.ts +0 -123
  21. package/src/Pages/Surveyanalytics/index.ts +0 -1
  22. package/src/Pages/Surveydetails/Surveydetails.tsx +0 -202
  23. package/src/Pages/Surveydetails/index.ts +0 -1
  24. package/src/Pages/Surveytemplates/Surveytemplates.tsx +0 -299
  25. package/src/Pages/Surveytemplates/index.ts +0 -1
  26. package/src/Pages/surveyPage.module.scss +0 -49
  27. package/src/cells/SurveyCells.tsx +0 -370
  28. package/src/hooks/useSurveyResponses.ts +0 -37
  29. package/src/hooks/useTableConfig.ts +0 -77
  30. package/src/hooks/useTableData.ts +0 -184
  31. package/src/index.ts +0 -24
  32. package/src/nav.ts +0 -55
  33. package/src/routes.ts +0 -98
  34. package/src/services/api/TableConfigDto.ts +0 -36
  35. package/src/services/api/TableQueryParams.ts +0 -10
  36. package/src/services/api/surveys.api.ts +0 -144
  37. package/src/services/api/types.ts +0 -113
  38. package/src/types/survey.types.ts +0 -175
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sources":["../node_modules/react/cjs/react.production.min.js","../node_modules/react/cjs/react.development.js","../node_modules/react/index.js","../src/routes.ts","../src/nav.ts","../node_modules/react/cjs/react-jsx-runtime.production.min.js","../node_modules/react/cjs/react-jsx-runtime.development.js","../node_modules/react/jsx-runtime.js","../src/components/ui/Icon.tsx","../src/components/StatCard/StatCard.tsx","../node_modules/@remix-run/router/dist/router.js","../node_modules/react-router/dist/index.js","../src/cells/SurveyCells.tsx","../src/components/DataTable/DataTable.tsx","../src/components/feedback/ConfirmModal.tsx","../src/components/layout/Header.tsx","../node_modules/@tanstack/react-query/build/modern/QueryClientProvider.js","../node_modules/@tanstack/query-core/build/modern/timeoutManager.js","../node_modules/@tanstack/query-core/build/modern/utils.js","../node_modules/@tanstack/query-core/build/modern/environmentManager.js","../node_modules/@tanstack/query-core/build/modern/subscribable.js","../node_modules/@tanstack/query-core/build/modern/focusManager.js","../node_modules/@tanstack/query-core/build/modern/notifyManager.js","../node_modules/@tanstack/query-core/build/modern/onlineManager.js","../node_modules/@tanstack/query-core/build/modern/retryer.js","../node_modules/@tanstack/query-core/build/modern/infiniteQueryBehavior.js","../node_modules/@tanstack/query-core/build/modern/query.js","../node_modules/@tanstack/query-core/build/modern/queryObserver.js","../node_modules/@tanstack/query-core/build/modern/infiniteQueryObserver.js","../node_modules/@tanstack/query-core/build/modern/mutation.js","../node_modules/@tanstack/query-core/build/modern/mutationObserver.js","../node_modules/@tanstack/react-query/build/modern/IsRestoringProvider.js","../node_modules/@tanstack/react-query/build/modern/QueryErrorResetBoundary.js","../node_modules/@tanstack/react-query/build/modern/errorBoundaryUtils.js","../node_modules/@tanstack/react-query/build/modern/suspense.js","../node_modules/@tanstack/react-query/build/modern/useBaseQuery.js","../node_modules/@tanstack/react-query/build/modern/useQuery.js","../node_modules/@tanstack/react-query/build/modern/useMutation.js","../node_modules/@tanstack/react-query/build/modern/useInfiniteQuery.js","../node_modules/axios/lib/helpers/bind.js","../node_modules/axios/lib/utils.js","../node_modules/axios/lib/helpers/parseHeaders.js","../node_modules/axios/lib/helpers/sanitizeHeaderValue.js","../node_modules/axios/lib/core/AxiosHeaders.js","../node_modules/axios/lib/core/AxiosError.js","../node_modules/axios/lib/helpers/null.js","../node_modules/axios/lib/helpers/toFormData.js","../node_modules/axios/lib/helpers/AxiosURLSearchParams.js","../node_modules/axios/lib/helpers/buildURL.js","../node_modules/axios/lib/core/InterceptorManager.js","../node_modules/axios/lib/defaults/transitional.js","../node_modules/axios/lib/platform/browser/classes/URLSearchParams.js","../node_modules/axios/lib/platform/browser/classes/FormData.js","../node_modules/axios/lib/platform/browser/classes/Blob.js","../node_modules/axios/lib/platform/browser/index.js","../node_modules/axios/lib/platform/common/utils.js","../node_modules/axios/lib/platform/index.js","../node_modules/axios/lib/helpers/toURLEncodedForm.js","../node_modules/axios/lib/helpers/formDataToJSON.js","../node_modules/axios/lib/core/methodList.js","../node_modules/axios/lib/defaults/index.js","../node_modules/axios/lib/core/transformData.js","../node_modules/axios/lib/cancel/isCancel.js","../node_modules/axios/lib/cancel/CanceledError.js","../node_modules/axios/lib/core/settle.js","../node_modules/axios/lib/helpers/normalizeURLForProtocolCheck.js","../node_modules/axios/lib/helpers/parseProtocol.js","../node_modules/axios/lib/helpers/cookies.js","../node_modules/axios/lib/helpers/speedometer.js","../node_modules/axios/lib/helpers/throttle.js","../node_modules/axios/lib/helpers/progressEventReducer.js","../node_modules/axios/lib/helpers/isURLSameOrigin.js","../node_modules/axios/lib/helpers/isAbsoluteURL.js","../node_modules/axios/lib/helpers/combineURLs.js","../node_modules/axios/lib/core/buildFullPath.js","../node_modules/axios/lib/core/assertParamsAcyclic.js","../node_modules/axios/lib/core/mergeConfig.js","../node_modules/axios/lib/core/setFormDataHeaders.js","../node_modules/axios/lib/helpers/resolveConfig.js","../node_modules/axios/lib/adapters/xhr.js","../node_modules/axios/lib/helpers/composeSignals.js","../node_modules/axios/lib/helpers/trackStream.js","../node_modules/axios/lib/helpers/formDataToBlob.js","../node_modules/axios/lib/core/createMultipartBody.js","../node_modules/axios/lib/helpers/estimateDataURLDecodedBytes.js","../node_modules/axios/lib/env/data.js","../node_modules/axios/lib/adapters/fetch.js","../node_modules/axios/lib/adapters/adapters.js","../node_modules/axios/lib/core/dispatchRequest.js","../node_modules/axios/lib/helpers/validator.js","../node_modules/axios/lib/core/Axios.js","../node_modules/axios/lib/cancel/CancelToken.js","../node_modules/axios/lib/helpers/spread.js","../node_modules/axios/lib/helpers/isAxiosError.js","../node_modules/axios/lib/helpers/HttpStatusCode.js","../node_modules/axios/lib/axios.js","../node_modules/axios/index.js","../src/hooks/useTableConfig.ts","../src/hooks/useTableData.ts","../src/services/api/surveys.api.ts","../src/components/ui/Card.tsx","../src/Pages/Allsurvey/SurveyGridCard.tsx","../src/Pages/Allsurvey/surveysTable.config.ts","../src/Pages/Allsurvey/Allsurvey.tsx","../src/Pages/Createsurvey/Createsurvey.tsx","../src/hooks/useSurveyResponses.ts","../src/Pages/Responses/responsesTable.config.ts","../src/Pages/Surveydetails/Surveydetails.tsx","../src/Pages/Surveytemplates/Surveytemplates.tsx","../src/Pages/Responses/Responses.tsx","../src/Pages/NPStracker/NPStracker.tsx","../src/Pages/Surveyanalytics/analyticsTable.config.ts","../src/Pages/Surveyanalytics/Surveyanalytics.tsx"],"sourcesContent":["/**\n * @license React\n * react.production.min.js\n *\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n'use strict';var l=Symbol.for(\"react.element\"),n=Symbol.for(\"react.portal\"),p=Symbol.for(\"react.fragment\"),q=Symbol.for(\"react.strict_mode\"),r=Symbol.for(\"react.profiler\"),t=Symbol.for(\"react.provider\"),u=Symbol.for(\"react.context\"),v=Symbol.for(\"react.forward_ref\"),w=Symbol.for(\"react.suspense\"),x=Symbol.for(\"react.memo\"),y=Symbol.for(\"react.lazy\"),z=Symbol.iterator;function A(a){if(null===a||\"object\"!==typeof a)return null;a=z&&a[z]||a[\"@@iterator\"];return\"function\"===typeof a?a:null}\nvar B={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},C=Object.assign,D={};function E(a,b,e){this.props=a;this.context=b;this.refs=D;this.updater=e||B}E.prototype.isReactComponent={};\nE.prototype.setState=function(a,b){if(\"object\"!==typeof a&&\"function\"!==typeof a&&null!=a)throw Error(\"setState(...): takes an object of state variables to update or a function which returns an object of state variables.\");this.updater.enqueueSetState(this,a,b,\"setState\")};E.prototype.forceUpdate=function(a){this.updater.enqueueForceUpdate(this,a,\"forceUpdate\")};function F(){}F.prototype=E.prototype;function G(a,b,e){this.props=a;this.context=b;this.refs=D;this.updater=e||B}var H=G.prototype=new F;\nH.constructor=G;C(H,E.prototype);H.isPureReactComponent=!0;var I=Array.isArray,J=Object.prototype.hasOwnProperty,K={current:null},L={key:!0,ref:!0,__self:!0,__source:!0};\nfunction M(a,b,e){var d,c={},k=null,h=null;if(null!=b)for(d in void 0!==b.ref&&(h=b.ref),void 0!==b.key&&(k=\"\"+b.key),b)J.call(b,d)&&!L.hasOwnProperty(d)&&(c[d]=b[d]);var g=arguments.length-2;if(1===g)c.children=e;else if(1<g){for(var f=Array(g),m=0;m<g;m++)f[m]=arguments[m+2];c.children=f}if(a&&a.defaultProps)for(d in g=a.defaultProps,g)void 0===c[d]&&(c[d]=g[d]);return{$$typeof:l,type:a,key:k,ref:h,props:c,_owner:K.current}}\nfunction N(a,b){return{$$typeof:l,type:a.type,key:b,ref:a.ref,props:a.props,_owner:a._owner}}function O(a){return\"object\"===typeof a&&null!==a&&a.$$typeof===l}function escape(a){var b={\"=\":\"=0\",\":\":\"=2\"};return\"$\"+a.replace(/[=:]/g,function(a){return b[a]})}var P=/\\/+/g;function Q(a,b){return\"object\"===typeof a&&null!==a&&null!=a.key?escape(\"\"+a.key):b.toString(36)}\nfunction R(a,b,e,d,c){var k=typeof a;if(\"undefined\"===k||\"boolean\"===k)a=null;var h=!1;if(null===a)h=!0;else switch(k){case \"string\":case \"number\":h=!0;break;case \"object\":switch(a.$$typeof){case l:case n:h=!0}}if(h)return h=a,c=c(h),a=\"\"===d?\".\"+Q(h,0):d,I(c)?(e=\"\",null!=a&&(e=a.replace(P,\"$&/\")+\"/\"),R(c,b,e,\"\",function(a){return a})):null!=c&&(O(c)&&(c=N(c,e+(!c.key||h&&h.key===c.key?\"\":(\"\"+c.key).replace(P,\"$&/\")+\"/\")+a)),b.push(c)),1;h=0;d=\"\"===d?\".\":d+\":\";if(I(a))for(var g=0;g<a.length;g++){k=\na[g];var f=d+Q(k,g);h+=R(k,b,e,f,c)}else if(f=A(a),\"function\"===typeof f)for(a=f.call(a),g=0;!(k=a.next()).done;)k=k.value,f=d+Q(k,g++),h+=R(k,b,e,f,c);else if(\"object\"===k)throw b=String(a),Error(\"Objects are not valid as a React child (found: \"+(\"[object Object]\"===b?\"object with keys {\"+Object.keys(a).join(\", \")+\"}\":b)+\"). If you meant to render a collection of children, use an array instead.\");return h}\nfunction S(a,b,e){if(null==a)return a;var d=[],c=0;R(a,d,\"\",\"\",function(a){return b.call(e,a,c++)});return d}function T(a){if(-1===a._status){var b=a._result;b=b();b.then(function(b){if(0===a._status||-1===a._status)a._status=1,a._result=b},function(b){if(0===a._status||-1===a._status)a._status=2,a._result=b});-1===a._status&&(a._status=0,a._result=b)}if(1===a._status)return a._result.default;throw a._result;}\nvar U={current:null},V={transition:null},W={ReactCurrentDispatcher:U,ReactCurrentBatchConfig:V,ReactCurrentOwner:K};function X(){throw Error(\"act(...) is not supported in production builds of React.\");}\nexports.Children={map:S,forEach:function(a,b,e){S(a,function(){b.apply(this,arguments)},e)},count:function(a){var b=0;S(a,function(){b++});return b},toArray:function(a){return S(a,function(a){return a})||[]},only:function(a){if(!O(a))throw Error(\"React.Children.only expected to receive a single React element child.\");return a}};exports.Component=E;exports.Fragment=p;exports.Profiler=r;exports.PureComponent=G;exports.StrictMode=q;exports.Suspense=w;\nexports.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=W;exports.act=X;\nexports.cloneElement=function(a,b,e){if(null===a||void 0===a)throw Error(\"React.cloneElement(...): The argument must be a React element, but you passed \"+a+\".\");var d=C({},a.props),c=a.key,k=a.ref,h=a._owner;if(null!=b){void 0!==b.ref&&(k=b.ref,h=K.current);void 0!==b.key&&(c=\"\"+b.key);if(a.type&&a.type.defaultProps)var g=a.type.defaultProps;for(f in b)J.call(b,f)&&!L.hasOwnProperty(f)&&(d[f]=void 0===b[f]&&void 0!==g?g[f]:b[f])}var f=arguments.length-2;if(1===f)d.children=e;else if(1<f){g=Array(f);\nfor(var m=0;m<f;m++)g[m]=arguments[m+2];d.children=g}return{$$typeof:l,type:a.type,key:c,ref:k,props:d,_owner:h}};exports.createContext=function(a){a={$$typeof:u,_currentValue:a,_currentValue2:a,_threadCount:0,Provider:null,Consumer:null,_defaultValue:null,_globalName:null};a.Provider={$$typeof:t,_context:a};return a.Consumer=a};exports.createElement=M;exports.createFactory=function(a){var b=M.bind(null,a);b.type=a;return b};exports.createRef=function(){return{current:null}};\nexports.forwardRef=function(a){return{$$typeof:v,render:a}};exports.isValidElement=O;exports.lazy=function(a){return{$$typeof:y,_payload:{_status:-1,_result:a},_init:T}};exports.memo=function(a,b){return{$$typeof:x,type:a,compare:void 0===b?null:b}};exports.startTransition=function(a){var b=V.transition;V.transition={};try{a()}finally{V.transition=b}};exports.unstable_act=X;exports.useCallback=function(a,b){return U.current.useCallback(a,b)};exports.useContext=function(a){return U.current.useContext(a)};\nexports.useDebugValue=function(){};exports.useDeferredValue=function(a){return U.current.useDeferredValue(a)};exports.useEffect=function(a,b){return U.current.useEffect(a,b)};exports.useId=function(){return U.current.useId()};exports.useImperativeHandle=function(a,b,e){return U.current.useImperativeHandle(a,b,e)};exports.useInsertionEffect=function(a,b){return U.current.useInsertionEffect(a,b)};exports.useLayoutEffect=function(a,b){return U.current.useLayoutEffect(a,b)};\nexports.useMemo=function(a,b){return U.current.useMemo(a,b)};exports.useReducer=function(a,b,e){return U.current.useReducer(a,b,e)};exports.useRef=function(a){return U.current.useRef(a)};exports.useState=function(a){return U.current.useState(a)};exports.useSyncExternalStore=function(a,b,e){return U.current.useSyncExternalStore(a,b,e)};exports.useTransition=function(){return U.current.useTransition()};exports.version=\"18.3.1\";\n","/**\n * @license React\n * react.development.js\n *\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n'use strict';\n\nif (process.env.NODE_ENV !== \"production\") {\n (function() {\n\n 'use strict';\n\n/* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */\nif (\n typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' &&\n typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart ===\n 'function'\n) {\n __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(new Error());\n}\n var ReactVersion = '18.3.1';\n\n// ATTENTION\n// When adding new symbols to this file,\n// Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols'\n// The Symbol used to tag the ReactElement-like types.\nvar REACT_ELEMENT_TYPE = Symbol.for('react.element');\nvar REACT_PORTAL_TYPE = Symbol.for('react.portal');\nvar REACT_FRAGMENT_TYPE = Symbol.for('react.fragment');\nvar REACT_STRICT_MODE_TYPE = Symbol.for('react.strict_mode');\nvar REACT_PROFILER_TYPE = Symbol.for('react.profiler');\nvar REACT_PROVIDER_TYPE = Symbol.for('react.provider');\nvar REACT_CONTEXT_TYPE = Symbol.for('react.context');\nvar REACT_FORWARD_REF_TYPE = Symbol.for('react.forward_ref');\nvar REACT_SUSPENSE_TYPE = Symbol.for('react.suspense');\nvar REACT_SUSPENSE_LIST_TYPE = Symbol.for('react.suspense_list');\nvar REACT_MEMO_TYPE = Symbol.for('react.memo');\nvar REACT_LAZY_TYPE = Symbol.for('react.lazy');\nvar REACT_OFFSCREEN_TYPE = Symbol.for('react.offscreen');\nvar MAYBE_ITERATOR_SYMBOL = Symbol.iterator;\nvar FAUX_ITERATOR_SYMBOL = '@@iterator';\nfunction getIteratorFn(maybeIterable) {\n if (maybeIterable === null || typeof maybeIterable !== 'object') {\n return null;\n }\n\n var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL];\n\n if (typeof maybeIterator === 'function') {\n return maybeIterator;\n }\n\n return null;\n}\n\n/**\n * Keeps track of the current dispatcher.\n */\nvar ReactCurrentDispatcher = {\n /**\n * @internal\n * @type {ReactComponent}\n */\n current: null\n};\n\n/**\n * Keeps track of the current batch's configuration such as how long an update\n * should suspend for if it needs to.\n */\nvar ReactCurrentBatchConfig = {\n transition: null\n};\n\nvar ReactCurrentActQueue = {\n current: null,\n // Used to reproduce behavior of `batchedUpdates` in legacy mode.\n isBatchingLegacy: false,\n didScheduleLegacyUpdate: false\n};\n\n/**\n * Keeps track of the current owner.\n *\n * The current owner is the component who should own any components that are\n * currently being constructed.\n */\nvar ReactCurrentOwner = {\n /**\n * @internal\n * @type {ReactComponent}\n */\n current: null\n};\n\nvar ReactDebugCurrentFrame = {};\nvar currentExtraStackFrame = null;\nfunction setExtraStackFrame(stack) {\n {\n currentExtraStackFrame = stack;\n }\n}\n\n{\n ReactDebugCurrentFrame.setExtraStackFrame = function (stack) {\n {\n currentExtraStackFrame = stack;\n }\n }; // Stack implementation injected by the current renderer.\n\n\n ReactDebugCurrentFrame.getCurrentStack = null;\n\n ReactDebugCurrentFrame.getStackAddendum = function () {\n var stack = ''; // Add an extra top frame while an element is being validated\n\n if (currentExtraStackFrame) {\n stack += currentExtraStackFrame;\n } // Delegate to the injected renderer-specific implementation\n\n\n var impl = ReactDebugCurrentFrame.getCurrentStack;\n\n if (impl) {\n stack += impl() || '';\n }\n\n return stack;\n };\n}\n\n// -----------------------------------------------------------------------------\n\nvar enableScopeAPI = false; // Experimental Create Event Handle API.\nvar enableCacheElement = false;\nvar enableTransitionTracing = false; // No known bugs, but needs performance testing\n\nvar enableLegacyHidden = false; // Enables unstable_avoidThisFallback feature in Fiber\n// stuff. Intended to enable React core members to more easily debug scheduling\n// issues in DEV builds.\n\nvar enableDebugTracing = false; // Track which Fiber(s) schedule render work.\n\nvar ReactSharedInternals = {\n ReactCurrentDispatcher: ReactCurrentDispatcher,\n ReactCurrentBatchConfig: ReactCurrentBatchConfig,\n ReactCurrentOwner: ReactCurrentOwner\n};\n\n{\n ReactSharedInternals.ReactDebugCurrentFrame = ReactDebugCurrentFrame;\n ReactSharedInternals.ReactCurrentActQueue = ReactCurrentActQueue;\n}\n\n// by calls to these methods by a Babel plugin.\n//\n// In PROD (or in packages without access to React internals),\n// they are left as they are instead.\n\nfunction warn(format) {\n {\n {\n for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {\n args[_key - 1] = arguments[_key];\n }\n\n printWarning('warn', format, args);\n }\n }\n}\nfunction error(format) {\n {\n {\n for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {\n args[_key2 - 1] = arguments[_key2];\n }\n\n printWarning('error', format, args);\n }\n }\n}\n\nfunction printWarning(level, format, args) {\n // When changing this logic, you might want to also\n // update consoleWithStackDev.www.js as well.\n {\n var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;\n var stack = ReactDebugCurrentFrame.getStackAddendum();\n\n if (stack !== '') {\n format += '%s';\n args = args.concat([stack]);\n } // eslint-disable-next-line react-internal/safe-string-coercion\n\n\n var argsWithFormat = args.map(function (item) {\n return String(item);\n }); // Careful: RN currently depends on this prefix\n\n argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it\n // breaks IE9: https://github.com/facebook/react/issues/13610\n // eslint-disable-next-line react-internal/no-production-logging\n\n Function.prototype.apply.call(console[level], console, argsWithFormat);\n }\n}\n\nvar didWarnStateUpdateForUnmountedComponent = {};\n\nfunction warnNoop(publicInstance, callerName) {\n {\n var _constructor = publicInstance.constructor;\n var componentName = _constructor && (_constructor.displayName || _constructor.name) || 'ReactClass';\n var warningKey = componentName + \".\" + callerName;\n\n if (didWarnStateUpdateForUnmountedComponent[warningKey]) {\n return;\n }\n\n error(\"Can't call %s on a component that is not yet mounted. \" + 'This is a no-op, but it might indicate a bug in your application. ' + 'Instead, assign to `this.state` directly or define a `state = {};` ' + 'class property with the desired state in the %s component.', callerName, componentName);\n\n didWarnStateUpdateForUnmountedComponent[warningKey] = true;\n }\n}\n/**\n * This is the abstract API for an update queue.\n */\n\n\nvar ReactNoopUpdateQueue = {\n /**\n * Checks whether or not this composite component is mounted.\n * @param {ReactClass} publicInstance The instance we want to test.\n * @return {boolean} True if mounted, false otherwise.\n * @protected\n * @final\n */\n isMounted: function (publicInstance) {\n return false;\n },\n\n /**\n * Forces an update. This should only be invoked when it is known with\n * certainty that we are **not** in a DOM transaction.\n *\n * You may want to call this when you know that some deeper aspect of the\n * component's state has changed but `setState` was not called.\n *\n * This will not invoke `shouldComponentUpdate`, but it will invoke\n * `componentWillUpdate` and `componentDidUpdate`.\n *\n * @param {ReactClass} publicInstance The instance that should rerender.\n * @param {?function} callback Called after component is updated.\n * @param {?string} callerName name of the calling function in the public API.\n * @internal\n */\n enqueueForceUpdate: function (publicInstance, callback, callerName) {\n warnNoop(publicInstance, 'forceUpdate');\n },\n\n /**\n * Replaces all of the state. Always use this or `setState` to mutate state.\n * You should treat `this.state` as immutable.\n *\n * There is no guarantee that `this.state` will be immediately updated, so\n * accessing `this.state` after calling this method may return the old value.\n *\n * @param {ReactClass} publicInstance The instance that should rerender.\n * @param {object} completeState Next state.\n * @param {?function} callback Called after component is updated.\n * @param {?string} callerName name of the calling function in the public API.\n * @internal\n */\n enqueueReplaceState: function (publicInstance, completeState, callback, callerName) {\n warnNoop(publicInstance, 'replaceState');\n },\n\n /**\n * Sets a subset of the state. This only exists because _pendingState is\n * internal. This provides a merging strategy that is not available to deep\n * properties which is confusing. TODO: Expose pendingState or don't use it\n * during the merge.\n *\n * @param {ReactClass} publicInstance The instance that should rerender.\n * @param {object} partialState Next partial state to be merged with state.\n * @param {?function} callback Called after component is updated.\n * @param {?string} Name of the calling function in the public API.\n * @internal\n */\n enqueueSetState: function (publicInstance, partialState, callback, callerName) {\n warnNoop(publicInstance, 'setState');\n }\n};\n\nvar assign = Object.assign;\n\nvar emptyObject = {};\n\n{\n Object.freeze(emptyObject);\n}\n/**\n * Base class helpers for the updating state of a component.\n */\n\n\nfunction Component(props, context, updater) {\n this.props = props;\n this.context = context; // If a component has string refs, we will assign a different object later.\n\n this.refs = emptyObject; // We initialize the default updater but the real one gets injected by the\n // renderer.\n\n this.updater = updater || ReactNoopUpdateQueue;\n}\n\nComponent.prototype.isReactComponent = {};\n/**\n * Sets a subset of the state. Always use this to mutate\n * state. You should treat `this.state` as immutable.\n *\n * There is no guarantee that `this.state` will be immediately updated, so\n * accessing `this.state` after calling this method may return the old value.\n *\n * There is no guarantee that calls to `setState` will run synchronously,\n * as they may eventually be batched together. You can provide an optional\n * callback that will be executed when the call to setState is actually\n * completed.\n *\n * When a function is provided to setState, it will be called at some point in\n * the future (not synchronously). It will be called with the up to date\n * component arguments (state, props, context). These values can be different\n * from this.* because your function may be called after receiveProps but before\n * shouldComponentUpdate, and this new state, props, and context will not yet be\n * assigned to this.\n *\n * @param {object|function} partialState Next partial state or function to\n * produce next partial state to be merged with current state.\n * @param {?function} callback Called after state is updated.\n * @final\n * @protected\n */\n\nComponent.prototype.setState = function (partialState, callback) {\n if (typeof partialState !== 'object' && typeof partialState !== 'function' && partialState != null) {\n throw new Error('setState(...): takes an object of state variables to update or a ' + 'function which returns an object of state variables.');\n }\n\n this.updater.enqueueSetState(this, partialState, callback, 'setState');\n};\n/**\n * Forces an update. This should only be invoked when it is known with\n * certainty that we are **not** in a DOM transaction.\n *\n * You may want to call this when you know that some deeper aspect of the\n * component's state has changed but `setState` was not called.\n *\n * This will not invoke `shouldComponentUpdate`, but it will invoke\n * `componentWillUpdate` and `componentDidUpdate`.\n *\n * @param {?function} callback Called after update is complete.\n * @final\n * @protected\n */\n\n\nComponent.prototype.forceUpdate = function (callback) {\n this.updater.enqueueForceUpdate(this, callback, 'forceUpdate');\n};\n/**\n * Deprecated APIs. These APIs used to exist on classic React classes but since\n * we would like to deprecate them, we're not going to move them over to this\n * modern base class. Instead, we define a getter that warns if it's accessed.\n */\n\n\n{\n var deprecatedAPIs = {\n isMounted: ['isMounted', 'Instead, make sure to clean up subscriptions and pending requests in ' + 'componentWillUnmount to prevent memory leaks.'],\n replaceState: ['replaceState', 'Refactor your code to use setState instead (see ' + 'https://github.com/facebook/react/issues/3236).']\n };\n\n var defineDeprecationWarning = function (methodName, info) {\n Object.defineProperty(Component.prototype, methodName, {\n get: function () {\n warn('%s(...) is deprecated in plain JavaScript React classes. %s', info[0], info[1]);\n\n return undefined;\n }\n });\n };\n\n for (var fnName in deprecatedAPIs) {\n if (deprecatedAPIs.hasOwnProperty(fnName)) {\n defineDeprecationWarning(fnName, deprecatedAPIs[fnName]);\n }\n }\n}\n\nfunction ComponentDummy() {}\n\nComponentDummy.prototype = Component.prototype;\n/**\n * Convenience component with default shallow equality check for sCU.\n */\n\nfunction PureComponent(props, context, updater) {\n this.props = props;\n this.context = context; // If a component has string refs, we will assign a different object later.\n\n this.refs = emptyObject;\n this.updater = updater || ReactNoopUpdateQueue;\n}\n\nvar pureComponentPrototype = PureComponent.prototype = new ComponentDummy();\npureComponentPrototype.constructor = PureComponent; // Avoid an extra prototype jump for these methods.\n\nassign(pureComponentPrototype, Component.prototype);\npureComponentPrototype.isPureReactComponent = true;\n\n// an immutable object with a single mutable value\nfunction createRef() {\n var refObject = {\n current: null\n };\n\n {\n Object.seal(refObject);\n }\n\n return refObject;\n}\n\nvar isArrayImpl = Array.isArray; // eslint-disable-next-line no-redeclare\n\nfunction isArray(a) {\n return isArrayImpl(a);\n}\n\n/*\n * The `'' + value` pattern (used in in perf-sensitive code) throws for Symbol\n * and Temporal.* types. See https://github.com/facebook/react/pull/22064.\n *\n * The functions in this module will throw an easier-to-understand,\n * easier-to-debug exception with a clear errors message message explaining the\n * problem. (Instead of a confusing exception thrown inside the implementation\n * of the `value` object).\n */\n// $FlowFixMe only called in DEV, so void return is not possible.\nfunction typeName(value) {\n {\n // toStringTag is needed for namespaced types like Temporal.Instant\n var hasToStringTag = typeof Symbol === 'function' && Symbol.toStringTag;\n var type = hasToStringTag && value[Symbol.toStringTag] || value.constructor.name || 'Object';\n return type;\n }\n} // $FlowFixMe only called in DEV, so void return is not possible.\n\n\nfunction willCoercionThrow(value) {\n {\n try {\n testStringCoercion(value);\n return false;\n } catch (e) {\n return true;\n }\n }\n}\n\nfunction testStringCoercion(value) {\n // If you ended up here by following an exception call stack, here's what's\n // happened: you supplied an object or symbol value to React (as a prop, key,\n // DOM attribute, CSS property, string ref, etc.) and when React tried to\n // coerce it to a string using `'' + value`, an exception was thrown.\n //\n // The most common types that will cause this exception are `Symbol` instances\n // and Temporal objects like `Temporal.Instant`. But any object that has a\n // `valueOf` or `[Symbol.toPrimitive]` method that throws will also cause this\n // exception. (Library authors do this to prevent users from using built-in\n // numeric operators like `+` or comparison operators like `>=` because custom\n // methods are needed to perform accurate arithmetic or comparison.)\n //\n // To fix the problem, coerce this object or symbol value to a string before\n // passing it to React. The most reliable way is usually `String(value)`.\n //\n // To find which value is throwing, check the browser or debugger console.\n // Before this exception was thrown, there should be `console.error` output\n // that shows the type (Symbol, Temporal.PlainDate, etc.) that caused the\n // problem and how that type was used: key, atrribute, input value prop, etc.\n // In most cases, this console output also shows the component and its\n // ancestor components where the exception happened.\n //\n // eslint-disable-next-line react-internal/safe-string-coercion\n return '' + value;\n}\nfunction checkKeyStringCoercion(value) {\n {\n if (willCoercionThrow(value)) {\n error('The provided key is an unsupported type %s.' + ' This value must be coerced to a string before before using it here.', typeName(value));\n\n return testStringCoercion(value); // throw (to help callers find troubleshooting comments)\n }\n }\n}\n\nfunction getWrappedName(outerType, innerType, wrapperName) {\n var displayName = outerType.displayName;\n\n if (displayName) {\n return displayName;\n }\n\n var functionName = innerType.displayName || innerType.name || '';\n return functionName !== '' ? wrapperName + \"(\" + functionName + \")\" : wrapperName;\n} // Keep in sync with react-reconciler/getComponentNameFromFiber\n\n\nfunction getContextName(type) {\n return type.displayName || 'Context';\n} // Note that the reconciler package should generally prefer to use getComponentNameFromFiber() instead.\n\n\nfunction getComponentNameFromType(type) {\n if (type == null) {\n // Host root, text node or just invalid type.\n return null;\n }\n\n {\n if (typeof type.tag === 'number') {\n error('Received an unexpected object in getComponentNameFromType(). ' + 'This is likely a bug in React. Please file an issue.');\n }\n }\n\n if (typeof type === 'function') {\n return type.displayName || type.name || null;\n }\n\n if (typeof type === 'string') {\n return type;\n }\n\n switch (type) {\n case REACT_FRAGMENT_TYPE:\n return 'Fragment';\n\n case REACT_PORTAL_TYPE:\n return 'Portal';\n\n case REACT_PROFILER_TYPE:\n return 'Profiler';\n\n case REACT_STRICT_MODE_TYPE:\n return 'StrictMode';\n\n case REACT_SUSPENSE_TYPE:\n return 'Suspense';\n\n case REACT_SUSPENSE_LIST_TYPE:\n return 'SuspenseList';\n\n }\n\n if (typeof type === 'object') {\n switch (type.$$typeof) {\n case REACT_CONTEXT_TYPE:\n var context = type;\n return getContextName(context) + '.Consumer';\n\n case REACT_PROVIDER_TYPE:\n var provider = type;\n return getContextName(provider._context) + '.Provider';\n\n case REACT_FORWARD_REF_TYPE:\n return getWrappedName(type, type.render, 'ForwardRef');\n\n case REACT_MEMO_TYPE:\n var outerName = type.displayName || null;\n\n if (outerName !== null) {\n return outerName;\n }\n\n return getComponentNameFromType(type.type) || 'Memo';\n\n case REACT_LAZY_TYPE:\n {\n var lazyComponent = type;\n var payload = lazyComponent._payload;\n var init = lazyComponent._init;\n\n try {\n return getComponentNameFromType(init(payload));\n } catch (x) {\n return null;\n }\n }\n\n // eslint-disable-next-line no-fallthrough\n }\n }\n\n return null;\n}\n\nvar hasOwnProperty = Object.prototype.hasOwnProperty;\n\nvar RESERVED_PROPS = {\n key: true,\n ref: true,\n __self: true,\n __source: true\n};\nvar specialPropKeyWarningShown, specialPropRefWarningShown, didWarnAboutStringRefs;\n\n{\n didWarnAboutStringRefs = {};\n}\n\nfunction hasValidRef(config) {\n {\n if (hasOwnProperty.call(config, 'ref')) {\n var getter = Object.getOwnPropertyDescriptor(config, 'ref').get;\n\n if (getter && getter.isReactWarning) {\n return false;\n }\n }\n }\n\n return config.ref !== undefined;\n}\n\nfunction hasValidKey(config) {\n {\n if (hasOwnProperty.call(config, 'key')) {\n var getter = Object.getOwnPropertyDescriptor(config, 'key').get;\n\n if (getter && getter.isReactWarning) {\n return false;\n }\n }\n }\n\n return config.key !== undefined;\n}\n\nfunction defineKeyPropWarningGetter(props, displayName) {\n var warnAboutAccessingKey = function () {\n {\n if (!specialPropKeyWarningShown) {\n specialPropKeyWarningShown = true;\n\n 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);\n }\n }\n };\n\n warnAboutAccessingKey.isReactWarning = true;\n Object.defineProperty(props, 'key', {\n get: warnAboutAccessingKey,\n configurable: true\n });\n}\n\nfunction defineRefPropWarningGetter(props, displayName) {\n var warnAboutAccessingRef = function () {\n {\n if (!specialPropRefWarningShown) {\n specialPropRefWarningShown = true;\n\n 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);\n }\n }\n };\n\n warnAboutAccessingRef.isReactWarning = true;\n Object.defineProperty(props, 'ref', {\n get: warnAboutAccessingRef,\n configurable: true\n });\n}\n\nfunction warnIfStringRefCannotBeAutoConverted(config) {\n {\n if (typeof config.ref === 'string' && ReactCurrentOwner.current && config.__self && ReactCurrentOwner.current.stateNode !== config.__self) {\n var componentName = getComponentNameFromType(ReactCurrentOwner.current.type);\n\n if (!didWarnAboutStringRefs[componentName]) {\n 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', componentName, config.ref);\n\n didWarnAboutStringRefs[componentName] = true;\n }\n }\n }\n}\n/**\n * Factory method to create a new React element. This no longer adheres to\n * the class pattern, so do not use new to call it. Also, instanceof check\n * will not work. Instead test $$typeof field against Symbol.for('react.element') to check\n * if something is a React Element.\n *\n * @param {*} type\n * @param {*} props\n * @param {*} key\n * @param {string|object} ref\n * @param {*} owner\n * @param {*} self A *temporary* helper to detect places where `this` is\n * different from the `owner` when React.createElement is called, so that we\n * can warn. We want to get rid of owner and replace string `ref`s with arrow\n * functions, and as long as `this` and owner are the same, there will be no\n * change in behavior.\n * @param {*} source An annotation object (added by a transpiler or otherwise)\n * indicating filename, line number, and/or other information.\n * @internal\n */\n\n\nvar ReactElement = function (type, key, ref, self, source, owner, props) {\n var element = {\n // This tag allows us to uniquely identify this as a React Element\n $$typeof: REACT_ELEMENT_TYPE,\n // Built-in properties that belong on the element\n type: type,\n key: key,\n ref: ref,\n props: props,\n // Record the component responsible for creating this element.\n _owner: owner\n };\n\n {\n // The validation flag is currently mutative. We put it on\n // an external backing store so that we can freeze the whole object.\n // This can be replaced with a WeakMap once they are implemented in\n // commonly used development environments.\n element._store = {}; // To make comparing ReactElements easier for testing purposes, we make\n // the validation flag non-enumerable (where possible, which should\n // include every environment we run tests in), so the test framework\n // ignores it.\n\n Object.defineProperty(element._store, 'validated', {\n configurable: false,\n enumerable: false,\n writable: true,\n value: false\n }); // self and source are DEV only properties.\n\n Object.defineProperty(element, '_self', {\n configurable: false,\n enumerable: false,\n writable: false,\n value: self\n }); // Two elements created in two different places should be considered\n // equal for testing purposes and therefore we hide it from enumeration.\n\n Object.defineProperty(element, '_source', {\n configurable: false,\n enumerable: false,\n writable: false,\n value: source\n });\n\n if (Object.freeze) {\n Object.freeze(element.props);\n Object.freeze(element);\n }\n }\n\n return element;\n};\n/**\n * Create and return a new ReactElement of the given type.\n * See https://reactjs.org/docs/react-api.html#createelement\n */\n\nfunction createElement(type, config, children) {\n var propName; // Reserved names are extracted\n\n var props = {};\n var key = null;\n var ref = null;\n var self = null;\n var source = null;\n\n if (config != null) {\n if (hasValidRef(config)) {\n ref = config.ref;\n\n {\n warnIfStringRefCannotBeAutoConverted(config);\n }\n }\n\n if (hasValidKey(config)) {\n {\n checkKeyStringCoercion(config.key);\n }\n\n key = '' + config.key;\n }\n\n self = config.__self === undefined ? null : config.__self;\n source = config.__source === undefined ? null : config.__source; // Remaining properties are added to a new props object\n\n for (propName in config) {\n if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) {\n props[propName] = config[propName];\n }\n }\n } // Children can be more than one argument, and those are transferred onto\n // the newly allocated props object.\n\n\n var childrenLength = arguments.length - 2;\n\n if (childrenLength === 1) {\n props.children = children;\n } else if (childrenLength > 1) {\n var childArray = Array(childrenLength);\n\n for (var i = 0; i < childrenLength; i++) {\n childArray[i] = arguments[i + 2];\n }\n\n {\n if (Object.freeze) {\n Object.freeze(childArray);\n }\n }\n\n props.children = childArray;\n } // Resolve default props\n\n\n if (type && type.defaultProps) {\n var defaultProps = type.defaultProps;\n\n for (propName in defaultProps) {\n if (props[propName] === undefined) {\n props[propName] = defaultProps[propName];\n }\n }\n }\n\n {\n if (key || ref) {\n var displayName = typeof type === 'function' ? type.displayName || type.name || 'Unknown' : type;\n\n if (key) {\n defineKeyPropWarningGetter(props, displayName);\n }\n\n if (ref) {\n defineRefPropWarningGetter(props, displayName);\n }\n }\n }\n\n return ReactElement(type, key, ref, self, source, ReactCurrentOwner.current, props);\n}\nfunction cloneAndReplaceKey(oldElement, newKey) {\n var newElement = ReactElement(oldElement.type, newKey, oldElement.ref, oldElement._self, oldElement._source, oldElement._owner, oldElement.props);\n return newElement;\n}\n/**\n * Clone and return a new ReactElement using element as the starting point.\n * See https://reactjs.org/docs/react-api.html#cloneelement\n */\n\nfunction cloneElement(element, config, children) {\n if (element === null || element === undefined) {\n throw new Error(\"React.cloneElement(...): The argument must be a React element, but you passed \" + element + \".\");\n }\n\n var propName; // Original props are copied\n\n var props = assign({}, element.props); // Reserved names are extracted\n\n var key = element.key;\n var ref = element.ref; // Self is preserved since the owner is preserved.\n\n var self = element._self; // Source is preserved since cloneElement is unlikely to be targeted by a\n // transpiler, and the original source is probably a better indicator of the\n // true owner.\n\n var source = element._source; // Owner will be preserved, unless ref is overridden\n\n var owner = element._owner;\n\n if (config != null) {\n if (hasValidRef(config)) {\n // Silently steal the ref from the parent.\n ref = config.ref;\n owner = ReactCurrentOwner.current;\n }\n\n if (hasValidKey(config)) {\n {\n checkKeyStringCoercion(config.key);\n }\n\n key = '' + config.key;\n } // Remaining properties override existing props\n\n\n var defaultProps;\n\n if (element.type && element.type.defaultProps) {\n defaultProps = element.type.defaultProps;\n }\n\n for (propName in config) {\n if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) {\n if (config[propName] === undefined && defaultProps !== undefined) {\n // Resolve default props\n props[propName] = defaultProps[propName];\n } else {\n props[propName] = config[propName];\n }\n }\n }\n } // Children can be more than one argument, and those are transferred onto\n // the newly allocated props object.\n\n\n var childrenLength = arguments.length - 2;\n\n if (childrenLength === 1) {\n props.children = children;\n } else if (childrenLength > 1) {\n var childArray = Array(childrenLength);\n\n for (var i = 0; i < childrenLength; i++) {\n childArray[i] = arguments[i + 2];\n }\n\n props.children = childArray;\n }\n\n return ReactElement(element.type, key, ref, self, source, owner, props);\n}\n/**\n * Verifies the object is a ReactElement.\n * See https://reactjs.org/docs/react-api.html#isvalidelement\n * @param {?object} object\n * @return {boolean} True if `object` is a ReactElement.\n * @final\n */\n\nfunction isValidElement(object) {\n return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE;\n}\n\nvar SEPARATOR = '.';\nvar SUBSEPARATOR = ':';\n/**\n * Escape and wrap key so it is safe to use as a reactid\n *\n * @param {string} key to be escaped.\n * @return {string} the escaped key.\n */\n\nfunction escape(key) {\n var escapeRegex = /[=:]/g;\n var escaperLookup = {\n '=': '=0',\n ':': '=2'\n };\n var escapedString = key.replace(escapeRegex, function (match) {\n return escaperLookup[match];\n });\n return '$' + escapedString;\n}\n/**\n * TODO: Test that a single child and an array with one item have the same key\n * pattern.\n */\n\n\nvar didWarnAboutMaps = false;\nvar userProvidedKeyEscapeRegex = /\\/+/g;\n\nfunction escapeUserProvidedKey(text) {\n return text.replace(userProvidedKeyEscapeRegex, '$&/');\n}\n/**\n * Generate a key string that identifies a element within a set.\n *\n * @param {*} element A element that could contain a manual key.\n * @param {number} index Index that is used if a manual key is not provided.\n * @return {string}\n */\n\n\nfunction getElementKey(element, index) {\n // Do some typechecking here since we call this blindly. We want to ensure\n // that we don't block potential future ES APIs.\n if (typeof element === 'object' && element !== null && element.key != null) {\n // Explicit key\n {\n checkKeyStringCoercion(element.key);\n }\n\n return escape('' + element.key);\n } // Implicit key determined by the index in the set\n\n\n return index.toString(36);\n}\n\nfunction mapIntoArray(children, array, escapedPrefix, nameSoFar, callback) {\n var type = typeof children;\n\n if (type === 'undefined' || type === 'boolean') {\n // All of the above are perceived as null.\n children = null;\n }\n\n var invokeCallback = false;\n\n if (children === null) {\n invokeCallback = true;\n } else {\n switch (type) {\n case 'string':\n case 'number':\n invokeCallback = true;\n break;\n\n case 'object':\n switch (children.$$typeof) {\n case REACT_ELEMENT_TYPE:\n case REACT_PORTAL_TYPE:\n invokeCallback = true;\n }\n\n }\n }\n\n if (invokeCallback) {\n var _child = children;\n var mappedChild = callback(_child); // If it's the only child, treat the name as if it was wrapped in an array\n // so that it's consistent if the number of children grows:\n\n var childKey = nameSoFar === '' ? SEPARATOR + getElementKey(_child, 0) : nameSoFar;\n\n if (isArray(mappedChild)) {\n var escapedChildKey = '';\n\n if (childKey != null) {\n escapedChildKey = escapeUserProvidedKey(childKey) + '/';\n }\n\n mapIntoArray(mappedChild, array, escapedChildKey, '', function (c) {\n return c;\n });\n } else if (mappedChild != null) {\n if (isValidElement(mappedChild)) {\n {\n // The `if` statement here prevents auto-disabling of the safe\n // coercion ESLint rule, so we must manually disable it below.\n // $FlowFixMe Flow incorrectly thinks React.Portal doesn't have a key\n if (mappedChild.key && (!_child || _child.key !== mappedChild.key)) {\n checkKeyStringCoercion(mappedChild.key);\n }\n }\n\n mappedChild = cloneAndReplaceKey(mappedChild, // Keep both the (mapped) and old keys if they differ, just as\n // traverseAllChildren used to do for objects as children\n escapedPrefix + ( // $FlowFixMe Flow incorrectly thinks React.Portal doesn't have a key\n mappedChild.key && (!_child || _child.key !== mappedChild.key) ? // $FlowFixMe Flow incorrectly thinks existing element's key can be a number\n // eslint-disable-next-line react-internal/safe-string-coercion\n escapeUserProvidedKey('' + mappedChild.key) + '/' : '') + childKey);\n }\n\n array.push(mappedChild);\n }\n\n return 1;\n }\n\n var child;\n var nextName;\n var subtreeCount = 0; // Count of children found in the current subtree.\n\n var nextNamePrefix = nameSoFar === '' ? SEPARATOR : nameSoFar + SUBSEPARATOR;\n\n if (isArray(children)) {\n for (var i = 0; i < children.length; i++) {\n child = children[i];\n nextName = nextNamePrefix + getElementKey(child, i);\n subtreeCount += mapIntoArray(child, array, escapedPrefix, nextName, callback);\n }\n } else {\n var iteratorFn = getIteratorFn(children);\n\n if (typeof iteratorFn === 'function') {\n var iterableChildren = children;\n\n {\n // Warn about using Maps as children\n if (iteratorFn === iterableChildren.entries) {\n if (!didWarnAboutMaps) {\n warn('Using Maps as children is not supported. ' + 'Use an array of keyed ReactElements instead.');\n }\n\n didWarnAboutMaps = true;\n }\n }\n\n var iterator = iteratorFn.call(iterableChildren);\n var step;\n var ii = 0;\n\n while (!(step = iterator.next()).done) {\n child = step.value;\n nextName = nextNamePrefix + getElementKey(child, ii++);\n subtreeCount += mapIntoArray(child, array, escapedPrefix, nextName, callback);\n }\n } else if (type === 'object') {\n // eslint-disable-next-line react-internal/safe-string-coercion\n var childrenString = String(children);\n throw new Error(\"Objects are not valid as a React child (found: \" + (childrenString === '[object Object]' ? 'object with keys {' + Object.keys(children).join(', ') + '}' : childrenString) + \"). \" + 'If you meant to render a collection of children, use an array ' + 'instead.');\n }\n }\n\n return subtreeCount;\n}\n\n/**\n * Maps children that are typically specified as `props.children`.\n *\n * See https://reactjs.org/docs/react-api.html#reactchildrenmap\n *\n * The provided mapFunction(child, index) will be called for each\n * leaf child.\n *\n * @param {?*} children Children tree container.\n * @param {function(*, int)} func The map function.\n * @param {*} context Context for mapFunction.\n * @return {object} Object containing the ordered map of results.\n */\nfunction mapChildren(children, func, context) {\n if (children == null) {\n return children;\n }\n\n var result = [];\n var count = 0;\n mapIntoArray(children, result, '', '', function (child) {\n return func.call(context, child, count++);\n });\n return result;\n}\n/**\n * Count the number of children that are typically specified as\n * `props.children`.\n *\n * See https://reactjs.org/docs/react-api.html#reactchildrencount\n *\n * @param {?*} children Children tree container.\n * @return {number} The number of children.\n */\n\n\nfunction countChildren(children) {\n var n = 0;\n mapChildren(children, function () {\n n++; // Don't return anything\n });\n return n;\n}\n\n/**\n * Iterates through children that are typically specified as `props.children`.\n *\n * See https://reactjs.org/docs/react-api.html#reactchildrenforeach\n *\n * The provided forEachFunc(child, index) will be called for each\n * leaf child.\n *\n * @param {?*} children Children tree container.\n * @param {function(*, int)} forEachFunc\n * @param {*} forEachContext Context for forEachContext.\n */\nfunction forEachChildren(children, forEachFunc, forEachContext) {\n mapChildren(children, function () {\n forEachFunc.apply(this, arguments); // Don't return anything.\n }, forEachContext);\n}\n/**\n * Flatten a children object (typically specified as `props.children`) and\n * return an array with appropriately re-keyed children.\n *\n * See https://reactjs.org/docs/react-api.html#reactchildrentoarray\n */\n\n\nfunction toArray(children) {\n return mapChildren(children, function (child) {\n return child;\n }) || [];\n}\n/**\n * Returns the first child in a collection of children and verifies that there\n * is only one child in the collection.\n *\n * See https://reactjs.org/docs/react-api.html#reactchildrenonly\n *\n * The current implementation of this function assumes that a single child gets\n * passed without a wrapper, but the purpose of this helper function is to\n * abstract away the particular structure of children.\n *\n * @param {?object} children Child collection structure.\n * @return {ReactElement} The first and only `ReactElement` contained in the\n * structure.\n */\n\n\nfunction onlyChild(children) {\n if (!isValidElement(children)) {\n throw new Error('React.Children.only expected to receive a single React element child.');\n }\n\n return children;\n}\n\nfunction createContext(defaultValue) {\n // TODO: Second argument used to be an optional `calculateChangedBits`\n // function. Warn to reserve for future use?\n var context = {\n $$typeof: REACT_CONTEXT_TYPE,\n // As a workaround to support multiple concurrent renderers, we categorize\n // some renderers as primary and others as secondary. We only expect\n // there to be two concurrent renderers at most: React Native (primary) and\n // Fabric (secondary); React DOM (primary) and React ART (secondary).\n // Secondary renderers store their context values on separate fields.\n _currentValue: defaultValue,\n _currentValue2: defaultValue,\n // Used to track how many concurrent renderers this context currently\n // supports within in a single renderer. Such as parallel server rendering.\n _threadCount: 0,\n // These are circular\n Provider: null,\n Consumer: null,\n // Add these to use same hidden class in VM as ServerContext\n _defaultValue: null,\n _globalName: null\n };\n context.Provider = {\n $$typeof: REACT_PROVIDER_TYPE,\n _context: context\n };\n var hasWarnedAboutUsingNestedContextConsumers = false;\n var hasWarnedAboutUsingConsumerProvider = false;\n var hasWarnedAboutDisplayNameOnConsumer = false;\n\n {\n // A separate object, but proxies back to the original context object for\n // backwards compatibility. It has a different $$typeof, so we can properly\n // warn for the incorrect usage of Context as a Consumer.\n var Consumer = {\n $$typeof: REACT_CONTEXT_TYPE,\n _context: context\n }; // $FlowFixMe: Flow complains about not setting a value, which is intentional here\n\n Object.defineProperties(Consumer, {\n Provider: {\n get: function () {\n if (!hasWarnedAboutUsingConsumerProvider) {\n hasWarnedAboutUsingConsumerProvider = true;\n\n error('Rendering <Context.Consumer.Provider> is not supported and will be removed in ' + 'a future major release. Did you mean to render <Context.Provider> instead?');\n }\n\n return context.Provider;\n },\n set: function (_Provider) {\n context.Provider = _Provider;\n }\n },\n _currentValue: {\n get: function () {\n return context._currentValue;\n },\n set: function (_currentValue) {\n context._currentValue = _currentValue;\n }\n },\n _currentValue2: {\n get: function () {\n return context._currentValue2;\n },\n set: function (_currentValue2) {\n context._currentValue2 = _currentValue2;\n }\n },\n _threadCount: {\n get: function () {\n return context._threadCount;\n },\n set: function (_threadCount) {\n context._threadCount = _threadCount;\n }\n },\n Consumer: {\n get: function () {\n if (!hasWarnedAboutUsingNestedContextConsumers) {\n hasWarnedAboutUsingNestedContextConsumers = true;\n\n error('Rendering <Context.Consumer.Consumer> is not supported and will be removed in ' + 'a future major release. Did you mean to render <Context.Consumer> instead?');\n }\n\n return context.Consumer;\n }\n },\n displayName: {\n get: function () {\n return context.displayName;\n },\n set: function (displayName) {\n if (!hasWarnedAboutDisplayNameOnConsumer) {\n warn('Setting `displayName` on Context.Consumer has no effect. ' + \"You should set it directly on the context with Context.displayName = '%s'.\", displayName);\n\n hasWarnedAboutDisplayNameOnConsumer = true;\n }\n }\n }\n }); // $FlowFixMe: Flow complains about missing properties because it doesn't understand defineProperty\n\n context.Consumer = Consumer;\n }\n\n {\n context._currentRenderer = null;\n context._currentRenderer2 = null;\n }\n\n return context;\n}\n\nvar Uninitialized = -1;\nvar Pending = 0;\nvar Resolved = 1;\nvar Rejected = 2;\n\nfunction lazyInitializer(payload) {\n if (payload._status === Uninitialized) {\n var ctor = payload._result;\n var thenable = ctor(); // Transition to the next state.\n // This might throw either because it's missing or throws. If so, we treat it\n // as still uninitialized and try again next time. Which is the same as what\n // happens if the ctor or any wrappers processing the ctor throws. This might\n // end up fixing it if the resolution was a concurrency bug.\n\n thenable.then(function (moduleObject) {\n if (payload._status === Pending || payload._status === Uninitialized) {\n // Transition to the next state.\n var resolved = payload;\n resolved._status = Resolved;\n resolved._result = moduleObject;\n }\n }, function (error) {\n if (payload._status === Pending || payload._status === Uninitialized) {\n // Transition to the next state.\n var rejected = payload;\n rejected._status = Rejected;\n rejected._result = error;\n }\n });\n\n if (payload._status === Uninitialized) {\n // In case, we're still uninitialized, then we're waiting for the thenable\n // to resolve. Set it as pending in the meantime.\n var pending = payload;\n pending._status = Pending;\n pending._result = thenable;\n }\n }\n\n if (payload._status === Resolved) {\n var moduleObject = payload._result;\n\n {\n if (moduleObject === undefined) {\n error('lazy: Expected the result of a dynamic imp' + 'ort() call. ' + 'Instead received: %s\\n\\nYour code should look like: \\n ' + // Break up imports to avoid accidentally parsing them as dependencies.\n 'const MyComponent = lazy(() => imp' + \"ort('./MyComponent'))\\n\\n\" + 'Did you accidentally put curly braces around the import?', moduleObject);\n }\n }\n\n {\n if (!('default' in moduleObject)) {\n error('lazy: Expected the result of a dynamic imp' + 'ort() call. ' + 'Instead received: %s\\n\\nYour code should look like: \\n ' + // Break up imports to avoid accidentally parsing them as dependencies.\n 'const MyComponent = lazy(() => imp' + \"ort('./MyComponent'))\", moduleObject);\n }\n }\n\n return moduleObject.default;\n } else {\n throw payload._result;\n }\n}\n\nfunction lazy(ctor) {\n var payload = {\n // We use these fields to store the result.\n _status: Uninitialized,\n _result: ctor\n };\n var lazyType = {\n $$typeof: REACT_LAZY_TYPE,\n _payload: payload,\n _init: lazyInitializer\n };\n\n {\n // In production, this would just set it on the object.\n var defaultProps;\n var propTypes; // $FlowFixMe\n\n Object.defineProperties(lazyType, {\n defaultProps: {\n configurable: true,\n get: function () {\n return defaultProps;\n },\n set: function (newDefaultProps) {\n error('React.lazy(...): It is not supported to assign `defaultProps` to ' + 'a lazy component import. Either specify them where the component ' + 'is defined, or create a wrapping component around it.');\n\n defaultProps = newDefaultProps; // Match production behavior more closely:\n // $FlowFixMe\n\n Object.defineProperty(lazyType, 'defaultProps', {\n enumerable: true\n });\n }\n },\n propTypes: {\n configurable: true,\n get: function () {\n return propTypes;\n },\n set: function (newPropTypes) {\n error('React.lazy(...): It is not supported to assign `propTypes` to ' + 'a lazy component import. Either specify them where the component ' + 'is defined, or create a wrapping component around it.');\n\n propTypes = newPropTypes; // Match production behavior more closely:\n // $FlowFixMe\n\n Object.defineProperty(lazyType, 'propTypes', {\n enumerable: true\n });\n }\n }\n });\n }\n\n return lazyType;\n}\n\nfunction forwardRef(render) {\n {\n if (render != null && render.$$typeof === REACT_MEMO_TYPE) {\n error('forwardRef requires a render function but received a `memo` ' + 'component. Instead of forwardRef(memo(...)), use ' + 'memo(forwardRef(...)).');\n } else if (typeof render !== 'function') {\n error('forwardRef requires a render function but was given %s.', render === null ? 'null' : typeof render);\n } else {\n if (render.length !== 0 && render.length !== 2) {\n error('forwardRef render functions accept exactly two parameters: props and ref. %s', render.length === 1 ? 'Did you forget to use the ref parameter?' : 'Any additional parameter will be undefined.');\n }\n }\n\n if (render != null) {\n if (render.defaultProps != null || render.propTypes != null) {\n error('forwardRef render functions do not support propTypes or defaultProps. ' + 'Did you accidentally pass a React component?');\n }\n }\n }\n\n var elementType = {\n $$typeof: REACT_FORWARD_REF_TYPE,\n render: render\n };\n\n {\n var ownName;\n Object.defineProperty(elementType, 'displayName', {\n enumerable: false,\n configurable: true,\n get: function () {\n return ownName;\n },\n set: function (name) {\n ownName = name; // The inner component shouldn't inherit this display name in most cases,\n // because the component may be used elsewhere.\n // But it's nice for anonymous functions to inherit the name,\n // so that our component-stack generation logic will display their frames.\n // An anonymous function generally suggests a pattern like:\n // React.forwardRef((props, ref) => {...});\n // This kind of inner function is not used elsewhere so the side effect is okay.\n\n if (!render.name && !render.displayName) {\n render.displayName = name;\n }\n }\n });\n }\n\n return elementType;\n}\n\nvar REACT_MODULE_REFERENCE;\n\n{\n REACT_MODULE_REFERENCE = Symbol.for('react.module.reference');\n}\n\nfunction isValidElementType(type) {\n if (typeof type === 'string' || typeof type === 'function') {\n return true;\n } // Note: typeof might be other than 'symbol' or 'number' (e.g. if it's a polyfill).\n\n\n 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 ) {\n return true;\n }\n\n if (typeof type === 'object' && type !== null) {\n 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\n // types supported by any Flight configuration anywhere since\n // we don't know which Flight build this will end up being used\n // with.\n type.$$typeof === REACT_MODULE_REFERENCE || type.getModuleId !== undefined) {\n return true;\n }\n }\n\n return false;\n}\n\nfunction memo(type, compare) {\n {\n if (!isValidElementType(type)) {\n error('memo: The first argument must be a component. Instead ' + 'received: %s', type === null ? 'null' : typeof type);\n }\n }\n\n var elementType = {\n $$typeof: REACT_MEMO_TYPE,\n type: type,\n compare: compare === undefined ? null : compare\n };\n\n {\n var ownName;\n Object.defineProperty(elementType, 'displayName', {\n enumerable: false,\n configurable: true,\n get: function () {\n return ownName;\n },\n set: function (name) {\n ownName = name; // The inner component shouldn't inherit this display name in most cases,\n // because the component may be used elsewhere.\n // But it's nice for anonymous functions to inherit the name,\n // so that our component-stack generation logic will display their frames.\n // An anonymous function generally suggests a pattern like:\n // React.memo((props) => {...});\n // This kind of inner function is not used elsewhere so the side effect is okay.\n\n if (!type.name && !type.displayName) {\n type.displayName = name;\n }\n }\n });\n }\n\n return elementType;\n}\n\nfunction resolveDispatcher() {\n var dispatcher = ReactCurrentDispatcher.current;\n\n {\n if (dispatcher === null) {\n error('Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for' + ' one of the following reasons:\\n' + '1. You might have mismatching versions of React and the renderer (such as React DOM)\\n' + '2. You might be breaking the Rules of Hooks\\n' + '3. You might have more than one copy of React in the same app\\n' + 'See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.');\n }\n } // Will result in a null access error if accessed outside render phase. We\n // intentionally don't throw our own error because this is in a hot path.\n // Also helps ensure this is inlined.\n\n\n return dispatcher;\n}\nfunction useContext(Context) {\n var dispatcher = resolveDispatcher();\n\n {\n // TODO: add a more generic warning for invalid values.\n if (Context._context !== undefined) {\n var realContext = Context._context; // Don't deduplicate because this legitimately causes bugs\n // and nobody should be using this in existing code.\n\n if (realContext.Consumer === Context) {\n error('Calling useContext(Context.Consumer) is not supported, may cause bugs, and will be ' + 'removed in a future major release. Did you mean to call useContext(Context) instead?');\n } else if (realContext.Provider === Context) {\n error('Calling useContext(Context.Provider) is not supported. ' + 'Did you mean to call useContext(Context) instead?');\n }\n }\n }\n\n return dispatcher.useContext(Context);\n}\nfunction useState(initialState) {\n var dispatcher = resolveDispatcher();\n return dispatcher.useState(initialState);\n}\nfunction useReducer(reducer, initialArg, init) {\n var dispatcher = resolveDispatcher();\n return dispatcher.useReducer(reducer, initialArg, init);\n}\nfunction useRef(initialValue) {\n var dispatcher = resolveDispatcher();\n return dispatcher.useRef(initialValue);\n}\nfunction useEffect(create, deps) {\n var dispatcher = resolveDispatcher();\n return dispatcher.useEffect(create, deps);\n}\nfunction useInsertionEffect(create, deps) {\n var dispatcher = resolveDispatcher();\n return dispatcher.useInsertionEffect(create, deps);\n}\nfunction useLayoutEffect(create, deps) {\n var dispatcher = resolveDispatcher();\n return dispatcher.useLayoutEffect(create, deps);\n}\nfunction useCallback(callback, deps) {\n var dispatcher = resolveDispatcher();\n return dispatcher.useCallback(callback, deps);\n}\nfunction useMemo(create, deps) {\n var dispatcher = resolveDispatcher();\n return dispatcher.useMemo(create, deps);\n}\nfunction useImperativeHandle(ref, create, deps) {\n var dispatcher = resolveDispatcher();\n return dispatcher.useImperativeHandle(ref, create, deps);\n}\nfunction useDebugValue(value, formatterFn) {\n {\n var dispatcher = resolveDispatcher();\n return dispatcher.useDebugValue(value, formatterFn);\n }\n}\nfunction useTransition() {\n var dispatcher = resolveDispatcher();\n return dispatcher.useTransition();\n}\nfunction useDeferredValue(value) {\n var dispatcher = resolveDispatcher();\n return dispatcher.useDeferredValue(value);\n}\nfunction useId() {\n var dispatcher = resolveDispatcher();\n return dispatcher.useId();\n}\nfunction useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) {\n var dispatcher = resolveDispatcher();\n return dispatcher.useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);\n}\n\n// Helpers to patch console.logs to avoid logging during side-effect free\n// replaying on render function. This currently only patches the object\n// lazily which won't cover if the log function was extracted eagerly.\n// We could also eagerly patch the method.\nvar disabledDepth = 0;\nvar prevLog;\nvar prevInfo;\nvar prevWarn;\nvar prevError;\nvar prevGroup;\nvar prevGroupCollapsed;\nvar prevGroupEnd;\n\nfunction disabledLog() {}\n\ndisabledLog.__reactDisabledLog = true;\nfunction disableLogs() {\n {\n if (disabledDepth === 0) {\n /* eslint-disable react-internal/no-production-logging */\n prevLog = console.log;\n prevInfo = console.info;\n prevWarn = console.warn;\n prevError = console.error;\n prevGroup = console.group;\n prevGroupCollapsed = console.groupCollapsed;\n prevGroupEnd = console.groupEnd; // https://github.com/facebook/react/issues/19099\n\n var props = {\n configurable: true,\n enumerable: true,\n value: disabledLog,\n writable: true\n }; // $FlowFixMe Flow thinks console is immutable.\n\n Object.defineProperties(console, {\n info: props,\n log: props,\n warn: props,\n error: props,\n group: props,\n groupCollapsed: props,\n groupEnd: props\n });\n /* eslint-enable react-internal/no-production-logging */\n }\n\n disabledDepth++;\n }\n}\nfunction reenableLogs() {\n {\n disabledDepth--;\n\n if (disabledDepth === 0) {\n /* eslint-disable react-internal/no-production-logging */\n var props = {\n configurable: true,\n enumerable: true,\n writable: true\n }; // $FlowFixMe Flow thinks console is immutable.\n\n Object.defineProperties(console, {\n log: assign({}, props, {\n value: prevLog\n }),\n info: assign({}, props, {\n value: prevInfo\n }),\n warn: assign({}, props, {\n value: prevWarn\n }),\n error: assign({}, props, {\n value: prevError\n }),\n group: assign({}, props, {\n value: prevGroup\n }),\n groupCollapsed: assign({}, props, {\n value: prevGroupCollapsed\n }),\n groupEnd: assign({}, props, {\n value: prevGroupEnd\n })\n });\n /* eslint-enable react-internal/no-production-logging */\n }\n\n if (disabledDepth < 0) {\n error('disabledDepth fell below zero. ' + 'This is a bug in React. Please file an issue.');\n }\n }\n}\n\nvar ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher;\nvar prefix;\nfunction describeBuiltInComponentFrame(name, source, ownerFn) {\n {\n if (prefix === undefined) {\n // Extract the VM specific prefix used by each line.\n try {\n throw Error();\n } catch (x) {\n var match = x.stack.trim().match(/\\n( *(at )?)/);\n prefix = match && match[1] || '';\n }\n } // We use the prefix to ensure our stacks line up with native stack frames.\n\n\n return '\\n' + prefix + name;\n }\n}\nvar reentry = false;\nvar componentFrameCache;\n\n{\n var PossiblyWeakMap = typeof WeakMap === 'function' ? WeakMap : Map;\n componentFrameCache = new PossiblyWeakMap();\n}\n\nfunction describeNativeComponentFrame(fn, construct) {\n // If something asked for a stack inside a fake render, it should get ignored.\n if ( !fn || reentry) {\n return '';\n }\n\n {\n var frame = componentFrameCache.get(fn);\n\n if (frame !== undefined) {\n return frame;\n }\n }\n\n var control;\n reentry = true;\n var previousPrepareStackTrace = Error.prepareStackTrace; // $FlowFixMe It does accept undefined.\n\n Error.prepareStackTrace = undefined;\n var previousDispatcher;\n\n {\n previousDispatcher = ReactCurrentDispatcher$1.current; // Set the dispatcher in DEV because this might be call in the render function\n // for warnings.\n\n ReactCurrentDispatcher$1.current = null;\n disableLogs();\n }\n\n try {\n // This should throw.\n if (construct) {\n // Something should be setting the props in the constructor.\n var Fake = function () {\n throw Error();\n }; // $FlowFixMe\n\n\n Object.defineProperty(Fake.prototype, 'props', {\n set: function () {\n // We use a throwing setter instead of frozen or non-writable props\n // because that won't throw in a non-strict mode function.\n throw Error();\n }\n });\n\n if (typeof Reflect === 'object' && Reflect.construct) {\n // We construct a different control for this case to include any extra\n // frames added by the construct call.\n try {\n Reflect.construct(Fake, []);\n } catch (x) {\n control = x;\n }\n\n Reflect.construct(fn, [], Fake);\n } else {\n try {\n Fake.call();\n } catch (x) {\n control = x;\n }\n\n fn.call(Fake.prototype);\n }\n } else {\n try {\n throw Error();\n } catch (x) {\n control = x;\n }\n\n fn();\n }\n } catch (sample) {\n // This is inlined manually because closure doesn't do it for us.\n if (sample && control && typeof sample.stack === 'string') {\n // This extracts the first frame from the sample that isn't also in the control.\n // Skipping one frame that we assume is the frame that calls the two.\n var sampleLines = sample.stack.split('\\n');\n var controlLines = control.stack.split('\\n');\n var s = sampleLines.length - 1;\n var c = controlLines.length - 1;\n\n while (s >= 1 && c >= 0 && sampleLines[s] !== controlLines[c]) {\n // We expect at least one stack frame to be shared.\n // Typically this will be the root most one. However, stack frames may be\n // cut off due to maximum stack limits. In this case, one maybe cut off\n // earlier than the other. We assume that the sample is longer or the same\n // and there for cut off earlier. So we should find the root most frame in\n // the sample somewhere in the control.\n c--;\n }\n\n for (; s >= 1 && c >= 0; s--, c--) {\n // Next we find the first one that isn't the same which should be the\n // frame that called our sample function and the control.\n if (sampleLines[s] !== controlLines[c]) {\n // In V8, the first line is describing the message but other VMs don't.\n // If we're about to return the first line, and the control is also on the same\n // line, that's a pretty good indicator that our sample threw at same line as\n // the control. I.e. before we entered the sample frame. So we ignore this result.\n // This can happen if you passed a class to function component, or non-function.\n if (s !== 1 || c !== 1) {\n do {\n s--;\n c--; // We may still have similar intermediate frames from the construct call.\n // The next one that isn't the same should be our match though.\n\n if (c < 0 || sampleLines[s] !== controlLines[c]) {\n // V8 adds a \"new\" prefix for native classes. Let's remove it to make it prettier.\n var _frame = '\\n' + sampleLines[s].replace(' at new ', ' at '); // If our component frame is labeled \"<anonymous>\"\n // but we have a user-provided \"displayName\"\n // splice it in to make the stack more readable.\n\n\n if (fn.displayName && _frame.includes('<anonymous>')) {\n _frame = _frame.replace('<anonymous>', fn.displayName);\n }\n\n {\n if (typeof fn === 'function') {\n componentFrameCache.set(fn, _frame);\n }\n } // Return the line we found.\n\n\n return _frame;\n }\n } while (s >= 1 && c >= 0);\n }\n\n break;\n }\n }\n }\n } finally {\n reentry = false;\n\n {\n ReactCurrentDispatcher$1.current = previousDispatcher;\n reenableLogs();\n }\n\n Error.prepareStackTrace = previousPrepareStackTrace;\n } // Fallback to just using the name if we couldn't make it throw.\n\n\n var name = fn ? fn.displayName || fn.name : '';\n var syntheticFrame = name ? describeBuiltInComponentFrame(name) : '';\n\n {\n if (typeof fn === 'function') {\n componentFrameCache.set(fn, syntheticFrame);\n }\n }\n\n return syntheticFrame;\n}\nfunction describeFunctionComponentFrame(fn, source, ownerFn) {\n {\n return describeNativeComponentFrame(fn, false);\n }\n}\n\nfunction shouldConstruct(Component) {\n var prototype = Component.prototype;\n return !!(prototype && prototype.isReactComponent);\n}\n\nfunction describeUnknownElementTypeFrameInDEV(type, source, ownerFn) {\n\n if (type == null) {\n return '';\n }\n\n if (typeof type === 'function') {\n {\n return describeNativeComponentFrame(type, shouldConstruct(type));\n }\n }\n\n if (typeof type === 'string') {\n return describeBuiltInComponentFrame(type);\n }\n\n switch (type) {\n case REACT_SUSPENSE_TYPE:\n return describeBuiltInComponentFrame('Suspense');\n\n case REACT_SUSPENSE_LIST_TYPE:\n return describeBuiltInComponentFrame('SuspenseList');\n }\n\n if (typeof type === 'object') {\n switch (type.$$typeof) {\n case REACT_FORWARD_REF_TYPE:\n return describeFunctionComponentFrame(type.render);\n\n case REACT_MEMO_TYPE:\n // Memo may contain any component type so we recursively resolve it.\n return describeUnknownElementTypeFrameInDEV(type.type, source, ownerFn);\n\n case REACT_LAZY_TYPE:\n {\n var lazyComponent = type;\n var payload = lazyComponent._payload;\n var init = lazyComponent._init;\n\n try {\n // Lazy may contain any component type so we recursively resolve it.\n return describeUnknownElementTypeFrameInDEV(init(payload), source, ownerFn);\n } catch (x) {}\n }\n }\n }\n\n return '';\n}\n\nvar loggedTypeFailures = {};\nvar ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame;\n\nfunction setCurrentlyValidatingElement(element) {\n {\n if (element) {\n var owner = element._owner;\n var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null);\n ReactDebugCurrentFrame$1.setExtraStackFrame(stack);\n } else {\n ReactDebugCurrentFrame$1.setExtraStackFrame(null);\n }\n }\n}\n\nfunction checkPropTypes(typeSpecs, values, location, componentName, element) {\n {\n // $FlowFixMe This is okay but Flow doesn't know it.\n var has = Function.call.bind(hasOwnProperty);\n\n for (var typeSpecName in typeSpecs) {\n if (has(typeSpecs, typeSpecName)) {\n var error$1 = void 0; // Prop type validation may throw. In case they do, we don't want to\n // fail the render phase where it didn't fail before. So we log it.\n // After these have been cleaned up, we'll let them throw.\n\n try {\n // This is intentionally an invariant that gets caught. It's the same\n // behavior as without this statement except with a better message.\n if (typeof typeSpecs[typeSpecName] !== 'function') {\n // eslint-disable-next-line react-internal/prod-error-codes\n 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`.');\n err.name = 'Invariant Violation';\n throw err;\n }\n\n error$1 = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED');\n } catch (ex) {\n error$1 = ex;\n }\n\n if (error$1 && !(error$1 instanceof Error)) {\n setCurrentlyValidatingElement(element);\n\n 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);\n\n setCurrentlyValidatingElement(null);\n }\n\n if (error$1 instanceof Error && !(error$1.message in loggedTypeFailures)) {\n // Only monitor this failure once because there tends to be a lot of the\n // same error.\n loggedTypeFailures[error$1.message] = true;\n setCurrentlyValidatingElement(element);\n\n error('Failed %s type: %s', location, error$1.message);\n\n setCurrentlyValidatingElement(null);\n }\n }\n }\n }\n}\n\nfunction setCurrentlyValidatingElement$1(element) {\n {\n if (element) {\n var owner = element._owner;\n var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null);\n setExtraStackFrame(stack);\n } else {\n setExtraStackFrame(null);\n }\n }\n}\n\nvar propTypesMisspellWarningShown;\n\n{\n propTypesMisspellWarningShown = false;\n}\n\nfunction getDeclarationErrorAddendum() {\n if (ReactCurrentOwner.current) {\n var name = getComponentNameFromType(ReactCurrentOwner.current.type);\n\n if (name) {\n return '\\n\\nCheck the render method of `' + name + '`.';\n }\n }\n\n return '';\n}\n\nfunction getSourceInfoErrorAddendum(source) {\n if (source !== undefined) {\n var fileName = source.fileName.replace(/^.*[\\\\\\/]/, '');\n var lineNumber = source.lineNumber;\n return '\\n\\nCheck your code at ' + fileName + ':' + lineNumber + '.';\n }\n\n return '';\n}\n\nfunction getSourceInfoErrorAddendumForProps(elementProps) {\n if (elementProps !== null && elementProps !== undefined) {\n return getSourceInfoErrorAddendum(elementProps.__source);\n }\n\n return '';\n}\n/**\n * Warn if there's no key explicitly set on dynamic arrays of children or\n * object keys are not valid. This allows us to keep track of children between\n * updates.\n */\n\n\nvar ownerHasKeyUseWarning = {};\n\nfunction getCurrentComponentErrorInfo(parentType) {\n var info = getDeclarationErrorAddendum();\n\n if (!info) {\n var parentName = typeof parentType === 'string' ? parentType : parentType.displayName || parentType.name;\n\n if (parentName) {\n info = \"\\n\\nCheck the top-level render call using <\" + parentName + \">.\";\n }\n }\n\n return info;\n}\n/**\n * Warn if the element doesn't have an explicit key assigned to it.\n * This element is in an array. The array could grow and shrink or be\n * reordered. All children that haven't already been validated are required to\n * have a \"key\" property assigned to it. Error statuses are cached so a warning\n * will only be shown once.\n *\n * @internal\n * @param {ReactElement} element Element that requires a key.\n * @param {*} parentType element's parent's type.\n */\n\n\nfunction validateExplicitKey(element, parentType) {\n if (!element._store || element._store.validated || element.key != null) {\n return;\n }\n\n element._store.validated = true;\n var currentComponentErrorInfo = getCurrentComponentErrorInfo(parentType);\n\n if (ownerHasKeyUseWarning[currentComponentErrorInfo]) {\n return;\n }\n\n ownerHasKeyUseWarning[currentComponentErrorInfo] = true; // Usually the current owner is the offender, but if it accepts children as a\n // property, it may be the creator of the child that's responsible for\n // assigning it a key.\n\n var childOwner = '';\n\n if (element && element._owner && element._owner !== ReactCurrentOwner.current) {\n // Give the component that originally created this child.\n childOwner = \" It was passed a child from \" + getComponentNameFromType(element._owner.type) + \".\";\n }\n\n {\n setCurrentlyValidatingElement$1(element);\n\n 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);\n\n setCurrentlyValidatingElement$1(null);\n }\n}\n/**\n * Ensure that every element either is passed in a static location, in an\n * array with an explicit keys property defined, or in an object literal\n * with valid key property.\n *\n * @internal\n * @param {ReactNode} node Statically passed child of any type.\n * @param {*} parentType node's parent's type.\n */\n\n\nfunction validateChildKeys(node, parentType) {\n if (typeof node !== 'object') {\n return;\n }\n\n if (isArray(node)) {\n for (var i = 0; i < node.length; i++) {\n var child = node[i];\n\n if (isValidElement(child)) {\n validateExplicitKey(child, parentType);\n }\n }\n } else if (isValidElement(node)) {\n // This element was passed in a valid location.\n if (node._store) {\n node._store.validated = true;\n }\n } else if (node) {\n var iteratorFn = getIteratorFn(node);\n\n if (typeof iteratorFn === 'function') {\n // Entry iterators used to provide implicit keys,\n // but now we print a separate warning for them later.\n if (iteratorFn !== node.entries) {\n var iterator = iteratorFn.call(node);\n var step;\n\n while (!(step = iterator.next()).done) {\n if (isValidElement(step.value)) {\n validateExplicitKey(step.value, parentType);\n }\n }\n }\n }\n }\n}\n/**\n * Given an element, validate that its props follow the propTypes definition,\n * provided by the type.\n *\n * @param {ReactElement} element\n */\n\n\nfunction validatePropTypes(element) {\n {\n var type = element.type;\n\n if (type === null || type === undefined || typeof type === 'string') {\n return;\n }\n\n var propTypes;\n\n if (typeof type === 'function') {\n propTypes = type.propTypes;\n } else if (typeof type === 'object' && (type.$$typeof === REACT_FORWARD_REF_TYPE || // Note: Memo only checks outer props here.\n // Inner props are checked in the reconciler.\n type.$$typeof === REACT_MEMO_TYPE)) {\n propTypes = type.propTypes;\n } else {\n return;\n }\n\n if (propTypes) {\n // Intentionally inside to avoid triggering lazy initializers:\n var name = getComponentNameFromType(type);\n checkPropTypes(propTypes, element.props, 'prop', name, element);\n } else if (type.PropTypes !== undefined && !propTypesMisspellWarningShown) {\n propTypesMisspellWarningShown = true; // Intentionally inside to avoid triggering lazy initializers:\n\n var _name = getComponentNameFromType(type);\n\n error('Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?', _name || 'Unknown');\n }\n\n if (typeof type.getDefaultProps === 'function' && !type.getDefaultProps.isReactClassApproved) {\n error('getDefaultProps is only used on classic React.createClass ' + 'definitions. Use a static property named `defaultProps` instead.');\n }\n }\n}\n/**\n * Given a fragment, validate that it can only be provided with fragment props\n * @param {ReactElement} fragment\n */\n\n\nfunction validateFragmentProps(fragment) {\n {\n var keys = Object.keys(fragment.props);\n\n for (var i = 0; i < keys.length; i++) {\n var key = keys[i];\n\n if (key !== 'children' && key !== 'key') {\n setCurrentlyValidatingElement$1(fragment);\n\n error('Invalid prop `%s` supplied to `React.Fragment`. ' + 'React.Fragment can only have `key` and `children` props.', key);\n\n setCurrentlyValidatingElement$1(null);\n break;\n }\n }\n\n if (fragment.ref !== null) {\n setCurrentlyValidatingElement$1(fragment);\n\n error('Invalid attribute `ref` supplied to `React.Fragment`.');\n\n setCurrentlyValidatingElement$1(null);\n }\n }\n}\nfunction createElementWithValidation(type, props, children) {\n var validType = isValidElementType(type); // We warn in this case but don't throw. We expect the element creation to\n // succeed and there will likely be errors in render.\n\n if (!validType) {\n var info = '';\n\n if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) {\n 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.\";\n }\n\n var sourceInfo = getSourceInfoErrorAddendumForProps(props);\n\n if (sourceInfo) {\n info += sourceInfo;\n } else {\n info += getDeclarationErrorAddendum();\n }\n\n var typeString;\n\n if (type === null) {\n typeString = 'null';\n } else if (isArray(type)) {\n typeString = 'array';\n } else if (type !== undefined && type.$$typeof === REACT_ELEMENT_TYPE) {\n typeString = \"<\" + (getComponentNameFromType(type.type) || 'Unknown') + \" />\";\n info = ' Did you accidentally export a JSX literal instead of a component?';\n } else {\n typeString = typeof type;\n }\n\n {\n error('React.createElement: type is invalid -- expected a string (for ' + 'built-in components) or a class/function (for composite ' + 'components) but got: %s.%s', typeString, info);\n }\n }\n\n var element = createElement.apply(this, arguments); // The result can be nullish if a mock or a custom function is used.\n // TODO: Drop this when these are no longer allowed as the type argument.\n\n if (element == null) {\n return element;\n } // Skip key warning if the type isn't valid since our key validation logic\n // doesn't expect a non-string/function type and can throw confusing errors.\n // We don't want exception behavior to differ between dev and prod.\n // (Rendering will throw with a helpful message and as soon as the type is\n // fixed, the key warnings will appear.)\n\n\n if (validType) {\n for (var i = 2; i < arguments.length; i++) {\n validateChildKeys(arguments[i], type);\n }\n }\n\n if (type === REACT_FRAGMENT_TYPE) {\n validateFragmentProps(element);\n } else {\n validatePropTypes(element);\n }\n\n return element;\n}\nvar didWarnAboutDeprecatedCreateFactory = false;\nfunction createFactoryWithValidation(type) {\n var validatedFactory = createElementWithValidation.bind(null, type);\n validatedFactory.type = type;\n\n {\n if (!didWarnAboutDeprecatedCreateFactory) {\n didWarnAboutDeprecatedCreateFactory = true;\n\n warn('React.createFactory() is deprecated and will be removed in ' + 'a future major release. Consider using JSX ' + 'or use React.createElement() directly instead.');\n } // Legacy hook: remove it\n\n\n Object.defineProperty(validatedFactory, 'type', {\n enumerable: false,\n get: function () {\n warn('Factory.type is deprecated. Access the class directly ' + 'before passing it to createFactory.');\n\n Object.defineProperty(this, 'type', {\n value: type\n });\n return type;\n }\n });\n }\n\n return validatedFactory;\n}\nfunction cloneElementWithValidation(element, props, children) {\n var newElement = cloneElement.apply(this, arguments);\n\n for (var i = 2; i < arguments.length; i++) {\n validateChildKeys(arguments[i], newElement.type);\n }\n\n validatePropTypes(newElement);\n return newElement;\n}\n\nfunction startTransition(scope, options) {\n var prevTransition = ReactCurrentBatchConfig.transition;\n ReactCurrentBatchConfig.transition = {};\n var currentTransition = ReactCurrentBatchConfig.transition;\n\n {\n ReactCurrentBatchConfig.transition._updatedFibers = new Set();\n }\n\n try {\n scope();\n } finally {\n ReactCurrentBatchConfig.transition = prevTransition;\n\n {\n if (prevTransition === null && currentTransition._updatedFibers) {\n var updatedFibersCount = currentTransition._updatedFibers.size;\n\n if (updatedFibersCount > 10) {\n warn('Detected a large number of updates inside startTransition. ' + 'If this is due to a subscription please re-write it to use React provided hooks. ' + 'Otherwise concurrent mode guarantees are off the table.');\n }\n\n currentTransition._updatedFibers.clear();\n }\n }\n }\n}\n\nvar didWarnAboutMessageChannel = false;\nvar enqueueTaskImpl = null;\nfunction enqueueTask(task) {\n if (enqueueTaskImpl === null) {\n try {\n // read require off the module object to get around the bundlers.\n // we don't want them to detect a require and bundle a Node polyfill.\n var requireString = ('require' + Math.random()).slice(0, 7);\n var nodeRequire = module && module[requireString]; // assuming we're in node, let's try to get node's\n // version of setImmediate, bypassing fake timers if any.\n\n enqueueTaskImpl = nodeRequire.call(module, 'timers').setImmediate;\n } catch (_err) {\n // we're in a browser\n // we can't use regular timers because they may still be faked\n // so we try MessageChannel+postMessage instead\n enqueueTaskImpl = function (callback) {\n {\n if (didWarnAboutMessageChannel === false) {\n didWarnAboutMessageChannel = true;\n\n if (typeof MessageChannel === 'undefined') {\n error('This browser does not have a MessageChannel implementation, ' + 'so enqueuing tasks via await act(async () => ...) will fail. ' + 'Please file an issue at https://github.com/facebook/react/issues ' + 'if you encounter this warning.');\n }\n }\n }\n\n var channel = new MessageChannel();\n channel.port1.onmessage = callback;\n channel.port2.postMessage(undefined);\n };\n }\n }\n\n return enqueueTaskImpl(task);\n}\n\nvar actScopeDepth = 0;\nvar didWarnNoAwaitAct = false;\nfunction act(callback) {\n {\n // `act` calls can be nested, so we track the depth. This represents the\n // number of `act` scopes on the stack.\n var prevActScopeDepth = actScopeDepth;\n actScopeDepth++;\n\n if (ReactCurrentActQueue.current === null) {\n // This is the outermost `act` scope. Initialize the queue. The reconciler\n // will detect the queue and use it instead of Scheduler.\n ReactCurrentActQueue.current = [];\n }\n\n var prevIsBatchingLegacy = ReactCurrentActQueue.isBatchingLegacy;\n var result;\n\n try {\n // Used to reproduce behavior of `batchedUpdates` in legacy mode. Only\n // set to `true` while the given callback is executed, not for updates\n // triggered during an async event, because this is how the legacy\n // implementation of `act` behaved.\n ReactCurrentActQueue.isBatchingLegacy = true;\n result = callback(); // Replicate behavior of original `act` implementation in legacy mode,\n // which flushed updates immediately after the scope function exits, even\n // if it's an async function.\n\n if (!prevIsBatchingLegacy && ReactCurrentActQueue.didScheduleLegacyUpdate) {\n var queue = ReactCurrentActQueue.current;\n\n if (queue !== null) {\n ReactCurrentActQueue.didScheduleLegacyUpdate = false;\n flushActQueue(queue);\n }\n }\n } catch (error) {\n popActScope(prevActScopeDepth);\n throw error;\n } finally {\n ReactCurrentActQueue.isBatchingLegacy = prevIsBatchingLegacy;\n }\n\n if (result !== null && typeof result === 'object' && typeof result.then === 'function') {\n var thenableResult = result; // The callback is an async function (i.e. returned a promise). Wait\n // for it to resolve before exiting the current scope.\n\n var wasAwaited = false;\n var thenable = {\n then: function (resolve, reject) {\n wasAwaited = true;\n thenableResult.then(function (returnValue) {\n popActScope(prevActScopeDepth);\n\n if (actScopeDepth === 0) {\n // We've exited the outermost act scope. Recursively flush the\n // queue until there's no remaining work.\n recursivelyFlushAsyncActWork(returnValue, resolve, reject);\n } else {\n resolve(returnValue);\n }\n }, function (error) {\n // The callback threw an error.\n popActScope(prevActScopeDepth);\n reject(error);\n });\n }\n };\n\n {\n if (!didWarnNoAwaitAct && typeof Promise !== 'undefined') {\n // eslint-disable-next-line no-undef\n Promise.resolve().then(function () {}).then(function () {\n if (!wasAwaited) {\n didWarnNoAwaitAct = true;\n\n error('You called act(async () => ...) without await. ' + 'This could lead to unexpected testing behaviour, ' + 'interleaving multiple act calls and mixing their ' + 'scopes. ' + 'You should - await act(async () => ...);');\n }\n });\n }\n }\n\n return thenable;\n } else {\n var returnValue = result; // The callback is not an async function. Exit the current scope\n // immediately, without awaiting.\n\n popActScope(prevActScopeDepth);\n\n if (actScopeDepth === 0) {\n // Exiting the outermost act scope. Flush the queue.\n var _queue = ReactCurrentActQueue.current;\n\n if (_queue !== null) {\n flushActQueue(_queue);\n ReactCurrentActQueue.current = null;\n } // Return a thenable. If the user awaits it, we'll flush again in\n // case additional work was scheduled by a microtask.\n\n\n var _thenable = {\n then: function (resolve, reject) {\n // Confirm we haven't re-entered another `act` scope, in case\n // the user does something weird like await the thenable\n // multiple times.\n if (ReactCurrentActQueue.current === null) {\n // Recursively flush the queue until there's no remaining work.\n ReactCurrentActQueue.current = [];\n recursivelyFlushAsyncActWork(returnValue, resolve, reject);\n } else {\n resolve(returnValue);\n }\n }\n };\n return _thenable;\n } else {\n // Since we're inside a nested `act` scope, the returned thenable\n // immediately resolves. The outer scope will flush the queue.\n var _thenable2 = {\n then: function (resolve, reject) {\n resolve(returnValue);\n }\n };\n return _thenable2;\n }\n }\n }\n}\n\nfunction popActScope(prevActScopeDepth) {\n {\n if (prevActScopeDepth !== actScopeDepth - 1) {\n error('You seem to have overlapping act() calls, this is not supported. ' + 'Be sure to await previous act() calls before making a new one. ');\n }\n\n actScopeDepth = prevActScopeDepth;\n }\n}\n\nfunction recursivelyFlushAsyncActWork(returnValue, resolve, reject) {\n {\n var queue = ReactCurrentActQueue.current;\n\n if (queue !== null) {\n try {\n flushActQueue(queue);\n enqueueTask(function () {\n if (queue.length === 0) {\n // No additional work was scheduled. Finish.\n ReactCurrentActQueue.current = null;\n resolve(returnValue);\n } else {\n // Keep flushing work until there's none left.\n recursivelyFlushAsyncActWork(returnValue, resolve, reject);\n }\n });\n } catch (error) {\n reject(error);\n }\n } else {\n resolve(returnValue);\n }\n }\n}\n\nvar isFlushing = false;\n\nfunction flushActQueue(queue) {\n {\n if (!isFlushing) {\n // Prevent re-entrance.\n isFlushing = true;\n var i = 0;\n\n try {\n for (; i < queue.length; i++) {\n var callback = queue[i];\n\n do {\n callback = callback(true);\n } while (callback !== null);\n }\n\n queue.length = 0;\n } catch (error) {\n // If something throws, leave the remaining callbacks on the queue.\n queue = queue.slice(i + 1);\n throw error;\n } finally {\n isFlushing = false;\n }\n }\n }\n}\n\nvar createElement$1 = createElementWithValidation ;\nvar cloneElement$1 = cloneElementWithValidation ;\nvar createFactory = createFactoryWithValidation ;\nvar Children = {\n map: mapChildren,\n forEach: forEachChildren,\n count: countChildren,\n toArray: toArray,\n only: onlyChild\n};\n\nexports.Children = Children;\nexports.Component = Component;\nexports.Fragment = REACT_FRAGMENT_TYPE;\nexports.Profiler = REACT_PROFILER_TYPE;\nexports.PureComponent = PureComponent;\nexports.StrictMode = REACT_STRICT_MODE_TYPE;\nexports.Suspense = REACT_SUSPENSE_TYPE;\nexports.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED = ReactSharedInternals;\nexports.act = act;\nexports.cloneElement = cloneElement$1;\nexports.createContext = createContext;\nexports.createElement = createElement$1;\nexports.createFactory = createFactory;\nexports.createRef = createRef;\nexports.forwardRef = forwardRef;\nexports.isValidElement = isValidElement;\nexports.lazy = lazy;\nexports.memo = memo;\nexports.startTransition = startTransition;\nexports.unstable_act = act;\nexports.useCallback = useCallback;\nexports.useContext = useContext;\nexports.useDebugValue = useDebugValue;\nexports.useDeferredValue = useDeferredValue;\nexports.useEffect = useEffect;\nexports.useId = useId;\nexports.useImperativeHandle = useImperativeHandle;\nexports.useInsertionEffect = useInsertionEffect;\nexports.useLayoutEffect = useLayoutEffect;\nexports.useMemo = useMemo;\nexports.useReducer = useReducer;\nexports.useRef = useRef;\nexports.useState = useState;\nexports.useSyncExternalStore = useSyncExternalStore;\nexports.useTransition = useTransition;\nexports.version = ReactVersion;\n /* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */\nif (\n typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' &&\n typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop ===\n 'function'\n) {\n __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(new Error());\n}\n \n })();\n}\n","'use strict';\n\nif (process.env.NODE_ENV === 'production') {\n module.exports = require('./cjs/react.production.min.js');\n} else {\n module.exports = require('./cjs/react.development.js');\n}\n","// src/modules/survey/routes.ts\r\nimport type { ComponentType, LazyExoticComponent } from 'react';\n\ninterface RouteConfig {\n path: string;\n element: LazyExoticComponent<ComponentType<any>>;\n isPublic?: boolean;\n meta?: {\n title?: string;\n module?: string;\n };\n}\r\nimport { lazy } from 'react';\r\n\r\nconst AllSurveys = lazy(() =>\r\n import('./Pages/Allsurvey/Allsurvey').then((module) => ({\r\n default: module.AllSurveys,\r\n }))\r\n);\r\n\r\nconst SurveyDetails = lazy(() =>\r\n import('./Pages/Surveydetails/Surveydetails').then((module) => ({\r\n default: module.SurveyDetails,\r\n }))\r\n);\r\n\r\nconst CreateSurvey = lazy(() =>\r\n import('./Pages/Createsurvey/Createsurvey').then((module) => ({\r\n default: module.CreateSurvey,\r\n }))\r\n);\r\n\r\nconst SurveyTemplates = lazy(() =>\r\n import('./Pages/Surveytemplates/Surveytemplates').then((module) => ({\r\n default: module.SurveyTemplates,\r\n }))\r\n);\r\n\r\nconst Responses = lazy(() =>\r\n import('./Pages/Responses/Responses').then((module) => ({\r\n default: module.Responses,\r\n }))\r\n);\r\n\r\nconst NPSTracker = lazy(() =>\r\n import('./Pages/NPStracker/NPStracker').then((module) => ({\r\n default: module.NPSTracker,\r\n }))\r\n);\r\n\r\nconst SurveyAnalytics = lazy(() =>\r\n import('./Pages/Surveyanalytics/Surveyanalytics').then((module) => ({\r\n default: module.SurveyAnalytics,\r\n }))\r\n);\r\n\r\nconst SurveyRoutes: RouteConfig[] = [\r\n {\r\n path: '/all-surveys',\r\n element: AllSurveys,\r\n isPublic: false,\r\n meta: { title: 'All Surveys', module: 'survey' },\r\n },\r\n {\r\n path: '/all-surveys/create-survey',\r\n element: CreateSurvey,\r\n isPublic: false,\r\n meta: { title: 'Create Survey', module: 'survey' },\r\n },\r\n {\r\n path: '/surveys/:surveyId',\r\n element: SurveyDetails,\r\n isPublic: false,\r\n meta: { title: 'Survey Details', module: 'survey' },\r\n },\r\n {\r\n path: '/survey-templates',\r\n element: SurveyTemplates,\r\n isPublic: false,\r\n meta: { title: 'Survey Templates', module: 'survey' },\r\n },\r\n {\r\n path: '/responses',\r\n element: Responses,\r\n isPublic: false,\r\n meta: { title: 'Responses', module: 'survey' },\r\n },\r\n {\r\n path: '/nps-tracker',\r\n element: NPSTracker,\r\n isPublic: false,\r\n meta: { title: 'NPS Tracker', module: 'survey' },\r\n },\r\n {\r\n path: '/survey-analytics',\r\n element: SurveyAnalytics,\r\n isPublic: false,\r\n meta: { title: 'Survey Analytics', module: 'survey' },\r\n },\r\n {\r\n path: '/survey-analytics/:surveyId',\r\n element: SurveyAnalytics,\r\n isPublic: false,\r\n meta: { title: 'Survey Analytics', module: 'survey' },\r\n },\r\n];\r\n\r\nexport default SurveyRoutes;\r\r\n\r\n\r\n","interface NavItem {\n id: string;\n label: string;\n icon: string;\n module: string;\n category: string;\n section: string;\n path: string;\n order: number;\n}\r\n\r\nconst surveyNav: NavItem[] = [\r\n {\r\n id: 'all-surveys',\r\n label: 'All Surveys',\r\n icon: 'LayoutDashboard',\r\n module: 'Survey',\r\n category: 'All Surveys',\r\n section: 'survey',\r\n path: '/app/all-surveys',\r\n order: 1,\r\n },\r\n {\r\n id: 'survey-templates',\r\n label: 'Survey Templates',\r\n icon: 'LayoutDashboard',\r\n module: 'Survey',\r\n category: 'Survey Templates',\r\n section: 'survey',\r\n path: '/app/survey-templates',\r\n order: 2,\r\n },\r\n {\r\n id: 'responses',\r\n label: 'Responses',\r\n icon: 'LayoutDashboard',\r\n module: 'Survey',\r\n category: 'Responses',\r\n section: 'survey',\r\n path: '/app/responses',\r\n order: 3,\r\n },\r\n {\r\n id: 'nps-tracker',\r\n label: 'NPS Tracker',\r\n icon: 'LayoutDashboard',\r\n module: 'Survey',\r\n category: 'NPS Tracker',\r\n section: 'survey',\r\n path: '/app/nps-tracker',\r\n order: 4,\r\n },\r\n {\r\n id: 'survey-analytics',\r\n label: 'Survey Analytics',\r\n icon: 'LayoutDashboard',\r\n module: 'Survey',\r\n category: 'Survey Analytics',\r\n section: 'survey',\r\n path: '/app/survey-analytics',\r\n order: 5,\r\n }\r\n];\r\nexport default surveyNav;\r\n\r\n\r\n","/**\n * @license React\n * react-jsx-runtime.production.min.js\n *\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n'use strict';var f=require(\"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};\nfunction 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}}exports.Fragment=l;exports.jsx=q;exports.jsxs=q;\n","/**\n * @license React\n * react-jsx-runtime.development.js\n *\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n'use strict';\n\nif (process.env.NODE_ENV !== \"production\") {\n (function() {\n'use strict';\n\nvar React = require('react');\n\n// ATTENTION\n// When adding new symbols to this file,\n// Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols'\n// The Symbol used to tag the ReactElement-like types.\nvar REACT_ELEMENT_TYPE = Symbol.for('react.element');\nvar REACT_PORTAL_TYPE = Symbol.for('react.portal');\nvar REACT_FRAGMENT_TYPE = Symbol.for('react.fragment');\nvar REACT_STRICT_MODE_TYPE = Symbol.for('react.strict_mode');\nvar REACT_PROFILER_TYPE = Symbol.for('react.profiler');\nvar REACT_PROVIDER_TYPE = Symbol.for('react.provider');\nvar REACT_CONTEXT_TYPE = Symbol.for('react.context');\nvar REACT_FORWARD_REF_TYPE = Symbol.for('react.forward_ref');\nvar REACT_SUSPENSE_TYPE = Symbol.for('react.suspense');\nvar REACT_SUSPENSE_LIST_TYPE = Symbol.for('react.suspense_list');\nvar REACT_MEMO_TYPE = Symbol.for('react.memo');\nvar REACT_LAZY_TYPE = Symbol.for('react.lazy');\nvar REACT_OFFSCREEN_TYPE = Symbol.for('react.offscreen');\nvar MAYBE_ITERATOR_SYMBOL = Symbol.iterator;\nvar FAUX_ITERATOR_SYMBOL = '@@iterator';\nfunction getIteratorFn(maybeIterable) {\n if (maybeIterable === null || typeof maybeIterable !== 'object') {\n return null;\n }\n\n var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL];\n\n if (typeof maybeIterator === 'function') {\n return maybeIterator;\n }\n\n return null;\n}\n\nvar ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;\n\nfunction error(format) {\n {\n {\n for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {\n args[_key2 - 1] = arguments[_key2];\n }\n\n printWarning('error', format, args);\n }\n }\n}\n\nfunction printWarning(level, format, args) {\n // When changing this logic, you might want to also\n // update consoleWithStackDev.www.js as well.\n {\n var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;\n var stack = ReactDebugCurrentFrame.getStackAddendum();\n\n if (stack !== '') {\n format += '%s';\n args = args.concat([stack]);\n } // eslint-disable-next-line react-internal/safe-string-coercion\n\n\n var argsWithFormat = args.map(function (item) {\n return String(item);\n }); // Careful: RN currently depends on this prefix\n\n argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it\n // breaks IE9: https://github.com/facebook/react/issues/13610\n // eslint-disable-next-line react-internal/no-production-logging\n\n Function.prototype.apply.call(console[level], console, argsWithFormat);\n }\n}\n\n// -----------------------------------------------------------------------------\n\nvar enableScopeAPI = false; // Experimental Create Event Handle API.\nvar enableCacheElement = false;\nvar enableTransitionTracing = false; // No known bugs, but needs performance testing\n\nvar enableLegacyHidden = false; // Enables unstable_avoidThisFallback feature in Fiber\n// stuff. Intended to enable React core members to more easily debug scheduling\n// issues in DEV builds.\n\nvar enableDebugTracing = false; // Track which Fiber(s) schedule render work.\n\nvar REACT_MODULE_REFERENCE;\n\n{\n REACT_MODULE_REFERENCE = Symbol.for('react.module.reference');\n}\n\nfunction isValidElementType(type) {\n if (typeof type === 'string' || typeof type === 'function') {\n return true;\n } // Note: typeof might be other than 'symbol' or 'number' (e.g. if it's a polyfill).\n\n\n 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 ) {\n return true;\n }\n\n if (typeof type === 'object' && type !== null) {\n 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\n // types supported by any Flight configuration anywhere since\n // we don't know which Flight build this will end up being used\n // with.\n type.$$typeof === REACT_MODULE_REFERENCE || type.getModuleId !== undefined) {\n return true;\n }\n }\n\n return false;\n}\n\nfunction getWrappedName(outerType, innerType, wrapperName) {\n var displayName = outerType.displayName;\n\n if (displayName) {\n return displayName;\n }\n\n var functionName = innerType.displayName || innerType.name || '';\n return functionName !== '' ? wrapperName + \"(\" + functionName + \")\" : wrapperName;\n} // Keep in sync with react-reconciler/getComponentNameFromFiber\n\n\nfunction getContextName(type) {\n return type.displayName || 'Context';\n} // Note that the reconciler package should generally prefer to use getComponentNameFromFiber() instead.\n\n\nfunction getComponentNameFromType(type) {\n if (type == null) {\n // Host root, text node or just invalid type.\n return null;\n }\n\n {\n if (typeof type.tag === 'number') {\n error('Received an unexpected object in getComponentNameFromType(). ' + 'This is likely a bug in React. Please file an issue.');\n }\n }\n\n if (typeof type === 'function') {\n return type.displayName || type.name || null;\n }\n\n if (typeof type === 'string') {\n return type;\n }\n\n switch (type) {\n case REACT_FRAGMENT_TYPE:\n return 'Fragment';\n\n case REACT_PORTAL_TYPE:\n return 'Portal';\n\n case REACT_PROFILER_TYPE:\n return 'Profiler';\n\n case REACT_STRICT_MODE_TYPE:\n return 'StrictMode';\n\n case REACT_SUSPENSE_TYPE:\n return 'Suspense';\n\n case REACT_SUSPENSE_LIST_TYPE:\n return 'SuspenseList';\n\n }\n\n if (typeof type === 'object') {\n switch (type.$$typeof) {\n case REACT_CONTEXT_TYPE:\n var context = type;\n return getContextName(context) + '.Consumer';\n\n case REACT_PROVIDER_TYPE:\n var provider = type;\n return getContextName(provider._context) + '.Provider';\n\n case REACT_FORWARD_REF_TYPE:\n return getWrappedName(type, type.render, 'ForwardRef');\n\n case REACT_MEMO_TYPE:\n var outerName = type.displayName || null;\n\n if (outerName !== null) {\n return outerName;\n }\n\n return getComponentNameFromType(type.type) || 'Memo';\n\n case REACT_LAZY_TYPE:\n {\n var lazyComponent = type;\n var payload = lazyComponent._payload;\n var init = lazyComponent._init;\n\n try {\n return getComponentNameFromType(init(payload));\n } catch (x) {\n return null;\n }\n }\n\n // eslint-disable-next-line no-fallthrough\n }\n }\n\n return null;\n}\n\nvar assign = Object.assign;\n\n// Helpers to patch console.logs to avoid logging during side-effect free\n// replaying on render function. This currently only patches the object\n// lazily which won't cover if the log function was extracted eagerly.\n// We could also eagerly patch the method.\nvar disabledDepth = 0;\nvar prevLog;\nvar prevInfo;\nvar prevWarn;\nvar prevError;\nvar prevGroup;\nvar prevGroupCollapsed;\nvar prevGroupEnd;\n\nfunction disabledLog() {}\n\ndisabledLog.__reactDisabledLog = true;\nfunction disableLogs() {\n {\n if (disabledDepth === 0) {\n /* eslint-disable react-internal/no-production-logging */\n prevLog = console.log;\n prevInfo = console.info;\n prevWarn = console.warn;\n prevError = console.error;\n prevGroup = console.group;\n prevGroupCollapsed = console.groupCollapsed;\n prevGroupEnd = console.groupEnd; // https://github.com/facebook/react/issues/19099\n\n var props = {\n configurable: true,\n enumerable: true,\n value: disabledLog,\n writable: true\n }; // $FlowFixMe Flow thinks console is immutable.\n\n Object.defineProperties(console, {\n info: props,\n log: props,\n warn: props,\n error: props,\n group: props,\n groupCollapsed: props,\n groupEnd: props\n });\n /* eslint-enable react-internal/no-production-logging */\n }\n\n disabledDepth++;\n }\n}\nfunction reenableLogs() {\n {\n disabledDepth--;\n\n if (disabledDepth === 0) {\n /* eslint-disable react-internal/no-production-logging */\n var props = {\n configurable: true,\n enumerable: true,\n writable: true\n }; // $FlowFixMe Flow thinks console is immutable.\n\n Object.defineProperties(console, {\n log: assign({}, props, {\n value: prevLog\n }),\n info: assign({}, props, {\n value: prevInfo\n }),\n warn: assign({}, props, {\n value: prevWarn\n }),\n error: assign({}, props, {\n value: prevError\n }),\n group: assign({}, props, {\n value: prevGroup\n }),\n groupCollapsed: assign({}, props, {\n value: prevGroupCollapsed\n }),\n groupEnd: assign({}, props, {\n value: prevGroupEnd\n })\n });\n /* eslint-enable react-internal/no-production-logging */\n }\n\n if (disabledDepth < 0) {\n error('disabledDepth fell below zero. ' + 'This is a bug in React. Please file an issue.');\n }\n }\n}\n\nvar ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher;\nvar prefix;\nfunction describeBuiltInComponentFrame(name, source, ownerFn) {\n {\n if (prefix === undefined) {\n // Extract the VM specific prefix used by each line.\n try {\n throw Error();\n } catch (x) {\n var match = x.stack.trim().match(/\\n( *(at )?)/);\n prefix = match && match[1] || '';\n }\n } // We use the prefix to ensure our stacks line up with native stack frames.\n\n\n return '\\n' + prefix + name;\n }\n}\nvar reentry = false;\nvar componentFrameCache;\n\n{\n var PossiblyWeakMap = typeof WeakMap === 'function' ? WeakMap : Map;\n componentFrameCache = new PossiblyWeakMap();\n}\n\nfunction describeNativeComponentFrame(fn, construct) {\n // If something asked for a stack inside a fake render, it should get ignored.\n if ( !fn || reentry) {\n return '';\n }\n\n {\n var frame = componentFrameCache.get(fn);\n\n if (frame !== undefined) {\n return frame;\n }\n }\n\n var control;\n reentry = true;\n var previousPrepareStackTrace = Error.prepareStackTrace; // $FlowFixMe It does accept undefined.\n\n Error.prepareStackTrace = undefined;\n var previousDispatcher;\n\n {\n previousDispatcher = ReactCurrentDispatcher.current; // Set the dispatcher in DEV because this might be call in the render function\n // for warnings.\n\n ReactCurrentDispatcher.current = null;\n disableLogs();\n }\n\n try {\n // This should throw.\n if (construct) {\n // Something should be setting the props in the constructor.\n var Fake = function () {\n throw Error();\n }; // $FlowFixMe\n\n\n Object.defineProperty(Fake.prototype, 'props', {\n set: function () {\n // We use a throwing setter instead of frozen or non-writable props\n // because that won't throw in a non-strict mode function.\n throw Error();\n }\n });\n\n if (typeof Reflect === 'object' && Reflect.construct) {\n // We construct a different control for this case to include any extra\n // frames added by the construct call.\n try {\n Reflect.construct(Fake, []);\n } catch (x) {\n control = x;\n }\n\n Reflect.construct(fn, [], Fake);\n } else {\n try {\n Fake.call();\n } catch (x) {\n control = x;\n }\n\n fn.call(Fake.prototype);\n }\n } else {\n try {\n throw Error();\n } catch (x) {\n control = x;\n }\n\n fn();\n }\n } catch (sample) {\n // This is inlined manually because closure doesn't do it for us.\n if (sample && control && typeof sample.stack === 'string') {\n // This extracts the first frame from the sample that isn't also in the control.\n // Skipping one frame that we assume is the frame that calls the two.\n var sampleLines = sample.stack.split('\\n');\n var controlLines = control.stack.split('\\n');\n var s = sampleLines.length - 1;\n var c = controlLines.length - 1;\n\n while (s >= 1 && c >= 0 && sampleLines[s] !== controlLines[c]) {\n // We expect at least one stack frame to be shared.\n // Typically this will be the root most one. However, stack frames may be\n // cut off due to maximum stack limits. In this case, one maybe cut off\n // earlier than the other. We assume that the sample is longer or the same\n // and there for cut off earlier. So we should find the root most frame in\n // the sample somewhere in the control.\n c--;\n }\n\n for (; s >= 1 && c >= 0; s--, c--) {\n // Next we find the first one that isn't the same which should be the\n // frame that called our sample function and the control.\n if (sampleLines[s] !== controlLines[c]) {\n // In V8, the first line is describing the message but other VMs don't.\n // If we're about to return the first line, and the control is also on the same\n // line, that's a pretty good indicator that our sample threw at same line as\n // the control. I.e. before we entered the sample frame. So we ignore this result.\n // This can happen if you passed a class to function component, or non-function.\n if (s !== 1 || c !== 1) {\n do {\n s--;\n c--; // We may still have similar intermediate frames from the construct call.\n // The next one that isn't the same should be our match though.\n\n if (c < 0 || sampleLines[s] !== controlLines[c]) {\n // V8 adds a \"new\" prefix for native classes. Let's remove it to make it prettier.\n var _frame = '\\n' + sampleLines[s].replace(' at new ', ' at '); // If our component frame is labeled \"<anonymous>\"\n // but we have a user-provided \"displayName\"\n // splice it in to make the stack more readable.\n\n\n if (fn.displayName && _frame.includes('<anonymous>')) {\n _frame = _frame.replace('<anonymous>', fn.displayName);\n }\n\n {\n if (typeof fn === 'function') {\n componentFrameCache.set(fn, _frame);\n }\n } // Return the line we found.\n\n\n return _frame;\n }\n } while (s >= 1 && c >= 0);\n }\n\n break;\n }\n }\n }\n } finally {\n reentry = false;\n\n {\n ReactCurrentDispatcher.current = previousDispatcher;\n reenableLogs();\n }\n\n Error.prepareStackTrace = previousPrepareStackTrace;\n } // Fallback to just using the name if we couldn't make it throw.\n\n\n var name = fn ? fn.displayName || fn.name : '';\n var syntheticFrame = name ? describeBuiltInComponentFrame(name) : '';\n\n {\n if (typeof fn === 'function') {\n componentFrameCache.set(fn, syntheticFrame);\n }\n }\n\n return syntheticFrame;\n}\nfunction describeFunctionComponentFrame(fn, source, ownerFn) {\n {\n return describeNativeComponentFrame(fn, false);\n }\n}\n\nfunction shouldConstruct(Component) {\n var prototype = Component.prototype;\n return !!(prototype && prototype.isReactComponent);\n}\n\nfunction describeUnknownElementTypeFrameInDEV(type, source, ownerFn) {\n\n if (type == null) {\n return '';\n }\n\n if (typeof type === 'function') {\n {\n return describeNativeComponentFrame(type, shouldConstruct(type));\n }\n }\n\n if (typeof type === 'string') {\n return describeBuiltInComponentFrame(type);\n }\n\n switch (type) {\n case REACT_SUSPENSE_TYPE:\n return describeBuiltInComponentFrame('Suspense');\n\n case REACT_SUSPENSE_LIST_TYPE:\n return describeBuiltInComponentFrame('SuspenseList');\n }\n\n if (typeof type === 'object') {\n switch (type.$$typeof) {\n case REACT_FORWARD_REF_TYPE:\n return describeFunctionComponentFrame(type.render);\n\n case REACT_MEMO_TYPE:\n // Memo may contain any component type so we recursively resolve it.\n return describeUnknownElementTypeFrameInDEV(type.type, source, ownerFn);\n\n case REACT_LAZY_TYPE:\n {\n var lazyComponent = type;\n var payload = lazyComponent._payload;\n var init = lazyComponent._init;\n\n try {\n // Lazy may contain any component type so we recursively resolve it.\n return describeUnknownElementTypeFrameInDEV(init(payload), source, ownerFn);\n } catch (x) {}\n }\n }\n }\n\n return '';\n}\n\nvar hasOwnProperty = Object.prototype.hasOwnProperty;\n\nvar loggedTypeFailures = {};\nvar ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;\n\nfunction setCurrentlyValidatingElement(element) {\n {\n if (element) {\n var owner = element._owner;\n var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null);\n ReactDebugCurrentFrame.setExtraStackFrame(stack);\n } else {\n ReactDebugCurrentFrame.setExtraStackFrame(null);\n }\n }\n}\n\nfunction checkPropTypes(typeSpecs, values, location, componentName, element) {\n {\n // $FlowFixMe This is okay but Flow doesn't know it.\n var has = Function.call.bind(hasOwnProperty);\n\n for (var typeSpecName in typeSpecs) {\n if (has(typeSpecs, typeSpecName)) {\n var error$1 = void 0; // Prop type validation may throw. In case they do, we don't want to\n // fail the render phase where it didn't fail before. So we log it.\n // After these have been cleaned up, we'll let them throw.\n\n try {\n // This is intentionally an invariant that gets caught. It's the same\n // behavior as without this statement except with a better message.\n if (typeof typeSpecs[typeSpecName] !== 'function') {\n // eslint-disable-next-line react-internal/prod-error-codes\n 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`.');\n err.name = 'Invariant Violation';\n throw err;\n }\n\n error$1 = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED');\n } catch (ex) {\n error$1 = ex;\n }\n\n if (error$1 && !(error$1 instanceof Error)) {\n setCurrentlyValidatingElement(element);\n\n 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);\n\n setCurrentlyValidatingElement(null);\n }\n\n if (error$1 instanceof Error && !(error$1.message in loggedTypeFailures)) {\n // Only monitor this failure once because there tends to be a lot of the\n // same error.\n loggedTypeFailures[error$1.message] = true;\n setCurrentlyValidatingElement(element);\n\n error('Failed %s type: %s', location, error$1.message);\n\n setCurrentlyValidatingElement(null);\n }\n }\n }\n }\n}\n\nvar isArrayImpl = Array.isArray; // eslint-disable-next-line no-redeclare\n\nfunction isArray(a) {\n return isArrayImpl(a);\n}\n\n/*\n * The `'' + value` pattern (used in in perf-sensitive code) throws for Symbol\n * and Temporal.* types. See https://github.com/facebook/react/pull/22064.\n *\n * The functions in this module will throw an easier-to-understand,\n * easier-to-debug exception with a clear errors message message explaining the\n * problem. (Instead of a confusing exception thrown inside the implementation\n * of the `value` object).\n */\n// $FlowFixMe only called in DEV, so void return is not possible.\nfunction typeName(value) {\n {\n // toStringTag is needed for namespaced types like Temporal.Instant\n var hasToStringTag = typeof Symbol === 'function' && Symbol.toStringTag;\n var type = hasToStringTag && value[Symbol.toStringTag] || value.constructor.name || 'Object';\n return type;\n }\n} // $FlowFixMe only called in DEV, so void return is not possible.\n\n\nfunction willCoercionThrow(value) {\n {\n try {\n testStringCoercion(value);\n return false;\n } catch (e) {\n return true;\n }\n }\n}\n\nfunction testStringCoercion(value) {\n // If you ended up here by following an exception call stack, here's what's\n // happened: you supplied an object or symbol value to React (as a prop, key,\n // DOM attribute, CSS property, string ref, etc.) and when React tried to\n // coerce it to a string using `'' + value`, an exception was thrown.\n //\n // The most common types that will cause this exception are `Symbol` instances\n // and Temporal objects like `Temporal.Instant`. But any object that has a\n // `valueOf` or `[Symbol.toPrimitive]` method that throws will also cause this\n // exception. (Library authors do this to prevent users from using built-in\n // numeric operators like `+` or comparison operators like `>=` because custom\n // methods are needed to perform accurate arithmetic or comparison.)\n //\n // To fix the problem, coerce this object or symbol value to a string before\n // passing it to React. The most reliable way is usually `String(value)`.\n //\n // To find which value is throwing, check the browser or debugger console.\n // Before this exception was thrown, there should be `console.error` output\n // that shows the type (Symbol, Temporal.PlainDate, etc.) that caused the\n // problem and how that type was used: key, atrribute, input value prop, etc.\n // In most cases, this console output also shows the component and its\n // ancestor components where the exception happened.\n //\n // eslint-disable-next-line react-internal/safe-string-coercion\n return '' + value;\n}\nfunction checkKeyStringCoercion(value) {\n {\n if (willCoercionThrow(value)) {\n error('The provided key is an unsupported type %s.' + ' This value must be coerced to a string before before using it here.', typeName(value));\n\n return testStringCoercion(value); // throw (to help callers find troubleshooting comments)\n }\n }\n}\n\nvar ReactCurrentOwner = ReactSharedInternals.ReactCurrentOwner;\nvar RESERVED_PROPS = {\n key: true,\n ref: true,\n __self: true,\n __source: true\n};\nvar specialPropKeyWarningShown;\nvar specialPropRefWarningShown;\nvar didWarnAboutStringRefs;\n\n{\n didWarnAboutStringRefs = {};\n}\n\nfunction hasValidRef(config) {\n {\n if (hasOwnProperty.call(config, 'ref')) {\n var getter = Object.getOwnPropertyDescriptor(config, 'ref').get;\n\n if (getter && getter.isReactWarning) {\n return false;\n }\n }\n }\n\n return config.ref !== undefined;\n}\n\nfunction hasValidKey(config) {\n {\n if (hasOwnProperty.call(config, 'key')) {\n var getter = Object.getOwnPropertyDescriptor(config, 'key').get;\n\n if (getter && getter.isReactWarning) {\n return false;\n }\n }\n }\n\n return config.key !== undefined;\n}\n\nfunction warnIfStringRefCannotBeAutoConverted(config, self) {\n {\n if (typeof config.ref === 'string' && ReactCurrentOwner.current && self && ReactCurrentOwner.current.stateNode !== self) {\n var componentName = getComponentNameFromType(ReactCurrentOwner.current.type);\n\n if (!didWarnAboutStringRefs[componentName]) {\n 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);\n\n didWarnAboutStringRefs[componentName] = true;\n }\n }\n }\n}\n\nfunction defineKeyPropWarningGetter(props, displayName) {\n {\n var warnAboutAccessingKey = function () {\n if (!specialPropKeyWarningShown) {\n specialPropKeyWarningShown = true;\n\n 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);\n }\n };\n\n warnAboutAccessingKey.isReactWarning = true;\n Object.defineProperty(props, 'key', {\n get: warnAboutAccessingKey,\n configurable: true\n });\n }\n}\n\nfunction defineRefPropWarningGetter(props, displayName) {\n {\n var warnAboutAccessingRef = function () {\n if (!specialPropRefWarningShown) {\n specialPropRefWarningShown = true;\n\n 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);\n }\n };\n\n warnAboutAccessingRef.isReactWarning = true;\n Object.defineProperty(props, 'ref', {\n get: warnAboutAccessingRef,\n configurable: true\n });\n }\n}\n/**\n * Factory method to create a new React element. This no longer adheres to\n * the class pattern, so do not use new to call it. Also, instanceof check\n * will not work. Instead test $$typeof field against Symbol.for('react.element') to check\n * if something is a React Element.\n *\n * @param {*} type\n * @param {*} props\n * @param {*} key\n * @param {string|object} ref\n * @param {*} owner\n * @param {*} self A *temporary* helper to detect places where `this` is\n * different from the `owner` when React.createElement is called, so that we\n * can warn. We want to get rid of owner and replace string `ref`s with arrow\n * functions, and as long as `this` and owner are the same, there will be no\n * change in behavior.\n * @param {*} source An annotation object (added by a transpiler or otherwise)\n * indicating filename, line number, and/or other information.\n * @internal\n */\n\n\nvar ReactElement = function (type, key, ref, self, source, owner, props) {\n var element = {\n // This tag allows us to uniquely identify this as a React Element\n $$typeof: REACT_ELEMENT_TYPE,\n // Built-in properties that belong on the element\n type: type,\n key: key,\n ref: ref,\n props: props,\n // Record the component responsible for creating this element.\n _owner: owner\n };\n\n {\n // The validation flag is currently mutative. We put it on\n // an external backing store so that we can freeze the whole object.\n // This can be replaced with a WeakMap once they are implemented in\n // commonly used development environments.\n element._store = {}; // To make comparing ReactElements easier for testing purposes, we make\n // the validation flag non-enumerable (where possible, which should\n // include every environment we run tests in), so the test framework\n // ignores it.\n\n Object.defineProperty(element._store, 'validated', {\n configurable: false,\n enumerable: false,\n writable: true,\n value: false\n }); // self and source are DEV only properties.\n\n Object.defineProperty(element, '_self', {\n configurable: false,\n enumerable: false,\n writable: false,\n value: self\n }); // Two elements created in two different places should be considered\n // equal for testing purposes and therefore we hide it from enumeration.\n\n Object.defineProperty(element, '_source', {\n configurable: false,\n enumerable: false,\n writable: false,\n value: source\n });\n\n if (Object.freeze) {\n Object.freeze(element.props);\n Object.freeze(element);\n }\n }\n\n return element;\n};\n/**\n * https://github.com/reactjs/rfcs/pull/107\n * @param {*} type\n * @param {object} props\n * @param {string} key\n */\n\nfunction jsxDEV(type, config, maybeKey, source, self) {\n {\n var propName; // Reserved names are extracted\n\n var props = {};\n var key = null;\n var ref = null; // Currently, key can be spread in as a prop. This causes a potential\n // issue if key is also explicitly declared (ie. <div {...props} key=\"Hi\" />\n // or <div key=\"Hi\" {...props} /> ). We want to deprecate key spread,\n // but as an intermediary step, we will use jsxDEV for everything except\n // <div {...props} key=\"Hi\" />, because we aren't currently able to tell if\n // key is explicitly declared to be undefined or not.\n\n if (maybeKey !== undefined) {\n {\n checkKeyStringCoercion(maybeKey);\n }\n\n key = '' + maybeKey;\n }\n\n if (hasValidKey(config)) {\n {\n checkKeyStringCoercion(config.key);\n }\n\n key = '' + config.key;\n }\n\n if (hasValidRef(config)) {\n ref = config.ref;\n warnIfStringRefCannotBeAutoConverted(config, self);\n } // Remaining properties are added to a new props object\n\n\n for (propName in config) {\n if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) {\n props[propName] = config[propName];\n }\n } // Resolve default props\n\n\n if (type && type.defaultProps) {\n var defaultProps = type.defaultProps;\n\n for (propName in defaultProps) {\n if (props[propName] === undefined) {\n props[propName] = defaultProps[propName];\n }\n }\n }\n\n if (key || ref) {\n var displayName = typeof type === 'function' ? type.displayName || type.name || 'Unknown' : type;\n\n if (key) {\n defineKeyPropWarningGetter(props, displayName);\n }\n\n if (ref) {\n defineRefPropWarningGetter(props, displayName);\n }\n }\n\n return ReactElement(type, key, ref, self, source, ReactCurrentOwner.current, props);\n }\n}\n\nvar ReactCurrentOwner$1 = ReactSharedInternals.ReactCurrentOwner;\nvar ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame;\n\nfunction setCurrentlyValidatingElement$1(element) {\n {\n if (element) {\n var owner = element._owner;\n var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null);\n ReactDebugCurrentFrame$1.setExtraStackFrame(stack);\n } else {\n ReactDebugCurrentFrame$1.setExtraStackFrame(null);\n }\n }\n}\n\nvar propTypesMisspellWarningShown;\n\n{\n propTypesMisspellWarningShown = false;\n}\n/**\n * Verifies the object is a ReactElement.\n * See https://reactjs.org/docs/react-api.html#isvalidelement\n * @param {?object} object\n * @return {boolean} True if `object` is a ReactElement.\n * @final\n */\n\n\nfunction isValidElement(object) {\n {\n return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE;\n }\n}\n\nfunction getDeclarationErrorAddendum() {\n {\n if (ReactCurrentOwner$1.current) {\n var name = getComponentNameFromType(ReactCurrentOwner$1.current.type);\n\n if (name) {\n return '\\n\\nCheck the render method of `' + name + '`.';\n }\n }\n\n return '';\n }\n}\n\nfunction getSourceInfoErrorAddendum(source) {\n {\n if (source !== undefined) {\n var fileName = source.fileName.replace(/^.*[\\\\\\/]/, '');\n var lineNumber = source.lineNumber;\n return '\\n\\nCheck your code at ' + fileName + ':' + lineNumber + '.';\n }\n\n return '';\n }\n}\n/**\n * Warn if there's no key explicitly set on dynamic arrays of children or\n * object keys are not valid. This allows us to keep track of children between\n * updates.\n */\n\n\nvar ownerHasKeyUseWarning = {};\n\nfunction getCurrentComponentErrorInfo(parentType) {\n {\n var info = getDeclarationErrorAddendum();\n\n if (!info) {\n var parentName = typeof parentType === 'string' ? parentType : parentType.displayName || parentType.name;\n\n if (parentName) {\n info = \"\\n\\nCheck the top-level render call using <\" + parentName + \">.\";\n }\n }\n\n return info;\n }\n}\n/**\n * Warn if the element doesn't have an explicit key assigned to it.\n * This element is in an array. The array could grow and shrink or be\n * reordered. All children that haven't already been validated are required to\n * have a \"key\" property assigned to it. Error statuses are cached so a warning\n * will only be shown once.\n *\n * @internal\n * @param {ReactElement} element Element that requires a key.\n * @param {*} parentType element's parent's type.\n */\n\n\nfunction validateExplicitKey(element, parentType) {\n {\n if (!element._store || element._store.validated || element.key != null) {\n return;\n }\n\n element._store.validated = true;\n var currentComponentErrorInfo = getCurrentComponentErrorInfo(parentType);\n\n if (ownerHasKeyUseWarning[currentComponentErrorInfo]) {\n return;\n }\n\n ownerHasKeyUseWarning[currentComponentErrorInfo] = true; // Usually the current owner is the offender, but if it accepts children as a\n // property, it may be the creator of the child that's responsible for\n // assigning it a key.\n\n var childOwner = '';\n\n if (element && element._owner && element._owner !== ReactCurrentOwner$1.current) {\n // Give the component that originally created this child.\n childOwner = \" It was passed a child from \" + getComponentNameFromType(element._owner.type) + \".\";\n }\n\n setCurrentlyValidatingElement$1(element);\n\n 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);\n\n setCurrentlyValidatingElement$1(null);\n }\n}\n/**\n * Ensure that every element either is passed in a static location, in an\n * array with an explicit keys property defined, or in an object literal\n * with valid key property.\n *\n * @internal\n * @param {ReactNode} node Statically passed child of any type.\n * @param {*} parentType node's parent's type.\n */\n\n\nfunction validateChildKeys(node, parentType) {\n {\n if (typeof node !== 'object') {\n return;\n }\n\n if (isArray(node)) {\n for (var i = 0; i < node.length; i++) {\n var child = node[i];\n\n if (isValidElement(child)) {\n validateExplicitKey(child, parentType);\n }\n }\n } else if (isValidElement(node)) {\n // This element was passed in a valid location.\n if (node._store) {\n node._store.validated = true;\n }\n } else if (node) {\n var iteratorFn = getIteratorFn(node);\n\n if (typeof iteratorFn === 'function') {\n // Entry iterators used to provide implicit keys,\n // but now we print a separate warning for them later.\n if (iteratorFn !== node.entries) {\n var iterator = iteratorFn.call(node);\n var step;\n\n while (!(step = iterator.next()).done) {\n if (isValidElement(step.value)) {\n validateExplicitKey(step.value, parentType);\n }\n }\n }\n }\n }\n }\n}\n/**\n * Given an element, validate that its props follow the propTypes definition,\n * provided by the type.\n *\n * @param {ReactElement} element\n */\n\n\nfunction validatePropTypes(element) {\n {\n var type = element.type;\n\n if (type === null || type === undefined || typeof type === 'string') {\n return;\n }\n\n var propTypes;\n\n if (typeof type === 'function') {\n propTypes = type.propTypes;\n } else if (typeof type === 'object' && (type.$$typeof === REACT_FORWARD_REF_TYPE || // Note: Memo only checks outer props here.\n // Inner props are checked in the reconciler.\n type.$$typeof === REACT_MEMO_TYPE)) {\n propTypes = type.propTypes;\n } else {\n return;\n }\n\n if (propTypes) {\n // Intentionally inside to avoid triggering lazy initializers:\n var name = getComponentNameFromType(type);\n checkPropTypes(propTypes, element.props, 'prop', name, element);\n } else if (type.PropTypes !== undefined && !propTypesMisspellWarningShown) {\n propTypesMisspellWarningShown = true; // Intentionally inside to avoid triggering lazy initializers:\n\n var _name = getComponentNameFromType(type);\n\n error('Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?', _name || 'Unknown');\n }\n\n if (typeof type.getDefaultProps === 'function' && !type.getDefaultProps.isReactClassApproved) {\n error('getDefaultProps is only used on classic React.createClass ' + 'definitions. Use a static property named `defaultProps` instead.');\n }\n }\n}\n/**\n * Given a fragment, validate that it can only be provided with fragment props\n * @param {ReactElement} fragment\n */\n\n\nfunction validateFragmentProps(fragment) {\n {\n var keys = Object.keys(fragment.props);\n\n for (var i = 0; i < keys.length; i++) {\n var key = keys[i];\n\n if (key !== 'children' && key !== 'key') {\n setCurrentlyValidatingElement$1(fragment);\n\n error('Invalid prop `%s` supplied to `React.Fragment`. ' + 'React.Fragment can only have `key` and `children` props.', key);\n\n setCurrentlyValidatingElement$1(null);\n break;\n }\n }\n\n if (fragment.ref !== null) {\n setCurrentlyValidatingElement$1(fragment);\n\n error('Invalid attribute `ref` supplied to `React.Fragment`.');\n\n setCurrentlyValidatingElement$1(null);\n }\n }\n}\n\nvar didWarnAboutKeySpread = {};\nfunction jsxWithValidation(type, props, key, isStaticChildren, source, self) {\n {\n var validType = isValidElementType(type); // We warn in this case but don't throw. We expect the element creation to\n // succeed and there will likely be errors in render.\n\n if (!validType) {\n var info = '';\n\n if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) {\n 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.\";\n }\n\n var sourceInfo = getSourceInfoErrorAddendum(source);\n\n if (sourceInfo) {\n info += sourceInfo;\n } else {\n info += getDeclarationErrorAddendum();\n }\n\n var typeString;\n\n if (type === null) {\n typeString = 'null';\n } else if (isArray(type)) {\n typeString = 'array';\n } else if (type !== undefined && type.$$typeof === REACT_ELEMENT_TYPE) {\n typeString = \"<\" + (getComponentNameFromType(type.type) || 'Unknown') + \" />\";\n info = ' Did you accidentally export a JSX literal instead of a component?';\n } else {\n typeString = typeof type;\n }\n\n 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);\n }\n\n var element = jsxDEV(type, props, key, source, self); // The result can be nullish if a mock or a custom function is used.\n // TODO: Drop this when these are no longer allowed as the type argument.\n\n if (element == null) {\n return element;\n } // Skip key warning if the type isn't valid since our key validation logic\n // doesn't expect a non-string/function type and can throw confusing errors.\n // We don't want exception behavior to differ between dev and prod.\n // (Rendering will throw with a helpful message and as soon as the type is\n // fixed, the key warnings will appear.)\n\n\n if (validType) {\n var children = props.children;\n\n if (children !== undefined) {\n if (isStaticChildren) {\n if (isArray(children)) {\n for (var i = 0; i < children.length; i++) {\n validateChildKeys(children[i], type);\n }\n\n if (Object.freeze) {\n Object.freeze(children);\n }\n } else {\n 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.');\n }\n } else {\n validateChildKeys(children, type);\n }\n }\n }\n\n {\n if (hasOwnProperty.call(props, 'key')) {\n var componentName = getComponentNameFromType(type);\n var keys = Object.keys(props).filter(function (k) {\n return k !== 'key';\n });\n var beforeExample = keys.length > 0 ? '{key: someKey, ' + keys.join(': ..., ') + ': ...}' : '{key: someKey}';\n\n if (!didWarnAboutKeySpread[componentName + beforeExample]) {\n var afterExample = keys.length > 0 ? '{' + keys.join(': ..., ') + ': ...}' : '{}';\n\n 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);\n\n didWarnAboutKeySpread[componentName + beforeExample] = true;\n }\n }\n }\n\n if (type === REACT_FRAGMENT_TYPE) {\n validateFragmentProps(element);\n } else {\n validatePropTypes(element);\n }\n\n return element;\n }\n} // These two functions exist to still get child warnings in dev\n// even with the prod transform. This means that jsxDEV is purely\n// opt-in behavior for better messages but that we won't stop\n// giving you warnings if you use production apis.\n\nfunction jsxWithValidationStatic(type, props, key) {\n {\n return jsxWithValidation(type, props, key, true);\n }\n}\nfunction jsxWithValidationDynamic(type, props, key) {\n {\n return jsxWithValidation(type, props, key, false);\n }\n}\n\nvar jsx = jsxWithValidationDynamic ; // we may want to special case jsxs internally to take advantage of static children.\n// for now we can ship identical prod functions\n\nvar jsxs = jsxWithValidationStatic ;\n\nexports.Fragment = REACT_FRAGMENT_TYPE;\nexports.jsx = jsx;\nexports.jsxs = jsxs;\n })();\n}\n","'use strict';\n\nif (process.env.NODE_ENV === 'production') {\n module.exports = require('./cjs/react-jsx-runtime.production.min.js');\n} else {\n module.exports = require('./cjs/react-jsx-runtime.development.js');\n}\n","import type { SVGProps } from 'react';\n\nexport interface IconProps extends SVGProps<SVGSVGElement> {\n icon?: string;\n name?: string;\n size?: number | string;\n}\n\nexport function Icon({ icon, name, size = 20, ...props }: IconProps) {\n const label = icon ?? name ?? 'Circle';\n const paths: Record<string, string> = {\n Check: 'M5 12l4 4L19 6',\n X: 'M18 6L6 18M6 6l12 12',\n Search: 'M21 21l-4.3-4.3M10.5 18a7.5 7.5 0 1 1 0-15 7.5 7.5 0 0 1 0 15Z',\n Plus: 'M12 5v14M5 12h14',\n Trash2: 'M3 6h18M8 6V4h8v2m-9 0 1 14h8l1-14M10 11v5m4-5v5',\n Edit: 'M12 20h9M16.5 3.5a2.1 2.1 0 0 1 3 3L8 18l-4 1 1-4Z',\n Circle: 'M12 12m-9 0a9 9 0 1 0 18 0a9 9 0 1 0-18 0',\n };\n const d = paths[label] ?? paths.Circle;\n\n return (\n <svg\n width={size}\n height={size}\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"1.8\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n aria-hidden=\"true\"\n {...props}\n >\n <path d={d} />\n </svg>\n );\n}\n\nexport default Icon;\r\n\r\n\r\n","import { Icon } from '../ui/Icon';\n\nexport interface StatCardProps {\n icon?: string;\n label: string;\n value: string | number;\n trendDirection?: 'up' | 'down' | 'neutral';\n color?: string;\n}\n\nexport default function StatCard({\n icon,\n label,\n value,\n trendDirection = 'neutral',\n color = '#7c3aed',\n}: StatCardProps) {\n return (\n <div className=\"rounded-xl border border-[var(--th-border)] bg-[var(--th-surface)] p-5\">\n <div className=\"mb-3 flex items-center justify-between\">\n <span className=\"text-sm text-[var(--th-text-3)]\">{label}</span>\n {icon && <Icon icon={icon} size={20} style={{ color }} />}\n </div>\n <div className=\"flex items-center gap-2\">\n <span className=\"text-2xl font-semibold text-[var(--th-text)]\">{value}</span>\n {trendDirection !== 'neutral' && (\n <span className=\"text-xs text-[var(--th-text-3)]\">\n {trendDirection === 'up' ? 'Up' : 'Up'}\n </span>\n )}\n </div>\n </div>\n );\n}\r\n\r\n\r\n\r\n","/**\n * @remix-run/router v1.23.4\n *\n * Copyright (c) Remix Software Inc.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE.md file in the root directory of this source tree.\n *\n * @license MIT\n */\nfunction _extends() {\n return _extends = Object.assign ? Object.assign.bind() : function (n) {\n for (var e = 1; e < arguments.length; e++) {\n var t = arguments[e];\n for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]);\n }\n return n;\n }, _extends.apply(null, arguments);\n}\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Types and Constants\n////////////////////////////////////////////////////////////////////////////////\n/**\n * Actions represent the type of change to a location value.\n */\nvar Action;\n(function (Action) {\n /**\n * A POP indicates a change to an arbitrary index in the history stack, such\n * as a back or forward navigation. It does not describe the direction of the\n * navigation, only that the current index changed.\n *\n * Note: This is the default action for newly created history objects.\n */\n Action[\"Pop\"] = \"POP\";\n /**\n * A PUSH indicates a new entry being added to the history stack, such as when\n * a link is clicked and a new page loads. When this happens, all subsequent\n * entries in the stack are lost.\n */\n Action[\"Push\"] = \"PUSH\";\n /**\n * A REPLACE indicates the entry at the current index in the history stack\n * being replaced by a new one.\n */\n Action[\"Replace\"] = \"REPLACE\";\n})(Action || (Action = {}));\nconst PopStateEventType = \"popstate\";\n/**\n * Memory history stores the current location in memory. It is designed for use\n * in stateful non-browser environments like tests and React Native.\n */\nfunction createMemoryHistory(options) {\n if (options === void 0) {\n options = {};\n }\n let {\n initialEntries = [\"/\"],\n initialIndex,\n v5Compat = false\n } = options;\n let entries; // Declare so we can access from createMemoryLocation\n entries = initialEntries.map((entry, index) => createMemoryLocation(entry, typeof entry === \"string\" ? null : entry.state, index === 0 ? \"default\" : undefined));\n let index = clampIndex(initialIndex == null ? entries.length - 1 : initialIndex);\n let action = Action.Pop;\n let listener = null;\n function clampIndex(n) {\n return Math.min(Math.max(n, 0), entries.length - 1);\n }\n function getCurrentLocation() {\n return entries[index];\n }\n function createMemoryLocation(to, state, key) {\n if (state === void 0) {\n state = null;\n }\n let location = createLocation(entries ? getCurrentLocation().pathname : \"/\", to, state, key);\n warning(location.pathname.charAt(0) === \"/\", \"relative pathnames are not supported in memory history: \" + JSON.stringify(to));\n return location;\n }\n function createHref(to) {\n return typeof to === \"string\" ? to : createPath(to);\n }\n let history = {\n get index() {\n return index;\n },\n get action() {\n return action;\n },\n get location() {\n return getCurrentLocation();\n },\n createHref,\n createURL(to) {\n return new URL(createHref(to), \"http://localhost\");\n },\n encodeLocation(to) {\n let path = typeof to === \"string\" ? parsePath(to) : to;\n return {\n pathname: path.pathname || \"\",\n search: path.search || \"\",\n hash: path.hash || \"\"\n };\n },\n push(to, state) {\n action = Action.Push;\n let nextLocation = createMemoryLocation(to, state);\n index += 1;\n entries.splice(index, entries.length, nextLocation);\n if (v5Compat && listener) {\n listener({\n action,\n location: nextLocation,\n delta: 1\n });\n }\n },\n replace(to, state) {\n action = Action.Replace;\n let nextLocation = createMemoryLocation(to, state);\n entries[index] = nextLocation;\n if (v5Compat && listener) {\n listener({\n action,\n location: nextLocation,\n delta: 0\n });\n }\n },\n go(delta) {\n action = Action.Pop;\n let nextIndex = clampIndex(index + delta);\n let nextLocation = entries[nextIndex];\n index = nextIndex;\n if (listener) {\n listener({\n action,\n location: nextLocation,\n delta\n });\n }\n },\n listen(fn) {\n listener = fn;\n return () => {\n listener = null;\n };\n }\n };\n return history;\n}\n/**\n * Browser history stores the location in regular URLs. This is the standard for\n * most web apps, but it requires some configuration on the server to ensure you\n * serve the same app at multiple URLs.\n *\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createbrowserhistory\n */\nfunction createBrowserHistory(options) {\n if (options === void 0) {\n options = {};\n }\n function createBrowserLocation(window, globalHistory) {\n let {\n pathname,\n search,\n hash\n } = window.location;\n return createLocation(\"\", {\n pathname,\n search,\n hash\n },\n // state defaults to `null` because `window.history.state` does\n globalHistory.state && globalHistory.state.usr || null, globalHistory.state && globalHistory.state.key || \"default\");\n }\n function createBrowserHref(window, to) {\n return typeof to === \"string\" ? to : createPath(to);\n }\n return getUrlBasedHistory(createBrowserLocation, createBrowserHref, null, options);\n}\n/**\n * Hash history stores the location in window.location.hash. This makes it ideal\n * for situations where you don't want to send the location to the server for\n * some reason, either because you do cannot configure it or the URL space is\n * reserved for something else.\n *\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createhashhistory\n */\nfunction createHashHistory(options) {\n if (options === void 0) {\n options = {};\n }\n function createHashLocation(window, globalHistory) {\n let {\n pathname = \"/\",\n search = \"\",\n hash = \"\"\n } = parsePath(window.location.hash.substr(1));\n // Hash URL should always have a leading / just like window.location.pathname\n // does, so if an app ends up at a route like /#something then we add a\n // leading slash so all of our path-matching behaves the same as if it would\n // in a browser router. This is particularly important when there exists a\n // root splat route (<Route path=\"*\">) since that matches internally against\n // \"/*\" and we'd expect /#something to 404 in a hash router app.\n if (!pathname.startsWith(\"/\") && !pathname.startsWith(\".\")) {\n pathname = \"/\" + pathname;\n }\n return createLocation(\"\", {\n pathname,\n search,\n hash\n },\n // state defaults to `null` because `window.history.state` does\n globalHistory.state && globalHistory.state.usr || null, globalHistory.state && globalHistory.state.key || \"default\");\n }\n function createHashHref(window, to) {\n let base = window.document.querySelector(\"base\");\n let href = \"\";\n if (base && base.getAttribute(\"href\")) {\n let url = window.location.href;\n let hashIndex = url.indexOf(\"#\");\n href = hashIndex === -1 ? url : url.slice(0, hashIndex);\n }\n return href + \"#\" + (typeof to === \"string\" ? to : createPath(to));\n }\n function validateHashLocation(location, to) {\n warning(location.pathname.charAt(0) === \"/\", \"relative pathnames are not supported in hash history.push(\" + JSON.stringify(to) + \")\");\n }\n return getUrlBasedHistory(createHashLocation, createHashHref, validateHashLocation, options);\n}\nfunction invariant(value, message) {\n if (value === false || value === null || typeof value === \"undefined\") {\n throw new Error(message);\n }\n}\nfunction warning(cond, message) {\n if (!cond) {\n // eslint-disable-next-line no-console\n if (typeof console !== \"undefined\") console.warn(message);\n try {\n // Welcome to debugging history!\n //\n // This error is thrown as a convenience, so you can more easily\n // find the source for a warning that appears in the console by\n // enabling \"pause on exceptions\" in your JavaScript debugger.\n throw new Error(message);\n // eslint-disable-next-line no-empty\n } catch (e) {}\n }\n}\nfunction createKey() {\n return Math.random().toString(36).substr(2, 8);\n}\n/**\n * For browser-based histories, we combine the state and key into an object\n */\nfunction getHistoryState(location, index) {\n return {\n usr: location.state,\n key: location.key,\n idx: index\n };\n}\n/**\n * Creates a Location object with a unique key from the given Path\n */\nfunction createLocation(current, to, state, key) {\n if (state === void 0) {\n state = null;\n }\n let location = _extends({\n pathname: typeof current === \"string\" ? current : current.pathname,\n search: \"\",\n hash: \"\"\n }, typeof to === \"string\" ? parsePath(to) : to, {\n state,\n // TODO: This could be cleaned up. push/replace should probably just take\n // full Locations now and avoid the need to run through this flow at all\n // But that's a pretty big refactor to the current test suite so going to\n // keep as is for the time being and just let any incoming keys take precedence\n key: to && to.key || key || createKey()\n });\n return location;\n}\n/**\n * Creates a string URL path from the given pathname, search, and hash components.\n */\nfunction createPath(_ref) {\n let {\n pathname = \"/\",\n search = \"\",\n hash = \"\"\n } = _ref;\n if (search && search !== \"?\") pathname += search.charAt(0) === \"?\" ? search : \"?\" + search;\n if (hash && hash !== \"#\") pathname += hash.charAt(0) === \"#\" ? hash : \"#\" + hash;\n return pathname;\n}\n/**\n * Parses a string URL path into its separate pathname, search, and hash components.\n */\nfunction parsePath(path) {\n let parsedPath = {};\n if (path) {\n let hashIndex = path.indexOf(\"#\");\n if (hashIndex >= 0) {\n parsedPath.hash = path.substr(hashIndex);\n path = path.substr(0, hashIndex);\n }\n let searchIndex = path.indexOf(\"?\");\n if (searchIndex >= 0) {\n parsedPath.search = path.substr(searchIndex);\n path = path.substr(0, searchIndex);\n }\n if (path) {\n parsedPath.pathname = path;\n }\n }\n return parsedPath;\n}\nfunction getUrlBasedHistory(getLocation, createHref, validateLocation, options) {\n if (options === void 0) {\n options = {};\n }\n let {\n window = document.defaultView,\n v5Compat = false\n } = options;\n let globalHistory = window.history;\n let action = Action.Pop;\n let listener = null;\n let index = getIndex();\n // Index should only be null when we initialize. If not, it's because the\n // user called history.pushState or history.replaceState directly, in which\n // case we should log a warning as it will result in bugs.\n if (index == null) {\n index = 0;\n globalHistory.replaceState(_extends({}, globalHistory.state, {\n idx: index\n }), \"\");\n }\n function getIndex() {\n let state = globalHistory.state || {\n idx: null\n };\n return state.idx;\n }\n function handlePop() {\n action = Action.Pop;\n let nextIndex = getIndex();\n let delta = nextIndex == null ? null : nextIndex - index;\n index = nextIndex;\n if (listener) {\n listener({\n action,\n location: history.location,\n delta\n });\n }\n }\n function push(to, state) {\n action = Action.Push;\n let location = createLocation(history.location, to, state);\n if (validateLocation) validateLocation(location, to);\n index = getIndex() + 1;\n let historyState = getHistoryState(location, index);\n let url = history.createHref(location);\n // try...catch because iOS limits us to 100 pushState calls :/\n try {\n globalHistory.pushState(historyState, \"\", url);\n } catch (error) {\n // If the exception is because `state` can't be serialized, let that throw\n // outwards just like a replace call would so the dev knows the cause\n // https://html.spec.whatwg.org/multipage/nav-history-apis.html#shared-history-push/replace-state-steps\n // https://html.spec.whatwg.org/multipage/structured-data.html#structuredserializeinternal\n if (error instanceof DOMException && error.name === \"DataCloneError\") {\n throw error;\n }\n // They are going to lose state here, but there is no real\n // way to warn them about it since the page will refresh...\n window.location.assign(url);\n }\n if (v5Compat && listener) {\n listener({\n action,\n location: history.location,\n delta: 1\n });\n }\n }\n function replace(to, state) {\n action = Action.Replace;\n let location = createLocation(history.location, to, state);\n if (validateLocation) validateLocation(location, to);\n index = getIndex();\n let historyState = getHistoryState(location, index);\n let url = history.createHref(location);\n globalHistory.replaceState(historyState, \"\", url);\n if (v5Compat && listener) {\n listener({\n action,\n location: history.location,\n delta: 0\n });\n }\n }\n function createURL(to) {\n // window.location.origin is \"null\" (the literal string value) in Firefox\n // under certain conditions, notably when serving from a local HTML file\n // See https://bugzilla.mozilla.org/show_bug.cgi?id=878297\n let base = window.location.origin !== \"null\" ? window.location.origin : window.location.href;\n let href = typeof to === \"string\" ? to : createPath(to);\n // Treating this as a full URL will strip any trailing spaces so we need to\n // pre-encode them since they might be part of a matching splat param from\n // an ancestor route\n href = href.replace(/ $/, \"%20\");\n invariant(base, \"No window.location.(origin|href) available to create URL for href: \" + href);\n return new URL(href, base);\n }\n let history = {\n get action() {\n return action;\n },\n get location() {\n return getLocation(window, globalHistory);\n },\n listen(fn) {\n if (listener) {\n throw new Error(\"A history only accepts one active listener\");\n }\n window.addEventListener(PopStateEventType, handlePop);\n listener = fn;\n return () => {\n window.removeEventListener(PopStateEventType, handlePop);\n listener = null;\n };\n },\n createHref(to) {\n return createHref(window, to);\n },\n createURL,\n encodeLocation(to) {\n // Encode a Location the same way window.location would\n let url = createURL(to);\n return {\n pathname: url.pathname,\n search: url.search,\n hash: url.hash\n };\n },\n push,\n replace,\n go(n) {\n return globalHistory.go(n);\n }\n };\n return history;\n}\n//#endregion\n\nvar ResultType;\n(function (ResultType) {\n ResultType[\"data\"] = \"data\";\n ResultType[\"deferred\"] = \"deferred\";\n ResultType[\"redirect\"] = \"redirect\";\n ResultType[\"error\"] = \"error\";\n})(ResultType || (ResultType = {}));\nconst immutableRouteKeys = new Set([\"lazy\", \"caseSensitive\", \"path\", \"id\", \"index\", \"children\"]);\nfunction isIndexRoute(route) {\n return route.index === true;\n}\n// Walk the route tree generating unique IDs where necessary, so we are working\n// solely with AgnosticDataRouteObject's within the Router\nfunction convertRoutesToDataRoutes(routes, mapRouteProperties, parentPath, manifest) {\n if (parentPath === void 0) {\n parentPath = [];\n }\n if (manifest === void 0) {\n manifest = {};\n }\n return routes.map((route, index) => {\n let treePath = [...parentPath, String(index)];\n let id = typeof route.id === \"string\" ? route.id : treePath.join(\"-\");\n invariant(route.index !== true || !route.children, \"Cannot specify children on an index route\");\n invariant(!manifest[id], \"Found a route id collision on id \\\"\" + id + \"\\\". Route \" + \"id's must be globally unique within Data Router usages\");\n if (isIndexRoute(route)) {\n let indexRoute = _extends({}, route, mapRouteProperties(route), {\n id\n });\n manifest[id] = indexRoute;\n return indexRoute;\n } else {\n let pathOrLayoutRoute = _extends({}, route, mapRouteProperties(route), {\n id,\n children: undefined\n });\n manifest[id] = pathOrLayoutRoute;\n if (route.children) {\n pathOrLayoutRoute.children = convertRoutesToDataRoutes(route.children, mapRouteProperties, treePath, manifest);\n }\n return pathOrLayoutRoute;\n }\n });\n}\n/**\n * Matches the given routes to a location and returns the match data.\n *\n * @see https://reactrouter.com/v6/utils/match-routes\n */\nfunction matchRoutes(routes, locationArg, basename) {\n if (basename === void 0) {\n basename = \"/\";\n }\n return matchRoutesImpl(routes, locationArg, basename, false);\n}\nfunction matchRoutesImpl(routes, locationArg, basename, allowPartial) {\n let location = typeof locationArg === \"string\" ? parsePath(locationArg) : locationArg;\n let pathname = stripBasename(location.pathname || \"/\", basename);\n if (pathname == null) {\n return null;\n }\n let branches = flattenRoutes(routes);\n rankRouteBranches(branches);\n let matches = null;\n let decoded = decodePath(pathname);\n for (let i = 0; matches == null && i < branches.length; ++i) {\n // Incoming pathnames are generally encoded from either window.location\n // or from router.navigate, but we want to match against the unencoded\n // paths in the route definitions. Memory router locations won't be\n // encoded here but there also shouldn't be anything to decode so this\n // should be a safe operation. This avoids needing matchRoutes to be\n // history-aware.\n matches = matchRouteBranch(branches[i], decoded, allowPartial);\n }\n return matches;\n}\nfunction convertRouteMatchToUiMatch(match, loaderData) {\n let {\n route,\n pathname,\n params\n } = match;\n return {\n id: route.id,\n pathname,\n params,\n data: loaderData[route.id],\n handle: route.handle\n };\n}\nfunction flattenRoutes(routes, branches, parentsMeta, parentPath) {\n if (branches === void 0) {\n branches = [];\n }\n if (parentsMeta === void 0) {\n parentsMeta = [];\n }\n if (parentPath === void 0) {\n parentPath = \"\";\n }\n let flattenRoute = (route, index, relativePath) => {\n let meta = {\n relativePath: relativePath === undefined ? route.path || \"\" : relativePath,\n caseSensitive: route.caseSensitive === true,\n childrenIndex: index,\n route\n };\n if (meta.relativePath.startsWith(\"/\")) {\n invariant(meta.relativePath.startsWith(parentPath), \"Absolute route path \\\"\" + meta.relativePath + \"\\\" nested under path \" + (\"\\\"\" + parentPath + \"\\\" is not valid. An absolute child route path \") + \"must start with the combined path of all its parent routes.\");\n meta.relativePath = meta.relativePath.slice(parentPath.length);\n }\n let path = joinPaths([parentPath, meta.relativePath]);\n let routesMeta = parentsMeta.concat(meta);\n // Add the children before adding this route to the array, so we traverse the\n // route tree depth-first and child routes appear before their parents in\n // the \"flattened\" version.\n if (route.children && route.children.length > 0) {\n invariant(\n // Our types know better, but runtime JS may not!\n // @ts-expect-error\n route.index !== true, \"Index routes must not have child routes. Please remove \" + (\"all child routes from route path \\\"\" + path + \"\\\".\"));\n flattenRoutes(route.children, branches, routesMeta, path);\n }\n // Routes without a path shouldn't ever match by themselves unless they are\n // index routes, so don't add them to the list of possible branches.\n if (route.path == null && !route.index) {\n return;\n }\n branches.push({\n path,\n score: computeScore(path, route.index),\n routesMeta\n });\n };\n routes.forEach((route, index) => {\n var _route$path;\n // coarse-grain check for optional params\n if (route.path === \"\" || !((_route$path = route.path) != null && _route$path.includes(\"?\"))) {\n flattenRoute(route, index);\n } else {\n for (let exploded of explodeOptionalSegments(route.path)) {\n flattenRoute(route, index, exploded);\n }\n }\n });\n return branches;\n}\n/**\n * Computes all combinations of optional path segments for a given path,\n * excluding combinations that are ambiguous and of lower priority.\n *\n * For example, `/one/:two?/three/:four?/:five?` explodes to:\n * - `/one/three`\n * - `/one/:two/three`\n * - `/one/three/:four`\n * - `/one/three/:five`\n * - `/one/:two/three/:four`\n * - `/one/:two/three/:five`\n * - `/one/three/:four/:five`\n * - `/one/:two/three/:four/:five`\n */\nfunction explodeOptionalSegments(path) {\n let segments = path.split(\"/\");\n if (segments.length === 0) return [];\n let [first, ...rest] = segments;\n // Optional path segments are denoted by a trailing `?`\n let isOptional = first.endsWith(\"?\");\n // Compute the corresponding required segment: `foo?` -> `foo`\n let required = first.replace(/\\?$/, \"\");\n if (rest.length === 0) {\n // Intepret empty string as omitting an optional segment\n // `[\"one\", \"\", \"three\"]` corresponds to omitting `:two` from `/one/:two?/three` -> `/one/three`\n return isOptional ? [required, \"\"] : [required];\n }\n let restExploded = explodeOptionalSegments(rest.join(\"/\"));\n let result = [];\n // All child paths with the prefix. Do this for all children before the\n // optional version for all children, so we get consistent ordering where the\n // parent optional aspect is preferred as required. Otherwise, we can get\n // child sections interspersed where deeper optional segments are higher than\n // parent optional segments, where for example, /:two would explode _earlier_\n // then /:one. By always including the parent as required _for all children_\n // first, we avoid this issue\n result.push(...restExploded.map(subpath => subpath === \"\" ? required : [required, subpath].join(\"/\")));\n // Then, if this is an optional value, add all child versions without\n if (isOptional) {\n result.push(...restExploded);\n }\n // for absolute paths, ensure `/` instead of empty segment\n return result.map(exploded => path.startsWith(\"/\") && exploded === \"\" ? \"/\" : exploded);\n}\nfunction rankRouteBranches(branches) {\n branches.sort((a, b) => a.score !== b.score ? b.score - a.score // Higher score first\n : compareIndexes(a.routesMeta.map(meta => meta.childrenIndex), b.routesMeta.map(meta => meta.childrenIndex)));\n}\nconst paramRe = /^:[\\w-]+$/;\nconst dynamicSegmentValue = 3;\nconst indexRouteValue = 2;\nconst emptySegmentValue = 1;\nconst staticSegmentValue = 10;\nconst splatPenalty = -2;\nconst isSplat = s => s === \"*\";\nfunction computeScore(path, index) {\n let segments = path.split(\"/\");\n let initialScore = segments.length;\n if (segments.some(isSplat)) {\n initialScore += splatPenalty;\n }\n if (index) {\n initialScore += indexRouteValue;\n }\n return segments.filter(s => !isSplat(s)).reduce((score, segment) => score + (paramRe.test(segment) ? dynamicSegmentValue : segment === \"\" ? emptySegmentValue : staticSegmentValue), initialScore);\n}\nfunction compareIndexes(a, b) {\n let siblings = a.length === b.length && a.slice(0, -1).every((n, i) => n === b[i]);\n return siblings ?\n // If two routes are siblings, we should try to match the earlier sibling\n // first. This allows people to have fine-grained control over the matching\n // behavior by simply putting routes with identical paths in the order they\n // want them tried.\n a[a.length - 1] - b[b.length - 1] :\n // Otherwise, it doesn't really make sense to rank non-siblings by index,\n // so they sort equally.\n 0;\n}\nfunction matchRouteBranch(branch, pathname, allowPartial) {\n if (allowPartial === void 0) {\n allowPartial = false;\n }\n let {\n routesMeta\n } = branch;\n let matchedParams = {};\n let matchedPathname = \"/\";\n let matches = [];\n for (let i = 0; i < routesMeta.length; ++i) {\n let meta = routesMeta[i];\n let end = i === routesMeta.length - 1;\n let remainingPathname = matchedPathname === \"/\" ? pathname : pathname.slice(matchedPathname.length) || \"/\";\n let match = matchPath({\n path: meta.relativePath,\n caseSensitive: meta.caseSensitive,\n end\n }, remainingPathname);\n let route = meta.route;\n if (!match && end && allowPartial && !routesMeta[routesMeta.length - 1].route.index) {\n match = matchPath({\n path: meta.relativePath,\n caseSensitive: meta.caseSensitive,\n end: false\n }, remainingPathname);\n }\n if (!match) {\n return null;\n }\n Object.assign(matchedParams, match.params);\n matches.push({\n // TODO: Can this as be avoided?\n params: matchedParams,\n pathname: joinPaths([matchedPathname, match.pathname]),\n pathnameBase: normalizePathname(joinPaths([matchedPathname, match.pathnameBase])),\n route\n });\n if (match.pathnameBase !== \"/\") {\n matchedPathname = joinPaths([matchedPathname, match.pathnameBase]);\n }\n }\n return matches;\n}\n/**\n * Returns a path with params interpolated.\n *\n * @see https://reactrouter.com/v6/utils/generate-path\n */\nfunction generatePath(originalPath, params) {\n if (params === void 0) {\n params = {};\n }\n let path = originalPath;\n if (path.endsWith(\"*\") && path !== \"*\" && !path.endsWith(\"/*\")) {\n warning(false, \"Route path \\\"\" + path + \"\\\" will be treated as if it were \" + (\"\\\"\" + path.replace(/\\*$/, \"/*\") + \"\\\" because the `*` character must \") + \"always follow a `/` in the pattern. To get rid of this warning, \" + (\"please change the route path to \\\"\" + path.replace(/\\*$/, \"/*\") + \"\\\".\"));\n path = path.replace(/\\*$/, \"/*\");\n }\n // ensure `/` is added at the beginning if the path is absolute\n const prefix = path.startsWith(\"/\") ? \"/\" : \"\";\n const stringify = p => p == null ? \"\" : typeof p === \"string\" ? p : String(p);\n const segments = path.split(/\\/+/).map((segment, index, array) => {\n const isLastSegment = index === array.length - 1;\n // only apply the splat if it's the last segment\n if (isLastSegment && segment === \"*\") {\n const star = \"*\";\n // Apply the splat\n return stringify(params[star]);\n }\n const keyMatch = segment.match(/^:([\\w-]+)(\\??)$/);\n if (keyMatch) {\n const [, key, optional] = keyMatch;\n let param = params[key];\n invariant(optional === \"?\" || param != null, \"Missing \\\":\" + key + \"\\\" param\");\n return stringify(param);\n }\n // Remove any optional markers from optional static segments\n return segment.replace(/\\?$/g, \"\");\n })\n // Remove empty segments\n .filter(segment => !!segment);\n return prefix + segments.join(\"/\");\n}\n/**\n * Performs pattern matching on a URL pathname and returns information about\n * the match.\n *\n * @see https://reactrouter.com/v6/utils/match-path\n */\nfunction matchPath(pattern, pathname) {\n if (typeof pattern === \"string\") {\n pattern = {\n path: pattern,\n caseSensitive: false,\n end: true\n };\n }\n let [matcher, compiledParams] = compilePath(pattern.path, pattern.caseSensitive, pattern.end);\n let match = pathname.match(matcher);\n if (!match) return null;\n let matchedPathname = match[0];\n let pathnameBase = matchedPathname.replace(/(.)\\/+$/, \"$1\");\n let captureGroups = match.slice(1);\n let params = compiledParams.reduce((memo, _ref, index) => {\n let {\n paramName,\n isOptional\n } = _ref;\n // We need to compute the pathnameBase here using the raw splat value\n // instead of using params[\"*\"] later because it will be decoded then\n if (paramName === \"*\") {\n let splatValue = captureGroups[index] || \"\";\n pathnameBase = matchedPathname.slice(0, matchedPathname.length - splatValue.length).replace(/(.)\\/+$/, \"$1\");\n }\n const value = captureGroups[index];\n if (isOptional && !value) {\n memo[paramName] = undefined;\n } else {\n memo[paramName] = (value || \"\").replace(/%2F/g, \"/\");\n }\n return memo;\n }, {});\n return {\n params,\n pathname: matchedPathname,\n pathnameBase,\n pattern\n };\n}\nfunction compilePath(path, caseSensitive, end) {\n if (caseSensitive === void 0) {\n caseSensitive = false;\n }\n if (end === void 0) {\n end = true;\n }\n warning(path === \"*\" || !path.endsWith(\"*\") || path.endsWith(\"/*\"), \"Route path \\\"\" + path + \"\\\" will be treated as if it were \" + (\"\\\"\" + path.replace(/\\*$/, \"/*\") + \"\\\" because the `*` character must \") + \"always follow a `/` in the pattern. To get rid of this warning, \" + (\"please change the route path to \\\"\" + path.replace(/\\*$/, \"/*\") + \"\\\".\"));\n let params = [];\n let regexpSource = \"^\" + path.replace(/\\/*\\*?$/, \"\") // Ignore trailing / and /*, we'll handle it below\n .replace(/^\\/*/, \"/\") // Make sure it has a leading /\n .replace(/[\\\\.*+^${}|()[\\]]/g, \"\\\\$&\") // Escape special regex chars\n .replace(/\\/:([\\w-]+)(\\?)?/g, (_, paramName, isOptional) => {\n params.push({\n paramName,\n isOptional: isOptional != null\n });\n return isOptional ? \"/?([^\\\\/]+)?\" : \"/([^\\\\/]+)\";\n });\n if (path.endsWith(\"*\")) {\n params.push({\n paramName: \"*\"\n });\n regexpSource += path === \"*\" || path === \"/*\" ? \"(.*)$\" // Already matched the initial /, just match the rest\n : \"(?:\\\\/(.+)|\\\\/*)$\"; // Don't include the / in params[\"*\"]\n } else if (end) {\n // When matching to the end, ignore trailing slashes\n regexpSource += \"\\\\/*$\";\n } else if (path !== \"\" && path !== \"/\") {\n // If our path is non-empty and contains anything beyond an initial slash,\n // then we have _some_ form of path in our regex, so we should expect to\n // match only if we find the end of this path segment. Look for an optional\n // non-captured trailing slash (to match a portion of the URL) or the end\n // of the path (if we've matched to the end). We used to do this with a\n // word boundary but that gives false positives on routes like\n // /user-preferences since `-` counts as a word boundary.\n regexpSource += \"(?:(?=\\\\/|$))\";\n } else ;\n let matcher = new RegExp(regexpSource, caseSensitive ? undefined : \"i\");\n return [matcher, params];\n}\nfunction decodePath(value) {\n try {\n return value.split(\"/\").map(v => decodeURIComponent(v).replace(/\\//g, \"%2F\")).join(\"/\");\n } catch (error) {\n warning(false, \"The URL path \\\"\" + value + \"\\\" could not be decoded because it is is a \" + \"malformed URL segment. This is probably due to a bad percent \" + (\"encoding (\" + error + \").\"));\n return value;\n }\n}\n/**\n * @private\n */\nfunction stripBasename(pathname, basename) {\n if (basename === \"/\") return pathname;\n if (!pathname.toLowerCase().startsWith(basename.toLowerCase())) {\n return null;\n }\n // We want to leave trailing slash behavior in the user's control, so if they\n // specify a basename with a trailing slash, we should support it\n let startIndex = basename.endsWith(\"/\") ? basename.length - 1 : basename.length;\n let nextChar = pathname.charAt(startIndex);\n if (nextChar && nextChar !== \"/\") {\n // pathname does not start with basename/\n return null;\n }\n return pathname.slice(startIndex) || \"/\";\n}\n/**\n * Returns a resolved path object relative to the given pathname.\n *\n * @see https://reactrouter.com/v6/utils/resolve-path\n */\nfunction resolvePath(to, fromPathname) {\n if (fromPathname === void 0) {\n fromPathname = \"/\";\n }\n let {\n pathname: toPathname,\n search = \"\",\n hash = \"\"\n } = typeof to === \"string\" ? parsePath(to) : to;\n let pathname;\n if (toPathname) {\n toPathname = removeDoubleSlashes(toPathname);\n if (toPathname.startsWith(\"/\")) {\n pathname = resolvePathname(toPathname.substring(1), \"/\");\n } else {\n pathname = resolvePathname(toPathname, fromPathname);\n }\n } else {\n pathname = fromPathname;\n }\n return {\n pathname,\n search: normalizeSearch(search),\n hash: normalizeHash(hash)\n };\n}\nfunction resolvePathname(relativePath, fromPathname) {\n let segments = fromPathname.replace(/\\/+$/, \"\").split(\"/\");\n let relativeSegments = relativePath.split(\"/\");\n relativeSegments.forEach(segment => {\n if (segment === \"..\") {\n // Keep the root \"\" segment so the pathname starts at /\n if (segments.length > 1) segments.pop();\n } else if (segment !== \".\") {\n segments.push(segment);\n }\n });\n return segments.length > 1 ? segments.join(\"/\") : \"/\";\n}\nfunction getInvalidPathError(char, field, dest, path) {\n return \"Cannot include a '\" + char + \"' character in a manually specified \" + (\"`to.\" + field + \"` field [\" + JSON.stringify(path) + \"]. Please separate it out to the \") + (\"`to.\" + dest + \"` field. Alternatively you may provide the full path as \") + \"a string in <Link to=\\\"...\\\"> and the router will parse it for you.\";\n}\n/**\n * @private\n *\n * When processing relative navigation we want to ignore ancestor routes that\n * do not contribute to the path, such that index/pathless layout routes don't\n * interfere.\n *\n * For example, when moving a route element into an index route and/or a\n * pathless layout route, relative link behavior contained within should stay\n * the same. Both of the following examples should link back to the root:\n *\n * <Route path=\"/\">\n * <Route path=\"accounts\" element={<Link to=\"..\"}>\n * </Route>\n *\n * <Route path=\"/\">\n * <Route path=\"accounts\">\n * <Route element={<AccountsLayout />}> // <-- Does not contribute\n * <Route index element={<Link to=\"..\"} /> // <-- Does not contribute\n * </Route\n * </Route>\n * </Route>\n */\nfunction getPathContributingMatches(matches) {\n return matches.filter((match, index) => index === 0 || match.route.path && match.route.path.length > 0);\n}\n// Return the array of pathnames for the current route matches - used to\n// generate the routePathnames input for resolveTo()\nfunction getResolveToMatches(matches, v7_relativeSplatPath) {\n let pathMatches = getPathContributingMatches(matches);\n // When v7_relativeSplatPath is enabled, use the full pathname for the leaf\n // match so we include splat values for \".\" links. See:\n // https://github.com/remix-run/react-router/issues/11052#issuecomment-1836589329\n if (v7_relativeSplatPath) {\n return pathMatches.map((match, idx) => idx === pathMatches.length - 1 ? match.pathname : match.pathnameBase);\n }\n return pathMatches.map(match => match.pathnameBase);\n}\n/**\n * @private\n */\nfunction resolveTo(toArg, routePathnames, locationPathname, isPathRelative) {\n if (isPathRelative === void 0) {\n isPathRelative = false;\n }\n let to;\n if (typeof toArg === \"string\") {\n to = parsePath(toArg);\n } else {\n to = _extends({}, toArg);\n invariant(!to.pathname || !to.pathname.includes(\"?\"), getInvalidPathError(\"?\", \"pathname\", \"search\", to));\n invariant(!to.pathname || !to.pathname.includes(\"#\"), getInvalidPathError(\"#\", \"pathname\", \"hash\", to));\n invariant(!to.search || !to.search.includes(\"#\"), getInvalidPathError(\"#\", \"search\", \"hash\", to));\n }\n let isEmptyPath = toArg === \"\" || to.pathname === \"\";\n let toPathname = isEmptyPath ? \"/\" : to.pathname;\n let from;\n // Routing is relative to the current pathname if explicitly requested.\n //\n // If a pathname is explicitly provided in `to`, it should be relative to the\n // route context. This is explained in `Note on `<Link to>` values` in our\n // migration guide from v5 as a means of disambiguation between `to` values\n // that begin with `/` and those that do not. However, this is problematic for\n // `to` values that do not provide a pathname. `to` can simply be a search or\n // hash string, in which case we should assume that the navigation is relative\n // to the current location's pathname and *not* the route pathname.\n if (toPathname == null) {\n from = locationPathname;\n } else {\n let routePathnameIndex = routePathnames.length - 1;\n // With relative=\"route\" (the default), each leading .. segment means\n // \"go up one route\" instead of \"go up one URL segment\". This is a key\n // difference from how <a href> works and a major reason we call this a\n // \"to\" value instead of a \"href\".\n if (!isPathRelative && toPathname.startsWith(\"..\")) {\n let toSegments = toPathname.split(\"/\");\n while (toSegments[0] === \"..\") {\n toSegments.shift();\n routePathnameIndex -= 1;\n }\n to.pathname = toSegments.join(\"/\");\n }\n from = routePathnameIndex >= 0 ? routePathnames[routePathnameIndex] : \"/\";\n }\n let path = resolvePath(to, from);\n // Ensure the pathname has a trailing slash if the original \"to\" had one\n let hasExplicitTrailingSlash = toPathname && toPathname !== \"/\" && toPathname.endsWith(\"/\");\n // Or if this was a link to the current path which has a trailing slash\n let hasCurrentTrailingSlash = (isEmptyPath || toPathname === \".\") && locationPathname.endsWith(\"/\");\n if (!path.pathname.endsWith(\"/\") && (hasExplicitTrailingSlash || hasCurrentTrailingSlash)) {\n path.pathname += \"/\";\n }\n return path;\n}\n/**\n * @private\n */\nfunction getToPathname(to) {\n // Empty strings should be treated the same as / paths\n return to === \"\" || to.pathname === \"\" ? \"/\" : typeof to === \"string\" ? parsePath(to).pathname : to.pathname;\n}\nconst removeDoubleSlashes = path => path.replace(/\\/\\/+/g, \"/\");\n/**\n * @private\n */\nconst joinPaths = paths => removeDoubleSlashes(paths.join(\"/\"));\n/**\n * @private\n */\nconst normalizePathname = pathname => pathname.replace(/\\/+$/, \"\").replace(/^\\/*/, \"/\");\n/**\n * @private\n */\nconst normalizeSearch = search => !search || search === \"?\" ? \"\" : search.startsWith(\"?\") ? search : \"?\" + search;\n/**\n * @private\n */\nconst normalizeHash = hash => !hash || hash === \"#\" ? \"\" : hash.startsWith(\"#\") ? hash : \"#\" + hash;\n/**\n * This is a shortcut for creating `application/json` responses. Converts `data`\n * to JSON and sets the `Content-Type` header.\n *\n * @deprecated The `json` method is deprecated in favor of returning raw objects.\n * This method will be removed in v7.\n */\nconst json = function json(data, init) {\n if (init === void 0) {\n init = {};\n }\n let responseInit = typeof init === \"number\" ? {\n status: init\n } : init;\n let headers = new Headers(responseInit.headers);\n if (!headers.has(\"Content-Type\")) {\n headers.set(\"Content-Type\", \"application/json; charset=utf-8\");\n }\n return new Response(JSON.stringify(data), _extends({}, responseInit, {\n headers\n }));\n};\nclass DataWithResponseInit {\n constructor(data, init) {\n this.type = \"DataWithResponseInit\";\n this.data = data;\n this.init = init || null;\n }\n}\n/**\n * Create \"responses\" that contain `status`/`headers` without forcing\n * serialization into an actual `Response` - used by Remix single fetch\n */\nfunction data(data, init) {\n return new DataWithResponseInit(data, typeof init === \"number\" ? {\n status: init\n } : init);\n}\nclass AbortedDeferredError extends Error {}\nclass DeferredData {\n constructor(data, responseInit) {\n this.pendingKeysSet = new Set();\n this.subscribers = new Set();\n this.deferredKeys = [];\n invariant(data && typeof data === \"object\" && !Array.isArray(data), \"defer() only accepts plain objects\");\n // Set up an AbortController + Promise we can race against to exit early\n // cancellation\n let reject;\n this.abortPromise = new Promise((_, r) => reject = r);\n this.controller = new AbortController();\n let onAbort = () => reject(new AbortedDeferredError(\"Deferred data aborted\"));\n this.unlistenAbortSignal = () => this.controller.signal.removeEventListener(\"abort\", onAbort);\n this.controller.signal.addEventListener(\"abort\", onAbort);\n this.data = Object.entries(data).reduce((acc, _ref2) => {\n let [key, value] = _ref2;\n return Object.assign(acc, {\n [key]: this.trackPromise(key, value)\n });\n }, {});\n if (this.done) {\n // All incoming values were resolved\n this.unlistenAbortSignal();\n }\n this.init = responseInit;\n }\n trackPromise(key, value) {\n if (!(value instanceof Promise)) {\n return value;\n }\n this.deferredKeys.push(key);\n this.pendingKeysSet.add(key);\n // We store a little wrapper promise that will be extended with\n // _data/_error props upon resolve/reject\n let promise = Promise.race([value, this.abortPromise]).then(data => this.onSettle(promise, key, undefined, data), error => this.onSettle(promise, key, error));\n // Register rejection listeners to avoid uncaught promise rejections on\n // errors or aborted deferred values\n promise.catch(() => {});\n Object.defineProperty(promise, \"_tracked\", {\n get: () => true\n });\n return promise;\n }\n onSettle(promise, key, error, data) {\n if (this.controller.signal.aborted && error instanceof AbortedDeferredError) {\n this.unlistenAbortSignal();\n Object.defineProperty(promise, \"_error\", {\n get: () => error\n });\n return Promise.reject(error);\n }\n this.pendingKeysSet.delete(key);\n if (this.done) {\n // Nothing left to abort!\n this.unlistenAbortSignal();\n }\n // If the promise was resolved/rejected with undefined, we'll throw an error as you\n // should always resolve with a value or null\n if (error === undefined && data === undefined) {\n let undefinedError = new Error(\"Deferred data for key \\\"\" + key + \"\\\" resolved/rejected with `undefined`, \" + \"you must resolve/reject with a value or `null`.\");\n Object.defineProperty(promise, \"_error\", {\n get: () => undefinedError\n });\n this.emit(false, key);\n return Promise.reject(undefinedError);\n }\n if (data === undefined) {\n Object.defineProperty(promise, \"_error\", {\n get: () => error\n });\n this.emit(false, key);\n return Promise.reject(error);\n }\n Object.defineProperty(promise, \"_data\", {\n get: () => data\n });\n this.emit(false, key);\n return data;\n }\n emit(aborted, settledKey) {\n this.subscribers.forEach(subscriber => subscriber(aborted, settledKey));\n }\n subscribe(fn) {\n this.subscribers.add(fn);\n return () => this.subscribers.delete(fn);\n }\n cancel() {\n this.controller.abort();\n this.pendingKeysSet.forEach((v, k) => this.pendingKeysSet.delete(k));\n this.emit(true);\n }\n async resolveData(signal) {\n let aborted = false;\n if (!this.done) {\n let onAbort = () => this.cancel();\n signal.addEventListener(\"abort\", onAbort);\n aborted = await new Promise(resolve => {\n this.subscribe(aborted => {\n signal.removeEventListener(\"abort\", onAbort);\n if (aborted || this.done) {\n resolve(aborted);\n }\n });\n });\n }\n return aborted;\n }\n get done() {\n return this.pendingKeysSet.size === 0;\n }\n get unwrappedData() {\n invariant(this.data !== null && this.done, \"Can only unwrap data on initialized and settled deferreds\");\n return Object.entries(this.data).reduce((acc, _ref3) => {\n let [key, value] = _ref3;\n return Object.assign(acc, {\n [key]: unwrapTrackedPromise(value)\n });\n }, {});\n }\n get pendingKeys() {\n return Array.from(this.pendingKeysSet);\n }\n}\nfunction isTrackedPromise(value) {\n return value instanceof Promise && value._tracked === true;\n}\nfunction unwrapTrackedPromise(value) {\n if (!isTrackedPromise(value)) {\n return value;\n }\n if (value._error) {\n throw value._error;\n }\n return value._data;\n}\n/**\n * @deprecated The `defer` method is deprecated in favor of returning raw\n * objects. This method will be removed in v7.\n */\nconst defer = function defer(data, init) {\n if (init === void 0) {\n init = {};\n }\n let responseInit = typeof init === \"number\" ? {\n status: init\n } : init;\n return new DeferredData(data, responseInit);\n};\n/**\n * A redirect response. Sets the status code and the `Location` header.\n * Defaults to \"302 Found\".\n */\nconst redirect = function redirect(url, init) {\n if (init === void 0) {\n init = 302;\n }\n let responseInit = init;\n if (typeof responseInit === \"number\") {\n responseInit = {\n status: responseInit\n };\n } else if (typeof responseInit.status === \"undefined\") {\n responseInit.status = 302;\n }\n let headers = new Headers(responseInit.headers);\n headers.set(\"Location\", url);\n return new Response(null, _extends({}, responseInit, {\n headers\n }));\n};\n/**\n * A redirect response that will force a document reload to the new location.\n * Sets the status code and the `Location` header.\n * Defaults to \"302 Found\".\n */\nconst redirectDocument = (url, init) => {\n let response = redirect(url, init);\n response.headers.set(\"X-Remix-Reload-Document\", \"true\");\n return response;\n};\n/**\n * A redirect response that will perform a `history.replaceState` instead of a\n * `history.pushState` for client-side navigation redirects.\n * Sets the status code and the `Location` header.\n * Defaults to \"302 Found\".\n */\nconst replace = (url, init) => {\n let response = redirect(url, init);\n response.headers.set(\"X-Remix-Replace\", \"true\");\n return response;\n};\n/**\n * @private\n * Utility class we use to hold auto-unwrapped 4xx/5xx Response bodies\n *\n * We don't export the class for public use since it's an implementation\n * detail, but we export the interface above so folks can build their own\n * abstractions around instances via isRouteErrorResponse()\n */\nclass ErrorResponseImpl {\n constructor(status, statusText, data, internal) {\n if (internal === void 0) {\n internal = false;\n }\n this.status = status;\n this.statusText = statusText || \"\";\n this.internal = internal;\n if (data instanceof Error) {\n this.data = data.toString();\n this.error = data;\n } else {\n this.data = data;\n }\n }\n}\n/**\n * Check if the given error is an ErrorResponse generated from a 4xx/5xx\n * Response thrown from an action/loader\n */\nfunction isRouteErrorResponse(error) {\n return error != null && typeof error.status === \"number\" && typeof error.statusText === \"string\" && typeof error.internal === \"boolean\" && \"data\" in error;\n}\n\nconst validMutationMethodsArr = [\"post\", \"put\", \"patch\", \"delete\"];\nconst validMutationMethods = new Set(validMutationMethodsArr);\nconst validRequestMethodsArr = [\"get\", ...validMutationMethodsArr];\nconst validRequestMethods = new Set(validRequestMethodsArr);\nconst redirectStatusCodes = new Set([301, 302, 303, 307, 308]);\nconst redirectPreserveMethodStatusCodes = new Set([307, 308]);\nconst IDLE_NAVIGATION = {\n state: \"idle\",\n location: undefined,\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n json: undefined,\n text: undefined\n};\nconst IDLE_FETCHER = {\n state: \"idle\",\n data: undefined,\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n json: undefined,\n text: undefined\n};\nconst IDLE_BLOCKER = {\n state: \"unblocked\",\n proceed: undefined,\n reset: undefined,\n location: undefined\n};\nconst ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\\/\\/)/i;\nconst defaultMapRouteProperties = route => ({\n hasErrorBoundary: Boolean(route.hasErrorBoundary)\n});\nconst TRANSITIONS_STORAGE_KEY = \"remix-router-transitions\";\n//#endregion\n////////////////////////////////////////////////////////////////////////////////\n//#region createRouter\n////////////////////////////////////////////////////////////////////////////////\n/**\n * Create a router and listen to history POP navigations\n */\nfunction createRouter(init) {\n const routerWindow = init.window ? init.window : typeof window !== \"undefined\" ? window : undefined;\n const isBrowser = typeof routerWindow !== \"undefined\" && typeof routerWindow.document !== \"undefined\" && typeof routerWindow.document.createElement !== \"undefined\";\n const isServer = !isBrowser;\n invariant(init.routes.length > 0, \"You must provide a non-empty routes array to createRouter\");\n let mapRouteProperties;\n if (init.mapRouteProperties) {\n mapRouteProperties = init.mapRouteProperties;\n } else if (init.detectErrorBoundary) {\n // If they are still using the deprecated version, wrap it with the new API\n let detectErrorBoundary = init.detectErrorBoundary;\n mapRouteProperties = route => ({\n hasErrorBoundary: detectErrorBoundary(route)\n });\n } else {\n mapRouteProperties = defaultMapRouteProperties;\n }\n // Routes keyed by ID\n let manifest = {};\n // Routes in tree format for matching\n let dataRoutes = convertRoutesToDataRoutes(init.routes, mapRouteProperties, undefined, manifest);\n let inFlightDataRoutes;\n let basename = init.basename || \"/\";\n let dataStrategyImpl = init.dataStrategy || defaultDataStrategy;\n let patchRoutesOnNavigationImpl = init.patchRoutesOnNavigation;\n // Config driven behavior flags\n let future = _extends({\n v7_fetcherPersist: false,\n v7_normalizeFormMethod: false,\n v7_partialHydration: false,\n v7_prependBasename: false,\n v7_relativeSplatPath: false,\n v7_skipActionErrorRevalidation: false\n }, init.future);\n // Cleanup function for history\n let unlistenHistory = null;\n // Externally-provided functions to call on all state changes\n let subscribers = new Set();\n // Externally-provided object to hold scroll restoration locations during routing\n let savedScrollPositions = null;\n // Externally-provided function to get scroll restoration keys\n let getScrollRestorationKey = null;\n // Externally-provided function to get current scroll position\n let getScrollPosition = null;\n // One-time flag to control the initial hydration scroll restoration. Because\n // we don't get the saved positions from <ScrollRestoration /> until _after_\n // the initial render, we need to manually trigger a separate updateState to\n // send along the restoreScrollPosition\n // Set to true if we have `hydrationData` since we assume we were SSR'd and that\n // SSR did the initial scroll restoration.\n let initialScrollRestored = init.hydrationData != null;\n let initialMatches = matchRoutes(dataRoutes, init.history.location, basename);\n let initialMatchesIsFOW = false;\n let initialErrors = null;\n if (initialMatches == null && !patchRoutesOnNavigationImpl) {\n // If we do not match a user-provided-route, fall back to the root\n // to allow the error boundary to take over\n let error = getInternalRouterError(404, {\n pathname: init.history.location.pathname\n });\n let {\n matches,\n route\n } = getShortCircuitMatches(dataRoutes);\n initialMatches = matches;\n initialErrors = {\n [route.id]: error\n };\n }\n // In SPA apps, if the user provided a patchRoutesOnNavigation implementation and\n // our initial match is a splat route, clear them out so we run through lazy\n // discovery on hydration in case there's a more accurate lazy route match.\n // In SSR apps (with `hydrationData`), we expect that the server will send\n // up the proper matched routes so we don't want to run lazy discovery on\n // initial hydration and want to hydrate into the splat route.\n if (initialMatches && !init.hydrationData) {\n let fogOfWar = checkFogOfWar(initialMatches, dataRoutes, init.history.location.pathname);\n if (fogOfWar.active) {\n initialMatches = null;\n }\n }\n let initialized;\n if (!initialMatches) {\n initialized = false;\n initialMatches = [];\n // If partial hydration and fog of war is enabled, we will be running\n // `patchRoutesOnNavigation` during hydration so include any partial matches as\n // the initial matches so we can properly render `HydrateFallback`'s\n if (future.v7_partialHydration) {\n let fogOfWar = checkFogOfWar(null, dataRoutes, init.history.location.pathname);\n if (fogOfWar.active && fogOfWar.matches) {\n initialMatchesIsFOW = true;\n initialMatches = fogOfWar.matches;\n }\n }\n } else if (initialMatches.some(m => m.route.lazy)) {\n // All initialMatches need to be loaded before we're ready. If we have lazy\n // functions around still then we'll need to run them in initialize()\n initialized = false;\n } else if (!initialMatches.some(m => m.route.loader)) {\n // If we've got no loaders to run, then we're good to go\n initialized = true;\n } else if (future.v7_partialHydration) {\n // If partial hydration is enabled, we're initialized so long as we were\n // provided with hydrationData for every route with a loader, and no loaders\n // were marked for explicit hydration\n let loaderData = init.hydrationData ? init.hydrationData.loaderData : null;\n let errors = init.hydrationData ? init.hydrationData.errors : null;\n // If errors exist, don't consider routes below the boundary\n if (errors) {\n let idx = initialMatches.findIndex(m => errors[m.route.id] !== undefined);\n initialized = initialMatches.slice(0, idx + 1).every(m => !shouldLoadRouteOnHydration(m.route, loaderData, errors));\n } else {\n initialized = initialMatches.every(m => !shouldLoadRouteOnHydration(m.route, loaderData, errors));\n }\n } else {\n // Without partial hydration - we're initialized if we were provided any\n // hydrationData - which is expected to be complete\n initialized = init.hydrationData != null;\n }\n let router;\n let state = {\n historyAction: init.history.action,\n location: init.history.location,\n matches: initialMatches,\n initialized,\n navigation: IDLE_NAVIGATION,\n // Don't restore on initial updateState() if we were SSR'd\n restoreScrollPosition: init.hydrationData != null ? false : null,\n preventScrollReset: false,\n revalidation: \"idle\",\n loaderData: init.hydrationData && init.hydrationData.loaderData || {},\n actionData: init.hydrationData && init.hydrationData.actionData || null,\n errors: init.hydrationData && init.hydrationData.errors || initialErrors,\n fetchers: new Map(),\n blockers: new Map()\n };\n // -- Stateful internal variables to manage navigations --\n // Current navigation in progress (to be committed in completeNavigation)\n let pendingAction = Action.Pop;\n // Should the current navigation prevent the scroll reset if scroll cannot\n // be restored?\n let pendingPreventScrollReset = false;\n // AbortController for the active navigation\n let pendingNavigationController;\n // Should the current navigation enable document.startViewTransition?\n let pendingViewTransitionEnabled = false;\n // Store applied view transitions so we can apply them on POP\n let appliedViewTransitions = new Map();\n // Cleanup function for persisting applied transitions to sessionStorage\n let removePageHideEventListener = null;\n // We use this to avoid touching history in completeNavigation if a\n // revalidation is entirely uninterrupted\n let isUninterruptedRevalidation = false;\n // Use this internal flag to force revalidation of all loaders:\n // - submissions (completed or interrupted)\n // - useRevalidator()\n // - X-Remix-Revalidate (from redirect)\n let isRevalidationRequired = false;\n // Use this internal array to capture routes that require revalidation due\n // to a cancelled deferred on action submission\n let cancelledDeferredRoutes = [];\n // Use this internal array to capture fetcher loads that were cancelled by an\n // action navigation and require revalidation\n let cancelledFetcherLoads = new Set();\n // AbortControllers for any in-flight fetchers\n let fetchControllers = new Map();\n // Track loads based on the order in which they started\n let incrementingLoadId = 0;\n // Track the outstanding pending navigation data load to be compared against\n // the globally incrementing load when a fetcher load lands after a completed\n // navigation\n let pendingNavigationLoadId = -1;\n // Fetchers that triggered data reloads as a result of their actions\n let fetchReloadIds = new Map();\n // Fetchers that triggered redirect navigations\n let fetchRedirectIds = new Set();\n // Most recent href/match for fetcher.load calls for fetchers\n let fetchLoadMatches = new Map();\n // Ref-count mounted fetchers so we know when it's ok to clean them up\n let activeFetchers = new Map();\n // Fetchers that have requested a delete when using v7_fetcherPersist,\n // they'll be officially removed after they return to idle\n let deletedFetchers = new Set();\n // Store DeferredData instances for active route matches. When a\n // route loader returns defer() we stick one in here. Then, when a nested\n // promise resolves we update loaderData. If a new navigation starts we\n // cancel active deferreds for eliminated routes.\n let activeDeferreds = new Map();\n // Store blocker functions in a separate Map outside of router state since\n // we don't need to update UI state if they change\n let blockerFunctions = new Map();\n // Flag to ignore the next history update, so we can revert the URL change on\n // a POP navigation that was blocked by the user without touching router state\n let unblockBlockerHistoryUpdate = undefined;\n // Initialize the router, all side effects should be kicked off from here.\n // Implemented as a Fluent API for ease of:\n // let router = createRouter(init).initialize();\n function initialize() {\n // If history informs us of a POP navigation, start the navigation but do not update\n // state. We'll update our own state once the navigation completes\n unlistenHistory = init.history.listen(_ref => {\n let {\n action: historyAction,\n location,\n delta\n } = _ref;\n // Ignore this event if it was just us resetting the URL from a\n // blocked POP navigation\n if (unblockBlockerHistoryUpdate) {\n unblockBlockerHistoryUpdate();\n unblockBlockerHistoryUpdate = undefined;\n return;\n }\n warning(blockerFunctions.size === 0 || delta != null, \"You are trying to use a blocker on a POP navigation to a location \" + \"that was not created by @remix-run/router. This will fail silently in \" + \"production. This can happen if you are navigating outside the router \" + \"via `window.history.pushState`/`window.location.hash` instead of using \" + \"router navigation APIs. This can also happen if you are using \" + \"createHashRouter and the user manually changes the URL.\");\n let blockerKey = shouldBlockNavigation({\n currentLocation: state.location,\n nextLocation: location,\n historyAction\n });\n if (blockerKey && delta != null) {\n // Restore the URL to match the current UI, but don't update router state\n let nextHistoryUpdatePromise = new Promise(resolve => {\n unblockBlockerHistoryUpdate = resolve;\n });\n init.history.go(delta * -1);\n // Put the blocker into a blocked state\n updateBlocker(blockerKey, {\n state: \"blocked\",\n location,\n proceed() {\n updateBlocker(blockerKey, {\n state: \"proceeding\",\n proceed: undefined,\n reset: undefined,\n location\n });\n // Re-do the same POP navigation we just blocked, after the url\n // restoration is also complete. See:\n // https://github.com/remix-run/react-router/issues/11613\n nextHistoryUpdatePromise.then(() => init.history.go(delta));\n },\n reset() {\n let blockers = new Map(state.blockers);\n blockers.set(blockerKey, IDLE_BLOCKER);\n updateState({\n blockers\n });\n }\n });\n return;\n }\n return startNavigation(historyAction, location);\n });\n if (isBrowser) {\n // FIXME: This feels gross. How can we cleanup the lines between\n // scrollRestoration/appliedTransitions persistance?\n restoreAppliedTransitions(routerWindow, appliedViewTransitions);\n let _saveAppliedTransitions = () => persistAppliedTransitions(routerWindow, appliedViewTransitions);\n routerWindow.addEventListener(\"pagehide\", _saveAppliedTransitions);\n removePageHideEventListener = () => routerWindow.removeEventListener(\"pagehide\", _saveAppliedTransitions);\n }\n // Kick off initial data load if needed. Use Pop to avoid modifying history\n // Note we don't do any handling of lazy here. For SPA's it'll get handled\n // in the normal navigation flow. For SSR it's expected that lazy modules are\n // resolved prior to router creation since we can't go into a fallbackElement\n // UI for SSR'd apps\n if (!state.initialized) {\n startNavigation(Action.Pop, state.location, {\n initialHydration: true\n });\n }\n return router;\n }\n // Clean up a router and it's side effects\n function dispose() {\n if (unlistenHistory) {\n unlistenHistory();\n }\n if (removePageHideEventListener) {\n removePageHideEventListener();\n }\n subscribers.clear();\n pendingNavigationController && pendingNavigationController.abort();\n state.fetchers.forEach((_, key) => deleteFetcher(key));\n state.blockers.forEach((_, key) => deleteBlocker(key));\n }\n // Subscribe to state updates for the router\n function subscribe(fn) {\n subscribers.add(fn);\n return () => subscribers.delete(fn);\n }\n // Update our state and notify the calling context of the change\n function updateState(newState, opts) {\n if (opts === void 0) {\n opts = {};\n }\n state = _extends({}, state, newState);\n // Prep fetcher cleanup so we can tell the UI which fetcher data entries\n // can be removed\n let completedFetchers = [];\n let deletedFetchersKeys = [];\n if (future.v7_fetcherPersist) {\n state.fetchers.forEach((fetcher, key) => {\n if (fetcher.state === \"idle\") {\n if (deletedFetchers.has(key)) {\n // Unmounted from the UI and can be totally removed\n deletedFetchersKeys.push(key);\n } else {\n // Returned to idle but still mounted in the UI, so semi-remains for\n // revalidations and such\n completedFetchers.push(key);\n }\n }\n });\n }\n // Remove any lingering deleted fetchers that have already been removed\n // from state.fetchers\n deletedFetchers.forEach(key => {\n if (!state.fetchers.has(key) && !fetchControllers.has(key)) {\n deletedFetchersKeys.push(key);\n }\n });\n // Iterate over a local copy so that if flushSync is used and we end up\n // removing and adding a new subscriber due to the useCallback dependencies,\n // we don't get ourselves into a loop calling the new subscriber immediately\n [...subscribers].forEach(subscriber => subscriber(state, {\n deletedFetchers: deletedFetchersKeys,\n viewTransitionOpts: opts.viewTransitionOpts,\n flushSync: opts.flushSync === true\n }));\n // Remove idle fetchers from state since we only care about in-flight fetchers.\n if (future.v7_fetcherPersist) {\n completedFetchers.forEach(key => state.fetchers.delete(key));\n deletedFetchersKeys.forEach(key => deleteFetcher(key));\n } else {\n // We already called deleteFetcher() on these, can remove them from this\n // Set now that we've handed the keys off to the data layer\n deletedFetchersKeys.forEach(key => deletedFetchers.delete(key));\n }\n }\n // Complete a navigation returning the state.navigation back to the IDLE_NAVIGATION\n // and setting state.[historyAction/location/matches] to the new route.\n // - Location is a required param\n // - Navigation will always be set to IDLE_NAVIGATION\n // - Can pass any other state in newState\n function completeNavigation(location, newState, _temp) {\n var _location$state, _location$state2;\n let {\n flushSync\n } = _temp === void 0 ? {} : _temp;\n // Deduce if we're in a loading/actionReload state:\n // - We have committed actionData in the store\n // - The current navigation was a mutation submission\n // - We're past the submitting state and into the loading state\n // - The location being loaded is not the result of a redirect\n let isActionReload = state.actionData != null && state.navigation.formMethod != null && isMutationMethod(state.navigation.formMethod) && state.navigation.state === \"loading\" && ((_location$state = location.state) == null ? void 0 : _location$state._isRedirect) !== true;\n let actionData;\n if (newState.actionData) {\n if (Object.keys(newState.actionData).length > 0) {\n actionData = newState.actionData;\n } else {\n // Empty actionData -> clear prior actionData due to an action error\n actionData = null;\n }\n } else if (isActionReload) {\n // Keep the current data if we're wrapping up the action reload\n actionData = state.actionData;\n } else {\n // Clear actionData on any other completed navigations\n actionData = null;\n }\n // Always preserve any existing loaderData from re-used routes\n let loaderData = newState.loaderData ? mergeLoaderData(state.loaderData, newState.loaderData, newState.matches || [], newState.errors) : state.loaderData;\n // On a successful navigation we can assume we got through all blockers\n // so we can start fresh\n let blockers = state.blockers;\n if (blockers.size > 0) {\n blockers = new Map(blockers);\n blockers.forEach((_, k) => blockers.set(k, IDLE_BLOCKER));\n }\n // Always respect the user flag. Otherwise don't reset on mutation\n // submission navigations unless they redirect\n let preventScrollReset = pendingPreventScrollReset === true || state.navigation.formMethod != null && isMutationMethod(state.navigation.formMethod) && ((_location$state2 = location.state) == null ? void 0 : _location$state2._isRedirect) !== true;\n // Commit any in-flight routes at the end of the HMR revalidation \"navigation\"\n if (inFlightDataRoutes) {\n dataRoutes = inFlightDataRoutes;\n inFlightDataRoutes = undefined;\n }\n if (isUninterruptedRevalidation) ; else if (pendingAction === Action.Pop) ; else if (pendingAction === Action.Push) {\n init.history.push(location, location.state);\n } else if (pendingAction === Action.Replace) {\n init.history.replace(location, location.state);\n }\n let viewTransitionOpts;\n // On POP, enable transitions if they were enabled on the original navigation\n if (pendingAction === Action.Pop) {\n // Forward takes precedence so they behave like the original navigation\n let priorPaths = appliedViewTransitions.get(state.location.pathname);\n if (priorPaths && priorPaths.has(location.pathname)) {\n viewTransitionOpts = {\n currentLocation: state.location,\n nextLocation: location\n };\n } else if (appliedViewTransitions.has(location.pathname)) {\n // If we don't have a previous forward nav, assume we're popping back to\n // the new location and enable if that location previously enabled\n viewTransitionOpts = {\n currentLocation: location,\n nextLocation: state.location\n };\n }\n } else if (pendingViewTransitionEnabled) {\n // Store the applied transition on PUSH/REPLACE\n let toPaths = appliedViewTransitions.get(state.location.pathname);\n if (toPaths) {\n toPaths.add(location.pathname);\n } else {\n toPaths = new Set([location.pathname]);\n appliedViewTransitions.set(state.location.pathname, toPaths);\n }\n viewTransitionOpts = {\n currentLocation: state.location,\n nextLocation: location\n };\n }\n updateState(_extends({}, newState, {\n actionData,\n loaderData,\n historyAction: pendingAction,\n location,\n initialized: true,\n navigation: IDLE_NAVIGATION,\n revalidation: \"idle\",\n restoreScrollPosition: getSavedScrollPosition(location, newState.matches || state.matches),\n preventScrollReset,\n blockers\n }), {\n viewTransitionOpts,\n flushSync: flushSync === true\n });\n // Reset stateful navigation vars\n pendingAction = Action.Pop;\n pendingPreventScrollReset = false;\n pendingViewTransitionEnabled = false;\n isUninterruptedRevalidation = false;\n isRevalidationRequired = false;\n cancelledDeferredRoutes = [];\n }\n // Trigger a navigation event, which can either be a numerical POP or a PUSH\n // replace with an optional submission\n async function navigate(to, opts) {\n if (typeof to === \"number\") {\n init.history.go(to);\n return;\n }\n let normalizedPath = normalizeTo(state.location, state.matches, basename, future.v7_prependBasename, to, future.v7_relativeSplatPath, opts == null ? void 0 : opts.fromRouteId, opts == null ? void 0 : opts.relative);\n let {\n path,\n submission,\n error\n } = normalizeNavigateOptions(future.v7_normalizeFormMethod, false, normalizedPath, opts);\n let currentLocation = state.location;\n let nextLocation = createLocation(state.location, path, opts && opts.state);\n // When using navigate as a PUSH/REPLACE we aren't reading an already-encoded\n // URL from window.location, so we need to encode it here so the behavior\n // remains the same as POP and non-data-router usages. new URL() does all\n // the same encoding we'd get from a history.pushState/window.location read\n // without having to touch history\n nextLocation = _extends({}, nextLocation, init.history.encodeLocation(nextLocation));\n let userReplace = opts && opts.replace != null ? opts.replace : undefined;\n let historyAction = Action.Push;\n if (userReplace === true) {\n historyAction = Action.Replace;\n } else if (userReplace === false) ; else if (submission != null && isMutationMethod(submission.formMethod) && submission.formAction === state.location.pathname + state.location.search) {\n // By default on submissions to the current location we REPLACE so that\n // users don't have to double-click the back button to get to the prior\n // location. If the user redirects to a different location from the\n // action/loader this will be ignored and the redirect will be a PUSH\n historyAction = Action.Replace;\n }\n let preventScrollReset = opts && \"preventScrollReset\" in opts ? opts.preventScrollReset === true : undefined;\n let flushSync = (opts && opts.flushSync) === true;\n let blockerKey = shouldBlockNavigation({\n currentLocation,\n nextLocation,\n historyAction\n });\n if (blockerKey) {\n // Put the blocker into a blocked state\n updateBlocker(blockerKey, {\n state: \"blocked\",\n location: nextLocation,\n proceed() {\n updateBlocker(blockerKey, {\n state: \"proceeding\",\n proceed: undefined,\n reset: undefined,\n location: nextLocation\n });\n // Send the same navigation through\n navigate(to, opts);\n },\n reset() {\n let blockers = new Map(state.blockers);\n blockers.set(blockerKey, IDLE_BLOCKER);\n updateState({\n blockers\n });\n }\n });\n return;\n }\n return await startNavigation(historyAction, nextLocation, {\n submission,\n // Send through the formData serialization error if we have one so we can\n // render at the right error boundary after we match routes\n pendingError: error,\n preventScrollReset,\n replace: opts && opts.replace,\n enableViewTransition: opts && opts.viewTransition,\n flushSync\n });\n }\n // Revalidate all current loaders. If a navigation is in progress or if this\n // is interrupted by a navigation, allow this to \"succeed\" by calling all\n // loaders during the next loader round\n function revalidate() {\n interruptActiveLoads();\n updateState({\n revalidation: \"loading\"\n });\n // If we're currently submitting an action, we don't need to start a new\n // navigation, we'll just let the follow up loader execution call all loaders\n if (state.navigation.state === \"submitting\") {\n return;\n }\n // If we're currently in an idle state, start a new navigation for the current\n // action/location and mark it as uninterrupted, which will skip the history\n // update in completeNavigation\n if (state.navigation.state === \"idle\") {\n startNavigation(state.historyAction, state.location, {\n startUninterruptedRevalidation: true\n });\n return;\n }\n // Otherwise, if we're currently in a loading state, just start a new\n // navigation to the navigation.location but do not trigger an uninterrupted\n // revalidation so that history correctly updates once the navigation completes\n startNavigation(pendingAction || state.historyAction, state.navigation.location, {\n overrideNavigation: state.navigation,\n // Proxy through any rending view transition\n enableViewTransition: pendingViewTransitionEnabled === true\n });\n }\n // Start a navigation to the given action/location. Can optionally provide a\n // overrideNavigation which will override the normalLoad in the case of a redirect\n // navigation\n async function startNavigation(historyAction, location, opts) {\n // Abort any in-progress navigations and start a new one. Unset any ongoing\n // uninterrupted revalidations unless told otherwise, since we want this\n // new navigation to update history normally\n pendingNavigationController && pendingNavigationController.abort();\n pendingNavigationController = null;\n pendingAction = historyAction;\n isUninterruptedRevalidation = (opts && opts.startUninterruptedRevalidation) === true;\n // Save the current scroll position every time we start a new navigation,\n // and track whether we should reset scroll on completion\n saveScrollPosition(state.location, state.matches);\n pendingPreventScrollReset = (opts && opts.preventScrollReset) === true;\n pendingViewTransitionEnabled = (opts && opts.enableViewTransition) === true;\n let routesToUse = inFlightDataRoutes || dataRoutes;\n let loadingNavigation = opts && opts.overrideNavigation;\n let matches = opts != null && opts.initialHydration && state.matches && state.matches.length > 0 && !initialMatchesIsFOW ?\n // `matchRoutes()` has already been called if we're in here via `router.initialize()`\n state.matches : matchRoutes(routesToUse, location, basename);\n let flushSync = (opts && opts.flushSync) === true;\n // Short circuit if it's only a hash change and not a revalidation or\n // mutation submission.\n //\n // Ignore on initial page loads because since the initial hydration will always\n // be \"same hash\". For example, on /page#hash and submit a <Form method=\"post\">\n // which will default to a navigation to /page\n if (matches && state.initialized && !isRevalidationRequired && isHashChangeOnly(state.location, location) && !(opts && opts.submission && isMutationMethod(opts.submission.formMethod))) {\n completeNavigation(location, {\n matches\n }, {\n flushSync\n });\n return;\n }\n let fogOfWar = checkFogOfWar(matches, routesToUse, location.pathname);\n if (fogOfWar.active && fogOfWar.matches) {\n matches = fogOfWar.matches;\n }\n // Short circuit with a 404 on the root error boundary if we match nothing\n if (!matches) {\n let {\n error,\n notFoundMatches,\n route\n } = handleNavigational404(location.pathname);\n completeNavigation(location, {\n matches: notFoundMatches,\n loaderData: {},\n errors: {\n [route.id]: error\n }\n }, {\n flushSync\n });\n return;\n }\n // Create a controller/Request for this navigation\n pendingNavigationController = new AbortController();\n let request = createClientSideRequest(init.history, location, pendingNavigationController.signal, opts && opts.submission);\n let pendingActionResult;\n if (opts && opts.pendingError) {\n // If we have a pendingError, it means the user attempted a GET submission\n // with binary FormData so assign here and skip to handleLoaders. That\n // way we handle calling loaders above the boundary etc. It's not really\n // different from an actionError in that sense.\n pendingActionResult = [findNearestBoundary(matches).route.id, {\n type: ResultType.error,\n error: opts.pendingError\n }];\n } else if (opts && opts.submission && isMutationMethod(opts.submission.formMethod)) {\n // Call action if we received an action submission\n let actionResult = await handleAction(request, location, opts.submission, matches, fogOfWar.active, {\n replace: opts.replace,\n flushSync\n });\n if (actionResult.shortCircuited) {\n return;\n }\n // If we received a 404 from handleAction, it's because we couldn't lazily\n // discover the destination route so we don't want to call loaders\n if (actionResult.pendingActionResult) {\n let [routeId, result] = actionResult.pendingActionResult;\n if (isErrorResult(result) && isRouteErrorResponse(result.error) && result.error.status === 404) {\n pendingNavigationController = null;\n completeNavigation(location, {\n matches: actionResult.matches,\n loaderData: {},\n errors: {\n [routeId]: result.error\n }\n });\n return;\n }\n }\n matches = actionResult.matches || matches;\n pendingActionResult = actionResult.pendingActionResult;\n loadingNavigation = getLoadingNavigation(location, opts.submission);\n flushSync = false;\n // No need to do fog of war matching again on loader execution\n fogOfWar.active = false;\n // Create a GET request for the loaders\n request = createClientSideRequest(init.history, request.url, request.signal);\n }\n // Call loaders\n let {\n shortCircuited,\n matches: updatedMatches,\n loaderData,\n errors\n } = await handleLoaders(request, location, matches, fogOfWar.active, loadingNavigation, opts && opts.submission, opts && opts.fetcherSubmission, opts && opts.replace, opts && opts.initialHydration === true, flushSync, pendingActionResult);\n if (shortCircuited) {\n return;\n }\n // Clean up now that the action/loaders have completed. Don't clean up if\n // we short circuited because pendingNavigationController will have already\n // been assigned to a new controller for the next navigation\n pendingNavigationController = null;\n completeNavigation(location, _extends({\n matches: updatedMatches || matches\n }, getActionDataForCommit(pendingActionResult), {\n loaderData,\n errors\n }));\n }\n // Call the action matched by the leaf route for this navigation and handle\n // redirects/errors\n async function handleAction(request, location, submission, matches, isFogOfWar, opts) {\n if (opts === void 0) {\n opts = {};\n }\n interruptActiveLoads();\n // Put us in a submitting state\n let navigation = getSubmittingNavigation(location, submission);\n updateState({\n navigation\n }, {\n flushSync: opts.flushSync === true\n });\n if (isFogOfWar) {\n let discoverResult = await discoverRoutes(matches, location.pathname, request.signal);\n if (discoverResult.type === \"aborted\") {\n return {\n shortCircuited: true\n };\n } else if (discoverResult.type === \"error\") {\n let boundaryId = findNearestBoundary(discoverResult.partialMatches).route.id;\n return {\n matches: discoverResult.partialMatches,\n pendingActionResult: [boundaryId, {\n type: ResultType.error,\n error: discoverResult.error\n }]\n };\n } else if (!discoverResult.matches) {\n let {\n notFoundMatches,\n error,\n route\n } = handleNavigational404(location.pathname);\n return {\n matches: notFoundMatches,\n pendingActionResult: [route.id, {\n type: ResultType.error,\n error\n }]\n };\n } else {\n matches = discoverResult.matches;\n }\n }\n // Call our action and get the result\n let result;\n let actionMatch = getTargetMatch(matches, location);\n if (!actionMatch.route.action && !actionMatch.route.lazy) {\n result = {\n type: ResultType.error,\n error: getInternalRouterError(405, {\n method: request.method,\n pathname: location.pathname,\n routeId: actionMatch.route.id\n })\n };\n } else {\n let results = await callDataStrategy(\"action\", state, request, [actionMatch], matches, null);\n result = results[actionMatch.route.id];\n if (request.signal.aborted) {\n return {\n shortCircuited: true\n };\n }\n }\n if (isRedirectResult(result)) {\n let replace;\n if (opts && opts.replace != null) {\n replace = opts.replace;\n } else {\n // If the user didn't explicity indicate replace behavior, replace if\n // we redirected to the exact same location we're currently at to avoid\n // double back-buttons\n let location = normalizeRedirectLocation(result.response.headers.get(\"Location\"), new URL(request.url), basename, init.history);\n replace = location === state.location.pathname + state.location.search;\n }\n await startRedirectNavigation(request, result, true, {\n submission,\n replace\n });\n return {\n shortCircuited: true\n };\n }\n if (isDeferredResult(result)) {\n throw getInternalRouterError(400, {\n type: \"defer-action\"\n });\n }\n if (isErrorResult(result)) {\n // Store off the pending error - we use it to determine which loaders\n // to call and will commit it when we complete the navigation\n let boundaryMatch = findNearestBoundary(matches, actionMatch.route.id);\n // By default, all submissions to the current location are REPLACE\n // navigations, but if the action threw an error that'll be rendered in\n // an errorElement, we fall back to PUSH so that the user can use the\n // back button to get back to the pre-submission form location to try\n // again\n if ((opts && opts.replace) !== true) {\n pendingAction = Action.Push;\n }\n return {\n matches,\n pendingActionResult: [boundaryMatch.route.id, result]\n };\n }\n return {\n matches,\n pendingActionResult: [actionMatch.route.id, result]\n };\n }\n // Call all applicable loaders for the given matches, handling redirects,\n // errors, etc.\n async function handleLoaders(request, location, matches, isFogOfWar, overrideNavigation, submission, fetcherSubmission, replace, initialHydration, flushSync, pendingActionResult) {\n // Figure out the right navigation we want to use for data loading\n let loadingNavigation = overrideNavigation || getLoadingNavigation(location, submission);\n // If this was a redirect from an action we don't have a \"submission\" but\n // we have it on the loading navigation so use that if available\n let activeSubmission = submission || fetcherSubmission || getSubmissionFromNavigation(loadingNavigation);\n // If this is an uninterrupted revalidation, we remain in our current idle\n // state. If not, we need to switch to our loading state and load data,\n // preserving any new action data or existing action data (in the case of\n // a revalidation interrupting an actionReload)\n // If we have partialHydration enabled, then don't update the state for the\n // initial data load since it's not a \"navigation\"\n let shouldUpdateNavigationState = !isUninterruptedRevalidation && (!future.v7_partialHydration || !initialHydration);\n // When fog of war is enabled, we enter our `loading` state earlier so we\n // can discover new routes during the `loading` state. We skip this if\n // we've already run actions since we would have done our matching already.\n // If the children() function threw then, we want to proceed with the\n // partial matches it discovered.\n if (isFogOfWar) {\n if (shouldUpdateNavigationState) {\n let actionData = getUpdatedActionData(pendingActionResult);\n updateState(_extends({\n navigation: loadingNavigation\n }, actionData !== undefined ? {\n actionData\n } : {}), {\n flushSync\n });\n }\n let discoverResult = await discoverRoutes(matches, location.pathname, request.signal);\n if (discoverResult.type === \"aborted\") {\n return {\n shortCircuited: true\n };\n } else if (discoverResult.type === \"error\") {\n let boundaryId = findNearestBoundary(discoverResult.partialMatches).route.id;\n return {\n matches: discoverResult.partialMatches,\n loaderData: {},\n errors: {\n [boundaryId]: discoverResult.error\n }\n };\n } else if (!discoverResult.matches) {\n let {\n error,\n notFoundMatches,\n route\n } = handleNavigational404(location.pathname);\n return {\n matches: notFoundMatches,\n loaderData: {},\n errors: {\n [route.id]: error\n }\n };\n } else {\n matches = discoverResult.matches;\n }\n }\n let routesToUse = inFlightDataRoutes || dataRoutes;\n let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(init.history, state, matches, activeSubmission, location, future.v7_partialHydration && initialHydration === true, future.v7_skipActionErrorRevalidation, isRevalidationRequired, cancelledDeferredRoutes, cancelledFetcherLoads, deletedFetchers, fetchLoadMatches, fetchRedirectIds, routesToUse, basename, pendingActionResult);\n // Cancel pending deferreds for no-longer-matched routes or routes we're\n // about to reload. Note that if this is an action reload we would have\n // already cancelled all pending deferreds so this would be a no-op\n cancelActiveDeferreds(routeId => !(matches && matches.some(m => m.route.id === routeId)) || matchesToLoad && matchesToLoad.some(m => m.route.id === routeId));\n pendingNavigationLoadId = ++incrementingLoadId;\n // Short circuit if we have no loaders to run\n if (matchesToLoad.length === 0 && revalidatingFetchers.length === 0) {\n let updatedFetchers = markFetchRedirectsDone();\n completeNavigation(location, _extends({\n matches,\n loaderData: {},\n // Commit pending error if we're short circuiting\n errors: pendingActionResult && isErrorResult(pendingActionResult[1]) ? {\n [pendingActionResult[0]]: pendingActionResult[1].error\n } : null\n }, getActionDataForCommit(pendingActionResult), updatedFetchers ? {\n fetchers: new Map(state.fetchers)\n } : {}), {\n flushSync\n });\n return {\n shortCircuited: true\n };\n }\n if (shouldUpdateNavigationState) {\n let updates = {};\n if (!isFogOfWar) {\n // Only update navigation/actionNData if we didn't already do it above\n updates.navigation = loadingNavigation;\n let actionData = getUpdatedActionData(pendingActionResult);\n if (actionData !== undefined) {\n updates.actionData = actionData;\n }\n }\n if (revalidatingFetchers.length > 0) {\n updates.fetchers = getUpdatedRevalidatingFetchers(revalidatingFetchers);\n }\n updateState(updates, {\n flushSync\n });\n }\n revalidatingFetchers.forEach(rf => {\n abortFetcher(rf.key);\n if (rf.controller) {\n // Fetchers use an independent AbortController so that aborting a fetcher\n // (via deleteFetcher) does not abort the triggering navigation that\n // triggered the revalidation\n fetchControllers.set(rf.key, rf.controller);\n }\n });\n // Proxy navigation abort through to revalidation fetchers\n let abortPendingFetchRevalidations = () => revalidatingFetchers.forEach(f => abortFetcher(f.key));\n if (pendingNavigationController) {\n pendingNavigationController.signal.addEventListener(\"abort\", abortPendingFetchRevalidations);\n }\n let {\n loaderResults,\n fetcherResults\n } = await callLoadersAndMaybeResolveData(state, matches, matchesToLoad, revalidatingFetchers, request);\n if (request.signal.aborted) {\n return {\n shortCircuited: true\n };\n }\n // Clean up _after_ loaders have completed. Don't clean up if we short\n // circuited because fetchControllers would have been aborted and\n // reassigned to new controllers for the next navigation\n if (pendingNavigationController) {\n pendingNavigationController.signal.removeEventListener(\"abort\", abortPendingFetchRevalidations);\n }\n revalidatingFetchers.forEach(rf => fetchControllers.delete(rf.key));\n // If any loaders returned a redirect Response, start a new REPLACE navigation\n let redirect = findRedirect(loaderResults);\n if (redirect) {\n await startRedirectNavigation(request, redirect.result, true, {\n replace\n });\n return {\n shortCircuited: true\n };\n }\n redirect = findRedirect(fetcherResults);\n if (redirect) {\n // If this redirect came from a fetcher make sure we mark it in\n // fetchRedirectIds so it doesn't get revalidated on the next set of\n // loader executions\n fetchRedirectIds.add(redirect.key);\n await startRedirectNavigation(request, redirect.result, true, {\n replace\n });\n return {\n shortCircuited: true\n };\n }\n // Process and commit output from loaders\n let {\n loaderData,\n errors\n } = processLoaderData(state, matches, loaderResults, pendingActionResult, revalidatingFetchers, fetcherResults, activeDeferreds);\n // Wire up subscribers to update loaderData as promises settle\n activeDeferreds.forEach((deferredData, routeId) => {\n deferredData.subscribe(aborted => {\n // Note: No need to updateState here since the TrackedPromise on\n // loaderData is stable across resolve/reject\n // Remove this instance if we were aborted or if promises have settled\n if (aborted || deferredData.done) {\n activeDeferreds.delete(routeId);\n }\n });\n });\n // Preserve SSR errors during partial hydration\n if (future.v7_partialHydration && initialHydration && state.errors) {\n errors = _extends({}, state.errors, errors);\n }\n let updatedFetchers = markFetchRedirectsDone();\n let didAbortFetchLoads = abortStaleFetchLoads(pendingNavigationLoadId);\n let shouldUpdateFetchers = updatedFetchers || didAbortFetchLoads || revalidatingFetchers.length > 0;\n return _extends({\n matches,\n loaderData,\n errors\n }, shouldUpdateFetchers ? {\n fetchers: new Map(state.fetchers)\n } : {});\n }\n function getUpdatedActionData(pendingActionResult) {\n if (pendingActionResult && !isErrorResult(pendingActionResult[1])) {\n // This is cast to `any` currently because `RouteData`uses any and it\n // would be a breaking change to use any.\n // TODO: v7 - change `RouteData` to use `unknown` instead of `any`\n return {\n [pendingActionResult[0]]: pendingActionResult[1].data\n };\n } else if (state.actionData) {\n if (Object.keys(state.actionData).length === 0) {\n return null;\n } else {\n return state.actionData;\n }\n }\n }\n function getUpdatedRevalidatingFetchers(revalidatingFetchers) {\n revalidatingFetchers.forEach(rf => {\n let fetcher = state.fetchers.get(rf.key);\n let revalidatingFetcher = getLoadingFetcher(undefined, fetcher ? fetcher.data : undefined);\n state.fetchers.set(rf.key, revalidatingFetcher);\n });\n return new Map(state.fetchers);\n }\n // Trigger a fetcher load/submit for the given fetcher key\n function fetch(key, routeId, href, opts) {\n if (isServer) {\n throw new Error(\"router.fetch() was called during the server render, but it shouldn't be. \" + \"You are likely calling a useFetcher() method in the body of your component. \" + \"Try moving it to a useEffect or a callback.\");\n }\n abortFetcher(key);\n let flushSync = (opts && opts.flushSync) === true;\n let routesToUse = inFlightDataRoutes || dataRoutes;\n let normalizedPath = normalizeTo(state.location, state.matches, basename, future.v7_prependBasename, href, future.v7_relativeSplatPath, routeId, opts == null ? void 0 : opts.relative);\n let matches = matchRoutes(routesToUse, normalizedPath, basename);\n let fogOfWar = checkFogOfWar(matches, routesToUse, normalizedPath);\n if (fogOfWar.active && fogOfWar.matches) {\n matches = fogOfWar.matches;\n }\n if (!matches) {\n setFetcherError(key, routeId, getInternalRouterError(404, {\n pathname: normalizedPath\n }), {\n flushSync\n });\n return;\n }\n let {\n path,\n submission,\n error\n } = normalizeNavigateOptions(future.v7_normalizeFormMethod, true, normalizedPath, opts);\n if (error) {\n setFetcherError(key, routeId, error, {\n flushSync\n });\n return;\n }\n let match = getTargetMatch(matches, path);\n let preventScrollReset = (opts && opts.preventScrollReset) === true;\n if (submission && isMutationMethod(submission.formMethod)) {\n handleFetcherAction(key, routeId, path, match, matches, fogOfWar.active, flushSync, preventScrollReset, submission);\n return;\n }\n // Store off the match so we can call it's shouldRevalidate on subsequent\n // revalidations\n fetchLoadMatches.set(key, {\n routeId,\n path\n });\n handleFetcherLoader(key, routeId, path, match, matches, fogOfWar.active, flushSync, preventScrollReset, submission);\n }\n // Call the action for the matched fetcher.submit(), and then handle redirects,\n // errors, and revalidation\n async function handleFetcherAction(key, routeId, path, match, requestMatches, isFogOfWar, flushSync, preventScrollReset, submission) {\n interruptActiveLoads();\n fetchLoadMatches.delete(key);\n function detectAndHandle405Error(m) {\n if (!m.route.action && !m.route.lazy) {\n let error = getInternalRouterError(405, {\n method: submission.formMethod,\n pathname: path,\n routeId: routeId\n });\n setFetcherError(key, routeId, error, {\n flushSync\n });\n return true;\n }\n return false;\n }\n if (!isFogOfWar && detectAndHandle405Error(match)) {\n return;\n }\n // Put this fetcher into it's submitting state\n let existingFetcher = state.fetchers.get(key);\n updateFetcherState(key, getSubmittingFetcher(submission, existingFetcher), {\n flushSync\n });\n let abortController = new AbortController();\n let fetchRequest = createClientSideRequest(init.history, path, abortController.signal, submission);\n if (isFogOfWar) {\n let discoverResult = await discoverRoutes(requestMatches, new URL(fetchRequest.url).pathname, fetchRequest.signal, key);\n if (discoverResult.type === \"aborted\") {\n return;\n } else if (discoverResult.type === \"error\") {\n setFetcherError(key, routeId, discoverResult.error, {\n flushSync\n });\n return;\n } else if (!discoverResult.matches) {\n setFetcherError(key, routeId, getInternalRouterError(404, {\n pathname: path\n }), {\n flushSync\n });\n return;\n } else {\n requestMatches = discoverResult.matches;\n match = getTargetMatch(requestMatches, path);\n if (detectAndHandle405Error(match)) {\n return;\n }\n }\n }\n // Call the action for the fetcher\n fetchControllers.set(key, abortController);\n let originatingLoadId = incrementingLoadId;\n let actionResults = await callDataStrategy(\"action\", state, fetchRequest, [match], requestMatches, key);\n let actionResult = actionResults[match.route.id];\n if (fetchRequest.signal.aborted) {\n // We can delete this so long as we weren't aborted by our own fetcher\n // re-submit which would have put _new_ controller is in fetchControllers\n if (fetchControllers.get(key) === abortController) {\n fetchControllers.delete(key);\n }\n return;\n }\n // When using v7_fetcherPersist, we don't want errors bubbling up to the UI\n // or redirects processed for unmounted fetchers so we just revert them to\n // idle\n if (future.v7_fetcherPersist && deletedFetchers.has(key)) {\n if (isRedirectResult(actionResult) || isErrorResult(actionResult)) {\n updateFetcherState(key, getDoneFetcher(undefined));\n return;\n }\n // Let SuccessResult's fall through for revalidation\n } else {\n if (isRedirectResult(actionResult)) {\n fetchControllers.delete(key);\n if (pendingNavigationLoadId > originatingLoadId) {\n // A new navigation was kicked off after our action started, so that\n // should take precedence over this redirect navigation. We already\n // set isRevalidationRequired so all loaders for the new route should\n // fire unless opted out via shouldRevalidate\n updateFetcherState(key, getDoneFetcher(undefined));\n return;\n } else {\n fetchRedirectIds.add(key);\n updateFetcherState(key, getLoadingFetcher(submission));\n return startRedirectNavigation(fetchRequest, actionResult, false, {\n fetcherSubmission: submission,\n preventScrollReset\n });\n }\n }\n // Process any non-redirect errors thrown\n if (isErrorResult(actionResult)) {\n setFetcherError(key, routeId, actionResult.error);\n return;\n }\n }\n if (isDeferredResult(actionResult)) {\n throw getInternalRouterError(400, {\n type: \"defer-action\"\n });\n }\n // Start the data load for current matches, or the next location if we're\n // in the middle of a navigation\n let nextLocation = state.navigation.location || state.location;\n let revalidationRequest = createClientSideRequest(init.history, nextLocation, abortController.signal);\n let routesToUse = inFlightDataRoutes || dataRoutes;\n let matches = state.navigation.state !== \"idle\" ? matchRoutes(routesToUse, state.navigation.location, basename) : state.matches;\n invariant(matches, \"Didn't find any matches after fetcher action\");\n let loadId = ++incrementingLoadId;\n fetchReloadIds.set(key, loadId);\n let loadFetcher = getLoadingFetcher(submission, actionResult.data);\n state.fetchers.set(key, loadFetcher);\n let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(init.history, state, matches, submission, nextLocation, false, future.v7_skipActionErrorRevalidation, isRevalidationRequired, cancelledDeferredRoutes, cancelledFetcherLoads, deletedFetchers, fetchLoadMatches, fetchRedirectIds, routesToUse, basename, [match.route.id, actionResult]);\n // Put all revalidating fetchers into the loading state, except for the\n // current fetcher which we want to keep in it's current loading state which\n // contains it's action submission info + action data\n revalidatingFetchers.filter(rf => rf.key !== key).forEach(rf => {\n let staleKey = rf.key;\n let existingFetcher = state.fetchers.get(staleKey);\n let revalidatingFetcher = getLoadingFetcher(undefined, existingFetcher ? existingFetcher.data : undefined);\n state.fetchers.set(staleKey, revalidatingFetcher);\n abortFetcher(staleKey);\n if (rf.controller) {\n fetchControllers.set(staleKey, rf.controller);\n }\n });\n updateState({\n fetchers: new Map(state.fetchers)\n });\n let abortPendingFetchRevalidations = () => revalidatingFetchers.forEach(rf => abortFetcher(rf.key));\n abortController.signal.addEventListener(\"abort\", abortPendingFetchRevalidations);\n let {\n loaderResults,\n fetcherResults\n } = await callLoadersAndMaybeResolveData(state, matches, matchesToLoad, revalidatingFetchers, revalidationRequest);\n if (abortController.signal.aborted) {\n return;\n }\n abortController.signal.removeEventListener(\"abort\", abortPendingFetchRevalidations);\n fetchReloadIds.delete(key);\n fetchControllers.delete(key);\n revalidatingFetchers.forEach(r => fetchControllers.delete(r.key));\n let redirect = findRedirect(loaderResults);\n if (redirect) {\n return startRedirectNavigation(revalidationRequest, redirect.result, false, {\n preventScrollReset\n });\n }\n redirect = findRedirect(fetcherResults);\n if (redirect) {\n // If this redirect came from a fetcher make sure we mark it in\n // fetchRedirectIds so it doesn't get revalidated on the next set of\n // loader executions\n fetchRedirectIds.add(redirect.key);\n return startRedirectNavigation(revalidationRequest, redirect.result, false, {\n preventScrollReset\n });\n }\n // Process and commit output from loaders\n let {\n loaderData,\n errors\n } = processLoaderData(state, matches, loaderResults, undefined, revalidatingFetchers, fetcherResults, activeDeferreds);\n // Since we let revalidations complete even if the submitting fetcher was\n // deleted, only put it back to idle if it hasn't been deleted\n if (state.fetchers.has(key)) {\n let doneFetcher = getDoneFetcher(actionResult.data);\n state.fetchers.set(key, doneFetcher);\n }\n abortStaleFetchLoads(loadId);\n // If we are currently in a navigation loading state and this fetcher is\n // more recent than the navigation, we want the newer data so abort the\n // navigation and complete it with the fetcher data\n if (state.navigation.state === \"loading\" && loadId > pendingNavigationLoadId) {\n invariant(pendingAction, \"Expected pending action\");\n pendingNavigationController && pendingNavigationController.abort();\n completeNavigation(state.navigation.location, {\n matches,\n loaderData,\n errors,\n fetchers: new Map(state.fetchers)\n });\n } else {\n // otherwise just update with the fetcher data, preserving any existing\n // loaderData for loaders that did not need to reload. We have to\n // manually merge here since we aren't going through completeNavigation\n updateState({\n errors,\n loaderData: mergeLoaderData(state.loaderData, loaderData, matches, errors),\n fetchers: new Map(state.fetchers)\n });\n isRevalidationRequired = false;\n }\n }\n // Call the matched loader for fetcher.load(), handling redirects, errors, etc.\n async function handleFetcherLoader(key, routeId, path, match, matches, isFogOfWar, flushSync, preventScrollReset, submission) {\n let existingFetcher = state.fetchers.get(key);\n updateFetcherState(key, getLoadingFetcher(submission, existingFetcher ? existingFetcher.data : undefined), {\n flushSync\n });\n let abortController = new AbortController();\n let fetchRequest = createClientSideRequest(init.history, path, abortController.signal);\n if (isFogOfWar) {\n let discoverResult = await discoverRoutes(matches, new URL(fetchRequest.url).pathname, fetchRequest.signal, key);\n if (discoverResult.type === \"aborted\") {\n return;\n } else if (discoverResult.type === \"error\") {\n setFetcherError(key, routeId, discoverResult.error, {\n flushSync\n });\n return;\n } else if (!discoverResult.matches) {\n setFetcherError(key, routeId, getInternalRouterError(404, {\n pathname: path\n }), {\n flushSync\n });\n return;\n } else {\n matches = discoverResult.matches;\n match = getTargetMatch(matches, path);\n }\n }\n // Call the loader for this fetcher route match\n fetchControllers.set(key, abortController);\n let originatingLoadId = incrementingLoadId;\n let results = await callDataStrategy(\"loader\", state, fetchRequest, [match], matches, key);\n let result = results[match.route.id];\n // Deferred isn't supported for fetcher loads, await everything and treat it\n // as a normal load. resolveDeferredData will return undefined if this\n // fetcher gets aborted, so we just leave result untouched and short circuit\n // below if that happens\n if (isDeferredResult(result)) {\n result = (await resolveDeferredData(result, fetchRequest.signal, true)) || result;\n }\n // We can delete this so long as we weren't aborted by our our own fetcher\n // re-load which would have put _new_ controller is in fetchControllers\n if (fetchControllers.get(key) === abortController) {\n fetchControllers.delete(key);\n }\n if (fetchRequest.signal.aborted) {\n return;\n }\n // We don't want errors bubbling up or redirects followed for unmounted\n // fetchers, so short circuit here if it was removed from the UI\n if (deletedFetchers.has(key)) {\n updateFetcherState(key, getDoneFetcher(undefined));\n return;\n }\n // If the loader threw a redirect Response, start a new REPLACE navigation\n if (isRedirectResult(result)) {\n if (pendingNavigationLoadId > originatingLoadId) {\n // A new navigation was kicked off after our loader started, so that\n // should take precedence over this redirect navigation\n updateFetcherState(key, getDoneFetcher(undefined));\n return;\n } else {\n fetchRedirectIds.add(key);\n await startRedirectNavigation(fetchRequest, result, false, {\n preventScrollReset\n });\n return;\n }\n }\n // Process any non-redirect errors thrown\n if (isErrorResult(result)) {\n setFetcherError(key, routeId, result.error);\n return;\n }\n invariant(!isDeferredResult(result), \"Unhandled fetcher deferred data\");\n // Put the fetcher back into an idle state\n updateFetcherState(key, getDoneFetcher(result.data));\n }\n /**\n * Utility function to handle redirects returned from an action or loader.\n * Normally, a redirect \"replaces\" the navigation that triggered it. So, for\n * example:\n *\n * - user is on /a\n * - user clicks a link to /b\n * - loader for /b redirects to /c\n *\n * In a non-JS app the browser would track the in-flight navigation to /b and\n * then replace it with /c when it encountered the redirect response. In\n * the end it would only ever update the URL bar with /c.\n *\n * In client-side routing using pushState/replaceState, we aim to emulate\n * this behavior and we also do not update history until the end of the\n * navigation (including processed redirects). This means that we never\n * actually touch history until we've processed redirects, so we just use\n * the history action from the original navigation (PUSH or REPLACE).\n */\n async function startRedirectNavigation(request, redirect, isNavigation, _temp2) {\n let {\n submission,\n fetcherSubmission,\n preventScrollReset,\n replace\n } = _temp2 === void 0 ? {} : _temp2;\n if (redirect.response.headers.has(\"X-Remix-Revalidate\")) {\n isRevalidationRequired = true;\n }\n let location = redirect.response.headers.get(\"Location\");\n invariant(location, \"Expected a Location header on the redirect Response\");\n location = normalizeRedirectLocation(location, new URL(request.url), basename, init.history);\n let redirectLocation = createLocation(state.location, location, {\n _isRedirect: true\n });\n if (isBrowser) {\n let isDocumentReload = false;\n if (redirect.response.headers.has(\"X-Remix-Reload-Document\")) {\n // Hard reload if the response contained X-Remix-Reload-Document\n isDocumentReload = true;\n } else if (ABSOLUTE_URL_REGEX.test(location)) {\n const url = init.history.createURL(location);\n isDocumentReload =\n // Hard reload if it's an absolute URL to a new origin\n url.origin !== routerWindow.location.origin ||\n // Hard reload if it's an absolute URL that does not match our basename\n stripBasename(url.pathname, basename) == null;\n }\n if (isDocumentReload) {\n if (replace) {\n routerWindow.location.replace(location);\n } else {\n routerWindow.location.assign(location);\n }\n return;\n }\n }\n // There's no need to abort on redirects, since we don't detect the\n // redirect until the action/loaders have settled\n pendingNavigationController = null;\n let redirectHistoryAction = replace === true || redirect.response.headers.has(\"X-Remix-Replace\") ? Action.Replace : Action.Push;\n // Use the incoming submission if provided, fallback on the active one in\n // state.navigation\n let {\n formMethod,\n formAction,\n formEncType\n } = state.navigation;\n if (!submission && !fetcherSubmission && formMethod && formAction && formEncType) {\n submission = getSubmissionFromNavigation(state.navigation);\n }\n // If this was a 307/308 submission we want to preserve the HTTP method and\n // re-submit the GET/POST/PUT/PATCH/DELETE as a submission navigation to the\n // redirected location\n let activeSubmission = submission || fetcherSubmission;\n if (redirectPreserveMethodStatusCodes.has(redirect.response.status) && activeSubmission && isMutationMethod(activeSubmission.formMethod)) {\n await startNavigation(redirectHistoryAction, redirectLocation, {\n submission: _extends({}, activeSubmission, {\n formAction: location\n }),\n // Preserve these flags across redirects\n preventScrollReset: preventScrollReset || pendingPreventScrollReset,\n enableViewTransition: isNavigation ? pendingViewTransitionEnabled : undefined\n });\n } else {\n // If we have a navigation submission, we will preserve it through the\n // redirect navigation\n let overrideNavigation = getLoadingNavigation(redirectLocation, submission);\n await startNavigation(redirectHistoryAction, redirectLocation, {\n overrideNavigation,\n // Send fetcher submissions through for shouldRevalidate\n fetcherSubmission,\n // Preserve these flags across redirects\n preventScrollReset: preventScrollReset || pendingPreventScrollReset,\n enableViewTransition: isNavigation ? pendingViewTransitionEnabled : undefined\n });\n }\n }\n // Utility wrapper for calling dataStrategy client-side without having to\n // pass around the manifest, mapRouteProperties, etc.\n async function callDataStrategy(type, state, request, matchesToLoad, matches, fetcherKey) {\n let results;\n let dataResults = {};\n try {\n results = await callDataStrategyImpl(dataStrategyImpl, type, state, request, matchesToLoad, matches, fetcherKey, manifest, mapRouteProperties);\n } catch (e) {\n // If the outer dataStrategy method throws, just return the error for all\n // matches - and it'll naturally bubble to the root\n matchesToLoad.forEach(m => {\n dataResults[m.route.id] = {\n type: ResultType.error,\n error: e\n };\n });\n return dataResults;\n }\n for (let [routeId, result] of Object.entries(results)) {\n if (isRedirectDataStrategyResultResult(result)) {\n let response = result.result;\n dataResults[routeId] = {\n type: ResultType.redirect,\n response: normalizeRelativeRoutingRedirectResponse(response, request, routeId, matches, basename, future.v7_relativeSplatPath)\n };\n } else {\n dataResults[routeId] = await convertDataStrategyResultToDataResult(result);\n }\n }\n return dataResults;\n }\n async function callLoadersAndMaybeResolveData(state, matches, matchesToLoad, fetchersToLoad, request) {\n let currentMatches = state.matches;\n // Kick off loaders and fetchers in parallel\n let loaderResultsPromise = callDataStrategy(\"loader\", state, request, matchesToLoad, matches, null);\n let fetcherResultsPromise = Promise.all(fetchersToLoad.map(async f => {\n if (f.matches && f.match && f.controller) {\n let results = await callDataStrategy(\"loader\", state, createClientSideRequest(init.history, f.path, f.controller.signal), [f.match], f.matches, f.key);\n let result = results[f.match.route.id];\n // Fetcher results are keyed by fetcher key from here on out, not routeId\n return {\n [f.key]: result\n };\n } else {\n return Promise.resolve({\n [f.key]: {\n type: ResultType.error,\n error: getInternalRouterError(404, {\n pathname: f.path\n })\n }\n });\n }\n }));\n let loaderResults = await loaderResultsPromise;\n let fetcherResults = (await fetcherResultsPromise).reduce((acc, r) => Object.assign(acc, r), {});\n await Promise.all([resolveNavigationDeferredResults(matches, loaderResults, request.signal, currentMatches, state.loaderData), resolveFetcherDeferredResults(matches, fetcherResults, fetchersToLoad)]);\n return {\n loaderResults,\n fetcherResults\n };\n }\n function interruptActiveLoads() {\n // Every interruption triggers a revalidation\n isRevalidationRequired = true;\n // Cancel pending route-level deferreds and mark cancelled routes for\n // revalidation\n cancelledDeferredRoutes.push(...cancelActiveDeferreds());\n // Abort in-flight fetcher loads\n fetchLoadMatches.forEach((_, key) => {\n if (fetchControllers.has(key)) {\n cancelledFetcherLoads.add(key);\n }\n abortFetcher(key);\n });\n }\n function updateFetcherState(key, fetcher, opts) {\n if (opts === void 0) {\n opts = {};\n }\n state.fetchers.set(key, fetcher);\n updateState({\n fetchers: new Map(state.fetchers)\n }, {\n flushSync: (opts && opts.flushSync) === true\n });\n }\n function setFetcherError(key, routeId, error, opts) {\n if (opts === void 0) {\n opts = {};\n }\n let boundaryMatch = findNearestBoundary(state.matches, routeId);\n deleteFetcher(key);\n updateState({\n errors: {\n [boundaryMatch.route.id]: error\n },\n fetchers: new Map(state.fetchers)\n }, {\n flushSync: (opts && opts.flushSync) === true\n });\n }\n function getFetcher(key) {\n activeFetchers.set(key, (activeFetchers.get(key) || 0) + 1);\n // If this fetcher was previously marked for deletion, unmark it since we\n // have a new instance\n if (deletedFetchers.has(key)) {\n deletedFetchers.delete(key);\n }\n return state.fetchers.get(key) || IDLE_FETCHER;\n }\n function deleteFetcher(key) {\n let fetcher = state.fetchers.get(key);\n // Don't abort the controller if this is a deletion of a fetcher.submit()\n // in it's loading phase since - we don't want to abort the corresponding\n // revalidation and want them to complete and land\n if (fetchControllers.has(key) && !(fetcher && fetcher.state === \"loading\" && fetchReloadIds.has(key))) {\n abortFetcher(key);\n }\n fetchLoadMatches.delete(key);\n fetchReloadIds.delete(key);\n fetchRedirectIds.delete(key);\n // If we opted into the flag we can clear this now since we're calling\n // deleteFetcher() at the end of updateState() and we've already handed the\n // deleted fetcher keys off to the data layer.\n // If not, we're eagerly calling deleteFetcher() and we need to keep this\n // Set populated until the next updateState call, and we'll clear\n // `deletedFetchers` then\n if (future.v7_fetcherPersist) {\n deletedFetchers.delete(key);\n }\n cancelledFetcherLoads.delete(key);\n state.fetchers.delete(key);\n }\n function deleteFetcherAndUpdateState(key) {\n let count = (activeFetchers.get(key) || 0) - 1;\n if (count <= 0) {\n activeFetchers.delete(key);\n deletedFetchers.add(key);\n if (!future.v7_fetcherPersist) {\n deleteFetcher(key);\n }\n } else {\n activeFetchers.set(key, count);\n }\n updateState({\n fetchers: new Map(state.fetchers)\n });\n }\n function abortFetcher(key) {\n let controller = fetchControllers.get(key);\n if (controller) {\n controller.abort();\n fetchControllers.delete(key);\n }\n }\n function markFetchersDone(keys) {\n for (let key of keys) {\n let fetcher = getFetcher(key);\n let doneFetcher = getDoneFetcher(fetcher.data);\n state.fetchers.set(key, doneFetcher);\n }\n }\n function markFetchRedirectsDone() {\n let doneKeys = [];\n let updatedFetchers = false;\n for (let key of fetchRedirectIds) {\n let fetcher = state.fetchers.get(key);\n invariant(fetcher, \"Expected fetcher: \" + key);\n if (fetcher.state === \"loading\") {\n fetchRedirectIds.delete(key);\n doneKeys.push(key);\n updatedFetchers = true;\n }\n }\n markFetchersDone(doneKeys);\n return updatedFetchers;\n }\n function abortStaleFetchLoads(landedId) {\n let yeetedKeys = [];\n for (let [key, id] of fetchReloadIds) {\n if (id < landedId) {\n let fetcher = state.fetchers.get(key);\n invariant(fetcher, \"Expected fetcher: \" + key);\n if (fetcher.state === \"loading\") {\n abortFetcher(key);\n fetchReloadIds.delete(key);\n yeetedKeys.push(key);\n }\n }\n }\n markFetchersDone(yeetedKeys);\n return yeetedKeys.length > 0;\n }\n function getBlocker(key, fn) {\n let blocker = state.blockers.get(key) || IDLE_BLOCKER;\n if (blockerFunctions.get(key) !== fn) {\n blockerFunctions.set(key, fn);\n }\n return blocker;\n }\n function deleteBlocker(key) {\n state.blockers.delete(key);\n blockerFunctions.delete(key);\n }\n // Utility function to update blockers, ensuring valid state transitions\n function updateBlocker(key, newBlocker) {\n let blocker = state.blockers.get(key) || IDLE_BLOCKER;\n // Poor mans state machine :)\n // https://mermaid.live/edit#pako:eNqVkc9OwzAMxl8l8nnjAYrEtDIOHEBIgwvKJTReGy3_lDpIqO27k6awMG0XcrLlnz87nwdonESogKXXBuE79rq75XZO3-yHds0RJVuv70YrPlUrCEe2HfrORS3rubqZfuhtpg5C9wk5tZ4VKcRUq88q9Z8RS0-48cE1iHJkL0ugbHuFLus9L6spZy8nX9MP2CNdomVaposqu3fGayT8T8-jJQwhepo_UtpgBQaDEUom04dZhAN1aJBDlUKJBxE1ceB2Smj0Mln-IBW5AFU2dwUiktt_2Qaq2dBfaKdEup85UV7Yd-dKjlnkabl2Pvr0DTkTreM\n invariant(blocker.state === \"unblocked\" && newBlocker.state === \"blocked\" || blocker.state === \"blocked\" && newBlocker.state === \"blocked\" || blocker.state === \"blocked\" && newBlocker.state === \"proceeding\" || blocker.state === \"blocked\" && newBlocker.state === \"unblocked\" || blocker.state === \"proceeding\" && newBlocker.state === \"unblocked\", \"Invalid blocker state transition: \" + blocker.state + \" -> \" + newBlocker.state);\n let blockers = new Map(state.blockers);\n blockers.set(key, newBlocker);\n updateState({\n blockers\n });\n }\n function shouldBlockNavigation(_ref2) {\n let {\n currentLocation,\n nextLocation,\n historyAction\n } = _ref2;\n if (blockerFunctions.size === 0) {\n return;\n }\n // We ony support a single active blocker at the moment since we don't have\n // any compelling use cases for multi-blocker yet\n if (blockerFunctions.size > 1) {\n warning(false, \"A router only supports one blocker at a time\");\n }\n let entries = Array.from(blockerFunctions.entries());\n let [blockerKey, blockerFunction] = entries[entries.length - 1];\n let blocker = state.blockers.get(blockerKey);\n if (blocker && blocker.state === \"proceeding\") {\n // If the blocker is currently proceeding, we don't need to re-check\n // it and can let this navigation continue\n return;\n }\n // At this point, we know we're unblocked/blocked so we need to check the\n // user-provided blocker function\n if (blockerFunction({\n currentLocation,\n nextLocation,\n historyAction\n })) {\n return blockerKey;\n }\n }\n function handleNavigational404(pathname) {\n let error = getInternalRouterError(404, {\n pathname\n });\n let routesToUse = inFlightDataRoutes || dataRoutes;\n let {\n matches,\n route\n } = getShortCircuitMatches(routesToUse);\n // Cancel all pending deferred on 404s since we don't keep any routes\n cancelActiveDeferreds();\n return {\n notFoundMatches: matches,\n route,\n error\n };\n }\n function cancelActiveDeferreds(predicate) {\n let cancelledRouteIds = [];\n activeDeferreds.forEach((dfd, routeId) => {\n if (!predicate || predicate(routeId)) {\n // Cancel the deferred - but do not remove from activeDeferreds here -\n // we rely on the subscribers to do that so our tests can assert proper\n // cleanup via _internalActiveDeferreds\n dfd.cancel();\n cancelledRouteIds.push(routeId);\n activeDeferreds.delete(routeId);\n }\n });\n return cancelledRouteIds;\n }\n // Opt in to capturing and reporting scroll positions during navigations,\n // used by the <ScrollRestoration> component\n function enableScrollRestoration(positions, getPosition, getKey) {\n savedScrollPositions = positions;\n getScrollPosition = getPosition;\n getScrollRestorationKey = getKey || null;\n // Perform initial hydration scroll restoration, since we miss the boat on\n // the initial updateState() because we've not yet rendered <ScrollRestoration/>\n // and therefore have no savedScrollPositions available\n if (!initialScrollRestored && state.navigation === IDLE_NAVIGATION) {\n initialScrollRestored = true;\n let y = getSavedScrollPosition(state.location, state.matches);\n if (y != null) {\n updateState({\n restoreScrollPosition: y\n });\n }\n }\n return () => {\n savedScrollPositions = null;\n getScrollPosition = null;\n getScrollRestorationKey = null;\n };\n }\n function getScrollKey(location, matches) {\n if (getScrollRestorationKey) {\n let key = getScrollRestorationKey(location, matches.map(m => convertRouteMatchToUiMatch(m, state.loaderData)));\n return key || location.key;\n }\n return location.key;\n }\n function saveScrollPosition(location, matches) {\n if (savedScrollPositions && getScrollPosition) {\n let key = getScrollKey(location, matches);\n savedScrollPositions[key] = getScrollPosition();\n }\n }\n function getSavedScrollPosition(location, matches) {\n if (savedScrollPositions) {\n let key = getScrollKey(location, matches);\n let y = savedScrollPositions[key];\n if (typeof y === \"number\") {\n return y;\n }\n }\n return null;\n }\n function checkFogOfWar(matches, routesToUse, pathname) {\n if (patchRoutesOnNavigationImpl) {\n if (!matches) {\n let fogMatches = matchRoutesImpl(routesToUse, pathname, basename, true);\n return {\n active: true,\n matches: fogMatches || []\n };\n } else {\n if (Object.keys(matches[0].params).length > 0) {\n // If we matched a dynamic param or a splat, it might only be because\n // we haven't yet discovered other routes that would match with a\n // higher score. Call patchRoutesOnNavigation just to be sure\n let partialMatches = matchRoutesImpl(routesToUse, pathname, basename, true);\n return {\n active: true,\n matches: partialMatches\n };\n }\n }\n }\n return {\n active: false,\n matches: null\n };\n }\n async function discoverRoutes(matches, pathname, signal, fetcherKey) {\n if (!patchRoutesOnNavigationImpl) {\n return {\n type: \"success\",\n matches\n };\n }\n let partialMatches = matches;\n while (true) {\n let isNonHMR = inFlightDataRoutes == null;\n let routesToUse = inFlightDataRoutes || dataRoutes;\n let localManifest = manifest;\n try {\n await patchRoutesOnNavigationImpl({\n signal,\n path: pathname,\n matches: partialMatches,\n fetcherKey,\n patch: (routeId, children) => {\n if (signal.aborted) return;\n patchRoutesImpl(routeId, children, routesToUse, localManifest, mapRouteProperties);\n }\n });\n } catch (e) {\n return {\n type: \"error\",\n error: e,\n partialMatches\n };\n } finally {\n // If we are not in the middle of an HMR revalidation and we changed the\n // routes, provide a new identity so when we `updateState` at the end of\n // this navigation/fetch `router.routes` will be a new identity and\n // trigger a re-run of memoized `router.routes` dependencies.\n // HMR will already update the identity and reflow when it lands\n // `inFlightDataRoutes` in `completeNavigation`\n if (isNonHMR && !signal.aborted) {\n dataRoutes = [...dataRoutes];\n }\n }\n if (signal.aborted) {\n return {\n type: \"aborted\"\n };\n }\n let newMatches = matchRoutes(routesToUse, pathname, basename);\n if (newMatches) {\n return {\n type: \"success\",\n matches: newMatches\n };\n }\n let newPartialMatches = matchRoutesImpl(routesToUse, pathname, basename, true);\n // Avoid loops if the second pass results in the same partial matches\n if (!newPartialMatches || partialMatches.length === newPartialMatches.length && partialMatches.every((m, i) => m.route.id === newPartialMatches[i].route.id)) {\n return {\n type: \"success\",\n matches: null\n };\n }\n partialMatches = newPartialMatches;\n }\n }\n function _internalSetRoutes(newRoutes) {\n manifest = {};\n inFlightDataRoutes = convertRoutesToDataRoutes(newRoutes, mapRouteProperties, undefined, manifest);\n }\n function patchRoutes(routeId, children) {\n let isNonHMR = inFlightDataRoutes == null;\n let routesToUse = inFlightDataRoutes || dataRoutes;\n patchRoutesImpl(routeId, children, routesToUse, manifest, mapRouteProperties);\n // If we are not in the middle of an HMR revalidation and we changed the\n // routes, provide a new identity and trigger a reflow via `updateState`\n // to re-run memoized `router.routes` dependencies.\n // HMR will already update the identity and reflow when it lands\n // `inFlightDataRoutes` in `completeNavigation`\n if (isNonHMR) {\n dataRoutes = [...dataRoutes];\n updateState({});\n }\n }\n router = {\n get basename() {\n return basename;\n },\n get future() {\n return future;\n },\n get state() {\n return state;\n },\n get routes() {\n return dataRoutes;\n },\n get window() {\n return routerWindow;\n },\n initialize,\n subscribe,\n enableScrollRestoration,\n navigate,\n fetch,\n revalidate,\n // Passthrough to history-aware createHref used by useHref so we get proper\n // hash-aware URLs in DOM paths\n createHref: to => init.history.createHref(to),\n encodeLocation: to => init.history.encodeLocation(to),\n getFetcher,\n deleteFetcher: deleteFetcherAndUpdateState,\n dispose,\n getBlocker,\n deleteBlocker,\n patchRoutes,\n _internalFetchControllers: fetchControllers,\n _internalActiveDeferreds: activeDeferreds,\n // TODO: Remove setRoutes, it's temporary to avoid dealing with\n // updating the tree while validating the update algorithm.\n _internalSetRoutes\n };\n return router;\n}\n//#endregion\n////////////////////////////////////////////////////////////////////////////////\n//#region createStaticHandler\n////////////////////////////////////////////////////////////////////////////////\nconst UNSAFE_DEFERRED_SYMBOL = Symbol(\"deferred\");\nfunction createStaticHandler(routes, opts) {\n invariant(routes.length > 0, \"You must provide a non-empty routes array to createStaticHandler\");\n let manifest = {};\n let basename = (opts ? opts.basename : null) || \"/\";\n let mapRouteProperties;\n if (opts != null && opts.mapRouteProperties) {\n mapRouteProperties = opts.mapRouteProperties;\n } else if (opts != null && opts.detectErrorBoundary) {\n // If they are still using the deprecated version, wrap it with the new API\n let detectErrorBoundary = opts.detectErrorBoundary;\n mapRouteProperties = route => ({\n hasErrorBoundary: detectErrorBoundary(route)\n });\n } else {\n mapRouteProperties = defaultMapRouteProperties;\n }\n // Config driven behavior flags\n let future = _extends({\n v7_relativeSplatPath: false,\n v7_throwAbortReason: false\n }, opts ? opts.future : null);\n let dataRoutes = convertRoutesToDataRoutes(routes, mapRouteProperties, undefined, manifest);\n /**\n * The query() method is intended for document requests, in which we want to\n * call an optional action and potentially multiple loaders for all nested\n * routes. It returns a StaticHandlerContext object, which is very similar\n * to the router state (location, loaderData, actionData, errors, etc.) and\n * also adds SSR-specific information such as the statusCode and headers\n * from action/loaders Responses.\n *\n * It _should_ never throw and should report all errors through the\n * returned context.errors object, properly associating errors to their error\n * boundary. Additionally, it tracks _deepestRenderedBoundaryId which can be\n * used to emulate React error boundaries during SSr by performing a second\n * pass only down to the boundaryId.\n *\n * The one exception where we do not return a StaticHandlerContext is when a\n * redirect response is returned or thrown from any action/loader. We\n * propagate that out and return the raw Response so the HTTP server can\n * return it directly.\n *\n * - `opts.requestContext` is an optional server context that will be passed\n * to actions/loaders in the `context` parameter\n * - `opts.skipLoaderErrorBubbling` is an optional parameter that will prevent\n * the bubbling of errors which allows single-fetch-type implementations\n * where the client will handle the bubbling and we may need to return data\n * for the handling route\n */\n async function query(request, _temp3) {\n let {\n requestContext,\n skipLoaderErrorBubbling,\n dataStrategy\n } = _temp3 === void 0 ? {} : _temp3;\n let url = new URL(request.url);\n let method = request.method;\n let location = createLocation(\"\", createPath(url), null, \"default\");\n let matches = matchRoutes(dataRoutes, location, basename);\n // SSR supports HEAD requests while SPA doesn't\n if (!isValidMethod(method) && method !== \"HEAD\") {\n let error = getInternalRouterError(405, {\n method\n });\n let {\n matches: methodNotAllowedMatches,\n route\n } = getShortCircuitMatches(dataRoutes);\n return {\n basename,\n location,\n matches: methodNotAllowedMatches,\n loaderData: {},\n actionData: null,\n errors: {\n [route.id]: error\n },\n statusCode: error.status,\n loaderHeaders: {},\n actionHeaders: {},\n activeDeferreds: null\n };\n } else if (!matches) {\n let error = getInternalRouterError(404, {\n pathname: location.pathname\n });\n let {\n matches: notFoundMatches,\n route\n } = getShortCircuitMatches(dataRoutes);\n return {\n basename,\n location,\n matches: notFoundMatches,\n loaderData: {},\n actionData: null,\n errors: {\n [route.id]: error\n },\n statusCode: error.status,\n loaderHeaders: {},\n actionHeaders: {},\n activeDeferreds: null\n };\n }\n let result = await queryImpl(request, location, matches, requestContext, dataStrategy || null, skipLoaderErrorBubbling === true, null);\n if (isResponse(result)) {\n return result;\n }\n // When returning StaticHandlerContext, we patch back in the location here\n // since we need it for React Context. But this helps keep our submit and\n // loadRouteData operating on a Request instead of a Location\n return _extends({\n location,\n basename\n }, result);\n }\n /**\n * The queryRoute() method is intended for targeted route requests, either\n * for fetch ?_data requests or resource route requests. In this case, we\n * are only ever calling a single action or loader, and we are returning the\n * returned value directly. In most cases, this will be a Response returned\n * from the action/loader, but it may be a primitive or other value as well -\n * and in such cases the calling context should handle that accordingly.\n *\n * We do respect the throw/return differentiation, so if an action/loader\n * throws, then this method will throw the value. This is important so we\n * can do proper boundary identification in Remix where a thrown Response\n * must go to the Catch Boundary but a returned Response is happy-path.\n *\n * One thing to note is that any Router-initiated Errors that make sense\n * to associate with a status code will be thrown as an ErrorResponse\n * instance which include the raw Error, such that the calling context can\n * serialize the error as they see fit while including the proper response\n * code. Examples here are 404 and 405 errors that occur prior to reaching\n * any user-defined loaders.\n *\n * - `opts.routeId` allows you to specify the specific route handler to call.\n * If not provided the handler will determine the proper route by matching\n * against `request.url`\n * - `opts.requestContext` is an optional server context that will be passed\n * to actions/loaders in the `context` parameter\n */\n async function queryRoute(request, _temp4) {\n let {\n routeId,\n requestContext,\n dataStrategy\n } = _temp4 === void 0 ? {} : _temp4;\n let url = new URL(request.url);\n let method = request.method;\n let location = createLocation(\"\", createPath(url), null, \"default\");\n let matches = matchRoutes(dataRoutes, location, basename);\n // SSR supports HEAD requests while SPA doesn't\n if (!isValidMethod(method) && method !== \"HEAD\" && method !== \"OPTIONS\") {\n throw getInternalRouterError(405, {\n method\n });\n } else if (!matches) {\n throw getInternalRouterError(404, {\n pathname: location.pathname\n });\n }\n let match = routeId ? matches.find(m => m.route.id === routeId) : getTargetMatch(matches, location);\n if (routeId && !match) {\n throw getInternalRouterError(403, {\n pathname: location.pathname,\n routeId\n });\n } else if (!match) {\n // This should never hit I don't think?\n throw getInternalRouterError(404, {\n pathname: location.pathname\n });\n }\n let result = await queryImpl(request, location, matches, requestContext, dataStrategy || null, false, match);\n if (isResponse(result)) {\n return result;\n }\n let error = result.errors ? Object.values(result.errors)[0] : undefined;\n if (error !== undefined) {\n // If we got back result.errors, that means the loader/action threw\n // _something_ that wasn't a Response, but it's not guaranteed/required\n // to be an `instanceof Error` either, so we have to use throw here to\n // preserve the \"error\" state outside of queryImpl.\n throw error;\n }\n // Pick off the right state value to return\n if (result.actionData) {\n return Object.values(result.actionData)[0];\n }\n if (result.loaderData) {\n var _result$activeDeferre;\n let data = Object.values(result.loaderData)[0];\n if ((_result$activeDeferre = result.activeDeferreds) != null && _result$activeDeferre[match.route.id]) {\n data[UNSAFE_DEFERRED_SYMBOL] = result.activeDeferreds[match.route.id];\n }\n return data;\n }\n return undefined;\n }\n async function queryImpl(request, location, matches, requestContext, dataStrategy, skipLoaderErrorBubbling, routeMatch) {\n invariant(request.signal, \"query()/queryRoute() requests must contain an AbortController signal\");\n try {\n if (isMutationMethod(request.method.toLowerCase())) {\n let result = await submit(request, matches, routeMatch || getTargetMatch(matches, location), requestContext, dataStrategy, skipLoaderErrorBubbling, routeMatch != null);\n return result;\n }\n let result = await loadRouteData(request, matches, requestContext, dataStrategy, skipLoaderErrorBubbling, routeMatch);\n return isResponse(result) ? result : _extends({}, result, {\n actionData: null,\n actionHeaders: {}\n });\n } catch (e) {\n // If the user threw/returned a Response in callLoaderOrAction for a\n // `queryRoute` call, we throw the `DataStrategyResult` to bail out early\n // and then return or throw the raw Response here accordingly\n if (isDataStrategyResult(e) && isResponse(e.result)) {\n if (e.type === ResultType.error) {\n throw e.result;\n }\n return e.result;\n }\n // Redirects are always returned since they don't propagate to catch\n // boundaries\n if (isRedirectResponse(e)) {\n return e;\n }\n throw e;\n }\n }\n async function submit(request, matches, actionMatch, requestContext, dataStrategy, skipLoaderErrorBubbling, isRouteRequest) {\n let result;\n if (!actionMatch.route.action && !actionMatch.route.lazy) {\n let error = getInternalRouterError(405, {\n method: request.method,\n pathname: new URL(request.url).pathname,\n routeId: actionMatch.route.id\n });\n if (isRouteRequest) {\n throw error;\n }\n result = {\n type: ResultType.error,\n error\n };\n } else {\n let results = await callDataStrategy(\"action\", request, [actionMatch], matches, isRouteRequest, requestContext, dataStrategy);\n result = results[actionMatch.route.id];\n if (request.signal.aborted) {\n throwStaticHandlerAbortedError(request, isRouteRequest, future);\n }\n }\n if (isRedirectResult(result)) {\n // Uhhhh - this should never happen, we should always throw these from\n // callLoaderOrAction, but the type narrowing here keeps TS happy and we\n // can get back on the \"throw all redirect responses\" train here should\n // this ever happen :/\n throw new Response(null, {\n status: result.response.status,\n headers: {\n Location: result.response.headers.get(\"Location\")\n }\n });\n }\n if (isDeferredResult(result)) {\n let error = getInternalRouterError(400, {\n type: \"defer-action\"\n });\n if (isRouteRequest) {\n throw error;\n }\n result = {\n type: ResultType.error,\n error\n };\n }\n if (isRouteRequest) {\n // Note: This should only be non-Response values if we get here, since\n // isRouteRequest should throw any Response received in callLoaderOrAction\n if (isErrorResult(result)) {\n throw result.error;\n }\n return {\n matches: [actionMatch],\n loaderData: {},\n actionData: {\n [actionMatch.route.id]: result.data\n },\n errors: null,\n // Note: statusCode + headers are unused here since queryRoute will\n // return the raw Response or value\n statusCode: 200,\n loaderHeaders: {},\n actionHeaders: {},\n activeDeferreds: null\n };\n }\n // Create a GET request for the loaders\n let loaderRequest = new Request(request.url, {\n headers: request.headers,\n redirect: request.redirect,\n signal: request.signal\n });\n if (isErrorResult(result)) {\n // Store off the pending error - we use it to determine which loaders\n // to call and will commit it when we complete the navigation\n let boundaryMatch = skipLoaderErrorBubbling ? actionMatch : findNearestBoundary(matches, actionMatch.route.id);\n let context = await loadRouteData(loaderRequest, matches, requestContext, dataStrategy, skipLoaderErrorBubbling, null, [boundaryMatch.route.id, result]);\n // action status codes take precedence over loader status codes\n return _extends({}, context, {\n statusCode: isRouteErrorResponse(result.error) ? result.error.status : result.statusCode != null ? result.statusCode : 500,\n actionData: null,\n actionHeaders: _extends({}, result.headers ? {\n [actionMatch.route.id]: result.headers\n } : {})\n });\n }\n let context = await loadRouteData(loaderRequest, matches, requestContext, dataStrategy, skipLoaderErrorBubbling, null);\n return _extends({}, context, {\n actionData: {\n [actionMatch.route.id]: result.data\n }\n }, result.statusCode ? {\n statusCode: result.statusCode\n } : {}, {\n actionHeaders: result.headers ? {\n [actionMatch.route.id]: result.headers\n } : {}\n });\n }\n async function loadRouteData(request, matches, requestContext, dataStrategy, skipLoaderErrorBubbling, routeMatch, pendingActionResult) {\n let isRouteRequest = routeMatch != null;\n // Short circuit if we have no loaders to run (queryRoute())\n if (isRouteRequest && !(routeMatch != null && routeMatch.route.loader) && !(routeMatch != null && routeMatch.route.lazy)) {\n throw getInternalRouterError(400, {\n method: request.method,\n pathname: new URL(request.url).pathname,\n routeId: routeMatch == null ? void 0 : routeMatch.route.id\n });\n }\n let requestMatches = routeMatch ? [routeMatch] : pendingActionResult && isErrorResult(pendingActionResult[1]) ? getLoaderMatchesUntilBoundary(matches, pendingActionResult[0]) : matches;\n let matchesToLoad = requestMatches.filter(m => m.route.loader || m.route.lazy);\n // Short circuit if we have no loaders to run (query())\n if (matchesToLoad.length === 0) {\n return {\n matches,\n // Add a null for all matched routes for proper revalidation on the client\n loaderData: matches.reduce((acc, m) => Object.assign(acc, {\n [m.route.id]: null\n }), {}),\n errors: pendingActionResult && isErrorResult(pendingActionResult[1]) ? {\n [pendingActionResult[0]]: pendingActionResult[1].error\n } : null,\n statusCode: 200,\n loaderHeaders: {},\n activeDeferreds: null\n };\n }\n let results = await callDataStrategy(\"loader\", request, matchesToLoad, matches, isRouteRequest, requestContext, dataStrategy);\n if (request.signal.aborted) {\n throwStaticHandlerAbortedError(request, isRouteRequest, future);\n }\n // Process and commit output from loaders\n let activeDeferreds = new Map();\n let context = processRouteLoaderData(matches, results, pendingActionResult, activeDeferreds, skipLoaderErrorBubbling);\n // Add a null for any non-loader matches for proper revalidation on the client\n let executedLoaders = new Set(matchesToLoad.map(match => match.route.id));\n matches.forEach(match => {\n if (!executedLoaders.has(match.route.id)) {\n context.loaderData[match.route.id] = null;\n }\n });\n return _extends({}, context, {\n matches,\n activeDeferreds: activeDeferreds.size > 0 ? Object.fromEntries(activeDeferreds.entries()) : null\n });\n }\n // Utility wrapper for calling dataStrategy server-side without having to\n // pass around the manifest, mapRouteProperties, etc.\n async function callDataStrategy(type, request, matchesToLoad, matches, isRouteRequest, requestContext, dataStrategy) {\n let results = await callDataStrategyImpl(dataStrategy || defaultDataStrategy, type, null, request, matchesToLoad, matches, null, manifest, mapRouteProperties, requestContext);\n let dataResults = {};\n await Promise.all(matches.map(async match => {\n if (!(match.route.id in results)) {\n return;\n }\n let result = results[match.route.id];\n if (isRedirectDataStrategyResultResult(result)) {\n let response = result.result;\n // Throw redirects and let the server handle them with an HTTP redirect\n throw normalizeRelativeRoutingRedirectResponse(response, request, match.route.id, matches, basename, future.v7_relativeSplatPath);\n }\n if (isResponse(result.result) && isRouteRequest) {\n // For SSR single-route requests, we want to hand Responses back\n // directly without unwrapping\n throw result;\n }\n dataResults[match.route.id] = await convertDataStrategyResultToDataResult(result);\n }));\n return dataResults;\n }\n return {\n dataRoutes,\n query,\n queryRoute\n };\n}\n//#endregion\n////////////////////////////////////////////////////////////////////////////////\n//#region Helpers\n////////////////////////////////////////////////////////////////////////////////\n/**\n * Given an existing StaticHandlerContext and an error thrown at render time,\n * provide an updated StaticHandlerContext suitable for a second SSR render\n */\nfunction getStaticContextFromError(routes, context, error) {\n let newContext = _extends({}, context, {\n statusCode: isRouteErrorResponse(error) ? error.status : 500,\n errors: {\n [context._deepestRenderedBoundaryId || routes[0].id]: error\n }\n });\n return newContext;\n}\nfunction throwStaticHandlerAbortedError(request, isRouteRequest, future) {\n if (future.v7_throwAbortReason && request.signal.reason !== undefined) {\n throw request.signal.reason;\n }\n let method = isRouteRequest ? \"queryRoute\" : \"query\";\n throw new Error(method + \"() call aborted: \" + request.method + \" \" + request.url);\n}\nfunction isSubmissionNavigation(opts) {\n return opts != null && (\"formData\" in opts && opts.formData != null || \"body\" in opts && opts.body !== undefined);\n}\nfunction normalizeTo(location, matches, basename, prependBasename, to, v7_relativeSplatPath, fromRouteId, relative) {\n let contextualMatches;\n let activeRouteMatch;\n if (fromRouteId) {\n // Grab matches up to the calling route so our route-relative logic is\n // relative to the correct source route\n contextualMatches = [];\n for (let match of matches) {\n contextualMatches.push(match);\n if (match.route.id === fromRouteId) {\n activeRouteMatch = match;\n break;\n }\n }\n } else {\n contextualMatches = matches;\n activeRouteMatch = matches[matches.length - 1];\n }\n // Resolve the relative path\n let path = resolveTo(to ? to : \".\", getResolveToMatches(contextualMatches, v7_relativeSplatPath), stripBasename(location.pathname, basename) || location.pathname, relative === \"path\");\n // When `to` is not specified we inherit search/hash from the current\n // location, unlike when to=\".\" and we just inherit the path.\n // See https://github.com/remix-run/remix/issues/927\n if (to == null) {\n path.search = location.search;\n path.hash = location.hash;\n }\n // Account for `?index` params when routing to the current location\n if ((to == null || to === \"\" || to === \".\") && activeRouteMatch) {\n let nakedIndex = hasNakedIndexQuery(path.search);\n if (activeRouteMatch.route.index && !nakedIndex) {\n // Add one when we're targeting an index route\n path.search = path.search ? path.search.replace(/^\\?/, \"?index&\") : \"?index\";\n } else if (!activeRouteMatch.route.index && nakedIndex) {\n // Remove existing ones when we're not\n let params = new URLSearchParams(path.search);\n let indexValues = params.getAll(\"index\");\n params.delete(\"index\");\n indexValues.filter(v => v).forEach(v => params.append(\"index\", v));\n let qs = params.toString();\n path.search = qs ? \"?\" + qs : \"\";\n }\n }\n // If we're operating within a basename, prepend it to the pathname. If\n // this is a root navigation, then just use the raw basename which allows\n // the basename to have full control over the presence of a trailing slash\n // on root actions\n if (prependBasename && basename !== \"/\") {\n path.pathname = path.pathname === \"/\" ? basename : joinPaths([basename, path.pathname]);\n }\n return createPath(path);\n}\n// Normalize navigation options by converting formMethod=GET formData objects to\n// URLSearchParams so they behave identically to links with query params\nfunction normalizeNavigateOptions(normalizeFormMethod, isFetcher, path, opts) {\n // Return location verbatim on non-submission navigations\n if (!opts || !isSubmissionNavigation(opts)) {\n return {\n path\n };\n }\n if (opts.formMethod && !isValidMethod(opts.formMethod)) {\n return {\n path,\n error: getInternalRouterError(405, {\n method: opts.formMethod\n })\n };\n }\n let getInvalidBodyError = () => ({\n path,\n error: getInternalRouterError(400, {\n type: \"invalid-body\"\n })\n });\n // Create a Submission on non-GET navigations\n let rawFormMethod = opts.formMethod || \"get\";\n let formMethod = normalizeFormMethod ? rawFormMethod.toUpperCase() : rawFormMethod.toLowerCase();\n let formAction = stripHashFromPath(path);\n if (opts.body !== undefined) {\n if (opts.formEncType === \"text/plain\") {\n // text only support POST/PUT/PATCH/DELETE submissions\n if (!isMutationMethod(formMethod)) {\n return getInvalidBodyError();\n }\n let text = typeof opts.body === \"string\" ? opts.body : opts.body instanceof FormData || opts.body instanceof URLSearchParams ?\n // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#plain-text-form-data\n Array.from(opts.body.entries()).reduce((acc, _ref3) => {\n let [name, value] = _ref3;\n return \"\" + acc + name + \"=\" + value + \"\\n\";\n }, \"\") : String(opts.body);\n return {\n path,\n submission: {\n formMethod,\n formAction,\n formEncType: opts.formEncType,\n formData: undefined,\n json: undefined,\n text\n }\n };\n } else if (opts.formEncType === \"application/json\") {\n // json only supports POST/PUT/PATCH/DELETE submissions\n if (!isMutationMethod(formMethod)) {\n return getInvalidBodyError();\n }\n try {\n let json = typeof opts.body === \"string\" ? JSON.parse(opts.body) : opts.body;\n return {\n path,\n submission: {\n formMethod,\n formAction,\n formEncType: opts.formEncType,\n formData: undefined,\n json,\n text: undefined\n }\n };\n } catch (e) {\n return getInvalidBodyError();\n }\n }\n }\n invariant(typeof FormData === \"function\", \"FormData is not available in this environment\");\n let searchParams;\n let formData;\n if (opts.formData) {\n searchParams = convertFormDataToSearchParams(opts.formData);\n formData = opts.formData;\n } else if (opts.body instanceof FormData) {\n searchParams = convertFormDataToSearchParams(opts.body);\n formData = opts.body;\n } else if (opts.body instanceof URLSearchParams) {\n searchParams = opts.body;\n formData = convertSearchParamsToFormData(searchParams);\n } else if (opts.body == null) {\n searchParams = new URLSearchParams();\n formData = new FormData();\n } else {\n try {\n searchParams = new URLSearchParams(opts.body);\n formData = convertSearchParamsToFormData(searchParams);\n } catch (e) {\n return getInvalidBodyError();\n }\n }\n let submission = {\n formMethod,\n formAction,\n formEncType: opts && opts.formEncType || \"application/x-www-form-urlencoded\",\n formData,\n json: undefined,\n text: undefined\n };\n if (isMutationMethod(submission.formMethod)) {\n return {\n path,\n submission\n };\n }\n // Flatten submission onto URLSearchParams for GET submissions\n let parsedPath = parsePath(path);\n // On GET navigation submissions we can drop the ?index param from the\n // resulting location since all loaders will run. But fetcher GET submissions\n // only run a single loader so we need to preserve any incoming ?index params\n if (isFetcher && parsedPath.search && hasNakedIndexQuery(parsedPath.search)) {\n searchParams.append(\"index\", \"\");\n }\n parsedPath.search = \"?\" + searchParams;\n return {\n path: createPath(parsedPath),\n submission\n };\n}\n// Filter out all routes at/below any caught error as they aren't going to\n// render so we don't need to load them\nfunction getLoaderMatchesUntilBoundary(matches, boundaryId, includeBoundary) {\n if (includeBoundary === void 0) {\n includeBoundary = false;\n }\n let index = matches.findIndex(m => m.route.id === boundaryId);\n if (index >= 0) {\n return matches.slice(0, includeBoundary ? index + 1 : index);\n }\n return matches;\n}\nfunction getMatchesToLoad(history, state, matches, submission, location, initialHydration, skipActionErrorRevalidation, isRevalidationRequired, cancelledDeferredRoutes, cancelledFetcherLoads, deletedFetchers, fetchLoadMatches, fetchRedirectIds, routesToUse, basename, pendingActionResult) {\n let actionResult = pendingActionResult ? isErrorResult(pendingActionResult[1]) ? pendingActionResult[1].error : pendingActionResult[1].data : undefined;\n let currentUrl = history.createURL(state.location);\n let nextUrl = history.createURL(location);\n // Pick navigation matches that are net-new or qualify for revalidation\n let boundaryMatches = matches;\n if (initialHydration && state.errors) {\n // On initial hydration, only consider matches up to _and including_ the boundary.\n // This is inclusive to handle cases where a server loader ran successfully,\n // a child server loader bubbled up to this route, but this route has\n // `clientLoader.hydrate` so we want to still run the `clientLoader` so that\n // we have a complete version of `loaderData`\n boundaryMatches = getLoaderMatchesUntilBoundary(matches, Object.keys(state.errors)[0], true);\n } else if (pendingActionResult && isErrorResult(pendingActionResult[1])) {\n // If an action threw an error, we call loaders up to, but not including the\n // boundary\n boundaryMatches = getLoaderMatchesUntilBoundary(matches, pendingActionResult[0]);\n }\n // Don't revalidate loaders by default after action 4xx/5xx responses\n // when the flag is enabled. They can still opt-into revalidation via\n // `shouldRevalidate` via `actionResult`\n let actionStatus = pendingActionResult ? pendingActionResult[1].statusCode : undefined;\n let shouldSkipRevalidation = skipActionErrorRevalidation && actionStatus && actionStatus >= 400;\n let navigationMatches = boundaryMatches.filter((match, index) => {\n let {\n route\n } = match;\n if (route.lazy) {\n // We haven't loaded this route yet so we don't know if it's got a loader!\n return true;\n }\n if (route.loader == null) {\n return false;\n }\n if (initialHydration) {\n return shouldLoadRouteOnHydration(route, state.loaderData, state.errors);\n }\n // Always call the loader on new route instances and pending defer cancellations\n if (isNewLoader(state.loaderData, state.matches[index], match) || cancelledDeferredRoutes.some(id => id === match.route.id)) {\n return true;\n }\n // This is the default implementation for when we revalidate. If the route\n // provides it's own implementation, then we give them full control but\n // provide this value so they can leverage it if needed after they check\n // their own specific use cases\n let currentRouteMatch = state.matches[index];\n let nextRouteMatch = match;\n return shouldRevalidateLoader(match, _extends({\n currentUrl,\n currentParams: currentRouteMatch.params,\n nextUrl,\n nextParams: nextRouteMatch.params\n }, submission, {\n actionResult,\n actionStatus,\n defaultShouldRevalidate: shouldSkipRevalidation ? false :\n // Forced revalidation due to submission, useRevalidator, or X-Remix-Revalidate\n isRevalidationRequired || currentUrl.pathname + currentUrl.search === nextUrl.pathname + nextUrl.search ||\n // Search params affect all loaders\n currentUrl.search !== nextUrl.search || isNewRouteInstance(currentRouteMatch, nextRouteMatch)\n }));\n });\n // Pick fetcher.loads that need to be revalidated\n let revalidatingFetchers = [];\n fetchLoadMatches.forEach((f, key) => {\n // Don't revalidate:\n // - on initial hydration (shouldn't be any fetchers then anyway)\n // - if fetcher won't be present in the subsequent render\n // - no longer matches the URL (v7_fetcherPersist=false)\n // - was unmounted but persisted due to v7_fetcherPersist=true\n if (initialHydration || !matches.some(m => m.route.id === f.routeId) || deletedFetchers.has(key)) {\n return;\n }\n let fetcherMatches = matchRoutes(routesToUse, f.path, basename);\n // If the fetcher path no longer matches, push it in with null matches so\n // we can trigger a 404 in callLoadersAndMaybeResolveData. Note this is\n // currently only a use-case for Remix HMR where the route tree can change\n // at runtime and remove a route previously loaded via a fetcher\n if (!fetcherMatches) {\n revalidatingFetchers.push({\n key,\n routeId: f.routeId,\n path: f.path,\n matches: null,\n match: null,\n controller: null\n });\n return;\n }\n // Revalidating fetchers are decoupled from the route matches since they\n // load from a static href. They revalidate based on explicit revalidation\n // (submission, useRevalidator, or X-Remix-Revalidate)\n let fetcher = state.fetchers.get(key);\n let fetcherMatch = getTargetMatch(fetcherMatches, f.path);\n let shouldRevalidate = false;\n if (fetchRedirectIds.has(key)) {\n // Never trigger a revalidation of an actively redirecting fetcher\n shouldRevalidate = false;\n } else if (cancelledFetcherLoads.has(key)) {\n // Always mark for revalidation if the fetcher was cancelled\n cancelledFetcherLoads.delete(key);\n shouldRevalidate = true;\n } else if (fetcher && fetcher.state !== \"idle\" && fetcher.data === undefined) {\n // If the fetcher hasn't ever completed loading yet, then this isn't a\n // revalidation, it would just be a brand new load if an explicit\n // revalidation is required\n shouldRevalidate = isRevalidationRequired;\n } else {\n // Otherwise fall back on any user-defined shouldRevalidate, defaulting\n // to explicit revalidations only\n shouldRevalidate = shouldRevalidateLoader(fetcherMatch, _extends({\n currentUrl,\n currentParams: state.matches[state.matches.length - 1].params,\n nextUrl,\n nextParams: matches[matches.length - 1].params\n }, submission, {\n actionResult,\n actionStatus,\n defaultShouldRevalidate: shouldSkipRevalidation ? false : isRevalidationRequired\n }));\n }\n if (shouldRevalidate) {\n revalidatingFetchers.push({\n key,\n routeId: f.routeId,\n path: f.path,\n matches: fetcherMatches,\n match: fetcherMatch,\n controller: new AbortController()\n });\n }\n });\n return [navigationMatches, revalidatingFetchers];\n}\nfunction shouldLoadRouteOnHydration(route, loaderData, errors) {\n // We dunno if we have a loader - gotta find out!\n if (route.lazy) {\n return true;\n }\n // No loader, nothing to initialize\n if (!route.loader) {\n return false;\n }\n let hasData = loaderData != null && loaderData[route.id] !== undefined;\n let hasError = errors != null && errors[route.id] !== undefined;\n // Don't run if we error'd during SSR\n if (!hasData && hasError) {\n return false;\n }\n // Explicitly opting-in to running on hydration\n if (typeof route.loader === \"function\" && route.loader.hydrate === true) {\n return true;\n }\n // Otherwise, run if we're not yet initialized with anything\n return !hasData && !hasError;\n}\nfunction isNewLoader(currentLoaderData, currentMatch, match) {\n let isNew =\n // [a] -> [a, b]\n !currentMatch ||\n // [a, b] -> [a, c]\n match.route.id !== currentMatch.route.id;\n // Handle the case that we don't have data for a re-used route, potentially\n // from a prior error or from a cancelled pending deferred\n let isMissingData = currentLoaderData[match.route.id] === undefined;\n // Always load if this is a net-new route or we don't yet have data\n return isNew || isMissingData;\n}\nfunction isNewRouteInstance(currentMatch, match) {\n let currentPath = currentMatch.route.path;\n return (\n // param change for this match, /users/123 -> /users/456\n currentMatch.pathname !== match.pathname ||\n // splat param changed, which is not present in match.path\n // e.g. /files/images/avatar.jpg -> files/finances.xls\n currentPath != null && currentPath.endsWith(\"*\") && currentMatch.params[\"*\"] !== match.params[\"*\"]\n );\n}\nfunction shouldRevalidateLoader(loaderMatch, arg) {\n if (loaderMatch.route.shouldRevalidate) {\n let routeChoice = loaderMatch.route.shouldRevalidate(arg);\n if (typeof routeChoice === \"boolean\") {\n return routeChoice;\n }\n }\n return arg.defaultShouldRevalidate;\n}\nfunction patchRoutesImpl(routeId, children, routesToUse, manifest, mapRouteProperties) {\n var _childrenToPatch;\n let childrenToPatch;\n if (routeId) {\n let route = manifest[routeId];\n invariant(route, \"No route found to patch children into: routeId = \" + routeId);\n if (!route.children) {\n route.children = [];\n }\n childrenToPatch = route.children;\n } else {\n childrenToPatch = routesToUse;\n }\n // Don't patch in routes we already know about so that `patch` is idempotent\n // to simplify user-land code. This is useful because we re-call the\n // `patchRoutesOnNavigation` function for matched routes with params.\n let uniqueChildren = children.filter(newRoute => !childrenToPatch.some(existingRoute => isSameRoute(newRoute, existingRoute)));\n let newRoutes = convertRoutesToDataRoutes(uniqueChildren, mapRouteProperties, [routeId || \"_\", \"patch\", String(((_childrenToPatch = childrenToPatch) == null ? void 0 : _childrenToPatch.length) || \"0\")], manifest);\n childrenToPatch.push(...newRoutes);\n}\nfunction isSameRoute(newRoute, existingRoute) {\n // Most optimal check is by id\n if (\"id\" in newRoute && \"id\" in existingRoute && newRoute.id === existingRoute.id) {\n return true;\n }\n // Second is by pathing differences\n if (!(newRoute.index === existingRoute.index && newRoute.path === existingRoute.path && newRoute.caseSensitive === existingRoute.caseSensitive)) {\n return false;\n }\n // Pathless layout routes are trickier since we need to check children.\n // If they have no children then they're the same as far as we can tell\n if ((!newRoute.children || newRoute.children.length === 0) && (!existingRoute.children || existingRoute.children.length === 0)) {\n return true;\n }\n // Otherwise, we look to see if every child in the new route is already\n // represented in the existing route's children\n return newRoute.children.every((aChild, i) => {\n var _existingRoute$childr;\n return (_existingRoute$childr = existingRoute.children) == null ? void 0 : _existingRoute$childr.some(bChild => isSameRoute(aChild, bChild));\n });\n}\n/**\n * Execute route.lazy() methods to lazily load route modules (loader, action,\n * shouldRevalidate) and update the routeManifest in place which shares objects\n * with dataRoutes so those get updated as well.\n */\nasync function loadLazyRouteModule(route, mapRouteProperties, manifest) {\n if (!route.lazy) {\n return;\n }\n let lazyRoute = await route.lazy();\n // If the lazy route function was executed and removed by another parallel\n // call then we can return - first lazy() to finish wins because the return\n // value of lazy is expected to be static\n if (!route.lazy) {\n return;\n }\n let routeToUpdate = manifest[route.id];\n invariant(routeToUpdate, \"No route found in manifest\");\n // Update the route in place. This should be safe because there's no way\n // we could yet be sitting on this route as we can't get there without\n // resolving lazy() first.\n //\n // This is different than the HMR \"update\" use-case where we may actively be\n // on the route being updated. The main concern boils down to \"does this\n // mutation affect any ongoing navigations or any current state.matches\n // values?\". If not, it should be safe to update in place.\n let routeUpdates = {};\n for (let lazyRouteProperty in lazyRoute) {\n let staticRouteValue = routeToUpdate[lazyRouteProperty];\n let isPropertyStaticallyDefined = staticRouteValue !== undefined &&\n // This property isn't static since it should always be updated based\n // on the route updates\n lazyRouteProperty !== \"hasErrorBoundary\";\n warning(!isPropertyStaticallyDefined, \"Route \\\"\" + routeToUpdate.id + \"\\\" has a static property \\\"\" + lazyRouteProperty + \"\\\" \" + \"defined but its lazy function is also returning a value for this property. \" + (\"The lazy route property \\\"\" + lazyRouteProperty + \"\\\" will be ignored.\"));\n if (!isPropertyStaticallyDefined && !immutableRouteKeys.has(lazyRouteProperty)) {\n routeUpdates[lazyRouteProperty] = lazyRoute[lazyRouteProperty];\n }\n }\n // Mutate the route with the provided updates. Do this first so we pass\n // the updated version to mapRouteProperties\n Object.assign(routeToUpdate, routeUpdates);\n // Mutate the `hasErrorBoundary` property on the route based on the route\n // updates and remove the `lazy` function so we don't resolve the lazy\n // route again.\n Object.assign(routeToUpdate, _extends({}, mapRouteProperties(routeToUpdate), {\n lazy: undefined\n }));\n}\n// Default implementation of `dataStrategy` which fetches all loaders in parallel\nasync function defaultDataStrategy(_ref4) {\n let {\n matches\n } = _ref4;\n let matchesToLoad = matches.filter(m => m.shouldLoad);\n let results = await Promise.all(matchesToLoad.map(m => m.resolve()));\n return results.reduce((acc, result, i) => Object.assign(acc, {\n [matchesToLoad[i].route.id]: result\n }), {});\n}\nasync function callDataStrategyImpl(dataStrategyImpl, type, state, request, matchesToLoad, matches, fetcherKey, manifest, mapRouteProperties, requestContext) {\n let loadRouteDefinitionsPromises = matches.map(m => m.route.lazy ? loadLazyRouteModule(m.route, mapRouteProperties, manifest) : undefined);\n let dsMatches = matches.map((match, i) => {\n let loadRoutePromise = loadRouteDefinitionsPromises[i];\n let shouldLoad = matchesToLoad.some(m => m.route.id === match.route.id);\n // `resolve` encapsulates route.lazy(), executing the loader/action,\n // and mapping return values/thrown errors to a `DataStrategyResult`. Users\n // can pass a callback to take fine-grained control over the execution\n // of the loader/action\n let resolve = async handlerOverride => {\n if (handlerOverride && request.method === \"GET\" && (match.route.lazy || match.route.loader)) {\n shouldLoad = true;\n }\n return shouldLoad ? callLoaderOrAction(type, request, match, loadRoutePromise, handlerOverride, requestContext) : Promise.resolve({\n type: ResultType.data,\n result: undefined\n });\n };\n return _extends({}, match, {\n shouldLoad,\n resolve\n });\n });\n // Send all matches here to allow for a middleware-type implementation.\n // handler will be a no-op for unneeded routes and we filter those results\n // back out below.\n let results = await dataStrategyImpl({\n matches: dsMatches,\n request,\n params: matches[0].params,\n fetcherKey,\n context: requestContext\n });\n // Wait for all routes to load here but 'swallow the error since we want\n // it to bubble up from the `await loadRoutePromise` in `callLoaderOrAction` -\n // called from `match.resolve()`\n try {\n await Promise.all(loadRouteDefinitionsPromises);\n } catch (e) {\n // No-op\n }\n return results;\n}\n// Default logic for calling a loader/action is the user has no specified a dataStrategy\nasync function callLoaderOrAction(type, request, match, loadRoutePromise, handlerOverride, staticContext) {\n let result;\n let onReject;\n let runHandler = handler => {\n // Setup a promise we can race against so that abort signals short circuit\n let reject;\n // This will never resolve so safe to type it as Promise<DataStrategyResult> to\n // satisfy the function return value\n let abortPromise = new Promise((_, r) => reject = r);\n onReject = () => reject();\n request.signal.addEventListener(\"abort\", onReject);\n let actualHandler = ctx => {\n if (typeof handler !== \"function\") {\n return Promise.reject(new Error(\"You cannot call the handler for a route which defines a boolean \" + (\"\\\"\" + type + \"\\\" [routeId: \" + match.route.id + \"]\")));\n }\n return handler({\n request,\n params: match.params,\n context: staticContext\n }, ...(ctx !== undefined ? [ctx] : []));\n };\n let handlerPromise = (async () => {\n try {\n let val = await (handlerOverride ? handlerOverride(ctx => actualHandler(ctx)) : actualHandler());\n return {\n type: \"data\",\n result: val\n };\n } catch (e) {\n return {\n type: \"error\",\n result: e\n };\n }\n })();\n return Promise.race([handlerPromise, abortPromise]);\n };\n try {\n let handler = match.route[type];\n // If we have a route.lazy promise, await that first\n if (loadRoutePromise) {\n if (handler) {\n // Run statically defined handler in parallel with lazy()\n let handlerError;\n let [value] = await Promise.all([\n // If the handler throws, don't let it immediately bubble out,\n // since we need to let the lazy() execution finish so we know if this\n // route has a boundary that can handle the error\n runHandler(handler).catch(e => {\n handlerError = e;\n }), loadRoutePromise]);\n if (handlerError !== undefined) {\n throw handlerError;\n }\n result = value;\n } else {\n // Load lazy route module, then run any returned handler\n await loadRoutePromise;\n handler = match.route[type];\n if (handler) {\n // Handler still runs even if we got interrupted to maintain consistency\n // with un-abortable behavior of handler execution on non-lazy or\n // previously-lazy-loaded routes\n result = await runHandler(handler);\n } else if (type === \"action\") {\n let url = new URL(request.url);\n let pathname = url.pathname + url.search;\n throw getInternalRouterError(405, {\n method: request.method,\n pathname,\n routeId: match.route.id\n });\n } else {\n // lazy() route has no loader to run. Short circuit here so we don't\n // hit the invariant below that errors on returning undefined.\n return {\n type: ResultType.data,\n result: undefined\n };\n }\n }\n } else if (!handler) {\n let url = new URL(request.url);\n let pathname = url.pathname + url.search;\n throw getInternalRouterError(404, {\n pathname\n });\n } else {\n result = await runHandler(handler);\n }\n invariant(result.result !== undefined, \"You defined \" + (type === \"action\" ? \"an action\" : \"a loader\") + \" for route \" + (\"\\\"\" + match.route.id + \"\\\" but didn't return anything from your `\" + type + \"` \") + \"function. Please return a value or `null`.\");\n } catch (e) {\n // We should already be catching and converting normal handler executions to\n // DataStrategyResults and returning them, so anything that throws here is an\n // unexpected error we still need to wrap\n return {\n type: ResultType.error,\n result: e\n };\n } finally {\n if (onReject) {\n request.signal.removeEventListener(\"abort\", onReject);\n }\n }\n return result;\n}\nasync function convertDataStrategyResultToDataResult(dataStrategyResult) {\n let {\n result,\n type\n } = dataStrategyResult;\n if (isResponse(result)) {\n let data;\n try {\n let contentType = result.headers.get(\"Content-Type\");\n // Check between word boundaries instead of startsWith() due to the last\n // paragraph of https://httpwg.org/specs/rfc9110.html#field.content-type\n if (contentType && /\\bapplication\\/json\\b/.test(contentType)) {\n if (result.body == null) {\n data = null;\n } else {\n data = await result.json();\n }\n } else {\n data = await result.text();\n }\n } catch (e) {\n return {\n type: ResultType.error,\n error: e\n };\n }\n if (type === ResultType.error) {\n return {\n type: ResultType.error,\n error: new ErrorResponseImpl(result.status, result.statusText, data),\n statusCode: result.status,\n headers: result.headers\n };\n }\n return {\n type: ResultType.data,\n data,\n statusCode: result.status,\n headers: result.headers\n };\n }\n if (type === ResultType.error) {\n if (isDataWithResponseInit(result)) {\n var _result$init3, _result$init4;\n if (result.data instanceof Error) {\n var _result$init, _result$init2;\n return {\n type: ResultType.error,\n error: result.data,\n statusCode: (_result$init = result.init) == null ? void 0 : _result$init.status,\n headers: (_result$init2 = result.init) != null && _result$init2.headers ? new Headers(result.init.headers) : undefined\n };\n }\n // Convert thrown data() to ErrorResponse instances\n return {\n type: ResultType.error,\n error: new ErrorResponseImpl(((_result$init3 = result.init) == null ? void 0 : _result$init3.status) || 500, undefined, result.data),\n statusCode: isRouteErrorResponse(result) ? result.status : undefined,\n headers: (_result$init4 = result.init) != null && _result$init4.headers ? new Headers(result.init.headers) : undefined\n };\n }\n return {\n type: ResultType.error,\n error: result,\n statusCode: isRouteErrorResponse(result) ? result.status : undefined\n };\n }\n if (isDeferredData(result)) {\n var _result$init5, _result$init6;\n return {\n type: ResultType.deferred,\n deferredData: result,\n statusCode: (_result$init5 = result.init) == null ? void 0 : _result$init5.status,\n headers: ((_result$init6 = result.init) == null ? void 0 : _result$init6.headers) && new Headers(result.init.headers)\n };\n }\n if (isDataWithResponseInit(result)) {\n var _result$init7, _result$init8;\n return {\n type: ResultType.data,\n data: result.data,\n statusCode: (_result$init7 = result.init) == null ? void 0 : _result$init7.status,\n headers: (_result$init8 = result.init) != null && _result$init8.headers ? new Headers(result.init.headers) : undefined\n };\n }\n return {\n type: ResultType.data,\n data: result\n };\n}\n// Support relative routing in internal redirects\nfunction normalizeRelativeRoutingRedirectResponse(response, request, routeId, matches, basename, v7_relativeSplatPath) {\n let location = response.headers.get(\"Location\");\n invariant(location, \"Redirects returned/thrown from loaders/actions must have a Location header\");\n if (!ABSOLUTE_URL_REGEX.test(location)) {\n let trimmedMatches = matches.slice(0, matches.findIndex(m => m.route.id === routeId) + 1);\n location = normalizeTo(new URL(request.url), trimmedMatches, basename, true, location, v7_relativeSplatPath);\n response.headers.set(\"Location\", location);\n }\n return response;\n}\nfunction normalizeRedirectLocation(location, currentUrl, basename, historyInstance) {\n // Match Chrome's behavior:\n // https://github.com/chromium/chromium/blob/216dbeb61db0c667e62082e5f5400a32d6983df3/content/public/common/url_utils.cc#L82\n let invalidProtocols = [\"about:\", \"blob:\", \"chrome:\", \"chrome-untrusted:\", \"content:\", \"data:\", \"devtools:\", \"file:\", \"filesystem:\",\n // eslint-disable-next-line no-script-url\n \"javascript:\"];\n if (ABSOLUTE_URL_REGEX.test(location)) {\n // Strip off the protocol+origin for same-origin + same-basename absolute redirects\n let normalizedLocation = location;\n let url = normalizedLocation.startsWith(\"//\") ? new URL(currentUrl.protocol + normalizedLocation) : new URL(normalizedLocation);\n if (invalidProtocols.includes(url.protocol)) {\n throw new Error(\"Invalid redirect location\");\n }\n let isSameBasename = stripBasename(url.pathname, basename) != null;\n if (url.origin === currentUrl.origin && isSameBasename) {\n return removeDoubleSlashes(url.pathname) + url.search + url.hash;\n }\n }\n try {\n let url = historyInstance.createURL(location);\n if (invalidProtocols.includes(url.protocol)) {\n throw new Error(\"Invalid redirect location\");\n }\n } catch (e) {}\n return location;\n}\n// Utility method for creating the Request instances for loaders/actions during\n// client-side navigations and fetches. During SSR we will always have a\n// Request instance from the static handler (query/queryRoute)\nfunction createClientSideRequest(history, location, signal, submission) {\n let url = history.createURL(stripHashFromPath(location)).toString();\n let init = {\n signal\n };\n if (submission && isMutationMethod(submission.formMethod)) {\n let {\n formMethod,\n formEncType\n } = submission;\n // Didn't think we needed this but it turns out unlike other methods, patch\n // won't be properly normalized to uppercase and results in a 405 error.\n // See: https://fetch.spec.whatwg.org/#concept-method\n init.method = formMethod.toUpperCase();\n if (formEncType === \"application/json\") {\n init.headers = new Headers({\n \"Content-Type\": formEncType\n });\n init.body = JSON.stringify(submission.json);\n } else if (formEncType === \"text/plain\") {\n // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request)\n init.body = submission.text;\n } else if (formEncType === \"application/x-www-form-urlencoded\" && submission.formData) {\n // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request)\n init.body = convertFormDataToSearchParams(submission.formData);\n } else {\n // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request)\n init.body = submission.formData;\n }\n }\n return new Request(url, init);\n}\nfunction convertFormDataToSearchParams(formData) {\n let searchParams = new URLSearchParams();\n for (let [key, value] of formData.entries()) {\n // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#converting-an-entry-list-to-a-list-of-name-value-pairs\n searchParams.append(key, typeof value === \"string\" ? value : value.name);\n }\n return searchParams;\n}\nfunction convertSearchParamsToFormData(searchParams) {\n let formData = new FormData();\n for (let [key, value] of searchParams.entries()) {\n formData.append(key, value);\n }\n return formData;\n}\nfunction processRouteLoaderData(matches, results, pendingActionResult, activeDeferreds, skipLoaderErrorBubbling) {\n // Fill in loaderData/errors from our loaders\n let loaderData = {};\n let errors = null;\n let statusCode;\n let foundError = false;\n let loaderHeaders = {};\n let pendingError = pendingActionResult && isErrorResult(pendingActionResult[1]) ? pendingActionResult[1].error : undefined;\n // Process loader results into state.loaderData/state.errors\n matches.forEach(match => {\n if (!(match.route.id in results)) {\n return;\n }\n let id = match.route.id;\n let result = results[id];\n invariant(!isRedirectResult(result), \"Cannot handle redirect results in processLoaderData\");\n if (isErrorResult(result)) {\n let error = result.error;\n // If we have a pending action error, we report it at the highest-route\n // that throws a loader error, and then clear it out to indicate that\n // it was consumed\n if (pendingError !== undefined) {\n error = pendingError;\n pendingError = undefined;\n }\n errors = errors || {};\n if (skipLoaderErrorBubbling) {\n errors[id] = error;\n } else {\n // Look upwards from the matched route for the closest ancestor error\n // boundary, defaulting to the root match. Prefer higher error values\n // if lower errors bubble to the same boundary\n let boundaryMatch = findNearestBoundary(matches, id);\n if (errors[boundaryMatch.route.id] == null) {\n errors[boundaryMatch.route.id] = error;\n }\n }\n // Clear our any prior loaderData for the throwing route\n loaderData[id] = undefined;\n // Once we find our first (highest) error, we set the status code and\n // prevent deeper status codes from overriding\n if (!foundError) {\n foundError = true;\n statusCode = isRouteErrorResponse(result.error) ? result.error.status : 500;\n }\n if (result.headers) {\n loaderHeaders[id] = result.headers;\n }\n } else {\n if (isDeferredResult(result)) {\n activeDeferreds.set(id, result.deferredData);\n loaderData[id] = result.deferredData.data;\n // Error status codes always override success status codes, but if all\n // loaders are successful we take the deepest status code.\n if (result.statusCode != null && result.statusCode !== 200 && !foundError) {\n statusCode = result.statusCode;\n }\n if (result.headers) {\n loaderHeaders[id] = result.headers;\n }\n } else {\n loaderData[id] = result.data;\n // Error status codes always override success status codes, but if all\n // loaders are successful we take the deepest status code.\n if (result.statusCode && result.statusCode !== 200 && !foundError) {\n statusCode = result.statusCode;\n }\n if (result.headers) {\n loaderHeaders[id] = result.headers;\n }\n }\n }\n });\n // If we didn't consume the pending action error (i.e., all loaders\n // resolved), then consume it here. Also clear out any loaderData for the\n // throwing route\n if (pendingError !== undefined && pendingActionResult) {\n errors = {\n [pendingActionResult[0]]: pendingError\n };\n loaderData[pendingActionResult[0]] = undefined;\n }\n return {\n loaderData,\n errors,\n statusCode: statusCode || 200,\n loaderHeaders\n };\n}\nfunction processLoaderData(state, matches, results, pendingActionResult, revalidatingFetchers, fetcherResults, activeDeferreds) {\n let {\n loaderData,\n errors\n } = processRouteLoaderData(matches, results, pendingActionResult, activeDeferreds, false // This method is only called client side so we always want to bubble\n );\n // Process results from our revalidating fetchers\n revalidatingFetchers.forEach(rf => {\n let {\n key,\n match,\n controller\n } = rf;\n let result = fetcherResults[key];\n invariant(result, \"Did not find corresponding fetcher result\");\n // Process fetcher non-redirect errors\n if (controller && controller.signal.aborted) {\n // Nothing to do for aborted fetchers\n return;\n } else if (isErrorResult(result)) {\n let boundaryMatch = findNearestBoundary(state.matches, match == null ? void 0 : match.route.id);\n if (!(errors && errors[boundaryMatch.route.id])) {\n errors = _extends({}, errors, {\n [boundaryMatch.route.id]: result.error\n });\n }\n state.fetchers.delete(key);\n } else if (isRedirectResult(result)) {\n // Should never get here, redirects should get processed above, but we\n // keep this to type narrow to a success result in the else\n invariant(false, \"Unhandled fetcher revalidation redirect\");\n } else if (isDeferredResult(result)) {\n // Should never get here, deferred data should be awaited for fetchers\n // in resolveDeferredResults\n invariant(false, \"Unhandled fetcher deferred data\");\n } else {\n let doneFetcher = getDoneFetcher(result.data);\n state.fetchers.set(key, doneFetcher);\n }\n });\n return {\n loaderData,\n errors\n };\n}\nfunction mergeLoaderData(loaderData, newLoaderData, matches, errors) {\n let mergedLoaderData = _extends({}, newLoaderData);\n for (let match of matches) {\n let id = match.route.id;\n if (newLoaderData.hasOwnProperty(id)) {\n if (newLoaderData[id] !== undefined) {\n mergedLoaderData[id] = newLoaderData[id];\n }\n } else if (loaderData[id] !== undefined && match.route.loader) {\n // Preserve existing keys not included in newLoaderData and where a loader\n // wasn't removed by HMR\n mergedLoaderData[id] = loaderData[id];\n }\n if (errors && errors.hasOwnProperty(id)) {\n // Don't keep any loader data below the boundary\n break;\n }\n }\n return mergedLoaderData;\n}\nfunction getActionDataForCommit(pendingActionResult) {\n if (!pendingActionResult) {\n return {};\n }\n return isErrorResult(pendingActionResult[1]) ? {\n // Clear out prior actionData on errors\n actionData: {}\n } : {\n actionData: {\n [pendingActionResult[0]]: pendingActionResult[1].data\n }\n };\n}\n// Find the nearest error boundary, looking upwards from the leaf route (or the\n// route specified by routeId) for the closest ancestor error boundary,\n// defaulting to the root match\nfunction findNearestBoundary(matches, routeId) {\n let eligibleMatches = routeId ? matches.slice(0, matches.findIndex(m => m.route.id === routeId) + 1) : [...matches];\n return eligibleMatches.reverse().find(m => m.route.hasErrorBoundary === true) || matches[0];\n}\nfunction getShortCircuitMatches(routes) {\n // Prefer a root layout route if present, otherwise shim in a route object\n let route = routes.length === 1 ? routes[0] : routes.find(r => r.index || !r.path || r.path === \"/\") || {\n id: \"__shim-error-route__\"\n };\n return {\n matches: [{\n params: {},\n pathname: \"\",\n pathnameBase: \"\",\n route\n }],\n route\n };\n}\nfunction getInternalRouterError(status, _temp5) {\n let {\n pathname,\n routeId,\n method,\n type,\n message\n } = _temp5 === void 0 ? {} : _temp5;\n let statusText = \"Unknown Server Error\";\n let errorMessage = \"Unknown @remix-run/router error\";\n if (status === 400) {\n statusText = \"Bad Request\";\n if (method && pathname && routeId) {\n errorMessage = \"You made a \" + method + \" request to \\\"\" + pathname + \"\\\" but \" + (\"did not provide a `loader` for route \\\"\" + routeId + \"\\\", \") + \"so there is no way to handle the request.\";\n } else if (type === \"defer-action\") {\n errorMessage = \"defer() is not supported in actions\";\n } else if (type === \"invalid-body\") {\n errorMessage = \"Unable to encode submission body\";\n }\n } else if (status === 403) {\n statusText = \"Forbidden\";\n errorMessage = \"Route \\\"\" + routeId + \"\\\" does not match URL \\\"\" + pathname + \"\\\"\";\n } else if (status === 404) {\n statusText = \"Not Found\";\n errorMessage = \"No route matches URL \\\"\" + pathname + \"\\\"\";\n } else if (status === 405) {\n statusText = \"Method Not Allowed\";\n if (method && pathname && routeId) {\n errorMessage = \"You made a \" + method.toUpperCase() + \" request to \\\"\" + pathname + \"\\\" but \" + (\"did not provide an `action` for route \\\"\" + routeId + \"\\\", \") + \"so there is no way to handle the request.\";\n } else if (method) {\n errorMessage = \"Invalid request method \\\"\" + method.toUpperCase() + \"\\\"\";\n }\n }\n return new ErrorResponseImpl(status || 500, statusText, new Error(errorMessage), true);\n}\n// Find any returned redirect errors, starting from the lowest match\nfunction findRedirect(results) {\n let entries = Object.entries(results);\n for (let i = entries.length - 1; i >= 0; i--) {\n let [key, result] = entries[i];\n if (isRedirectResult(result)) {\n return {\n key,\n result\n };\n }\n }\n}\nfunction stripHashFromPath(path) {\n let parsedPath = typeof path === \"string\" ? parsePath(path) : path;\n return createPath(_extends({}, parsedPath, {\n hash: \"\"\n }));\n}\nfunction isHashChangeOnly(a, b) {\n if (a.pathname !== b.pathname || a.search !== b.search) {\n return false;\n }\n if (a.hash === \"\") {\n // /page -> /page#hash\n return b.hash !== \"\";\n } else if (a.hash === b.hash) {\n // /page#hash -> /page#hash\n return true;\n } else if (b.hash !== \"\") {\n // /page#hash -> /page#other\n return true;\n }\n // If the hash is removed the browser will re-perform a request to the server\n // /page#hash -> /page\n return false;\n}\nfunction isDataStrategyResult(result) {\n return result != null && typeof result === \"object\" && \"type\" in result && \"result\" in result && (result.type === ResultType.data || result.type === ResultType.error);\n}\nfunction isRedirectDataStrategyResultResult(result) {\n return isResponse(result.result) && redirectStatusCodes.has(result.result.status);\n}\nfunction isDeferredResult(result) {\n return result.type === ResultType.deferred;\n}\nfunction isErrorResult(result) {\n return result.type === ResultType.error;\n}\nfunction isRedirectResult(result) {\n return (result && result.type) === ResultType.redirect;\n}\nfunction isDataWithResponseInit(value) {\n return typeof value === \"object\" && value != null && \"type\" in value && \"data\" in value && \"init\" in value && value.type === \"DataWithResponseInit\";\n}\nfunction isDeferredData(value) {\n let deferred = value;\n return deferred && typeof deferred === \"object\" && typeof deferred.data === \"object\" && typeof deferred.subscribe === \"function\" && typeof deferred.cancel === \"function\" && typeof deferred.resolveData === \"function\";\n}\nfunction isResponse(value) {\n return value != null && typeof value.status === \"number\" && typeof value.statusText === \"string\" && typeof value.headers === \"object\" && typeof value.body !== \"undefined\";\n}\nfunction isRedirectResponse(result) {\n if (!isResponse(result)) {\n return false;\n }\n let status = result.status;\n let location = result.headers.get(\"Location\");\n return status >= 300 && status <= 399 && location != null;\n}\nfunction isValidMethod(method) {\n return validRequestMethods.has(method.toLowerCase());\n}\nfunction isMutationMethod(method) {\n return validMutationMethods.has(method.toLowerCase());\n}\nasync function resolveNavigationDeferredResults(matches, results, signal, currentMatches, currentLoaderData) {\n let entries = Object.entries(results);\n for (let index = 0; index < entries.length; index++) {\n let [routeId, result] = entries[index];\n let match = matches.find(m => (m == null ? void 0 : m.route.id) === routeId);\n // If we don't have a match, then we can have a deferred result to do\n // anything with. This is for revalidating fetchers where the route was\n // removed during HMR\n if (!match) {\n continue;\n }\n let currentMatch = currentMatches.find(m => m.route.id === match.route.id);\n let isRevalidatingLoader = currentMatch != null && !isNewRouteInstance(currentMatch, match) && (currentLoaderData && currentLoaderData[match.route.id]) !== undefined;\n if (isDeferredResult(result) && isRevalidatingLoader) {\n // Note: we do not have to touch activeDeferreds here since we race them\n // against the signal in resolveDeferredData and they'll get aborted\n // there if needed\n await resolveDeferredData(result, signal, false).then(result => {\n if (result) {\n results[routeId] = result;\n }\n });\n }\n }\n}\nasync function resolveFetcherDeferredResults(matches, results, revalidatingFetchers) {\n for (let index = 0; index < revalidatingFetchers.length; index++) {\n let {\n key,\n routeId,\n controller\n } = revalidatingFetchers[index];\n let result = results[key];\n let match = matches.find(m => (m == null ? void 0 : m.route.id) === routeId);\n // If we don't have a match, then we can have a deferred result to do\n // anything with. This is for revalidating fetchers where the route was\n // removed during HMR\n if (!match) {\n continue;\n }\n if (isDeferredResult(result)) {\n // Note: we do not have to touch activeDeferreds here since we race them\n // against the signal in resolveDeferredData and they'll get aborted\n // there if needed\n invariant(controller, \"Expected an AbortController for revalidating fetcher deferred result\");\n await resolveDeferredData(result, controller.signal, true).then(result => {\n if (result) {\n results[key] = result;\n }\n });\n }\n }\n}\nasync function resolveDeferredData(result, signal, unwrap) {\n if (unwrap === void 0) {\n unwrap = false;\n }\n let aborted = await result.deferredData.resolveData(signal);\n if (aborted) {\n return;\n }\n if (unwrap) {\n try {\n return {\n type: ResultType.data,\n data: result.deferredData.unwrappedData\n };\n } catch (e) {\n // Handle any TrackedPromise._error values encountered while unwrapping\n return {\n type: ResultType.error,\n error: e\n };\n }\n }\n return {\n type: ResultType.data,\n data: result.deferredData.data\n };\n}\nfunction hasNakedIndexQuery(search) {\n return new URLSearchParams(search).getAll(\"index\").some(v => v === \"\");\n}\nfunction getTargetMatch(matches, location) {\n let search = typeof location === \"string\" ? parsePath(location).search : location.search;\n if (matches[matches.length - 1].route.index && hasNakedIndexQuery(search || \"\")) {\n // Return the leaf index route when index is present\n return matches[matches.length - 1];\n }\n // Otherwise grab the deepest \"path contributing\" match (ignoring index and\n // pathless layout routes)\n let pathMatches = getPathContributingMatches(matches);\n return pathMatches[pathMatches.length - 1];\n}\nfunction getSubmissionFromNavigation(navigation) {\n let {\n formMethod,\n formAction,\n formEncType,\n text,\n formData,\n json\n } = navigation;\n if (!formMethod || !formAction || !formEncType) {\n return;\n }\n if (text != null) {\n return {\n formMethod,\n formAction,\n formEncType,\n formData: undefined,\n json: undefined,\n text\n };\n } else if (formData != null) {\n return {\n formMethod,\n formAction,\n formEncType,\n formData,\n json: undefined,\n text: undefined\n };\n } else if (json !== undefined) {\n return {\n formMethod,\n formAction,\n formEncType,\n formData: undefined,\n json,\n text: undefined\n };\n }\n}\nfunction getLoadingNavigation(location, submission) {\n if (submission) {\n let navigation = {\n state: \"loading\",\n location,\n formMethod: submission.formMethod,\n formAction: submission.formAction,\n formEncType: submission.formEncType,\n formData: submission.formData,\n json: submission.json,\n text: submission.text\n };\n return navigation;\n } else {\n let navigation = {\n state: \"loading\",\n location,\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n json: undefined,\n text: undefined\n };\n return navigation;\n }\n}\nfunction getSubmittingNavigation(location, submission) {\n let navigation = {\n state: \"submitting\",\n location,\n formMethod: submission.formMethod,\n formAction: submission.formAction,\n formEncType: submission.formEncType,\n formData: submission.formData,\n json: submission.json,\n text: submission.text\n };\n return navigation;\n}\nfunction getLoadingFetcher(submission, data) {\n if (submission) {\n let fetcher = {\n state: \"loading\",\n formMethod: submission.formMethod,\n formAction: submission.formAction,\n formEncType: submission.formEncType,\n formData: submission.formData,\n json: submission.json,\n text: submission.text,\n data\n };\n return fetcher;\n } else {\n let fetcher = {\n state: \"loading\",\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n json: undefined,\n text: undefined,\n data\n };\n return fetcher;\n }\n}\nfunction getSubmittingFetcher(submission, existingFetcher) {\n let fetcher = {\n state: \"submitting\",\n formMethod: submission.formMethod,\n formAction: submission.formAction,\n formEncType: submission.formEncType,\n formData: submission.formData,\n json: submission.json,\n text: submission.text,\n data: existingFetcher ? existingFetcher.data : undefined\n };\n return fetcher;\n}\nfunction getDoneFetcher(data) {\n let fetcher = {\n state: \"idle\",\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n json: undefined,\n text: undefined,\n data\n };\n return fetcher;\n}\nfunction restoreAppliedTransitions(_window, transitions) {\n try {\n let sessionPositions = _window.sessionStorage.getItem(TRANSITIONS_STORAGE_KEY);\n if (sessionPositions) {\n let json = JSON.parse(sessionPositions);\n for (let [k, v] of Object.entries(json || {})) {\n if (v && Array.isArray(v)) {\n transitions.set(k, new Set(v || []));\n }\n }\n }\n } catch (e) {\n // no-op, use default empty object\n }\n}\nfunction persistAppliedTransitions(_window, transitions) {\n if (transitions.size > 0) {\n let json = {};\n for (let [k, v] of transitions) {\n json[k] = [...v];\n }\n try {\n _window.sessionStorage.setItem(TRANSITIONS_STORAGE_KEY, JSON.stringify(json));\n } catch (error) {\n warning(false, \"Failed to save applied view transitions in sessionStorage (\" + error + \").\");\n }\n }\n}\n//#endregion\n\nexport { AbortedDeferredError, Action, IDLE_BLOCKER, IDLE_FETCHER, IDLE_NAVIGATION, UNSAFE_DEFERRED_SYMBOL, DeferredData as UNSAFE_DeferredData, ErrorResponseImpl as UNSAFE_ErrorResponseImpl, convertRouteMatchToUiMatch as UNSAFE_convertRouteMatchToUiMatch, convertRoutesToDataRoutes as UNSAFE_convertRoutesToDataRoutes, decodePath as UNSAFE_decodePath, getResolveToMatches as UNSAFE_getResolveToMatches, invariant as UNSAFE_invariant, warning as UNSAFE_warning, createBrowserHistory, createHashHistory, createMemoryHistory, createPath, createRouter, createStaticHandler, data, defer, generatePath, getStaticContextFromError, getToPathname, isDataWithResponseInit, isDeferredData, isRouteErrorResponse, joinPaths, json, matchPath, matchRoutes, normalizePathname, parsePath, redirect, redirectDocument, replace, resolvePath, resolveTo, stripBasename };\n//# sourceMappingURL=router.js.map\n","/**\n * React Router v6.30.6\n *\n * Copyright (c) Remix Software Inc.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE.md file in the root directory of this source tree.\n *\n * @license MIT\n */\nimport * as React from 'react';\nimport { UNSAFE_invariant, joinPaths, matchPath, UNSAFE_decodePath, UNSAFE_getResolveToMatches, UNSAFE_warning, resolveTo, parsePath, matchRoutes, Action, UNSAFE_convertRouteMatchToUiMatch, stripBasename, IDLE_BLOCKER, isRouteErrorResponse, createMemoryHistory, AbortedDeferredError, createRouter } from '@remix-run/router';\nexport { AbortedDeferredError, Action as NavigationType, createPath, defer, generatePath, isRouteErrorResponse, json, matchPath, matchRoutes, parsePath, redirect, redirectDocument, replace, resolvePath } from '@remix-run/router';\n\nfunction _extends() {\n return _extends = Object.assign ? Object.assign.bind() : function (n) {\n for (var e = 1; e < arguments.length; e++) {\n var t = arguments[e];\n for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]);\n }\n return n;\n }, _extends.apply(null, arguments);\n}\n\n// Create react-specific types from the agnostic types in @remix-run/router to\n// export from react-router\n\nconst DataRouterContext = /*#__PURE__*/React.createContext(null);\nif (process.env.NODE_ENV !== \"production\") {\n DataRouterContext.displayName = \"DataRouter\";\n}\nconst DataRouterStateContext = /*#__PURE__*/React.createContext(null);\nif (process.env.NODE_ENV !== \"production\") {\n DataRouterStateContext.displayName = \"DataRouterState\";\n}\nconst AwaitContext = /*#__PURE__*/React.createContext(null);\nif (process.env.NODE_ENV !== \"production\") {\n AwaitContext.displayName = \"Await\";\n}\n\n/**\n * A Navigator is a \"location changer\"; it's how you get to different locations.\n *\n * Every history instance conforms to the Navigator interface, but the\n * distinction is useful primarily when it comes to the low-level `<Router>` API\n * where both the location and a navigator must be provided separately in order\n * to avoid \"tearing\" that may occur in a suspense-enabled app if the action\n * and/or location were to be read directly from the history instance.\n */\n\nconst NavigationContext = /*#__PURE__*/React.createContext(null);\nif (process.env.NODE_ENV !== \"production\") {\n NavigationContext.displayName = \"Navigation\";\n}\nconst LocationContext = /*#__PURE__*/React.createContext(null);\nif (process.env.NODE_ENV !== \"production\") {\n LocationContext.displayName = \"Location\";\n}\nconst RouteContext = /*#__PURE__*/React.createContext({\n outlet: null,\n matches: [],\n isDataRoute: false\n});\nif (process.env.NODE_ENV !== \"production\") {\n RouteContext.displayName = \"Route\";\n}\nconst RouteErrorContext = /*#__PURE__*/React.createContext(null);\nif (process.env.NODE_ENV !== \"production\") {\n RouteErrorContext.displayName = \"RouteError\";\n}\n\n/**\n * Returns the full href for the given \"to\" value. This is useful for building\n * custom links that are also accessible and preserve right-click behavior.\n *\n * @see https://reactrouter.com/v6/hooks/use-href\n */\nfunction useHref(to, _temp) {\n let {\n relative\n } = _temp === void 0 ? {} : _temp;\n !useInRouterContext() ? process.env.NODE_ENV !== \"production\" ? UNSAFE_invariant(false, // TODO: This error is probably because they somehow have 2 versions of the\n // router loaded. We can help them understand how to avoid that.\n \"useHref() may be used only in the context of a <Router> component.\") : UNSAFE_invariant(false) : void 0;\n let {\n basename,\n navigator\n } = React.useContext(NavigationContext);\n let {\n hash,\n pathname,\n search\n } = useResolvedPath(to, {\n relative\n });\n let joinedPathname = pathname;\n\n // If we're operating within a basename, prepend it to the pathname prior\n // to creating the href. If this is a root navigation, then just use the raw\n // basename which allows the basename to have full control over the presence\n // of a trailing slash on root links\n if (basename !== \"/\") {\n joinedPathname = pathname === \"/\" ? basename : joinPaths([basename, pathname]);\n }\n return navigator.createHref({\n pathname: joinedPathname,\n search,\n hash\n });\n}\n\n/**\n * Returns true if this component is a descendant of a `<Router>`.\n *\n * @see https://reactrouter.com/v6/hooks/use-in-router-context\n */\nfunction useInRouterContext() {\n return React.useContext(LocationContext) != null;\n}\n\n/**\n * Returns the current location object, which represents the current URL in web\n * browsers.\n *\n * Note: If you're using this it may mean you're doing some of your own\n * \"routing\" in your app, and we'd like to know what your use case is. We may\n * be able to provide something higher-level to better suit your needs.\n *\n * @see https://reactrouter.com/v6/hooks/use-location\n */\nfunction useLocation() {\n !useInRouterContext() ? process.env.NODE_ENV !== \"production\" ? UNSAFE_invariant(false, // TODO: This error is probably because they somehow have 2 versions of the\n // router loaded. We can help them understand how to avoid that.\n \"useLocation() may be used only in the context of a <Router> component.\") : UNSAFE_invariant(false) : void 0;\n return React.useContext(LocationContext).location;\n}\n\n/**\n * Returns the current navigation action which describes how the router came to\n * the current location, either by a pop, push, or replace on the history stack.\n *\n * @see https://reactrouter.com/v6/hooks/use-navigation-type\n */\nfunction useNavigationType() {\n return React.useContext(LocationContext).navigationType;\n}\n\n/**\n * Returns a PathMatch object if the given pattern matches the current URL.\n * This is useful for components that need to know \"active\" state, e.g.\n * `<NavLink>`.\n *\n * @see https://reactrouter.com/v6/hooks/use-match\n */\nfunction useMatch(pattern) {\n !useInRouterContext() ? process.env.NODE_ENV !== \"production\" ? UNSAFE_invariant(false, // TODO: This error is probably because they somehow have 2 versions of the\n // router loaded. We can help them understand how to avoid that.\n \"useMatch() may be used only in the context of a <Router> component.\") : UNSAFE_invariant(false) : void 0;\n let {\n pathname\n } = useLocation();\n return React.useMemo(() => matchPath(pattern, UNSAFE_decodePath(pathname)), [pathname, pattern]);\n}\n\n/**\n * The interface for the navigate() function returned from useNavigate().\n */\n\nconst navigateEffectWarning = \"You should call navigate() in a React.useEffect(), not when \" + \"your component is first rendered.\";\n\n// Mute warnings for calls to useNavigate in SSR environments\nfunction useIsomorphicLayoutEffect(cb) {\n let isStatic = React.useContext(NavigationContext).static;\n if (!isStatic) {\n // We should be able to get rid of this once react 18.3 is released\n // See: https://github.com/facebook/react/pull/26395\n // eslint-disable-next-line react-hooks/rules-of-hooks\n React.useLayoutEffect(cb);\n }\n}\n\n/**\n * Returns an imperative method for changing the location. Used by `<Link>`s, but\n * may also be used by other elements to change the location.\n *\n * @see https://reactrouter.com/v6/hooks/use-navigate\n */\nfunction useNavigate() {\n let {\n isDataRoute\n } = React.useContext(RouteContext);\n // Conditional usage is OK here because the usage of a data router is static\n // eslint-disable-next-line react-hooks/rules-of-hooks\n return isDataRoute ? useNavigateStable() : useNavigateUnstable();\n}\nfunction useNavigateUnstable() {\n !useInRouterContext() ? process.env.NODE_ENV !== \"production\" ? UNSAFE_invariant(false, // TODO: This error is probably because they somehow have 2 versions of the\n // router loaded. We can help them understand how to avoid that.\n \"useNavigate() may be used only in the context of a <Router> component.\") : UNSAFE_invariant(false) : void 0;\n let dataRouterContext = React.useContext(DataRouterContext);\n let {\n basename,\n future,\n navigator\n } = React.useContext(NavigationContext);\n let {\n matches\n } = React.useContext(RouteContext);\n let {\n pathname: locationPathname\n } = useLocation();\n let routePathnamesJson = JSON.stringify(UNSAFE_getResolveToMatches(matches, future.v7_relativeSplatPath));\n let activeRef = React.useRef(false);\n useIsomorphicLayoutEffect(() => {\n activeRef.current = true;\n });\n let navigate = React.useCallback(function (to, options) {\n if (options === void 0) {\n options = {};\n }\n process.env.NODE_ENV !== \"production\" ? UNSAFE_warning(activeRef.current, navigateEffectWarning) : void 0;\n\n // Short circuit here since if this happens on first render the navigate\n // is useless because we haven't wired up our history listener yet\n if (!activeRef.current) return;\n if (typeof to === \"number\") {\n navigator.go(to);\n return;\n }\n let path = resolveTo(to, JSON.parse(routePathnamesJson), locationPathname, options.relative === \"path\");\n\n // If we're operating within a basename, prepend it to the pathname prior\n // to handing off to history (but only if we're not in a data router,\n // otherwise it'll prepend the basename inside of the router).\n // If this is a root navigation, then we navigate to the raw basename\n // which allows the basename to have full control over the presence of a\n // trailing slash on root links\n if (dataRouterContext == null && basename !== \"/\") {\n path.pathname = path.pathname === \"/\" ? basename : joinPaths([basename, path.pathname]);\n }\n (!!options.replace ? navigator.replace : navigator.push)(path, options.state, options);\n }, [basename, navigator, routePathnamesJson, locationPathname, dataRouterContext]);\n return navigate;\n}\nconst OutletContext = /*#__PURE__*/React.createContext(null);\n\n/**\n * Returns the context (if provided) for the child route at this level of the route\n * hierarchy.\n * @see https://reactrouter.com/v6/hooks/use-outlet-context\n */\nfunction useOutletContext() {\n return React.useContext(OutletContext);\n}\n\n/**\n * Returns the element for the child route at this level of the route\n * hierarchy. Used internally by `<Outlet>` to render child routes.\n *\n * @see https://reactrouter.com/v6/hooks/use-outlet\n */\nfunction useOutlet(context) {\n let outlet = React.useContext(RouteContext).outlet;\n if (outlet) {\n return /*#__PURE__*/React.createElement(OutletContext.Provider, {\n value: context\n }, outlet);\n }\n return outlet;\n}\n\n/**\n * Returns an object of key/value pairs of the dynamic params from the current\n * URL that were matched by the route path.\n *\n * @see https://reactrouter.com/v6/hooks/use-params\n */\nfunction useParams() {\n let {\n matches\n } = React.useContext(RouteContext);\n let routeMatch = matches[matches.length - 1];\n return routeMatch ? routeMatch.params : {};\n}\n\n/**\n * Resolves the pathname of the given `to` value against the current location.\n *\n * @see https://reactrouter.com/v6/hooks/use-resolved-path\n */\nfunction useResolvedPath(to, _temp2) {\n let {\n relative\n } = _temp2 === void 0 ? {} : _temp2;\n let {\n future\n } = React.useContext(NavigationContext);\n let {\n matches\n } = React.useContext(RouteContext);\n let {\n pathname: locationPathname\n } = useLocation();\n let routePathnamesJson = JSON.stringify(UNSAFE_getResolveToMatches(matches, future.v7_relativeSplatPath));\n return React.useMemo(() => resolveTo(to, JSON.parse(routePathnamesJson), locationPathname, relative === \"path\"), [to, routePathnamesJson, locationPathname, relative]);\n}\n\n/**\n * Returns the element of the route that matched the current location, prepared\n * with the correct context to render the remainder of the route tree. Route\n * elements in the tree must render an `<Outlet>` to render their child route's\n * element.\n *\n * @see https://reactrouter.com/v6/hooks/use-routes\n */\nfunction useRoutes(routes, locationArg) {\n return useRoutesImpl(routes, locationArg);\n}\n\n// Internal implementation with accept optional param for RouterProvider usage\nfunction useRoutesImpl(routes, locationArg, dataRouterState, future) {\n !useInRouterContext() ? process.env.NODE_ENV !== \"production\" ? UNSAFE_invariant(false, // TODO: This error is probably because they somehow have 2 versions of the\n // router loaded. We can help them understand how to avoid that.\n \"useRoutes() may be used only in the context of a <Router> component.\") : UNSAFE_invariant(false) : void 0;\n let {\n navigator\n } = React.useContext(NavigationContext);\n let {\n matches: parentMatches\n } = React.useContext(RouteContext);\n let routeMatch = parentMatches[parentMatches.length - 1];\n let parentParams = routeMatch ? routeMatch.params : {};\n let parentPathname = routeMatch ? routeMatch.pathname : \"/\";\n let parentPathnameBase = routeMatch ? routeMatch.pathnameBase : \"/\";\n let parentRoute = routeMatch && routeMatch.route;\n if (process.env.NODE_ENV !== \"production\") {\n // You won't get a warning about 2 different <Routes> under a <Route>\n // without a trailing *, but this is a best-effort warning anyway since we\n // cannot even give the warning unless they land at the parent route.\n //\n // Example:\n //\n // <Routes>\n // {/* This route path MUST end with /* because otherwise\n // it will never match /blog/post/123 */}\n // <Route path=\"blog\" element={<Blog />} />\n // <Route path=\"blog/feed\" element={<BlogFeed />} />\n // </Routes>\n //\n // function Blog() {\n // return (\n // <Routes>\n // <Route path=\"post/:id\" element={<Post />} />\n // </Routes>\n // );\n // }\n let parentPath = parentRoute && parentRoute.path || \"\";\n warningOnce(parentPathname, !parentRoute || parentPath.endsWith(\"*\"), \"You rendered descendant <Routes> (or called `useRoutes()`) at \" + (\"\\\"\" + parentPathname + \"\\\" (under <Route path=\\\"\" + parentPath + \"\\\">) but the \") + \"parent route path has no trailing \\\"*\\\". This means if you navigate \" + \"deeper, the parent won't match anymore and therefore the child \" + \"routes will never render.\\n\\n\" + (\"Please change the parent <Route path=\\\"\" + parentPath + \"\\\"> to <Route \") + (\"path=\\\"\" + (parentPath === \"/\" ? \"*\" : parentPath + \"/*\") + \"\\\">.\"));\n }\n let locationFromContext = useLocation();\n let location;\n if (locationArg) {\n var _parsedLocationArg$pa;\n let parsedLocationArg = typeof locationArg === \"string\" ? parsePath(locationArg) : locationArg;\n !(parentPathnameBase === \"/\" || ((_parsedLocationArg$pa = parsedLocationArg.pathname) == null ? void 0 : _parsedLocationArg$pa.startsWith(parentPathnameBase))) ? process.env.NODE_ENV !== \"production\" ? UNSAFE_invariant(false, \"When overriding the location using `<Routes location>` or `useRoutes(routes, location)`, \" + \"the location pathname must begin with the portion of the URL pathname that was \" + (\"matched by all parent routes. The current pathname base is \\\"\" + parentPathnameBase + \"\\\" \") + (\"but pathname \\\"\" + parsedLocationArg.pathname + \"\\\" was given in the `location` prop.\")) : UNSAFE_invariant(false) : void 0;\n location = parsedLocationArg;\n } else {\n location = locationFromContext;\n }\n let pathname = location.pathname || \"/\";\n let remainingPathname = pathname;\n if (parentPathnameBase !== \"/\") {\n // Determine the remaining pathname by removing the # of URL segments the\n // parentPathnameBase has, instead of removing based on character count.\n // This is because we can't guarantee that incoming/outgoing encodings/\n // decodings will match exactly.\n // We decode paths before matching on a per-segment basis with\n // decodeURIComponent(), but we re-encode pathnames via `new URL()` so they\n // match what `window.location.pathname` would reflect. Those don't 100%\n // align when it comes to encoded URI characters such as % and &.\n //\n // So we may end up with:\n // pathname: \"/descendant/a%25b/match\"\n // parentPathnameBase: \"/descendant/a%b\"\n //\n // And the direct substring removal approach won't work :/\n let parentSegments = parentPathnameBase.replace(/^\\//, \"\").split(\"/\");\n let segments = pathname.replace(/^\\//, \"\").split(\"/\");\n remainingPathname = \"/\" + segments.slice(parentSegments.length).join(\"/\");\n }\n let matches = matchRoutes(routes, {\n pathname: remainingPathname\n });\n if (process.env.NODE_ENV !== \"production\") {\n process.env.NODE_ENV !== \"production\" ? UNSAFE_warning(parentRoute || matches != null, \"No routes matched location \\\"\" + location.pathname + location.search + location.hash + \"\\\" \") : void 0;\n process.env.NODE_ENV !== \"production\" ? UNSAFE_warning(matches == null || matches[matches.length - 1].route.element !== undefined || matches[matches.length - 1].route.Component !== undefined || matches[matches.length - 1].route.lazy !== undefined, \"Matched leaf route at location \\\"\" + location.pathname + location.search + location.hash + \"\\\" \" + \"does not have an element or Component. This means it will render an <Outlet /> with a \" + \"null value by default resulting in an \\\"empty\\\" page.\") : void 0;\n }\n let renderedMatches = _renderMatches(matches && matches.map(match => Object.assign({}, match, {\n params: Object.assign({}, parentParams, match.params),\n pathname: joinPaths([parentPathnameBase,\n // Re-encode pathnames that were decoded inside matchRoutes\n navigator.encodeLocation ? navigator.encodeLocation(match.pathname).pathname : match.pathname]),\n pathnameBase: match.pathnameBase === \"/\" ? parentPathnameBase : joinPaths([parentPathnameBase,\n // Re-encode pathnames that were decoded inside matchRoutes\n navigator.encodeLocation ? navigator.encodeLocation(match.pathnameBase).pathname : match.pathnameBase])\n })), parentMatches, dataRouterState, future);\n\n // When a user passes in a `locationArg`, the associated routes need to\n // be wrapped in a new `LocationContext.Provider` in order for `useLocation`\n // to use the scoped location instead of the global location.\n if (locationArg && renderedMatches) {\n return /*#__PURE__*/React.createElement(LocationContext.Provider, {\n value: {\n location: _extends({\n pathname: \"/\",\n search: \"\",\n hash: \"\",\n state: null,\n key: \"default\"\n }, location),\n navigationType: Action.Pop\n }\n }, renderedMatches);\n }\n return renderedMatches;\n}\nfunction DefaultErrorComponent() {\n let error = useRouteError();\n let message = isRouteErrorResponse(error) ? error.status + \" \" + error.statusText : error instanceof Error ? error.message : JSON.stringify(error);\n let stack = error instanceof Error ? error.stack : null;\n let lightgrey = \"rgba(200,200,200, 0.5)\";\n let preStyles = {\n padding: \"0.5rem\",\n backgroundColor: lightgrey\n };\n let codeStyles = {\n padding: \"2px 4px\",\n backgroundColor: lightgrey\n };\n let devInfo = null;\n if (process.env.NODE_ENV !== \"production\") {\n console.error(\"Error handled by React Router default ErrorBoundary:\", error);\n devInfo = /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(\"p\", null, \"\\uD83D\\uDCBF Hey developer \\uD83D\\uDC4B\"), /*#__PURE__*/React.createElement(\"p\", null, \"You can provide a way better UX than this when your app throws errors by providing your own \", /*#__PURE__*/React.createElement(\"code\", {\n style: codeStyles\n }, \"ErrorBoundary\"), \" or\", \" \", /*#__PURE__*/React.createElement(\"code\", {\n style: codeStyles\n }, \"errorElement\"), \" prop on your route.\"));\n }\n return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(\"h2\", null, \"Unexpected Application Error!\"), /*#__PURE__*/React.createElement(\"h3\", {\n style: {\n fontStyle: \"italic\"\n }\n }, message), stack ? /*#__PURE__*/React.createElement(\"pre\", {\n style: preStyles\n }, stack) : null, devInfo);\n}\nconst defaultErrorElement = /*#__PURE__*/React.createElement(DefaultErrorComponent, null);\nclass RenderErrorBoundary extends React.Component {\n constructor(props) {\n super(props);\n this.state = {\n location: props.location,\n revalidation: props.revalidation,\n error: props.error\n };\n }\n static getDerivedStateFromError(error) {\n return {\n error: error\n };\n }\n static getDerivedStateFromProps(props, state) {\n // When we get into an error state, the user will likely click \"back\" to the\n // previous page that didn't have an error. Because this wraps the entire\n // application, that will have no effect--the error page continues to display.\n // This gives us a mechanism to recover from the error when the location changes.\n //\n // Whether we're in an error state or not, we update the location in state\n // so that when we are in an error state, it gets reset when a new location\n // comes in and the user recovers from the error.\n if (state.location !== props.location || state.revalidation !== \"idle\" && props.revalidation === \"idle\") {\n return {\n error: props.error,\n location: props.location,\n revalidation: props.revalidation\n };\n }\n\n // If we're not changing locations, preserve the location but still surface\n // any new errors that may come through. We retain the existing error, we do\n // this because the error provided from the app state may be cleared without\n // the location changing.\n return {\n error: props.error !== undefined ? props.error : state.error,\n location: state.location,\n revalidation: props.revalidation || state.revalidation\n };\n }\n componentDidCatch(error, errorInfo) {\n console.error(\"React Router caught the following error during render\", error, errorInfo);\n }\n render() {\n return this.state.error !== undefined ? /*#__PURE__*/React.createElement(RouteContext.Provider, {\n value: this.props.routeContext\n }, /*#__PURE__*/React.createElement(RouteErrorContext.Provider, {\n value: this.state.error,\n children: this.props.component\n })) : this.props.children;\n }\n}\nfunction RenderedRoute(_ref) {\n let {\n routeContext,\n match,\n children\n } = _ref;\n let dataRouterContext = React.useContext(DataRouterContext);\n\n // Track how deep we got in our render pass to emulate SSR componentDidCatch\n // in a DataStaticRouter\n if (dataRouterContext && dataRouterContext.static && dataRouterContext.staticContext && (match.route.errorElement || match.route.ErrorBoundary)) {\n dataRouterContext.staticContext._deepestRenderedBoundaryId = match.route.id;\n }\n return /*#__PURE__*/React.createElement(RouteContext.Provider, {\n value: routeContext\n }, children);\n}\nfunction _renderMatches(matches, parentMatches, dataRouterState, future) {\n var _dataRouterState;\n if (parentMatches === void 0) {\n parentMatches = [];\n }\n if (dataRouterState === void 0) {\n dataRouterState = null;\n }\n if (future === void 0) {\n future = null;\n }\n if (matches == null) {\n var _future;\n if (!dataRouterState) {\n return null;\n }\n if (dataRouterState.errors) {\n // Don't bail if we have data router errors so we can render them in the\n // boundary. Use the pre-matched (or shimmed) matches\n matches = dataRouterState.matches;\n } else if ((_future = future) != null && _future.v7_partialHydration && parentMatches.length === 0 && !dataRouterState.initialized && dataRouterState.matches.length > 0) {\n // Don't bail if we're initializing with partial hydration and we have\n // router matches. That means we're actively running `patchRoutesOnNavigation`\n // so we should render down the partial matches to the appropriate\n // `HydrateFallback`. We only do this if `parentMatches` is empty so it\n // only impacts the root matches for `RouterProvider` and no descendant\n // `<Routes>`\n matches = dataRouterState.matches;\n } else {\n return null;\n }\n }\n let renderedMatches = matches;\n\n // If we have data errors, trim matches to the highest error boundary\n let errors = (_dataRouterState = dataRouterState) == null ? void 0 : _dataRouterState.errors;\n if (errors != null) {\n let errorIndex = renderedMatches.findIndex(m => m.route.id && (errors == null ? void 0 : errors[m.route.id]) !== undefined);\n !(errorIndex >= 0) ? process.env.NODE_ENV !== \"production\" ? UNSAFE_invariant(false, \"Could not find a matching route for errors on route IDs: \" + Object.keys(errors).join(\",\")) : UNSAFE_invariant(false) : void 0;\n renderedMatches = renderedMatches.slice(0, Math.min(renderedMatches.length, errorIndex + 1));\n }\n\n // If we're in a partial hydration mode, detect if we need to render down to\n // a given HydrateFallback while we load the rest of the hydration data\n let renderFallback = false;\n let fallbackIndex = -1;\n if (dataRouterState && future && future.v7_partialHydration) {\n for (let i = 0; i < renderedMatches.length; i++) {\n let match = renderedMatches[i];\n // Track the deepest fallback up until the first route without data\n if (match.route.HydrateFallback || match.route.hydrateFallbackElement) {\n fallbackIndex = i;\n }\n if (match.route.id) {\n let {\n loaderData,\n errors\n } = dataRouterState;\n let needsToRunLoader = match.route.loader && loaderData[match.route.id] === undefined && (!errors || errors[match.route.id] === undefined);\n if (match.route.lazy || needsToRunLoader) {\n // We found the first route that's not ready to render (waiting on\n // lazy, or has a loader that hasn't run yet). Flag that we need to\n // render a fallback and render up until the appropriate fallback\n renderFallback = true;\n if (fallbackIndex >= 0) {\n renderedMatches = renderedMatches.slice(0, fallbackIndex + 1);\n } else {\n renderedMatches = [renderedMatches[0]];\n }\n break;\n }\n }\n }\n }\n return renderedMatches.reduceRight((outlet, match, index) => {\n // Only data routers handle errors/fallbacks\n let error;\n let shouldRenderHydrateFallback = false;\n let errorElement = null;\n let hydrateFallbackElement = null;\n if (dataRouterState) {\n error = errors && match.route.id ? errors[match.route.id] : undefined;\n errorElement = match.route.errorElement || defaultErrorElement;\n if (renderFallback) {\n if (fallbackIndex < 0 && index === 0) {\n warningOnce(\"route-fallback\", false, \"No `HydrateFallback` element provided to render during initial hydration\");\n shouldRenderHydrateFallback = true;\n hydrateFallbackElement = null;\n } else if (fallbackIndex === index) {\n shouldRenderHydrateFallback = true;\n hydrateFallbackElement = match.route.hydrateFallbackElement || null;\n }\n }\n }\n let matches = parentMatches.concat(renderedMatches.slice(0, index + 1));\n let getChildren = () => {\n let children;\n if (error) {\n children = errorElement;\n } else if (shouldRenderHydrateFallback) {\n children = hydrateFallbackElement;\n } else if (match.route.Component) {\n // Note: This is a de-optimized path since React won't re-use the\n // ReactElement since it's identity changes with each new\n // React.createElement call. We keep this so folks can use\n // `<Route Component={...}>` in `<Routes>` but generally `Component`\n // usage is only advised in `RouterProvider` when we can convert it to\n // `element` ahead of time.\n children = /*#__PURE__*/React.createElement(match.route.Component, null);\n } else if (match.route.element) {\n children = match.route.element;\n } else {\n children = outlet;\n }\n return /*#__PURE__*/React.createElement(RenderedRoute, {\n match: match,\n routeContext: {\n outlet,\n matches,\n isDataRoute: dataRouterState != null\n },\n children: children\n });\n };\n // Only wrap in an error boundary within data router usages when we have an\n // ErrorBoundary/errorElement on this route. Otherwise let it bubble up to\n // an ancestor ErrorBoundary/errorElement\n return dataRouterState && (match.route.ErrorBoundary || match.route.errorElement || index === 0) ? /*#__PURE__*/React.createElement(RenderErrorBoundary, {\n location: dataRouterState.location,\n revalidation: dataRouterState.revalidation,\n component: errorElement,\n error: error,\n children: getChildren(),\n routeContext: {\n outlet: null,\n matches,\n isDataRoute: true\n }\n }) : getChildren();\n }, null);\n}\nvar DataRouterHook = /*#__PURE__*/function (DataRouterHook) {\n DataRouterHook[\"UseBlocker\"] = \"useBlocker\";\n DataRouterHook[\"UseRevalidator\"] = \"useRevalidator\";\n DataRouterHook[\"UseNavigateStable\"] = \"useNavigate\";\n return DataRouterHook;\n}(DataRouterHook || {});\nvar DataRouterStateHook = /*#__PURE__*/function (DataRouterStateHook) {\n DataRouterStateHook[\"UseBlocker\"] = \"useBlocker\";\n DataRouterStateHook[\"UseLoaderData\"] = \"useLoaderData\";\n DataRouterStateHook[\"UseActionData\"] = \"useActionData\";\n DataRouterStateHook[\"UseRouteError\"] = \"useRouteError\";\n DataRouterStateHook[\"UseNavigation\"] = \"useNavigation\";\n DataRouterStateHook[\"UseRouteLoaderData\"] = \"useRouteLoaderData\";\n DataRouterStateHook[\"UseMatches\"] = \"useMatches\";\n DataRouterStateHook[\"UseRevalidator\"] = \"useRevalidator\";\n DataRouterStateHook[\"UseNavigateStable\"] = \"useNavigate\";\n DataRouterStateHook[\"UseRouteId\"] = \"useRouteId\";\n return DataRouterStateHook;\n}(DataRouterStateHook || {});\nfunction getDataRouterConsoleError(hookName) {\n return hookName + \" must be used within a data router. See https://reactrouter.com/v6/routers/picking-a-router.\";\n}\nfunction useDataRouterContext(hookName) {\n let ctx = React.useContext(DataRouterContext);\n !ctx ? process.env.NODE_ENV !== \"production\" ? UNSAFE_invariant(false, getDataRouterConsoleError(hookName)) : UNSAFE_invariant(false) : void 0;\n return ctx;\n}\nfunction useDataRouterState(hookName) {\n let state = React.useContext(DataRouterStateContext);\n !state ? process.env.NODE_ENV !== \"production\" ? UNSAFE_invariant(false, getDataRouterConsoleError(hookName)) : UNSAFE_invariant(false) : void 0;\n return state;\n}\nfunction useRouteContext(hookName) {\n let route = React.useContext(RouteContext);\n !route ? process.env.NODE_ENV !== \"production\" ? UNSAFE_invariant(false, getDataRouterConsoleError(hookName)) : UNSAFE_invariant(false) : void 0;\n return route;\n}\n\n// Internal version with hookName-aware debugging\nfunction useCurrentRouteId(hookName) {\n let route = useRouteContext(hookName);\n let thisRoute = route.matches[route.matches.length - 1];\n !thisRoute.route.id ? process.env.NODE_ENV !== \"production\" ? UNSAFE_invariant(false, hookName + \" can only be used on routes that contain a unique \\\"id\\\"\") : UNSAFE_invariant(false) : void 0;\n return thisRoute.route.id;\n}\n\n/**\n * Returns the ID for the nearest contextual route\n */\nfunction useRouteId() {\n return useCurrentRouteId(DataRouterStateHook.UseRouteId);\n}\n\n/**\n * Returns the current navigation, defaulting to an \"idle\" navigation when\n * no navigation is in progress\n */\nfunction useNavigation() {\n let state = useDataRouterState(DataRouterStateHook.UseNavigation);\n return state.navigation;\n}\n\n/**\n * Returns a revalidate function for manually triggering revalidation, as well\n * as the current state of any manual revalidations\n */\nfunction useRevalidator() {\n let dataRouterContext = useDataRouterContext(DataRouterHook.UseRevalidator);\n let state = useDataRouterState(DataRouterStateHook.UseRevalidator);\n return React.useMemo(() => ({\n revalidate: dataRouterContext.router.revalidate,\n state: state.revalidation\n }), [dataRouterContext.router.revalidate, state.revalidation]);\n}\n\n/**\n * Returns the active route matches, useful for accessing loaderData for\n * parent/child routes or the route \"handle\" property\n */\nfunction useMatches() {\n let {\n matches,\n loaderData\n } = useDataRouterState(DataRouterStateHook.UseMatches);\n return React.useMemo(() => matches.map(m => UNSAFE_convertRouteMatchToUiMatch(m, loaderData)), [matches, loaderData]);\n}\n\n/**\n * Returns the loader data for the nearest ancestor Route loader\n */\nfunction useLoaderData() {\n let state = useDataRouterState(DataRouterStateHook.UseLoaderData);\n let routeId = useCurrentRouteId(DataRouterStateHook.UseLoaderData);\n if (state.errors && state.errors[routeId] != null) {\n console.error(\"You cannot `useLoaderData` in an errorElement (routeId: \" + routeId + \")\");\n return undefined;\n }\n return state.loaderData[routeId];\n}\n\n/**\n * Returns the loaderData for the given routeId\n */\nfunction useRouteLoaderData(routeId) {\n let state = useDataRouterState(DataRouterStateHook.UseRouteLoaderData);\n return state.loaderData[routeId];\n}\n\n/**\n * Returns the action data for the nearest ancestor Route action\n */\nfunction useActionData() {\n let state = useDataRouterState(DataRouterStateHook.UseActionData);\n let routeId = useCurrentRouteId(DataRouterStateHook.UseLoaderData);\n return state.actionData ? state.actionData[routeId] : undefined;\n}\n\n/**\n * Returns the nearest ancestor Route error, which could be a loader/action\n * error or a render error. This is intended to be called from your\n * ErrorBoundary/errorElement to display a proper error message.\n */\nfunction useRouteError() {\n var _state$errors;\n let error = React.useContext(RouteErrorContext);\n let state = useDataRouterState(DataRouterStateHook.UseRouteError);\n let routeId = useCurrentRouteId(DataRouterStateHook.UseRouteError);\n\n // If this was a render error, we put it in a RouteError context inside\n // of RenderErrorBoundary\n if (error !== undefined) {\n return error;\n }\n\n // Otherwise look for errors from our data router state\n return (_state$errors = state.errors) == null ? void 0 : _state$errors[routeId];\n}\n\n/**\n * Returns the happy-path data from the nearest ancestor `<Await />` value\n */\nfunction useAsyncValue() {\n let value = React.useContext(AwaitContext);\n return value == null ? void 0 : value._data;\n}\n\n/**\n * Returns the error from the nearest ancestor `<Await />` value\n */\nfunction useAsyncError() {\n let value = React.useContext(AwaitContext);\n return value == null ? void 0 : value._error;\n}\nlet blockerId = 0;\n\n/**\n * Allow the application to block navigations within the SPA and present the\n * user a confirmation dialog to confirm the navigation. Mostly used to avoid\n * using half-filled form data. This does not handle hard-reloads or\n * cross-origin navigations.\n */\nfunction useBlocker(shouldBlock) {\n let {\n router,\n basename\n } = useDataRouterContext(DataRouterHook.UseBlocker);\n let state = useDataRouterState(DataRouterStateHook.UseBlocker);\n let [blockerKey, setBlockerKey] = React.useState(\"\");\n let blockerFunction = React.useCallback(arg => {\n if (typeof shouldBlock !== \"function\") {\n return !!shouldBlock;\n }\n if (basename === \"/\") {\n return shouldBlock(arg);\n }\n\n // If they provided us a function and we've got an active basename, strip\n // it from the locations we expose to the user to match the behavior of\n // useLocation\n let {\n currentLocation,\n nextLocation,\n historyAction\n } = arg;\n return shouldBlock({\n currentLocation: _extends({}, currentLocation, {\n pathname: stripBasename(currentLocation.pathname, basename) || currentLocation.pathname\n }),\n nextLocation: _extends({}, nextLocation, {\n pathname: stripBasename(nextLocation.pathname, basename) || nextLocation.pathname\n }),\n historyAction\n });\n }, [basename, shouldBlock]);\n\n // This effect is in charge of blocker key assignment and deletion (which is\n // tightly coupled to the key)\n React.useEffect(() => {\n let key = String(++blockerId);\n setBlockerKey(key);\n return () => router.deleteBlocker(key);\n }, [router]);\n\n // This effect handles assigning the blockerFunction. This is to handle\n // unstable blocker function identities, and happens only after the prior\n // effect so we don't get an orphaned blockerFunction in the router with a\n // key of \"\". Until then we just have the IDLE_BLOCKER.\n React.useEffect(() => {\n if (blockerKey !== \"\") {\n router.getBlocker(blockerKey, blockerFunction);\n }\n }, [router, blockerKey, blockerFunction]);\n\n // Prefer the blocker from `state` not `router.state` since DataRouterContext\n // is memoized so this ensures we update on blocker state updates\n return blockerKey && state.blockers.has(blockerKey) ? state.blockers.get(blockerKey) : IDLE_BLOCKER;\n}\n\n/**\n * Stable version of useNavigate that is used when we are in the context of\n * a RouterProvider.\n */\nfunction useNavigateStable() {\n let {\n router\n } = useDataRouterContext(DataRouterHook.UseNavigateStable);\n let id = useCurrentRouteId(DataRouterStateHook.UseNavigateStable);\n let activeRef = React.useRef(false);\n useIsomorphicLayoutEffect(() => {\n activeRef.current = true;\n });\n let navigate = React.useCallback(function (to, options) {\n if (options === void 0) {\n options = {};\n }\n process.env.NODE_ENV !== \"production\" ? UNSAFE_warning(activeRef.current, navigateEffectWarning) : void 0;\n\n // Short circuit here since if this happens on first render the navigate\n // is useless because we haven't wired up our router subscriber yet\n if (!activeRef.current) return;\n if (typeof to === \"number\") {\n router.navigate(to);\n } else {\n router.navigate(to, _extends({\n fromRouteId: id\n }, options));\n }\n }, [router, id]);\n return navigate;\n}\nconst alreadyWarned$1 = {};\nfunction warningOnce(key, cond, message) {\n if (!cond && !alreadyWarned$1[key]) {\n alreadyWarned$1[key] = true;\n process.env.NODE_ENV !== \"production\" ? UNSAFE_warning(false, message) : void 0;\n }\n}\n\nconst alreadyWarned = {};\nfunction warnOnce(key, message) {\n if (process.env.NODE_ENV !== \"production\" && !alreadyWarned[message]) {\n alreadyWarned[message] = true;\n console.warn(message);\n }\n}\nconst logDeprecation = (flag, msg, link) => warnOnce(flag, \"\\u26A0\\uFE0F React Router Future Flag Warning: \" + msg + \". \" + (\"You can use the `\" + flag + \"` future flag to opt-in early. \") + (\"For more information, see \" + link + \".\"));\nfunction logV6DeprecationWarnings(renderFuture, routerFuture) {\n if ((renderFuture == null ? void 0 : renderFuture.v7_startTransition) === undefined) {\n logDeprecation(\"v7_startTransition\", \"React Router will begin wrapping state updates in `React.startTransition` in v7\", \"https://reactrouter.com/v6/upgrading/future#v7_starttransition\");\n }\n if ((renderFuture == null ? void 0 : renderFuture.v7_relativeSplatPath) === undefined && (!routerFuture || routerFuture.v7_relativeSplatPath === undefined)) {\n logDeprecation(\"v7_relativeSplatPath\", \"Relative route resolution within Splat routes is changing in v7\", \"https://reactrouter.com/v6/upgrading/future#v7_relativesplatpath\");\n }\n if (routerFuture) {\n if (routerFuture.v7_fetcherPersist === undefined) {\n logDeprecation(\"v7_fetcherPersist\", \"The persistence behavior of fetchers is changing in v7\", \"https://reactrouter.com/v6/upgrading/future#v7_fetcherpersist\");\n }\n if (routerFuture.v7_normalizeFormMethod === undefined) {\n logDeprecation(\"v7_normalizeFormMethod\", \"Casing of `formMethod` fields is being normalized to uppercase in v7\", \"https://reactrouter.com/v6/upgrading/future#v7_normalizeformmethod\");\n }\n if (routerFuture.v7_partialHydration === undefined) {\n logDeprecation(\"v7_partialHydration\", \"`RouterProvider` hydration behavior is changing in v7\", \"https://reactrouter.com/v6/upgrading/future#v7_partialhydration\");\n }\n if (routerFuture.v7_skipActionErrorRevalidation === undefined) {\n logDeprecation(\"v7_skipActionErrorRevalidation\", \"The revalidation behavior after 4xx/5xx `action` responses is changing in v7\", \"https://reactrouter.com/v6/upgrading/future#v7_skipactionerrorrevalidation\");\n }\n }\n}\n\n/**\n Webpack + React 17 fails to compile on any of the following because webpack\n complains that `startTransition` doesn't exist in `React`:\n * import { startTransition } from \"react\"\n * import * as React from from \"react\";\n \"startTransition\" in React ? React.startTransition(() => setState()) : setState()\n * import * as React from from \"react\";\n \"startTransition\" in React ? React[\"startTransition\"](() => setState()) : setState()\n\n Moving it to a constant such as the following solves the Webpack/React 17 issue:\n * import * as React from from \"react\";\n const START_TRANSITION = \"startTransition\";\n START_TRANSITION in React ? React[START_TRANSITION](() => setState()) : setState()\n\n However, that introduces webpack/terser minification issues in production builds\n in React 18 where minification/obfuscation ends up removing the call of\n React.startTransition entirely from the first half of the ternary. Grabbing\n this exported reference once up front resolves that issue.\n\n See https://github.com/remix-run/react-router/issues/10579\n*/\nconst START_TRANSITION = \"startTransition\";\nconst startTransitionImpl = React[START_TRANSITION];\n\n/**\n * Given a Remix Router instance, render the appropriate UI\n */\nfunction RouterProvider(_ref) {\n let {\n fallbackElement,\n router,\n future\n } = _ref;\n let [state, setStateImpl] = React.useState(router.state);\n let {\n v7_startTransition\n } = future || {};\n let setState = React.useCallback(newState => {\n if (v7_startTransition && startTransitionImpl) {\n startTransitionImpl(() => setStateImpl(newState));\n } else {\n setStateImpl(newState);\n }\n }, [setStateImpl, v7_startTransition]);\n\n // Need to use a layout effect here so we are subscribed early enough to\n // pick up on any render-driven redirects/navigations (useEffect/<Navigate>)\n React.useLayoutEffect(() => router.subscribe(setState), [router, setState]);\n React.useEffect(() => {\n process.env.NODE_ENV !== \"production\" ? UNSAFE_warning(fallbackElement == null || !router.future.v7_partialHydration, \"`<RouterProvider fallbackElement>` is deprecated when using \" + \"`v7_partialHydration`, use a `HydrateFallback` component instead\") : void 0;\n // Only log this once on initial mount\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n let navigator = React.useMemo(() => {\n return {\n createHref: router.createHref,\n encodeLocation: router.encodeLocation,\n go: n => router.navigate(n),\n push: (to, state, opts) => router.navigate(to, {\n state,\n preventScrollReset: opts == null ? void 0 : opts.preventScrollReset\n }),\n replace: (to, state, opts) => router.navigate(to, {\n replace: true,\n state,\n preventScrollReset: opts == null ? void 0 : opts.preventScrollReset\n })\n };\n }, [router]);\n let basename = router.basename || \"/\";\n let dataRouterContext = React.useMemo(() => ({\n router,\n navigator,\n static: false,\n basename\n }), [router, navigator, basename]);\n React.useEffect(() => logV6DeprecationWarnings(future, router.future), [router, future]);\n\n // The fragment and {null} here are important! We need them to keep React 18's\n // useId happy when we are server-rendering since we may have a <script> here\n // containing the hydrated server-side staticContext (from StaticRouterProvider).\n // useId relies on the component tree structure to generate deterministic id's\n // so we need to ensure it remains the same on the client even though\n // we don't need the <script> tag\n return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(DataRouterContext.Provider, {\n value: dataRouterContext\n }, /*#__PURE__*/React.createElement(DataRouterStateContext.Provider, {\n value: state\n }, /*#__PURE__*/React.createElement(Router, {\n basename: basename,\n location: state.location,\n navigationType: state.historyAction,\n navigator: navigator,\n future: {\n v7_relativeSplatPath: router.future.v7_relativeSplatPath\n }\n }, state.initialized || router.future.v7_partialHydration ? /*#__PURE__*/React.createElement(DataRoutes, {\n routes: router.routes,\n future: router.future,\n state: state\n }) : fallbackElement))), null);\n}\nfunction DataRoutes(_ref2) {\n let {\n routes,\n future,\n state\n } = _ref2;\n return useRoutesImpl(routes, undefined, state, future);\n}\n/**\n * A `<Router>` that stores all entries in memory.\n *\n * @see https://reactrouter.com/v6/router-components/memory-router\n */\nfunction MemoryRouter(_ref3) {\n let {\n basename,\n children,\n initialEntries,\n initialIndex,\n future\n } = _ref3;\n let historyRef = React.useRef();\n if (historyRef.current == null) {\n historyRef.current = createMemoryHistory({\n initialEntries,\n initialIndex,\n v5Compat: true\n });\n }\n let history = historyRef.current;\n let [state, setStateImpl] = React.useState({\n action: history.action,\n location: history.location\n });\n let {\n v7_startTransition\n } = future || {};\n let setState = React.useCallback(newState => {\n v7_startTransition && startTransitionImpl ? startTransitionImpl(() => setStateImpl(newState)) : setStateImpl(newState);\n }, [setStateImpl, v7_startTransition]);\n React.useLayoutEffect(() => history.listen(setState), [history, setState]);\n React.useEffect(() => logV6DeprecationWarnings(future), [future]);\n return /*#__PURE__*/React.createElement(Router, {\n basename: basename,\n children: children,\n location: state.location,\n navigationType: state.action,\n navigator: history,\n future: future\n });\n}\n/**\n * Changes the current location.\n *\n * Note: This API is mostly useful in React.Component subclasses that are not\n * able to use hooks. In functional components, we recommend you use the\n * `useNavigate` hook instead.\n *\n * @see https://reactrouter.com/v6/components/navigate\n */\nfunction Navigate(_ref4) {\n let {\n to,\n replace,\n state,\n relative\n } = _ref4;\n !useInRouterContext() ? process.env.NODE_ENV !== \"production\" ? UNSAFE_invariant(false, // TODO: This error is probably because they somehow have 2 versions of\n // the router loaded. We can help them understand how to avoid that.\n \"<Navigate> may be used only in the context of a <Router> component.\") : UNSAFE_invariant(false) : void 0;\n let {\n future,\n static: isStatic\n } = React.useContext(NavigationContext);\n process.env.NODE_ENV !== \"production\" ? UNSAFE_warning(!isStatic, \"<Navigate> must not be used on the initial render in a <StaticRouter>. \" + \"This is a no-op, but you should modify your code so the <Navigate> is \" + \"only ever rendered in response to some user interaction or state change.\") : void 0;\n let {\n matches\n } = React.useContext(RouteContext);\n let {\n pathname: locationPathname\n } = useLocation();\n let navigate = useNavigate();\n\n // Resolve the path outside of the effect so that when effects run twice in\n // StrictMode they navigate to the same place\n let path = resolveTo(to, UNSAFE_getResolveToMatches(matches, future.v7_relativeSplatPath), locationPathname, relative === \"path\");\n let jsonPath = JSON.stringify(path);\n React.useEffect(() => navigate(JSON.parse(jsonPath), {\n replace,\n state,\n relative\n }), [navigate, jsonPath, relative, replace, state]);\n return null;\n}\n/**\n * Renders the child route's element, if there is one.\n *\n * @see https://reactrouter.com/v6/components/outlet\n */\nfunction Outlet(props) {\n return useOutlet(props.context);\n}\n/**\n * Declares an element that should be rendered at a certain URL path.\n *\n * @see https://reactrouter.com/v6/components/route\n */\nfunction Route(_props) {\n process.env.NODE_ENV !== \"production\" ? UNSAFE_invariant(false, \"A <Route> is only ever to be used as the child of <Routes> element, \" + \"never rendered directly. Please wrap your <Route> in a <Routes>.\") : UNSAFE_invariant(false) ;\n}\n/**\n * Provides location context for the rest of the app.\n *\n * Note: You usually won't render a `<Router>` directly. Instead, you'll render a\n * router that is more specific to your environment such as a `<BrowserRouter>`\n * in web browsers or a `<StaticRouter>` for server rendering.\n *\n * @see https://reactrouter.com/v6/router-components/router\n */\nfunction Router(_ref5) {\n let {\n basename: basenameProp = \"/\",\n children = null,\n location: locationProp,\n navigationType = Action.Pop,\n navigator,\n static: staticProp = false,\n future\n } = _ref5;\n !!useInRouterContext() ? process.env.NODE_ENV !== \"production\" ? UNSAFE_invariant(false, \"You cannot render a <Router> inside another <Router>.\" + \" You should never have more than one in your app.\") : UNSAFE_invariant(false) : void 0;\n\n // Preserve trailing slashes on basename, so we can let the user control\n // the enforcement of trailing slashes throughout the app\n let basename = basenameProp.replace(/^\\/*/, \"/\");\n let navigationContext = React.useMemo(() => ({\n basename,\n navigator,\n static: staticProp,\n future: _extends({\n v7_relativeSplatPath: false\n }, future)\n }), [basename, future, navigator, staticProp]);\n if (typeof locationProp === \"string\") {\n locationProp = parsePath(locationProp);\n }\n let {\n pathname = \"/\",\n search = \"\",\n hash = \"\",\n state = null,\n key = \"default\"\n } = locationProp;\n let locationContext = React.useMemo(() => {\n let trailingPathname = stripBasename(pathname, basename);\n if (trailingPathname == null) {\n return null;\n }\n return {\n location: {\n pathname: trailingPathname,\n search,\n hash,\n state,\n key\n },\n navigationType\n };\n }, [basename, pathname, search, hash, state, key, navigationType]);\n process.env.NODE_ENV !== \"production\" ? UNSAFE_warning(locationContext != null, \"<Router basename=\\\"\" + basename + \"\\\"> is not able to match the URL \" + (\"\\\"\" + pathname + search + hash + \"\\\" because it does not start with the \") + \"basename, so the <Router> won't render anything.\") : void 0;\n if (locationContext == null) {\n return null;\n }\n return /*#__PURE__*/React.createElement(NavigationContext.Provider, {\n value: navigationContext\n }, /*#__PURE__*/React.createElement(LocationContext.Provider, {\n children: children,\n value: locationContext\n }));\n}\n/**\n * A container for a nested tree of `<Route>` elements that renders the branch\n * that best matches the current location.\n *\n * @see https://reactrouter.com/v6/components/routes\n */\nfunction Routes(_ref6) {\n let {\n children,\n location\n } = _ref6;\n return useRoutes(createRoutesFromChildren(children), location);\n}\n/**\n * Component to use for rendering lazily loaded data from returning defer()\n * in a loader function\n */\nfunction Await(_ref7) {\n let {\n children,\n errorElement,\n resolve\n } = _ref7;\n return /*#__PURE__*/React.createElement(AwaitErrorBoundary, {\n resolve: resolve,\n errorElement: errorElement\n }, /*#__PURE__*/React.createElement(ResolveAwait, null, children));\n}\nvar AwaitRenderStatus = /*#__PURE__*/function (AwaitRenderStatus) {\n AwaitRenderStatus[AwaitRenderStatus[\"pending\"] = 0] = \"pending\";\n AwaitRenderStatus[AwaitRenderStatus[\"success\"] = 1] = \"success\";\n AwaitRenderStatus[AwaitRenderStatus[\"error\"] = 2] = \"error\";\n return AwaitRenderStatus;\n}(AwaitRenderStatus || {});\nconst neverSettledPromise = new Promise(() => {});\nclass AwaitErrorBoundary extends React.Component {\n constructor(props) {\n super(props);\n this.state = {\n error: null\n };\n }\n static getDerivedStateFromError(error) {\n return {\n error\n };\n }\n componentDidCatch(error, errorInfo) {\n console.error(\"<Await> caught the following error during render\", error, errorInfo);\n }\n render() {\n let {\n children,\n errorElement,\n resolve\n } = this.props;\n let promise = null;\n let status = AwaitRenderStatus.pending;\n if (!(resolve instanceof Promise)) {\n // Didn't get a promise - provide as a resolved promise\n status = AwaitRenderStatus.success;\n promise = Promise.resolve();\n Object.defineProperty(promise, \"_tracked\", {\n get: () => true\n });\n Object.defineProperty(promise, \"_data\", {\n get: () => resolve\n });\n } else if (this.state.error) {\n // Caught a render error, provide it as a rejected promise\n status = AwaitRenderStatus.error;\n let renderError = this.state.error;\n promise = Promise.reject().catch(() => {}); // Avoid unhandled rejection warnings\n Object.defineProperty(promise, \"_tracked\", {\n get: () => true\n });\n Object.defineProperty(promise, \"_error\", {\n get: () => renderError\n });\n } else if (resolve._tracked) {\n // Already tracked promise - check contents\n promise = resolve;\n status = \"_error\" in promise ? AwaitRenderStatus.error : \"_data\" in promise ? AwaitRenderStatus.success : AwaitRenderStatus.pending;\n } else {\n // Raw (untracked) promise - track it\n status = AwaitRenderStatus.pending;\n Object.defineProperty(resolve, \"_tracked\", {\n get: () => true\n });\n promise = resolve.then(data => Object.defineProperty(resolve, \"_data\", {\n get: () => data\n }), error => Object.defineProperty(resolve, \"_error\", {\n get: () => error\n }));\n }\n if (status === AwaitRenderStatus.error && promise._error instanceof AbortedDeferredError) {\n // Freeze the UI by throwing a never resolved promise\n throw neverSettledPromise;\n }\n if (status === AwaitRenderStatus.error && !errorElement) {\n // No errorElement, throw to the nearest route-level error boundary\n throw promise._error;\n }\n if (status === AwaitRenderStatus.error) {\n // Render via our errorElement\n return /*#__PURE__*/React.createElement(AwaitContext.Provider, {\n value: promise,\n children: errorElement\n });\n }\n if (status === AwaitRenderStatus.success) {\n // Render children with resolved value\n return /*#__PURE__*/React.createElement(AwaitContext.Provider, {\n value: promise,\n children: children\n });\n }\n\n // Throw to the suspense boundary\n throw promise;\n }\n}\n\n/**\n * @private\n * Indirection to leverage useAsyncValue for a render-prop API on `<Await>`\n */\nfunction ResolveAwait(_ref8) {\n let {\n children\n } = _ref8;\n let data = useAsyncValue();\n let toRender = typeof children === \"function\" ? children(data) : children;\n return /*#__PURE__*/React.createElement(React.Fragment, null, toRender);\n}\n\n///////////////////////////////////////////////////////////////////////////////\n// UTILS\n///////////////////////////////////////////////////////////////////////////////\n\n/**\n * Creates a route config from a React \"children\" object, which is usually\n * either a `<Route>` element or an array of them. Used internally by\n * `<Routes>` to create a route config from its children.\n *\n * @see https://reactrouter.com/v6/utils/create-routes-from-children\n */\nfunction createRoutesFromChildren(children, parentPath) {\n if (parentPath === void 0) {\n parentPath = [];\n }\n let routes = [];\n React.Children.forEach(children, (element, index) => {\n if (! /*#__PURE__*/React.isValidElement(element)) {\n // Ignore non-elements. This allows people to more easily inline\n // conditionals in their route config.\n return;\n }\n let treePath = [...parentPath, index];\n if (element.type === React.Fragment) {\n // Transparently support React.Fragment and its children.\n routes.push.apply(routes, createRoutesFromChildren(element.props.children, treePath));\n return;\n }\n !(element.type === Route) ? process.env.NODE_ENV !== \"production\" ? UNSAFE_invariant(false, \"[\" + (typeof element.type === \"string\" ? element.type : element.type.name) + \"] is not a <Route> component. All component children of <Routes> must be a <Route> or <React.Fragment>\") : UNSAFE_invariant(false) : void 0;\n !(!element.props.index || !element.props.children) ? process.env.NODE_ENV !== \"production\" ? UNSAFE_invariant(false, \"An index route cannot have child routes.\") : UNSAFE_invariant(false) : void 0;\n let route = {\n id: element.props.id || treePath.join(\"-\"),\n caseSensitive: element.props.caseSensitive,\n element: element.props.element,\n Component: element.props.Component,\n index: element.props.index,\n path: element.props.path,\n loader: element.props.loader,\n action: element.props.action,\n errorElement: element.props.errorElement,\n ErrorBoundary: element.props.ErrorBoundary,\n hasErrorBoundary: element.props.ErrorBoundary != null || element.props.errorElement != null,\n shouldRevalidate: element.props.shouldRevalidate,\n handle: element.props.handle,\n lazy: element.props.lazy\n };\n if (element.props.children) {\n route.children = createRoutesFromChildren(element.props.children, treePath);\n }\n routes.push(route);\n });\n return routes;\n}\n\n/**\n * Renders the result of `matchRoutes()` into a React element.\n */\nfunction renderMatches(matches) {\n return _renderMatches(matches);\n}\n\nfunction mapRouteProperties(route) {\n let updates = {\n // Note: this check also occurs in createRoutesFromChildren so update\n // there if you change this -- please and thank you!\n hasErrorBoundary: route.ErrorBoundary != null || route.errorElement != null\n };\n if (route.Component) {\n if (process.env.NODE_ENV !== \"production\") {\n if (route.element) {\n process.env.NODE_ENV !== \"production\" ? UNSAFE_warning(false, \"You should not include both `Component` and `element` on your route - \" + \"`Component` will be used.\") : void 0;\n }\n }\n Object.assign(updates, {\n element: /*#__PURE__*/React.createElement(route.Component),\n Component: undefined\n });\n }\n if (route.HydrateFallback) {\n if (process.env.NODE_ENV !== \"production\") {\n if (route.hydrateFallbackElement) {\n process.env.NODE_ENV !== \"production\" ? UNSAFE_warning(false, \"You should not include both `HydrateFallback` and `hydrateFallbackElement` on your route - \" + \"`HydrateFallback` will be used.\") : void 0;\n }\n }\n Object.assign(updates, {\n hydrateFallbackElement: /*#__PURE__*/React.createElement(route.HydrateFallback),\n HydrateFallback: undefined\n });\n }\n if (route.ErrorBoundary) {\n if (process.env.NODE_ENV !== \"production\") {\n if (route.errorElement) {\n process.env.NODE_ENV !== \"production\" ? UNSAFE_warning(false, \"You should not include both `ErrorBoundary` and `errorElement` on your route - \" + \"`ErrorBoundary` will be used.\") : void 0;\n }\n }\n Object.assign(updates, {\n errorElement: /*#__PURE__*/React.createElement(route.ErrorBoundary),\n ErrorBoundary: undefined\n });\n }\n return updates;\n}\nfunction createMemoryRouter(routes, opts) {\n return createRouter({\n basename: opts == null ? void 0 : opts.basename,\n future: _extends({}, opts == null ? void 0 : opts.future, {\n v7_prependBasename: true\n }),\n history: createMemoryHistory({\n initialEntries: opts == null ? void 0 : opts.initialEntries,\n initialIndex: opts == null ? void 0 : opts.initialIndex\n }),\n hydrationData: opts == null ? void 0 : opts.hydrationData,\n routes,\n mapRouteProperties,\n dataStrategy: opts == null ? void 0 : opts.dataStrategy,\n patchRoutesOnNavigation: opts == null ? void 0 : opts.patchRoutesOnNavigation\n }).initialize();\n}\n\nexport { Await, MemoryRouter, Navigate, Outlet, Route, Router, RouterProvider, Routes, DataRouterContext as UNSAFE_DataRouterContext, DataRouterStateContext as UNSAFE_DataRouterStateContext, LocationContext as UNSAFE_LocationContext, NavigationContext as UNSAFE_NavigationContext, RouteContext as UNSAFE_RouteContext, logV6DeprecationWarnings as UNSAFE_logV6DeprecationWarnings, mapRouteProperties as UNSAFE_mapRouteProperties, useRouteId as UNSAFE_useRouteId, useRoutesImpl as UNSAFE_useRoutesImpl, createMemoryRouter, createRoutesFromChildren, createRoutesFromChildren as createRoutesFromElements, renderMatches, useActionData, useAsyncError, useAsyncValue, useBlocker, useHref, useInRouterContext, useLoaderData, useLocation, useMatch, useMatches, useNavigate, useNavigation, useNavigationType, useOutlet, useOutletContext, useParams, useResolvedPath, useRevalidator, useRouteError, useRouteLoaderData, useRoutes };\n//# sourceMappingURL=index.js.map\n","// src/features/surveys/cells/SurveyCells.tsx\r\nimport type { CellRegistration } from '../components/DataTable/types';\r\nimport type { RecordIdentifier, TableCellProps } from '../components/DataTable/types';\r\nimport { Icon } from '../components/ui/Icon';\r\nimport { memo } from 'react';\r\nimport type { SurveyAnalyticsRow, SurveyResponseItem, SurveyRow } from '../types/survey.types';\r\n\r\ntype CellProps = TableCellProps<RecordIdentifier>;\r\n\r\n/** Row actions the page can inject through DataTable's `extra`. */\r\ntype SurveyActions = {\r\n onView?: (row: SurveyRow) => void;\r\n onEdit?: (row: SurveyRow) => void;\r\n onDelete?: (row: SurveyRow) => void;\r\n};\r\n\r\nconst asSurvey = (row: RecordIdentifier) => row as unknown as SurveyRow;\r\nconst asAnalytics = (row: RecordIdentifier) => row as unknown as SurveyAnalyticsRow;\r\nconst asResponse = (row: RecordIdentifier) => row as unknown as SurveyResponseItem;\r\n\r\n// ─────────────────────────────────────────────────────────────────────────────\r\n// Status map & Helpers\r\n// ─────────────────────────────────────────────────────────────────────────────\r\n\r\nconst str = (v: unknown): string => (v != null ? String(v) : '');\r\n\r\nconst num = (v: unknown): number => {\r\n const n = Number(v);\r\n return Number.isFinite(n) ? n : 0;\r\n};\r\n\r\nconst STATUS: Record<string, { dot: string; badge: string }> = {\r\n active: {\r\n dot: 'bg-[#4edea3] animate-pulse',\r\n badge: 'bg-[color:color-mix(in_srgb,var(--th-success)_10%,transparent)] text-[color:var(--th-success)]',\r\n },\r\n draft: {\r\n dot: 'bg-[#ffcc6b]',\r\n badge: 'bg-[color:color-mix(in_srgb,var(--th-warning-soft)_10%,transparent)] text-[color:var(--th-warning-soft)]',\r\n },\r\n paused: {\r\n dot: 'bg-[#adc6ff]',\r\n badge: 'bg-[color:color-mix(in_srgb,var(--th-info-soft)_10%,transparent)] text-[color:var(--th-info-soft)]',\r\n },\r\n closed: {\r\n dot: 'bg-[#958da1]',\r\n badge: 'bg-[color:color-mix(in_srgb,var(--th-ov-base)_5%,transparent)] text-[color:var(--th-text-3)]',\r\n },\r\n};\r\n\r\n// ─────────────────────────────────────────────────────────────────────────────\r\n// 1. Survey Status Cell\r\n// ─────────────────────────────────────────────────────────────────────────────\r\n\r\nconst SurveyStatusCell = memo(({ row }: CellProps) => {\r\n const status = str(asSurvey(row).status);\r\n const c = STATUS[status] ?? STATUS.draft;\r\n\r\n return (\r\n <div className=\"flex items-center justify-center\">\r\n <span className={`w-2.5 h-2.5 rounded-full ${c.dot}`} />\r\n </div>\r\n );\r\n});\r\nSurveyStatusCell.displayName = 'SurveyStatusCell';\r\n\r\n// ─────────────────────────────────────────────────────────────────────────────\r\n// 2. Survey Name Cell\r\n// ─────────────────────────────────────────────────────────────────────────────\r\n\r\nconst SurveyNameCell = memo(({ row }: CellProps) => {\r\n const x = asSurvey(row);\r\n const status = str(x.status);\r\n const c = STATUS[status] ?? STATUS.draft;\r\n const name = str(x.name);\r\n const description = str(x.description);\r\n const npsScore = x.npsScore;\r\n\r\n return (\r\n <div className=\"flex flex-col gap-0.5 min-w-0\">\r\n <div className=\"flex items-center gap-1.5 flex-wrap\">\r\n <Icon\r\n icon=\"ClipboardList\"\r\n size={14}\r\n className=\"text-[#7c3aed] shrink-0\"\r\n />\r\n\r\n <span className=\"text-[13px] font-medium text-white truncate max-w-[280px]\">\r\n {name}\r\n </span>\r\n\r\n <span\r\n className={`text-[9px] px-1.5 py-0.5 rounded font-medium capitalize shrink-0 ${c.badge}`}\r\n >\r\n {status}\r\n </span>\r\n\r\n {npsScore !== null && npsScore !== undefined && (\r\n <span\r\n className={`text-[9px] px-1.5 py-0.5 rounded shrink-0 ${npsScore >= 70\r\n ? 'bg-[color:color-mix(in_srgb,var(--th-success)_10%,transparent)] text-[color:var(--th-success)]'\r\n : npsScore >= 50\r\n ? 'bg-[color:color-mix(in_srgb,var(--th-warning-soft)_10%,transparent)] text-[color:var(--th-warning-soft)]'\r\n : 'bg-[color:color-mix(in_srgb,var(--th-danger-soft)_10%,transparent)] text-[color:var(--th-danger-soft)]'\r\n }`}\r\n >\r\n NPS {npsScore}\r\n </span>\r\n )}\r\n </div>\r\n\r\n {description && (\r\n <span className=\"text-[11px] text-[color:var(--th-text-3)] truncate max-w-[320px] pl-5\">\r\n {description}\r\n </span>\r\n )}\r\n </div>\r\n );\r\n});\r\nSurveyNameCell.displayName = 'SurveyNameCell';\r\n\r\n// ─────────────────────────────────────────────────────────────────────────────\r\n// 3. Response Progress Cell\r\n// ─────────────────────────────────────────────────────────────────────────────\r\n\r\nconst ResponseProgressCell = memo(({ row }: CellProps) => {\r\n const x = asSurvey(row);\r\n const responses = num(x.responses);\r\n const target = num(x.target);\r\n const pct = target > 0 ? Math.min((responses / target) * 100, 100) : 0;\r\n\r\n return (\r\n <div className=\"flex flex-col items-center gap-1 min-w-[100px]\">\r\n <span className=\"text-[12px] font-mono text-[color:var(--th-text-1)] tabular-nums\">\r\n {responses.toLocaleString()}\r\n <span className=\"text-[color:var(--th-text-3)]\">/{target.toLocaleString()}</span>\r\n </span>\r\n\r\n <div className=\"w-full h-1.5 rounded-full bg-[color:color-mix(in_srgb,var(--th-ov-base)_5%,transparent)] overflow-hidden\">\r\n <div\r\n className={`h-full rounded-full ${pct >= 80 ? 'bg-[#4edea3]' : 'bg-[#7c3aed]'\r\n }`}\r\n style={{ width: `${pct}%` }}\r\n />\r\n </div>\r\n </div>\r\n );\r\n});\r\nResponseProgressCell.displayName = 'ResponseProgressCell';\r\n\r\n// ─────────────────────────────────────────────────────────────────────────────\r\n// 4. NPS Score Cell\r\n// ─────────────────────────────────────────────────────────────────────────────\r\n\r\nconst NpsScoreCell = memo(({ row }: CellProps) => {\r\n const value = asSurvey(row).npsScore;\r\n if (value == null) {\r\n return <span className=\"text-[12px] text-[color:var(--th-text-3)]\">—</span>;\r\n }\r\n\r\n const n = num(value);\r\n const cls =\r\n n >= 70\r\n ? 'bg-[color:color-mix(in_srgb,var(--th-success)_10%,transparent)] text-[color:var(--th-success)]'\r\n : n >= 50\r\n ? 'bg-[color:color-mix(in_srgb,var(--th-warning-soft)_10%,transparent)] text-[color:var(--th-warning-soft)]'\r\n : 'bg-[color:color-mix(in_srgb,var(--th-danger-soft)_10%,transparent)] text-[color:var(--th-danger-soft)]';\r\n\r\n return (\r\n <span className={`text-[12px] font-bold font-mono px-2 py-0.5 rounded ${cls}`}>\r\n {n}\r\n </span>\r\n );\r\n});\r\nNpsScoreCell.displayName = 'NpsScoreCell';\r\n\r\n// ─────────────────────────────────────────────────────────────────────────────\r\n// 5. Survey Actions Cell\r\n// ─────────────────────────────────────────────────────────────────────────────\r\n\r\nconst SurveyActionsCell = memo(({ row, extra }: CellProps) => {\r\n const actions = extra as SurveyActions | undefined;\r\n const x = asSurvey(row);\r\n\r\n return (\r\n <div className=\"flex items-center justify-end gap-1\">\r\n <button\r\n onClick={(e) => {\r\n e.stopPropagation();\r\n actions?.onView?.(x);\r\n }}\r\n className=\"p-1.5 rounded-lg hover:bg-[color:color-mix(in_srgb,var(--th-ov-base)_5%,transparent)] text-[color:var(--th-text-3)] hover:text-[color:var(--th-text-2)] transition-colors\"\r\n >\r\n <Icon icon=\"BarChart3\" size={13} />\r\n </button>\r\n\r\n <button\r\n onClick={(e) => {\r\n e.stopPropagation();\r\n actions?.onEdit?.(x);\r\n }}\r\n className=\"p-1.5 rounded-lg hover:bg-[color:color-mix(in_srgb,var(--th-ov-base)_5%,transparent)] text-[color:var(--th-text-3)] hover:text-[color:var(--th-text-2)] transition-colors\"\r\n >\r\n <Icon icon=\"Edit3\" size={13} />\r\n </button>\r\n\r\n <button\r\n onClick={(e) => {\r\n e.stopPropagation();\r\n actions?.onDelete?.(x);\r\n }}\r\n className=\"p-1.5 rounded-lg hover:bg-[color:color-mix(in_srgb,var(--th-danger-soft)_10%,transparent)] text-[color:var(--th-text-3)] hover:text-[color:var(--th-danger-soft)] transition-colors\"\r\n >\r\n <Icon icon=\"Trash2\" size={13} />\r\n </button>\r\n </div>\r\n );\r\n});\r\nSurveyActionsCell.displayName = 'SurveyActionsCell';\r\n\r\n// ─────────────────────────────────────────────────────────────────────────────\r\n// 6-9. Response table cells\r\n// ─────────────────────────────────────────────────────────────────────────────\r\n\r\nconst NPS_CAT: Record<string, string> = {\r\n promoter: 'bg-[color:color-mix(in_srgb,var(--th-success)_10%,transparent)] text-[color:var(--th-success)]',\r\n passive: 'bg-[color:color-mix(in_srgb,var(--th-warning-soft)_10%,transparent)] text-[color:var(--th-warning-soft)]',\r\n detractor: 'bg-[color:color-mix(in_srgb,var(--th-danger-soft)_10%,transparent)] text-[color:var(--th-danger-soft)]',\r\n};\r\n\r\nconst ResponseUserCell = memo(({ row }: CellProps) => {\r\n const x = asResponse(row);\r\n return (\r\n <div className=\"flex items-center gap-2.5 min-w-0\">\r\n <div className=\"w-8 h-8 rounded-full bg-[#7c3aed]/20 flex items-center justify-center shrink-0\">\r\n <Icon icon=\"User\" size={14} className=\"text-[color:var(--th-accent-soft)]\" />\r\n </div>\r\n <span className=\"text-[12px] font-mono text-[color:var(--th-text-2)] truncate\">{str(x.userId)}</span>\r\n </div>\r\n );\r\n});\r\nResponseUserCell.displayName = 'ResponseUserCell';\r\n\r\nconst ResponseNpsCategoryCell = memo(({ row }: CellProps) => {\r\n const cat = str(asResponse(row).npsCategory);\r\n if (!cat) return <span className=\"text-[12px] text-[color:var(--th-text-3)]\">—</span>;\r\n return (\r\n <span className={`text-[10px] px-2 py-0.5 rounded font-medium capitalize ${NPS_CAT[cat] ?? 'bg-[color:color-mix(in_srgb,var(--th-ov-base)_5%,transparent)] text-[color:var(--th-text-3)]'}`}>\r\n {cat}\r\n </span>\r\n );\r\n});\r\nResponseNpsCategoryCell.displayName = 'ResponseNpsCategoryCell';\r\n\r\nconst ResponseRatingCell = memo(({ row }: CellProps) => {\r\n const rating = asResponse(row).rating;\r\n if (rating == null) return <span className=\"text-[12px] text-[color:var(--th-text-3)]\">—</span>;\r\n return (\r\n <div className=\"flex items-center gap-0.5\">\r\n {Array.from({ length: 5 }, (_, i) => (\r\n <Icon\r\n key={i}\r\n icon=\"Star\"\r\n size={11}\r\n className={i < rating ? 'text-[color:var(--th-warning-soft)] fill-[color:var(--th-warning-soft)]' : 'text-[color:color-mix(in_srgb,var(--th-text-3)_20%,transparent)]'}\r\n />\r\n ))}\r\n </div>\r\n );\r\n});\r\nResponseRatingCell.displayName = 'ResponseRatingCell';\r\n\r\nconst ResponseTextCell = memo(({ row }: CellProps) => {\r\n const t = str(asResponse(row).responseText);\r\n return t ? (\r\n <span className=\"block max-w-[360px] truncate text-[12px] text-[color:var(--th-text-1)]\" title={t}>{t}</span>\r\n ) : (\r\n <span className=\"text-[12px] text-[color:var(--th-text-3)]\">—</span>\r\n );\r\n});\r\nResponseTextCell.displayName = 'ResponseTextCell';\r\n\r\n// ─────────────────────────────────────────────────────────────────────────────\r\n// 10-12. Survey Analytics table cells\r\n// ─────────────────────────────────────────────────────────────────────────────\r\n\r\nconst AnalyticsSurveyCell = memo(({ row }: CellProps) => (\r\n <div className=\"flex items-center gap-2.5 min-w-0\">\r\n <div className=\"w-8 h-8 rounded-lg bg-[#7c3aed]/15 flex items-center justify-center shrink-0\">\r\n <Icon icon=\"BarChart3\" size={14} className=\"text-[color:var(--th-accent-soft)]\" />\r\n </div>\r\n <span className=\"text-[13px] font-medium text-white truncate max-w-[260px]\">\r\n {str(asAnalytics(row).surveyName)}\r\n </span>\r\n </div>\r\n));\r\nAnalyticsSurveyCell.displayName = 'AnalyticsSurveyCell';\r\n\r\nconst AnalyticsCompletionCell = memo(({ row }: CellProps) => {\r\n const pct = Math.min(100, Math.max(0, num(asAnalytics(row).completionRate)));\r\n return (\r\n <div className=\"w-28\">\r\n <div className=\"mb-1 text-[12px] font-mono tabular-nums text-[color:var(--th-text-1)]\">{pct}%</div>\r\n <div className=\"h-1.5 rounded-full bg-[color:color-mix(in_srgb,var(--th-ov-base)_5%,transparent)] overflow-hidden\">\r\n <div\r\n className={`h-full rounded-full ${pct >= 80 ? 'bg-[#4edea3]' : pct >= 60 ? 'bg-[#ffcc6b]' : 'bg-[#ffb4ab]'}`}\r\n style={{ width: `${pct}%` }}\r\n />\r\n </div>\r\n </div>\r\n );\r\n});\r\nAnalyticsCompletionCell.displayName = 'AnalyticsCompletionCell';\r\n\r\nconst AnalyticsRatingCell = memo(({ row }: CellProps) => {\r\n const r = num(asAnalytics(row).averageRating);\r\n return (\r\n <div className=\"flex items-center gap-1.5\">\r\n <Icon icon=\"Star\" size={12} className=\"text-[color:var(--th-warning-soft)] fill-[color:var(--th-warning-soft)]\" />\r\n <span className=\"text-[12px] font-mono tabular-nums text-[color:var(--th-text-1)]\">{r.toFixed(1)}</span>\r\n </div>\r\n );\r\n});\r\nAnalyticsRatingCell.displayName = 'AnalyticsRatingCell';\r\n\r\n// ─────────────────────────────────────────────────────────────────────────────\r\n// Registration\r\n// ─────────────────────────────────────────────────────────────────────────────\r\n\r\n/**\r\n * Registers the survey cells.\r\n *\r\n * @returns The `CellRegistration[]` result.\r\n */\r\nexport default function registerSurveyCells(): CellRegistration[] {\r\n return [\r\n {\r\n type: 'surveyStatus',\r\n module: 'Surveys',\r\n component: SurveyStatusCell,\r\n },\r\n {\r\n type: 'surveyName',\r\n module: 'Surveys',\r\n component: SurveyNameCell,\r\n },\r\n {\r\n type: 'responseProgress',\r\n module: 'Surveys',\r\n component: ResponseProgressCell,\r\n },\r\n {\r\n type: 'npsScore',\r\n module: 'Surveys',\r\n component: NpsScoreCell,\r\n },\r\n {\r\n type: 'surveyActions',\r\n module: 'Surveys',\r\n component: SurveyActionsCell,\r\n },\r\n { type: 'responseUser', module: 'Surveys', component: ResponseUserCell },\r\n { type: 'responseNpsCategory', module: 'Surveys', component: ResponseNpsCategoryCell },\r\n { type: 'responseRating', module: 'Surveys', component: ResponseRatingCell },\r\n { type: 'responseText', module: 'Surveys', component: ResponseTextCell },\r\n { type: 'analyticsSurvey', module: 'Surveys', component: AnalyticsSurveyCell },\r\n { type: 'analyticsCompletion', module: 'Surveys', component: AnalyticsCompletionCell },\r\n { type: 'analyticsRating', module: 'Surveys', component: AnalyticsRatingCell },\r\n ];\r\n}\r\n\r\n\r\n\r\n\r\n","import { useMemo, useState } from 'react';\nimport { useNavigate } from 'react-router-dom';\nimport registerSurveyCells from '../../cells/SurveyCells';\nimport type { ComponentType, CSSProperties } from 'react';\nimport type {\n DataTableProps,\n RowData,\n RowId,\n SortDirection,\n TableExtra,\n} from './types';\n\nconst surveyCellRenderers = Object.fromEntries(registerSurveyCells().map(({ type, component }) => [type, component])) as Record<string, ComponentType<any>>;\n\nexport function DataTable<T extends RowData>(props: DataTableProps<T>) {\n const {\n columns,\n data,\n totalCount,\n isLoading,\n hasMore,\n onLoadMore,\n tabs,\n activeTab,\n onTabChange,\n controls,\n searchConfig,\n filters,\n selectable,\n selectedIds = new Set<RowId>(),\n onSelectionChange,\n rowClickBehavior,\n onRowClick,\n currentPage,\n onEditRow,\n onActionClick,\n sortBy,\n sortOrder = 'asc',\n onSort,\n className = '',\n height,\n stickyHeader,\n emptyMessage = 'No records found.',\n availableViews = ['table'],\n renderCard: CardRenderer,\n gridCols = 3,\n } = props;\n\n const navigate = useNavigate();\n const [search, setSearch] = useState('');\n const [filterValues, setFilterValues] = useState<Record<string, string>>({});\n const [view, setView] = useState<'table' | 'grid'>(availableViews[0] ?? 'table');\n const [localSort, setLocalSort] = useState<{ key: string; order: SortDirection } | null>(null);\n\n const visibleColumns = columns.filter((column) => !column.hidden);\n const activeSort = localSort ?? (sortBy ? { key: sortBy, order: sortOrder } : null);\n\n const filteredRows = useMemo(() => {\n let rows = [...data];\n\n const query = search.trim().toLowerCase();\n if (query && searchConfig) {\n rows = rows.filter((row) =>\n searchConfig.keys.some((key) =>\n String(row[key] ?? '').toLowerCase().includes(query)\n )\n );\n }\n\n for (const filter of filters ?? []) {\n const value = filterValues[filter.id] ?? filter.defaultValue ?? '';\n if (value) rows = rows.filter((row) => filter.predicate(row, value));\n }\n\n if (activeSort && !onSort) {\n const column = columns.find((item) => String(item.key) === activeSort.key);\n if (column?.sortFn) {\n rows.sort((a, b) => column.sortFn!(a, b, activeSort.order));\n } else {\n rows.sort((a, b) => {\n const av = (a as Record<string, unknown>)[activeSort.key];\r\n const bv = (b as Record<string, unknown>)[activeSort.key];\n const result = String(av ?? '').localeCompare(String(bv ?? ''), undefined, {\n numeric: true,\n sensitivity: 'base',\n });\n return activeSort.order === 'asc' ? result : -result;\n });\n }\n }\n return rows;\n }, [data, search, searchConfig, filters, filterValues, activeSort, onSort, columns]);\n\n const toggleSelection = (id: RowId) => {\n const next = new Set(selectedIds);\n if (next.has(id)) next.delete(id);\n else next.add(id);\n onSelectionChange?.(next);\n };\n\n const selectAll = (checked: boolean) => {\n onSelectionChange?.(checked ? new Set(filteredRows.map((row) => row.id)) : new Set());\n };\n\n const handleRowClick = (row: T) => {\n onRowClick?.(row);\n if (!rowClickBehavior) return;\n if (rowClickBehavior.type === 'callback') rowClickBehavior.handler(row);\n if (rowClickBehavior.type === 'navigate') {\n const path = typeof rowClickBehavior.path === 'function'\n ? rowClickBehavior.path(row)\n : rowClickBehavior.path;\n navigate(path);\n }\n };\n\n const extra: TableExtra<T> = {\n selectedIds,\n onToggle: toggleSelection,\n onSelectAll: selectAll,\n allChecked: filteredRows.length > 0 && filteredRows.every((row) => selectedIds.has(row.id)),\n onActionClick,\n onEditRow,\n navigate: (path) => navigate(path),\n currentPage,\n };\n\n const gridStyle: CSSProperties = {\n gridTemplateColumns: `repeat(${typeof gridCols === 'number' ? gridCols : gridCols.lg ?? gridCols.md ?? gridCols.sm ?? 3}, minmax(0, 1fr))`,\n };\n\n\n return (\n <section className={`w-full overflow-hidden rounded-xl border border-[var(--th-border)] bg-[var(--th-surface)] ${className}`}>\n <div className=\"flex flex-wrap items-center justify-between gap-3 border-b border-[var(--th-border)] p-3\">\n <div className=\"flex flex-wrap gap-2\">\n {tabs?.map((tab) => {\n const key = typeof tab === 'string' ? tab : tab.key;\n const label = typeof tab === 'string' ? tab : tab.label;\n const count = typeof tab === 'string' ? undefined : tab.count;\n return (\n <button\n key={key}\n type=\"button\"\n onClick={() => onTabChange?.(key)}\n className={`rounded-lg px-3 py-2 text-sm ${activeTab === key ? 'bg-violet-600 text-white' : 'text-[var(--th-text-2)] hover:bg-black/5'}`}\n >\n {label}{count !== undefined ? ` (${count})` : ''}\n </button>\n );\n })}\n </div>\n <div className=\"flex flex-wrap items-center gap-2\">\n {(searchConfig || props.showSearch) && (\n <input\n value={search}\n onChange={(event) => {\n setSearch(event.target.value);\n props.onFilterChange?.(event.target.value);\n }}\n placeholder={searchConfig?.placeholder ?? 'Search...'}\n className=\"rounded-lg border border-[var(--th-border)] bg-transparent px-3 py-2 text-sm\"\n />\n )}\n {(filters ?? []).map((filter) => (\n <select\n key={filter.id}\n value={filterValues[filter.id] ?? filter.defaultValue ?? ''}\n onChange={(event) => setFilterValues((old) => ({ ...old, [filter.id]: event.target.value }))}\n className=\"rounded-lg border border-[var(--th-border)] bg-[var(--th-surface)] px-3 py-2 text-sm\"\n >\n <option value=\"\">{filter.label}</option>\n {filter.options.map((option) => (\n <option key={option.value} value={option.value}>{option.label}</option>\n ))}\n </select>\n ))}\n {availableViews.length > 1 && availableViews.map((item) => (\n <button\n key={item}\n type=\"button\"\n onClick={() => setView(item)}\n className={`rounded-lg px-3 py-2 text-sm capitalize ${view === item ? 'bg-violet-600 text-white' : 'border border-[var(--th-border)]'}`}\n >\n {item}\n </button>\n ))}\n {controls?.map((control) => (\n <button\n key={control.action}\n type=\"button\"\n disabled={control.disabled}\n onClick={control.onClick}\n className=\"rounded-lg bg-violet-600 px-3 py-2 text-sm text-white disabled:opacity-50\"\n >\n {control.label}\n </button>\n ))}\n </div>\n </div>\n\n {isLoading && data.length === 0 ? (\n <div className=\"p-10 text-center text-sm text-[var(--th-text-3)]\">Loading...</div>\n ) : filteredRows.length === 0 ? (\n <div className=\"p-10 text-center text-sm text-[var(--th-text-3)]\">{emptyMessage}</div>\n ) : view === 'grid' && CardRenderer ? (\n <div className=\"grid gap-4 p-4\" style={gridStyle}>\n {filteredRows.map((row, index) => (\n <CardRenderer\n key={row.id}\n row={row}\n rowIndex={index}\n index={index}\n isSelected={selectedIds.has(row.id)}\n onSelect={toggleSelection}\n onRowClick={handleRowClick}\n onEditRow={onEditRow}\n onActionClick={onActionClick}\n />\n ))}\n </div>\n ) : (\n <div className=\"overflow-auto\" style={{ height }}>\n <table className=\"w-full border-collapse text-left text-sm\">\n <thead className={stickyHeader ? 'sticky top-0 z-10 bg-[var(--th-surface)]' : 'bg-[var(--th-surface)]'}>\n <tr className=\"border-b border-[var(--th-border)]\">\n {selectable && (\n <th className=\"w-10 p-3\">\n <input\n type=\"checkbox\"\n checked={extra.allChecked}\n onChange={(event) => selectAll(event.target.checked)}\n aria-label=\"Select all rows\"\n />\n </th>\n )}\n {visibleColumns.map((column) => (\n <th\n key={String(column.key)}\n className={`p-3 font-medium text-[var(--th-text-2)] ${column.align === 'right' ? 'text-right' : column.align === 'center' ? 'text-center' : 'text-left'}`}\n style={{ width: column.width, minWidth: column.minWidth, maxWidth: column.maxWidth }}\n >\n <button\n type=\"button\"\n disabled={!column.sortable}\n onClick={() => {\n const order = activeSort?.key === String(column.key) && activeSort.order === 'asc' ? 'desc' : 'asc';\n setLocalSort({ key: String(column.key), order });\n onSort?.(String(column.key), order);\n }}\n className=\"disabled:cursor-default\"\n >\n {column.label}\n {activeSort?.key === String(column.key) ? (activeSort.order === 'asc' ? ' ?' : ' ?') : ''}\n </button>\n </th>\n ))}\n </tr>\n </thead>\n <tbody>\n {filteredRows.map((row, rowIndex) => (\n <tr\n key={row.id}\n onClick={() => handleRowClick(row)}\n className={`border-b border-[var(--th-border)] hover:bg-black/[0.03] ${rowClickBehavior?.type === 'none' ? '' : 'cursor-pointer'} ${typeof props.rowClassName === 'function' ? props.rowClassName(row) : props.rowClassName ?? ''}`}\n style={{ height: props.rowHeight }}\n >\n {selectable && (\n <td className=\"p-3\" onClick={(event) => event.stopPropagation()}>\n <input\n type=\"checkbox\"\n checked={selectedIds.has(row.id)}\n onChange={() => toggleSelection(row.id)}\n aria-label={`Select row ${row.id}`}\n />\n </td>\n )}\n {visibleColumns.map((column) => {\n const value = (row as Record<string, unknown>)[String(column.key)];\n const registration = surveyCellRenderers[column.cellType ?? ''];\n const Cell = registration;\n return (\n <td\n key={String(column.key)}\n className={`p-3 ${column.align === 'right' ? 'text-right' : column.align === 'center' ? 'text-center' : ''}`}\n >\n {Cell ? (\n <Cell value={value} row={row} column={column} rowIndex={rowIndex} currentPage={currentPage} extra={extra} />\n ) : String(value ?? ' ')}\n </td>\n );\n })}\n </tr>\n ))}\n </tbody>\n </table>\n </div>\n )}\n\n <div className=\"flex items-center justify-between gap-3 p-3 text-xs text-[var(--th-text-3)]\">\n <span>{filteredRows.length} of {totalCount ?? data.length} records</span>\n {hasMore && onLoadMore && (\n <button\n type=\"button\"\n onClick={() => void onLoadMore()}\n disabled={isLoading}\n className=\"rounded-lg border border-[var(--th-border)] px-3 py-2 text-sm disabled:opacity-50\"\n >\n {isLoading ? 'Loading...' : 'Load more'}\n </button>\n )}\n </div>\n </section>\n );\n}\n\nexport default DataTable;\n\n\n\r\n\r\n\r\n\r\n","import { useState } from 'react';\nimport type { ReactNode } from 'react';\n\nexport interface ConfirmModalProps {\n open: boolean;\n onClose: () => void;\n onConfirm: () => void;\n isLoading?: boolean;\n title: string;\n description?: ReactNode;\n confirmLabel?: string;\n confirmTone?: 'danger' | 'primary';\n requireConfirmText?: string;\n}\n\nexport function ConfirmModal({\n open,\n onClose,\n onConfirm,\n isLoading = false,\n title,\n description,\n confirmLabel = 'Confirm',\n confirmTone = 'primary',\n requireConfirmText,\n}: ConfirmModalProps) {\n const [typedText, setTypedText] = useState('');\n\n if (!open) return null;\n\n const canConfirm =\n !isLoading &&\n (!requireConfirmText || typedText === requireConfirmText);\n\n return (\n <div className=\"fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4\">\n <div\n role=\"dialog\"\n aria-modal=\"true\"\n aria-labelledby=\"confirm-modal-title\"\n className=\"w-full max-w-md rounded-xl border border-[var(--th-border)] bg-[var(--th-surface)] p-6 shadow-xl\"\n >\n <h2 id=\"confirm-modal-title\" className=\"text-lg font-semibold text-[var(--th-text)]\">\n {title}\n </h2>\n <div className=\"mt-3 text-sm text-[var(--th-text-3)]\">{description}</div>\n\n {requireConfirmText && (\n <input\n value={typedText}\n onChange={(event) => setTypedText(event.target.value)}\n placeholder={`Type ${requireConfirmText} to confirm`}\n className=\"mt-4 w-full rounded-lg border border-[var(--th-border)] bg-transparent px-3 py-2 text-sm\"\n />\n )}\n\n <div className=\"mt-6 flex justify-end gap-3\">\n <button\n type=\"button\"\n onClick={() => {\n setTypedText('');\n onClose();\n }}\n disabled={isLoading}\n className=\"rounded-lg border border-[var(--th-border)] px-4 py-2 text-sm\"\n >\n Cancel\n </button>\n <button\n type=\"button\"\n onClick={onConfirm}\n disabled={!canConfirm}\n className={`rounded-lg px-4 py-2 text-sm font-medium text-white disabled:opacity-50 ${\n confirmTone === 'danger' ? 'bg-red-600' : 'bg-violet-600'\n }`}\n >\n {isLoading ? 'Please wait...' : confirmLabel}\n </button>\n </div>\n </div>\n </div>\n );\n}\n\nexport default ConfirmModal;\r\n\r\n\r\n","import type { ReactNode } from 'react';\nimport { Icon } from '../ui/Icon';\n\nexport interface HeaderProps {\n title: string;\n subtitle?: string;\n primaryText?: string;\n primaryIcon?: string;\n onPrimaryClick?: () => void;\n children?: ReactNode;\n}\n\nexport function Header({\n title,\n subtitle,\n primaryText,\n primaryIcon,\n onPrimaryClick,\n children,\n}: HeaderProps) {\n return (\n <header className=\"mb-6 flex flex-wrap items-center justify-between gap-4\">\n <div>\n <h1 className=\"text-2xl font-semibold text-[var(--th-text)]\">{title}</h1>\n {subtitle && (\n <p className=\"mt-1 text-sm text-[var(--th-text-3)]\">{subtitle}</p>\n )}\n </div>\n\n <div className=\"flex items-center gap-3\">\n {children}\n {primaryText && onPrimaryClick && (\n <button\n type=\"button\"\n onClick={onPrimaryClick}\n className=\"inline-flex items-center gap-2 rounded-lg bg-violet-600 px-4 py-2 text-sm font-medium text-white hover:bg-violet-700\"\n >\n {primaryIcon && <Icon icon={primaryIcon} size={16} />}\n {primaryText}\n </button>\n )}\n </div>\n </header>\n );\n}\n\nexport default Header;\r\n\r\n\r\n","\"use client\";\nimport * as React from \"react\";\nimport { jsx } from \"react/jsx-runtime\";\n// src/QueryClientProvider.tsx\n/**\n* The context that `useQueryClient` reads from. `QueryClientProvider` is the normal way to set it.\n*/\nconst QueryClientContext = React.createContext(void 0);\n/**\n* The `useQueryClient` hook returns the current `QueryClient` instance.\n* @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will\n* be used.\n* @returns The current `QueryClient` instance.\n* @throws {Error} If no `queryClient` argument is passed and no `QueryClientProvider` is found in the\n* component tree.\n*/\nconst useQueryClient = (queryClient) => {\n\tconst client = React.useContext(QueryClientContext);\n\tif (queryClient) return queryClient;\n\tif (!client) throw new Error(\"No QueryClient set, use QueryClientProvider to set one\");\n\treturn client;\n};\n/**\n* Use the `QueryClientProvider` component to connect and provide a `QueryClient` to your application. Also\n* calls `client.mount()`/`client.unmount()` as this component mounts/unmounts, which subscribes the client to\n* focus/online events (resuming any paused mutations and refetching as needed when the app regains focus or\n* comes back online).\n* @param props - The `client` to provide, and the `children` that get access to it.\n* @returns The provided `children`, wrapped so they can read the `QueryClient` via `useQueryClient`.\n* @example\n* ```tsx\n* import { QueryClient, QueryClientProvider } from '@tanstack/react-query'\n*\n* const queryClient = new QueryClient()\n*\n* function App() {\n* return <QueryClientProvider client={queryClient}>...</QueryClientProvider>\n* }\n* ```\n*/\nconst QueryClientProvider = ({ client, children }) => {\n\tReact.useEffect(() => {\n\t\tclient.mount();\n\t\treturn () => {\n\t\t\tclient.unmount();\n\t\t};\n\t}, [client]);\n\treturn /* @__PURE__ */ jsx(QueryClientContext.Provider, {\n\t\tvalue: client,\n\t\tchildren\n\t});\n};\nexport { QueryClientContext, QueryClientProvider, useQueryClient };\n\n//# sourceMappingURL=QueryClientProvider.js.map","// src/timeoutManager.ts\nconst defaultTimeoutProvider = {\n\tsetTimeout: (callback, delay) => setTimeout(callback, delay),\n\tclearTimeout: (timeoutId) => clearTimeout(timeoutId),\n\tsetInterval: (callback, delay) => setInterval(callback, delay),\n\tclearInterval: (intervalId) => clearInterval(intervalId)\n};\n/**\n* Allows customization of how timeouts are created.\n*\n* `@tanstack/query-core` makes liberal use of timeouts to implement `staleTime`\n* and `gcTime`. The default TimeoutManager provider uses the platform's global\n* `setTimeout` implementation, which is known to have scalability issues with\n* thousands of timeouts on the event loop.\n*\n* If you hit this limitation, consider providing a custom TimeoutProvider that\n* coalesces timeouts.\n*/\nvar TimeoutManager = class {\n\t#provider = defaultTimeoutProvider;\n\t#providerCalled = false;\n\t/**\n\t* `setTimeoutProvider` can be used to set a custom implementation of the\n\t* `setTimeout`, `clearTimeout`, `setInterval`, `clearInterval` functions,\n\t* called a `TimeoutProvider`.\n\t*\n\t* This may be useful if you notice event loop performance issues with\n\t* thousands of queries. A custom TimeoutProvider could also support timer\n\t* delays longer than the global `setTimeout` maximum delay value of about\n\t* 24 days.\n\t*\n\t* It is important to call `setTimeoutProvider` before creating a\n\t* QueryClient or queries, so that the same provider is used consistently\n\t* for all timers in the application, since different TimeoutProviders\n\t* cannot cancel each others' timers.\n\t* @param provider - The `TimeoutProvider` to use for all timers from now on.\n\t* @example\n\t* ```ts\n\t* import { timeoutManager, QueryClient } from '@tanstack/query-core'\n\t* import { CustomTimeoutProvider } from './CustomTimeoutProvider'\n\t*\n\t* timeoutManager.setTimeoutProvider(new CustomTimeoutProvider())\n\t*\n\t* export const queryClient = new QueryClient()\n\t* ```\n\t*/\n\tsetTimeoutProvider(provider) {\n\t\tif (process.env.NODE_ENV !== \"production\") {\n\t\t\tif (this.#providerCalled && provider !== this.#provider) console.error(`[timeoutManager]: Switching provider after calls to previous provider might result in unexpected behavior.`, {\n\t\t\t\tprevious: this.#provider,\n\t\t\t\tprovider\n\t\t\t});\n\t\t}\n\t\tthis.#provider = provider;\n\t\tif (process.env.NODE_ENV !== \"production\") this.#providerCalled = false;\n\t}\n\t/**\n\t* `setTimeout` schedules a callback to run after approximately `delay`\n\t* milliseconds, like the global `setTimeout` function. The callback can be\n\t* canceled with `clearTimeout`.\n\t*\n\t* It returns a timer ID, which may be a number or an object that can be\n\t* coerced to a number via `Symbol.toPrimitive`.\n\t* @param callback - The function to call when the timeout elapses.\n\t* @param delay - The time to wait before calling `callback`, in milliseconds.\n\t* @returns The timer ID, to pass to {@link TimeoutManager#clearTimeout}.\n\t* @example\n\t* ```ts\n\t* import { timeoutManager } from '@tanstack/query-core'\n\t*\n\t* const timeoutId = timeoutManager.setTimeout(\n\t* () => console.log('ran at:', new Date()),\n\t* 1000,\n\t* )\n\t*\n\t* const timeoutIdNumber: number = Number(timeoutId)\n\t* ```\n\t*/\n\tsetTimeout(callback, delay) {\n\t\tif (process.env.NODE_ENV !== \"production\") this.#providerCalled = true;\n\t\treturn this.#provider.setTimeout(callback, delay);\n\t}\n\t/**\n\t* `clearTimeout` cancels a timeout callback scheduled with `setTimeout`,\n\t* like the global `clearTimeout` function. It should be called with a\n\t* timer ID returned by `setTimeout`.\n\t* @param timeoutId - The timer ID returned by `setTimeout`, or `undefined`.\n\t* @example\n\t* ```ts\n\t* import { timeoutManager } from '@tanstack/query-core'\n\t*\n\t* const timeoutId = timeoutManager.setTimeout(\n\t* () => console.log('ran at:', new Date()),\n\t* 1000,\n\t* )\n\t*\n\t* timeoutManager.clearTimeout(timeoutId)\n\t* ```\n\t*/\n\tclearTimeout(timeoutId) {\n\t\tthis.#provider.clearTimeout(timeoutId);\n\t}\n\t/**\n\t* `setInterval` schedules a callback to be called approximately every\n\t* `delay` milliseconds, like the global `setInterval` function.\n\t*\n\t* Like `setTimeout`, it returns a timer ID, which may be a number or an\n\t* object that can be coerced to a number via `Symbol.toPrimitive`.\n\t* @param callback - The function to call on every interval.\n\t* @param delay - The time between calls, in milliseconds.\n\t* @returns The timer ID, to pass to {@link TimeoutManager#clearInterval}.\n\t* @example\n\t* ```ts\n\t* import { timeoutManager } from '@tanstack/query-core'\n\t*\n\t* const intervalId = timeoutManager.setInterval(\n\t* () => console.log('ran at:', new Date()),\n\t* 1000,\n\t* )\n\t* ```\n\t*/\n\tsetInterval(callback, delay) {\n\t\tif (process.env.NODE_ENV !== \"production\") this.#providerCalled = true;\n\t\treturn this.#provider.setInterval(callback, delay);\n\t}\n\t/**\n\t* `clearInterval` can be used to cancel an interval, like the global\n\t* `clearInterval` function. It should be called with an interval ID\n\t* returned by `setInterval`.\n\t* @param intervalId - The timer ID returned by `setInterval`, or `undefined`.\n\t* @example\n\t* ```ts\n\t* import { timeoutManager } from '@tanstack/query-core'\n\t*\n\t* const intervalId = timeoutManager.setInterval(\n\t* () => console.log('ran at:', new Date()),\n\t* 1000,\n\t* )\n\t*\n\t* timeoutManager.clearInterval(intervalId)\n\t* ```\n\t*/\n\tclearInterval(intervalId) {\n\t\tthis.#provider.clearInterval(intervalId);\n\t}\n};\n/**\n* Singleton instance of {@link TimeoutManager}, used throughout TanStack Query to schedule and cancel timers.\n*/\nconst timeoutManager = new TimeoutManager();\n/**\n* In many cases code wants to delay to the next event loop tick; this is not\n* mediated by {@link timeoutManager}.\n*\n* This function is provided to make auditing the `tanstack/query-core` for\n* incorrect use of system `setTimeout` easier.\n* @param callback - The function to call on the next event loop tick.\n*/\nfunction systemSetTimeoutZero(callback) {\n\tsetTimeout(callback, 0);\n}\nexport { TimeoutManager, defaultTimeoutProvider, systemSetTimeoutZero, timeoutManager };\n\n//# sourceMappingURL=timeoutManager.js.map","import { timeoutManager } from \"./timeoutManager.js\";\n// src/utils.ts\n/**\n* @deprecated use `environmentManager.isServer()` instead.\n*/\nconst isServer = typeof window === \"undefined\" || \"Deno\" in globalThis;\nfunction noop() {}\n/**\n* Resolves an {@link Updater}: calls it with `input` if it is a function, otherwise returns it as\n* is.\n* @param updater - The new value, or a function that receives `input` and returns the new value.\n* @param input - The current value, passed to `updater` if it is a function.\n* @returns The new value.\n*/\nfunction functionalUpdate(updater, input) {\n\treturn typeof updater === \"function\" ? updater(input) : updater;\n}\n/**\n* Checks whether a value can be used as a timeout: a non-negative, finite number.\n* @param value - The value to check.\n* @returns `true` if `value` is a number that is `>= 0` and not `Infinity`.\n*/\nfunction isValidTimeout(value) {\n\treturn typeof value === \"number\" && value >= 0 && value !== Infinity;\n}\n/**\n* Calculates how long until data updated at `updatedAt` becomes stale.\n* @param updatedAt - The timestamp, in milliseconds, at which the data was last updated.\n* @param staleTime - The time, in milliseconds, after which data is considered stale. Defaults to\n* `0`.\n* @returns The remaining time in milliseconds, or `0` if the data is already stale.\n*/\nfunction timeUntilStale(updatedAt, staleTime) {\n\treturn Math.max(updatedAt + (staleTime || 0) - Date.now(), 0);\n}\n/**\n* Resolves an option that can be given either as a value or as a function of the query, such as\n* `staleTime`.\n* @param value - The option value, or a function that receives `query` and returns the value.\n* @param query - The query passed to `value` if it is a function.\n* @returns The resolved value, or `undefined` if `value` is `undefined`.\n*/\nfunction resolveQueryValue(value, query) {\n\treturn typeof value === \"function\" ? value(query) : value;\n}\n/**\n* Checks whether a query matches the given {@link QueryFilters}.\n* Every filter that is specified must match; filters that are left unspecified are ignored.\n* @param filters - The filters to check the query against.\n* @param query - The query to check.\n* @returns `true` if the query matches every specified filter.\n* @example\n* ```ts\n* const queryCache = queryClient.getQueryCache()\n*\n* const matchingQueries = queryCache\n* .getAll()\n* .filter((query) => matchQuery({ queryKey: ['posts'] }, query))\n* ```\n*/\nfunction matchQuery(filters, query) {\n\tconst { type = \"all\", exact, fetchStatus, predicate, queryKey, stale } = filters;\n\tif (queryKey) {\n\t\tif (exact) {\n\t\t\tif (query.queryHash !== hashQueryKeyByOptions(queryKey, query.options)) return false;\n\t\t} else if (!partialMatchKey(query.queryKey, queryKey)) return false;\n\t}\n\tif (type !== \"all\") {\n\t\tconst isActive = query.isActive();\n\t\tif (type === \"active\" && !isActive) return false;\n\t\tif (type === \"inactive\" && isActive) return false;\n\t}\n\tif (typeof stale === \"boolean\" && query.isStale() !== stale) return false;\n\tif (fetchStatus && fetchStatus !== query.state.fetchStatus) return false;\n\tif (predicate && !predicate(query)) return false;\n\treturn true;\n}\n/**\n* Checks whether a mutation matches the given {@link MutationFilters}.\n* Every filter that is specified must match; filters that are left unspecified are ignored.\n* If a `mutationKey` filter is provided but the mutation has no `mutationKey` of its own, it does not match.\n* @param filters - The filters to check the mutation against.\n* @param mutation - The mutation to check.\n* @returns `true` if the mutation matches every specified filter.\n* @example\n* ```ts\n* const mutationCache = queryClient.getMutationCache()\n*\n* const matchingMutations = mutationCache\n* .getAll()\n* .filter((mutation) => matchMutation({ mutationKey: ['addPost'] }, mutation))\n* ```\n*/\nfunction matchMutation(filters, mutation) {\n\tconst { exact, status, predicate, mutationKey } = filters;\n\tif (mutationKey) {\n\t\tif (!mutation.options.mutationKey) return false;\n\t\tif (exact) {\n\t\t\tif (hashKey(mutation.options.mutationKey) !== hashKey(mutationKey)) return false;\n\t\t} else if (!partialMatchKey(mutation.options.mutationKey, mutationKey)) return false;\n\t}\n\tif (status && mutation.state.status !== status) return false;\n\tif (predicate && !predicate(mutation)) return false;\n\treturn true;\n}\n/**\n* Hashes a query key with the query's `queryKeyHashFn` option, falling back to {@link hashKey}.\n* @param queryKey - The query key to hash.\n* @param options - The query options that may provide a custom `queryKeyHashFn`.\n* @returns The query hash, a string that identifies the query in the cache.\n*/\nfunction hashQueryKeyByOptions(queryKey, options) {\n\treturn (options?.queryKeyHashFn || hashKey)(queryKey);\n}\n/**\n* Default query & mutation keys hash function.\n* Hashes the value into a stable hash.\n* @param queryKey - The query or mutation key to hash.\n* @returns The stable hash of the key, as a JSON string.\n* @example\n* ```ts\n* // Object keys are sorted, so key order doesn't affect the hash:\n* hashKey(['todos', { page: 1, filter: 'done' }]) // === '[\"todos\",{\"filter\":\"done\",\"page\":1}]'\n* ```\n*/\nfunction hashKey(queryKey) {\n\treturn JSON.stringify(queryKey, (_, val) => isPlainObject(val) ? Object.keys(val).sort().reduce((result, key) => {\n\t\tresult[key] = val[key];\n\t\treturn result;\n\t}, {}) : val);\n}\nfunction partialMatchKey(a, b) {\n\tif (a === b) return true;\n\tif (typeof a !== typeof b) return false;\n\tif (a && b && typeof a === \"object\" && typeof b === \"object\") {\n\t\tif (Array.isArray(a) && Array.isArray(b)) {\n\t\t\tif (b.length > a.length) return false;\n\t\t\tfor (let i = 0; i < b.length; i++) if (!partialMatchKey(a[i], b[i])) return false;\n\t\t\treturn true;\n\t\t}\n\t\tconst bKeys = Object.keys(b);\n\t\tfor (const key of bKeys) if (!partialMatchKey(a[key], b[key])) return false;\n\t\treturn true;\n\t}\n\treturn false;\n}\nconst hasOwn = Object.prototype.hasOwnProperty;\nfunction replaceEqualDeep(a, b, depth = 0) {\n\tif (a === b) return a;\n\tif (depth > 500) return b;\n\tconst array = isPlainArray(a) && isPlainArray(b);\n\tif (!array && !(isPlainObject(a) && isPlainObject(b))) return b;\n\tconst aSize = (array ? a : Object.keys(a)).length;\n\tconst bItems = array ? b : Object.keys(b);\n\tconst bSize = bItems.length;\n\tconst copy = array ? new Array(bSize) : {};\n\tlet equalItems = 0;\n\tfor (let i = 0; i < bSize; i++) {\n\t\tconst key = array ? i : bItems[i];\n\t\tconst aItem = a[key];\n\t\tconst bItem = b[key];\n\t\tif (aItem === bItem) {\n\t\t\tcopy[key] = aItem;\n\t\t\tif (array ? i < aSize : hasOwn.call(a, key)) equalItems++;\n\t\t\tcontinue;\n\t\t}\n\t\tif (aItem === null || bItem === null || typeof aItem !== \"object\" || typeof bItem !== \"object\") {\n\t\t\tcopy[key] = bItem;\n\t\t\tcontinue;\n\t\t}\n\t\tconst v = replaceEqualDeep(aItem, bItem, depth + 1);\n\t\tcopy[key] = v;\n\t\tif (v === aItem) equalItems++;\n\t}\n\treturn aSize === bSize && equalItems === aSize ? a : copy;\n}\n/**\n* Shallow compare objects.\n* @param a - The first object.\n* @param b - The second object, or `undefined`.\n* @returns `true` if both objects have the same keys, with strictly equal values for each key.\n*/\nfunction shallowEqualObjects(a, b) {\n\tif (!b || Object.keys(a).length !== Object.keys(b).length) return false;\n\tfor (const key of Object.keys(a)) if (!hasOwn.call(b, key) || a[key] !== b[key]) return false;\n\treturn true;\n}\n/**\n* Checks whether a value is an array with no holes and no extra properties.\n* @param value - The value to check.\n* @returns `true` if `value` is an array whose number of own keys equals its `length`.\n*/\nfunction isPlainArray(value) {\n\treturn Array.isArray(value) && value.length === Object.keys(value).length;\n}\n/**\n* Checks whether a value is a plain object, e.g. created with an object literal or\n* `Object.create(null)`.\n* @param o - The value to check.\n* @returns `true` if `o` is a plain object.\n*/\nfunction isPlainObject(o) {\n\tif (!hasObjectPrototype(o)) return false;\n\tconst objectPrototype = Object.getPrototypeOf(o);\n\tconst ctor = objectPrototype?.constructor;\n\tif (ctor === void 0) return true;\n\tif (typeof ctor !== \"function\") return false;\n\tconst prot = ctor.prototype;\n\tif (!hasObjectPrototype(prot)) return false;\n\tif (!prot.hasOwnProperty(\"isPrototypeOf\")) return false;\n\tif (objectPrototype !== Object.prototype) return false;\n\treturn true;\n}\n/**\n* Checks whether a value's `Object.prototype.toString` tag is `[object Object]`.\n* @param o - The value to check.\n* @returns `true` if the tag is `[object Object]`.\n*/\nfunction hasObjectPrototype(o) {\n\treturn Object.prototype.toString.call(o) === \"[object Object]\";\n}\n/**\n* Waits for the given time, using the configured {@link timeoutManager}.\n* @param timeout - The time to wait, in milliseconds.\n* @returns A promise that resolves after `timeout` milliseconds.\n*/\nfunction sleep(timeout) {\n\treturn new Promise((resolve) => {\n\t\ttimeoutManager.setTimeout(resolve, timeout);\n\t});\n}\n/**\n* Applies a query's `structuralSharing` option when writing new data.\n* @param prevData - The previously cached data.\n* @param data - The new data.\n* @param options - The query options, whose `structuralSharing` decides how the data is merged.\n* @returns The result of a custom `structuralSharing` function, `data` with its unchanged parts\n* replaced by those of `prevData` by default, or `data` as is if `structuralSharing` is `false`.\n* @throws {Error} The error from the default structural sharing, e.g. when the data is not JSON serializable.\n* Outside production, it is also logged to the console.\n*/\nfunction replaceData(prevData, data, options) {\n\tif (typeof options.structuralSharing === \"function\") return options.structuralSharing(prevData, data);\n\telse if (options.structuralSharing !== false) {\n\t\tif (process.env.NODE_ENV !== \"production\") try {\n\t\t\treturn replaceEqualDeep(prevData, data);\n\t\t} catch (error) {\n\t\t\tconsole.error(`Structural sharing requires data to be JSON serializable. To fix this, turn off structuralSharing or return JSON-serializable data from your queryFn. [${options.queryHash}]: ${error}`);\n\t\t\tthrow error;\n\t\t}\n\t\treturn replaceEqualDeep(prevData, data);\n\t}\n\treturn data;\n}\n/**\n* Intended to be passed as a query's `placeholderData` option, for example\n* `placeholderData: keepPreviousData`. Instead of resetting the query's data to `undefined` while a new\n* query key is fetching, it keeps displaying the previously fetched data until the new data arrives.\n* @param previousData - The data of the previous query key, passed by the observer.\n* @returns The previous data, unchanged.\n* @example\n* ```ts\n* new QueryObserver(queryClient, {\n* queryKey: ['posts', page],\n* queryFn: () => fetchPosts(page),\n* placeholderData: keepPreviousData,\n* })\n* ```\n*/\nfunction keepPreviousData(previousData) {\n\treturn previousData;\n}\n/**\n* Returns a new array with `item` added at the end. If that makes the array longer than `max`,\n* excess items are removed from the start.\n* @param items - The current items.\n* @param item - The value to append.\n* @param max - The maximum number of items to keep. `0` (the default) means no limit.\n* @returns A new array with `item` added.\n*/\nfunction addToEnd(items, item, max = 0) {\n\tconst newItems = [...items, item];\n\treturn max && newItems.length > max ? newItems.slice(-max) : newItems;\n}\n/**\n* Returns a new array with `item` added at the start. If that makes the array longer than `max`,\n* excess items are removed from the end.\n* @param items - The current items.\n* @param item - The value to prepend.\n* @param max - The maximum number of items to keep. `0` (the default) means no limit.\n* @returns A new array with `item` added.\n*/\nfunction addToStart(items, item, max = 0) {\n\tconst newItems = [item, ...items];\n\treturn max && newItems.length > max ? newItems.slice(0, max) : newItems;\n}\n/**\n* Sentinel value that can be passed as a query's `queryFn` to conditionally disable the query (equivalent\n* to `enabled: false`) while preserving full type inference for the query's data. Unlike `enabled: false`,\n* a query disabled via `skipToken` cannot be triggered with `refetch`.\n* @example\n* ```ts\n* new QueryObserver(queryClient, {\n* queryKey: ['post', postId],\n* queryFn: postId != null ? () => fetchPost(postId) : skipToken,\n* })\n* ```\n*/\nconst skipToken = Symbol();\n/**\n* Returns the function to call for a fetch. If there is no `queryFn` but the fetch was started from\n* an `initialPromise`, that promise is returned instead. If there is no usable `queryFn` (missing or\n* {@link skipToken}), the returned function rejects with a `Missing queryFn` error.\n* @param options - The query options with the `queryFn`, and the `queryHash` used in error messages.\n* @param fetchOptions - The fetch options, which may carry an `initialPromise`.\n* @returns The function to call for the fetch.\n*/\nfunction ensureQueryFn(options, fetchOptions) {\n\tif (process.env.NODE_ENV !== \"production\") {\n\t\tif (options.queryFn === skipToken) console.error(`Attempted to invoke queryFn when set to skipToken. This is likely a configuration error. Query hash: '${options.queryHash}'`);\n\t}\n\tif (!options.queryFn && fetchOptions?.initialPromise) return () => fetchOptions.initialPromise;\n\tif (!options.queryFn || options.queryFn === skipToken) return () => Promise.reject(/* @__PURE__ */ new Error(`Missing queryFn: '${options.queryHash}'`));\n\treturn options.queryFn;\n}\n/**\n* Resolves a `throwOnError` option to a boolean.\n* If `throwOnError` is a function, it is called with `params` (e.g. the error and, depending on the caller,\n* additional context such as the query or mutation) and its result is returned, allowing the throwing\n* behavior to be decided per error. Otherwise, `throwOnError` itself is coerced to a boolean (`undefined`\n* resolves to `false`).\n* @param throwOnError - The `throwOnError` option: a boolean, a function that decides per error, or\n* `undefined`.\n* @param params - The arguments passed to `throwOnError` if it is a function.\n* @returns Whether the error should be thrown.\n* @example\n* ```ts\n* const throwOnError =\n* query.state.error && typeof options.throwOnError === 'function'\n* ? shouldThrowError(options.throwOnError, [query.state.error, query])\n* : options.throwOnError\n* ```\n*/\nfunction shouldThrowError(throwOnError, params) {\n\tif (typeof throwOnError === \"function\") return throwOnError(...params);\n\treturn !!throwOnError;\n}\nconst fetchSignal = Symbol();\n/**\n* Adds a lazy `signal` getter to an object, such as a query function context. The first time\n* `signal` is read, `onCancelled` is registered for the signal's `abort` event (or called right\n* away if it is already aborted), so cancellation is only tracked when the signal is actually used.\n* @param object - The object to add the `signal` property to.\n* @param getSignal - Returns the `AbortSignal`. Called once, when `signal` is first read.\n* @param onCancelled - Called when the signal is aborted, if `signal` was read.\n* @param internalSignal - The fetch signal to forward without consuming the getter.\n* @returns The same object, with the `signal` property added.\n*/\nfunction addConsumeAwareSignal(object, getSignal, onCancelled, internalSignal) {\n\tlet consumed = false;\n\tlet signal;\n\tObject.defineProperties(object, {\n\t\t[fetchSignal]: { value: internalSignal },\n\t\tsignal: {\n\t\t\tenumerable: true,\n\t\t\tget: () => {\n\t\t\t\tsignal ??= getSignal();\n\t\t\t\tif (consumed) return signal;\n\t\t\t\tconsumed = true;\n\t\t\t\tif (signal.aborted) onCancelled();\n\t\t\t\telse signal.addEventListener(\"abort\", onCancelled, { once: true });\n\t\t\t\treturn signal;\n\t\t\t}\n\t\t}\n\t});\n\treturn object;\n}\nexport { addConsumeAwareSignal, addToEnd, addToStart, ensureQueryFn, fetchSignal, functionalUpdate, hashKey, hashQueryKeyByOptions, isPlainArray, isPlainObject, isServer, isValidTimeout, keepPreviousData, matchMutation, matchQuery, noop, partialMatchKey, replaceData, replaceEqualDeep, resolveQueryValue, shallowEqualObjects, shouldThrowError, skipToken, sleep, timeUntilStale };\n\n//# sourceMappingURL=utils.js.map","import { isServer as isServer$1 } from \"./utils.js\";\n// src/environmentManager.ts\nlet isServerFn = () => isServer$1;\n/**\n* Returns whether the current runtime should be treated as a server environment.\n* @returns `true` if the runtime is treated as a server.\n*/\nconst isServer = () => isServerFn();\n/**\n* Manages how TanStack Query detects whether the current runtime should be treated as\n* server-side, which disables scheduling refetch timers and changes the default `retry` count\n* and `gcTime`. By default, the detection treats a missing `window` (or the presence of a\n* `Deno` global) as server.\n*\n* Override this for runtimes where that default detection would give the wrong answer — for\n* example, a Service Worker, where `window` is undefined even though the environment should\n* behave like a client.\n* @example\n* ```ts\n* import { environmentManager } from '@tanstack/query-core'\n*\n* environmentManager.setIsServer(() => false)\n* ```\n*/\nconst environmentManager = {\n\tisServer,\n\t/**\n\t* Overrides the server check globally.\n\t* @param isServerValue - A function that returns whether the runtime should be treated as a\n\t* server.\n\t*/\n\tsetIsServer(isServerValue) {\n\t\tisServerFn = isServerValue;\n\t}\n};\nexport { environmentManager, isServer };\n\n//# sourceMappingURL=environmentManager.js.map","// src/subscribable.ts\n/**\n* The base class behind everything in Query that you can subscribe to: `QueryCache`, `MutationCache`,\n* the observers, and the `FocusManager`/`OnlineManager` behind `focusManager` and `onlineManager`.\n* Subclasses decide what a listener receives and when it is called.\n*/\nvar Subscribable = class {\n\tconstructor() {\n\t\tthis.listeners = /* @__PURE__ */ new Set();\n\t\tthis.subscribe = this.subscribe.bind(this);\n\t}\n\t/**\n\t* Registers a listener to be called on every update this object notifies about. Returns a function\n\t* that removes the listener again — call it to stop listening. The base class never drops a listener\n\t* on its own, though some subclasses clear all of theirs in `destroy()`.\n\t* @param listener - Called on each update, with whatever the subclass passes to its subscribers.\n\t* @returns A function that removes the listener.\n\t* @example\n\t* ```ts\n\t* const unsubscribe = subscribable.subscribe(() => {\n\t* // react to the update\n\t* })\n\t*\n\t* unsubscribe()\n\t* ```\n\t*/\n\tsubscribe(listener) {\n\t\tthis.listeners.add(listener);\n\t\tthis.onSubscribe();\n\t\treturn () => {\n\t\t\tthis.listeners.delete(listener);\n\t\t\tthis.onUnsubscribe();\n\t\t};\n\t}\n\t/**\n\t* Returns `true` while at least one listener is registered, `false` once they have all unsubscribed.\n\t* @returns `true` if at least one listener is registered.\n\t*/\n\thasListeners() {\n\t\treturn this.listeners.size > 0;\n\t}\n\t/**\n\t* Called after a listener is added. Does nothing here; subclasses override it, e.g. to start\n\t* tracking what they observe once the first listener subscribes.\n\t*/\n\tonSubscribe() {}\n\t/**\n\t* Called after a listener is removed. Does nothing here; subclasses override it, e.g. to clean up\n\t* once the last listener unsubscribes.\n\t*/\n\tonUnsubscribe() {}\n};\nexport { Subscribable };\n\n//# sourceMappingURL=subscribable.js.map","import { Subscribable } from \"./subscribable.js\";\n// src/focusManager.ts\n/**\n* The `FocusManager` manages the focus state within TanStack Query.\n*\n* It can be used to change the default event listeners or to manually change the focus state.\n*/\nvar FocusManager = class extends Subscribable {\n\t#focused;\n\t#cleanup;\n\t#setup;\n\tconstructor() {\n\t\tsuper();\n\t\tthis.#setup = (onFocus) => {\n\t\t\tif (typeof window !== \"undefined\" && window.addEventListener) {\n\t\t\t\tconst listener = () => onFocus();\n\t\t\t\twindow.addEventListener(\"visibilitychange\", listener, false);\n\t\t\t\treturn () => {\n\t\t\t\t\twindow.removeEventListener(\"visibilitychange\", listener);\n\t\t\t\t};\n\t\t\t}\n\t\t};\n\t}\n\tonSubscribe() {\n\t\tif (!this.#cleanup) this.setEventListener(this.#setup);\n\t}\n\tonUnsubscribe() {\n\t\tif (!this.hasListeners()) {\n\t\t\tthis.#cleanup?.();\n\t\t\tthis.#cleanup = void 0;\n\t\t}\n\t}\n\t/**\n\t* `setEventListener` can be used to set a custom event listener that will\n\t* be used to determine the focus state. The provided `setup` function\n\t* receives a `setFocused` callback: call it with a `boolean` to manually\n\t* set the focus state, or with no arguments to re-evaluate the current\n\t* focus state and notify subscribers.\n\t* @param setup - Receives the `setFocused` callback, registers the event listener, and may return\n\t* a cleanup function that is called when the listener is replaced or no longer needed.\n\t* @example\n\t* ```ts\n\t* import { focusManager } from '@tanstack/query-core'\n\t*\n\t* focusManager.setEventListener((handleFocus) => {\n\t* const listener = () => handleFocus()\n\t* // Listen to visibilitychange\n\t* if (typeof window !== 'undefined' && window.addEventListener) {\n\t* window.addEventListener('visibilitychange', listener, false)\n\t* }\n\t*\n\t* return () => {\n\t* // Be sure to unsubscribe if a new handler is set\n\t* window.removeEventListener('visibilitychange', listener)\n\t* }\n\t* })\n\t* ```\n\t*/\n\tsetEventListener(setup) {\n\t\tthis.#setup = setup;\n\t\tthis.#cleanup?.();\n\t\tthis.#cleanup = setup((focused) => {\n\t\t\tif (typeof focused === \"boolean\") this.setFocused(focused);\n\t\t\telse this.onFocus();\n\t\t});\n\t}\n\t/**\n\t* `setFocused` can be used to manually set the focus state. Set `undefined`\n\t* to fall back to the default focus check.\n\t* @param focused - The focus state, or `undefined` to use the default focus check.\n\t* @example\n\t* ```ts\n\t* import { focusManager } from '@tanstack/query-core'\n\t*\n\t* // Set focused\n\t* focusManager.setFocused(true)\n\t*\n\t* // Set unfocused\n\t* focusManager.setFocused(false)\n\t*\n\t* // Fallback to the default focus check\n\t* focusManager.setFocused(undefined)\n\t* ```\n\t*/\n\tsetFocused(focused) {\n\t\tif (this.#focused !== focused) {\n\t\t\tthis.#focused = focused;\n\t\t\tthis.onFocus();\n\t\t}\n\t}\n\t/**\n\t* `onFocus` notifies all subscribed listeners with the current focus state.\n\t*/\n\tonFocus() {\n\t\tconst isFocused = this.isFocused();\n\t\tthis.listeners.forEach((listener) => {\n\t\t\tlistener(isFocused);\n\t\t});\n\t}\n\t/**\n\t* `isFocused` can be used to get the current focus state.\n\t* @returns The focus state set with `setFocused`, or otherwise whether the document is visible.\n\t*/\n\tisFocused() {\n\t\tif (typeof this.#focused === \"boolean\") return this.#focused;\n\t\treturn globalThis.document?.visibilityState !== \"hidden\";\n\t}\n};\n/**\n* Singleton instance of {@link FocusManager}, used to manage and observe the focus state within TanStack Query.\n*/\nconst focusManager = new FocusManager();\nexport { FocusManager, focusManager };\n\n//# sourceMappingURL=focusManager.js.map","import { systemSetTimeoutZero } from \"./timeoutManager.js\";\n// src/notifyManager.ts\n/**\n* Default scheduling function used by the notify manager.\n* Schedules the callback with the system's `setTimeout(callback, 0)`.\n*/\nconst defaultScheduler = systemSetTimeoutZero;\n/**\n* Creates a notify manager, which schedules and batches notifications to subscribers. Query uses a\n* single instance of it, exported as {@link notifyManager}.\n* @returns A new notify manager.\n*/\nfunction createNotifyManager() {\n\tlet queue = [];\n\tlet transactions = 0;\n\tlet notifyFn = (callback) => {\n\t\tcallback();\n\t};\n\tlet batchNotifyFn = (callback) => {\n\t\tcallback();\n\t};\n\tlet scheduleFn = defaultScheduler;\n\tconst schedule = (callback) => {\n\t\tif (transactions) queue.push(callback);\n\t\telse scheduleFn(() => {\n\t\t\tnotifyFn(callback);\n\t\t});\n\t};\n\tconst flush = () => {\n\t\tconst originalQueue = queue;\n\t\tqueue = [];\n\t\tif (originalQueue.length) scheduleFn(() => {\n\t\t\tbatchNotifyFn(() => {\n\t\t\t\toriginalQueue.forEach((callback) => {\n\t\t\t\t\tnotifyFn(callback);\n\t\t\t\t});\n\t\t\t});\n\t\t});\n\t};\n\treturn {\n\t\t/**\n\t\t* Batches all updates scheduled inside the passed callback.\n\t\t* This is mainly used internally to optimize query client updating.\n\t\t* Batches can be nested; the queue is only flushed once the outermost `batch` call finishes.\n\t\t* The return value of `callback` is passed through.\n\t\t* @param callback - The function to run in the batch.\n\t\t* @returns The return value of `callback`.\n\t\t*/\n\t\tbatch: (callback) => {\n\t\t\tlet result;\n\t\t\ttransactions++;\n\t\t\ttry {\n\t\t\t\tresult = callback();\n\t\t\t} finally {\n\t\t\t\ttransactions--;\n\t\t\t\tif (!transactions) flush();\n\t\t\t}\n\t\t\treturn result;\n\t\t},\n\t\t/**\n\t\t* All calls to the wrapped function will be batched.\n\t\t* @param callback - The function to wrap.\n\t\t* @returns A function that schedules a call to `callback` with the given arguments.\n\t\t*/\n\t\tbatchCalls: (callback) => {\n\t\t\treturn (...args) => {\n\t\t\t\tschedule(() => {\n\t\t\t\t\tcallback(...args);\n\t\t\t\t});\n\t\t\t};\n\t\t},\n\t\t/**\n\t\t* Schedules a function to be run on the next batch.\n\t\t* By default, the batch is run with a `setTimeout`, but this can be configured via `setScheduler`.\n\t\t*/\n\t\tschedule,\n\t\t/**\n\t\t* Use this method to set a custom notify function.\n\t\t* This can be used to for example wrap notifications with `React.act` while running tests.\n\t\t* @param fn - Receives each notification callback and must call it.\n\t\t*/\n\t\tsetNotifyFunction: (fn) => {\n\t\t\tnotifyFn = fn;\n\t\t},\n\t\t/**\n\t\t* Use this method to set a custom function to batch notifications together into a single tick.\n\t\t* Framework adapters use this to plug in their own batching primitive, so that a single query\n\t\t* update only triggers one re-render instead of one per subscriber.\n\t\t* @param fn - Receives a function that runs a batch of notifications and must call it.\n\t\t* @example\n\t\t* ```ts\n\t\t* import { notifyManager } from '@tanstack/query-core'\n\t\t* import { batch } from 'solid-js'\n\t\t*\n\t\t* notifyManager.setBatchNotifyFunction(batch)\n\t\t* ```\n\t\t*/\n\t\tsetBatchNotifyFunction: (fn) => {\n\t\t\tbatchNotifyFn = fn;\n\t\t},\n\t\t/**\n\t\t* Configures a custom callback that schedules when the next batch runs.\n\t\t* The default behavior is `setTimeout(callback, 0)`.\n\t\t* @param fn - Receives a callback that runs the next batch, and schedules it.\n\t\t* @example\n\t\t* ```ts\n\t\t* import { notifyManager } from '@tanstack/query-core'\n\t\t*\n\t\t* // Schedule batches in the next microtask\n\t\t* notifyManager.setScheduler(queueMicrotask)\n\t\t*\n\t\t* // Schedule batches before the next frame is rendered\n\t\t* notifyManager.setScheduler(requestAnimationFrame)\n\t\t*\n\t\t* // Schedule batches some time in the future\n\t\t* notifyManager.setScheduler((cb) => setTimeout(cb, 10))\n\t\t* ```\n\t\t*/\n\t\tsetScheduler: (fn) => {\n\t\t\tscheduleFn = fn;\n\t\t}\n\t};\n}\n/**\n* Handles scheduling and batching callbacks in TanStack Query.\n*/\nconst notifyManager = createNotifyManager();\nexport { createNotifyManager, defaultScheduler, notifyManager };\n\n//# sourceMappingURL=notifyManager.js.map","import { Subscribable } from \"./subscribable.js\";\n// src/onlineManager.ts\n/**\n* The `OnlineManager` manages the online state within TanStack Query. It can\n* be used to change the default event listeners or to manually change the\n* online state.\n*\n* By default, the `onlineManager` assumes an active network connection, and\n* listens to the `online` and `offline` events on the `window` object to\n* detect changes.\n*/\nvar OnlineManager = class extends Subscribable {\n\t#online = true;\n\t#cleanup;\n\t#setup;\n\tconstructor() {\n\t\tsuper();\n\t\tthis.#setup = (onOnline) => {\n\t\t\tif (typeof window !== \"undefined\" && window.addEventListener) {\n\t\t\t\tconst onlineListener = () => onOnline(true);\n\t\t\t\tconst offlineListener = () => onOnline(false);\n\t\t\t\twindow.addEventListener(\"online\", onlineListener, false);\n\t\t\t\twindow.addEventListener(\"offline\", offlineListener, false);\n\t\t\t\treturn () => {\n\t\t\t\t\twindow.removeEventListener(\"online\", onlineListener);\n\t\t\t\t\twindow.removeEventListener(\"offline\", offlineListener);\n\t\t\t\t};\n\t\t\t}\n\t\t};\n\t}\n\tonSubscribe() {\n\t\tif (!this.#cleanup) this.setEventListener(this.#setup);\n\t}\n\tonUnsubscribe() {\n\t\tif (!this.hasListeners()) {\n\t\t\tthis.#cleanup?.();\n\t\t\tthis.#cleanup = void 0;\n\t\t}\n\t}\n\t/**\n\t* `setEventListener` can be used to set a custom event listener that will\n\t* be used to determine the online state. The provided `setup` function\n\t* receives a `setOnline` callback that should be called with a `boolean`\n\t* whenever the online state changes.\n\t* @param setup - Receives the `setOnline` callback, registers the event listener, and may return\n\t* a cleanup function that is called when the listener is replaced or no longer needed.\n\t* @example\n\t* ```ts\n\t* import NetInfo from '@react-native-community/netinfo'\n\t* import { onlineManager } from '@tanstack/query-core'\n\t*\n\t* onlineManager.setEventListener((setOnline) => {\n\t* return NetInfo.addEventListener((state) => {\n\t* setOnline(!!state.isConnected)\n\t* })\n\t* })\n\t* ```\n\t*/\n\tsetEventListener(setup) {\n\t\tthis.#setup = setup;\n\t\tthis.#cleanup?.();\n\t\tthis.#cleanup = setup(this.setOnline.bind(this));\n\t}\n\t/**\n\t* `setOnline` can be used to manually set the online state.\n\t* @param online - The online state.\n\t* @example\n\t* ```ts\n\t* import { onlineManager } from '@tanstack/query-core'\n\t*\n\t* // Set to online\n\t* onlineManager.setOnline(true)\n\t*\n\t* // Set to offline\n\t* onlineManager.setOnline(false)\n\t* ```\n\t*/\n\tsetOnline(online) {\n\t\tif (this.#online !== online) {\n\t\t\tthis.#online = online;\n\t\t\tthis.listeners.forEach((listener) => {\n\t\t\t\tlistener(online);\n\t\t\t});\n\t\t}\n\t}\n\t/**\n\t* `isOnline` can be used to get the current online state.\n\t* @returns `true` if online.\n\t*/\n\tisOnline() {\n\t\treturn this.#online;\n\t}\n};\n/**\n* Singleton instance of {@link OnlineManager}, used to manage and observe the online state within TanStack Query.\n*/\nconst onlineManager = new OnlineManager();\nexport { OnlineManager, onlineManager };\n\n//# sourceMappingURL=onlineManager.js.map","import { noop, sleep } from \"./utils.js\";\nimport { isServer } from \"./environmentManager.js\";\nimport { focusManager } from \"./focusManager.js\";\nimport { onlineManager } from \"./onlineManager.js\";\n// src/retryer.ts\n/**\n* The default `retryDelay`: doubles with every failure, starting at 1 second, up to 30 seconds.\n* @param failureCount - The number of failures so far.\n* @returns The delay before the next retry, in milliseconds.\n*/\nfunction defaultRetryDelay(failureCount) {\n\treturn Math.min(1e3 * 2 ** failureCount, 3e4);\n}\n/**\n* Checks whether a fetch can run for the given network mode.\n* @param networkMode - The `networkMode` option. Defaults to `'online'`.\n* @returns `true` if the network mode is not `'online'`, or if it is and the client is online.\n*/\nfunction canFetch(networkMode) {\n\treturn (networkMode ?? \"online\") === \"online\" ? onlineManager.isOnline() : true;\n}\n/**\n* The error thrown by a `Retryer` (and surfaced to `query.promise`/`mutation`) when a fetch is cancelled, e.g. via\n* `query.cancel()`. `revert`, if `true`, tells the caller to restore the state the query was in before the fetch\n* started instead of surfacing the error. `silent`, if `true`, tells the caller to suppress this error and instead\n* resolve with the promise of the fetch that triggered the cancellation.\n* @example\n* ```ts\n* query.cancel()\n*\n* try {\n* await query.promise\n* } catch (error) {\n* if (error instanceof CancelledError) {\n* // the fetch was cancelled, e.g. via `query.cancel()`\n* }\n* }\n* ```\n*/\nvar CancelledError = class extends Error {\n\tconstructor(options) {\n\t\tsuper(\"CancelledError\");\n\t\tthis.revert = options?.revert;\n\t\tthis.silent = options?.silent;\n\t}\n};\n/**\n* Checks whether a value is a `CancelledError`.\n* @param value - The value to check.\n* @returns `true` if `value` is a `CancelledError`.\n* @deprecated Use instanceof `CancelledError` instead.\n*/\nfunction isCancelledError(value) {\n\treturn value instanceof CancelledError;\n}\n/**\n* Creates a retryer, which runs a function and retries it on failure according to the `retry` and\n* `retryDelay` options. It pauses while the network mode doesn't allow fetching or `canRun` returns\n* `false`, and can be cancelled. Queries and mutations use it to run their `queryFn` and\n* `mutationFn`.\n* @param config - The function to run, the retry options, and the callbacks for failures, pausing,\n* continuing, and cancellation.\n* @returns The retryer, whose `promise` settles with the result of the function.\n*/\nfunction createRetryer(config) {\n\tlet isRetryCancelled = false;\n\tlet failureCount = 0;\n\tlet continueFn;\n\tlet status = \"pending\";\n\tlet promiseResolve;\n\tlet promiseReject;\n\tconst promise = new Promise((resolve, reject) => {\n\t\tpromiseResolve = resolve;\n\t\tpromiseReject = reject;\n\t});\n\tpromise.catch(noop);\n\tconst isResolved = () => status !== \"pending\";\n\tconst cancel = (cancelOptions) => {\n\t\tif (!isResolved()) {\n\t\t\tconst error = new CancelledError(cancelOptions);\n\t\t\treject(error);\n\t\t\tconfig.onCancel?.(error);\n\t\t}\n\t};\n\tconst cancelRetry = () => {\n\t\tisRetryCancelled = true;\n\t};\n\tconst continueRetry = () => {\n\t\tisRetryCancelled = false;\n\t};\n\tconst canContinue = () => focusManager.isFocused() && (config.networkMode === \"always\" || onlineManager.isOnline()) && config.canRun();\n\tconst canStart = () => canFetch(config.networkMode) && config.canRun();\n\tconst resolve = (value) => {\n\t\tif (!isResolved()) {\n\t\t\tcontinueFn?.();\n\t\t\tstatus = \"resolved\";\n\t\t\tpromiseResolve(value);\n\t\t}\n\t};\n\tconst reject = (value) => {\n\t\tif (!isResolved()) {\n\t\t\tcontinueFn?.();\n\t\t\tstatus = \"rejected\";\n\t\t\tpromiseReject(value);\n\t\t}\n\t};\n\tconst pause = (canResume) => {\n\t\treturn new Promise((continueResolve) => {\n\t\t\tcontinueFn = (value) => {\n\t\t\t\tif (isResolved() || canResume()) continueResolve(value);\n\t\t\t};\n\t\t\tconfig.onPause?.();\n\t\t}).then(() => {\n\t\t\tcontinueFn = void 0;\n\t\t\tif (!isResolved()) config.onContinue?.();\n\t\t});\n\t};\n\tconst run = () => {\n\t\tif (isResolved()) return;\n\t\tlet promiseOrValue;\n\t\tconst initialPromise = failureCount === 0 ? config.initialPromise : void 0;\n\t\ttry {\n\t\t\tpromiseOrValue = initialPromise ?? config.fn();\n\t\t} catch (error) {\n\t\t\tpromiseOrValue = Promise.reject(error);\n\t\t}\n\t\tPromise.resolve(promiseOrValue).then(resolve).catch((error) => {\n\t\t\tif (isResolved()) return;\n\t\t\tconst retry = config.retry ?? (isServer() ? 0 : 3);\n\t\t\tconst retryDelay = config.retryDelay ?? defaultRetryDelay;\n\t\t\tconst delay = typeof retryDelay === \"function\" ? retryDelay(failureCount, error) : retryDelay;\n\t\t\tconst shouldRetry = retry === true || typeof retry === \"number\" && failureCount < retry || typeof retry === \"function\" && retry(failureCount, error);\n\t\t\tif (isRetryCancelled || !shouldRetry) {\n\t\t\t\treject(error);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tfailureCount++;\n\t\t\tconfig.onFail?.(failureCount, error);\n\t\t\tsleep(delay).then(() => {\n\t\t\t\treturn isResolved() || canContinue() ? void 0 : pause(canContinue);\n\t\t\t}).then(() => {\n\t\t\t\tif (isRetryCancelled) reject(error);\n\t\t\t\telse run();\n\t\t\t});\n\t\t});\n\t};\n\treturn {\n\t\tpromise,\n\t\tstatus: () => status,\n\t\tcancel,\n\t\tcontinue: () => {\n\t\t\tcontinueFn?.();\n\t\t\treturn promise;\n\t\t},\n\t\tcancelRetry,\n\t\tcontinueRetry,\n\t\tcanStart,\n\t\tstart: () => {\n\t\t\tif (canStart()) run();\n\t\t\telse pause(canStart).then(run);\n\t\t\treturn promise;\n\t\t}\n\t};\n}\nexport { CancelledError, canFetch, createRetryer, isCancelledError };\n\n//# sourceMappingURL=retryer.js.map","import { addConsumeAwareSignal, addToEnd, addToStart, ensureQueryFn, fetchSignal } from \"./utils.js\";\n// src/infiniteQueryBehavior.ts\n/**\n* Creates the behavior that fetches the pages of an infinite query: the next or previous page for\n* `fetchNextPage`/`fetchPreviousPage`, or all pages again from the start on a refetch.\n* @param pages - The number of pages to fetch from the start when all pages are fetched again,\n* e.g. from the `pages` option of `queryClient.infiniteQuery`. Defaults to the number of cached\n* pages.\n* @returns The query behavior to set on an infinite query.\n*/\nfunction infiniteQueryBehavior(pages) {\n\treturn { onFetch: (context, query) => {\n\t\tconst options = context.options;\n\t\tconst direction = context.fetchOptions?.meta?.fetchMore?.direction;\n\t\tconst oldPages = context.state.data?.pages || [];\n\t\tconst oldPageParams = context.state.data?.pageParams || [];\n\t\tlet result = {\n\t\t\tpages: [],\n\t\t\tpageParams: []\n\t\t};\n\t\tlet currentPage = 0;\n\t\tconst fetchFn = async () => {\n\t\t\tlet cancelled = false;\n\t\t\tconst signalContext = context;\n\t\t\tconst addSignalProperty = (object) => {\n\t\t\t\taddConsumeAwareSignal(object, () => context.signal, () => cancelled = true, signalContext[fetchSignal]);\n\t\t\t};\n\t\t\tconst queryFn = ensureQueryFn(context.options, context.fetchOptions);\n\t\t\tconst fetchPage = async (data, param, previous) => {\n\t\t\t\tif (cancelled) return Promise.reject(context.signal.reason);\n\t\t\t\tif (param == null && data.pages.length) return Promise.resolve(data);\n\t\t\t\tconst createQueryFnContext = () => {\n\t\t\t\t\tconst queryFnContext = {\n\t\t\t\t\t\tclient: context.client,\n\t\t\t\t\t\tqueryKey: context.queryKey,\n\t\t\t\t\t\tpageParam: param,\n\t\t\t\t\t\tdirection: previous ? \"backward\" : \"forward\",\n\t\t\t\t\t\tmeta: context.options.meta\n\t\t\t\t\t};\n\t\t\t\t\taddSignalProperty(queryFnContext);\n\t\t\t\t\treturn queryFnContext;\n\t\t\t\t};\n\t\t\t\tconst queryFnContext = createQueryFnContext();\n\t\t\t\tconst page = await queryFn(queryFnContext);\n\t\t\t\tconst { maxPages } = context.options;\n\t\t\t\tconst addTo = previous ? addToStart : addToEnd;\n\t\t\t\treturn {\n\t\t\t\t\tpages: addTo(data.pages, page, maxPages),\n\t\t\t\t\tpageParams: addTo(data.pageParams, param, maxPages)\n\t\t\t\t};\n\t\t\t};\n\t\t\tif (direction && oldPages.length) {\n\t\t\t\tconst previous = direction === \"backward\";\n\t\t\t\tconst pageParamFn = previous ? getPreviousPageParam : getNextPageParam;\n\t\t\t\tconst oldData = {\n\t\t\t\t\tpages: oldPages,\n\t\t\t\t\tpageParams: oldPageParams\n\t\t\t\t};\n\t\t\t\tresult = await fetchPage(oldData, pageParamFn(options, oldData), previous);\n\t\t\t} else {\n\t\t\t\tconst remainingPages = pages ?? oldPages.length;\n\t\t\t\tdo {\n\t\t\t\t\tconst param = currentPage === 0 ? oldPageParams[0] === void 0 ? options.initialPageParam : oldPageParams[0] : getNextPageParam(options, result);\n\t\t\t\t\tif (currentPage > 0 && param == null) break;\n\t\t\t\t\tresult = await fetchPage(result, param);\n\t\t\t\t\tcurrentPage++;\n\t\t\t\t} while (currentPage < remainingPages);\n\t\t\t}\n\t\t\treturn result;\n\t\t};\n\t\tif (context.options.persister) context.fetchFn = () => {\n\t\t\treturn context.options.persister?.(fetchFn, {\n\t\t\t\tclient: context.client,\n\t\t\t\tqueryKey: context.queryKey,\n\t\t\t\tmeta: context.options.meta,\n\t\t\t\tsignal: context.signal\n\t\t\t}, query);\n\t\t};\n\t\telse context.fetchFn = fetchFn;\n\t} };\n}\n/**\n* Computes the page param of the page after the last one, with the `getNextPageParam` option.\n* @param options - The infinite query options.\n* @param data - The current pages and page params.\n* @returns The next page param, or `undefined` if there are no pages yet.\n*/\nfunction getNextPageParam(options, { pages, pageParams }) {\n\tconst lastIndex = pages.length - 1;\n\treturn pages.length > 0 ? options.getNextPageParam(pages[lastIndex], pages, pageParams[lastIndex], pageParams) : void 0;\n}\n/**\n* Computes the page param of the page before the first one, with the `getPreviousPageParam`\n* option.\n* @param options - The infinite query options.\n* @param data - The current pages and page params.\n* @returns The previous page param, or `undefined` if there are no pages yet or no\n* `getPreviousPageParam` option.\n*/\nfunction getPreviousPageParam(options, { pages, pageParams }) {\n\treturn pages.length > 0 ? options.getPreviousPageParam?.(pages[0], pages, pageParams[0], pageParams) : void 0;\n}\n/**\n* Checks if there is a next page.\n* @param options - The infinite query options with `getNextPageParam`.\n* @param data - The current pages and page params.\n* @returns `true` if `getNextPageParam` returns a value other than `null` or `undefined`.\n*/\nfunction hasNextPage(options, data) {\n\tif (!data) return false;\n\treturn getNextPageParam(options, data) != null;\n}\n/**\n* Checks if there is a previous page.\n* @param options - The infinite query options with `getPreviousPageParam`.\n* @param data - The current pages and page params.\n* @returns `true` if `getPreviousPageParam` is set and returns a value other than `null` or\n* `undefined`.\n*/\nfunction hasPreviousPage(options, data) {\n\tif (!data || !options.getPreviousPageParam) return false;\n\treturn getPreviousPageParam(options, data) != null;\n}\nexport { hasNextPage, hasPreviousPage, infiniteQueryBehavior };\n\n//# sourceMappingURL=infiniteQueryBehavior.js.map","import { ensureQueryFn, fetchSignal, noop, replaceData, resolveQueryValue, skipToken, timeUntilStale } from \"./utils.js\";\nimport { notifyManager } from \"./notifyManager.js\";\nimport { CancelledError, canFetch, createRetryer } from \"./retryer.js\";\nimport { Removable } from \"./removable.js\";\nimport { infiniteQueryBehavior } from \"./infiniteQueryBehavior.js\";\n// src/query.ts\n/**\n* Represents a single cached query. A `Query` holds the query's key, options,\n* state (data/error/status), and the observers currently subscribed to it.\n*\n* Instances are created and managed internally by `QueryCache`; application\n* code typically interacts with queries indirectly through `QueryClient` or\n* a framework hook like `useQuery`. Direct access to a `Query` instance is\n* possible via `queryCache.find()`/`findAll()` for inspecting cache state.\n* @example\n* ```ts\n* const queryCache = queryClient.getQueryCache()\n* const query = queryCache.find({ queryKey: ['posts'] })\n*\n* if (query) {\n* console.log(query.state.dataUpdatedAt)\n* }\n* ```\n*/\nvar Query = class extends Removable {\n\t#queryType;\n\t#initialState;\n\t#revertState;\n\t#cache;\n\t#client;\n\t#retryer;\n\t#fetchPromise;\n\t#defaultOptions;\n\t#abortSignalConsumed;\n\tconstructor(config) {\n\t\tsuper();\n\t\tthis.#abortSignalConsumed = false;\n\t\tthis.#defaultOptions = config.defaultOptions;\n\t\tthis.setOptions(config.options);\n\t\tthis.observers = [];\n\t\tthis.#client = config.client;\n\t\tthis.#cache = this.#client.getQueryCache();\n\t\tthis.queryKey = config.queryKey;\n\t\tthis.queryHash = config.queryHash;\n\t\tthis.#initialState = getDefaultState(this.options);\n\t\tthis.state = config.state ?? this.#initialState;\n\t\tthis.scheduleGc();\n\t}\n\t/**\n\t* The `meta` object passed in the query's options, if any.\n\t* @returns The query's `meta`, or `undefined` if none was set.\n\t*/\n\tget meta() {\n\t\treturn this.options.meta;\n\t}\n\t/**\n\t* `'infinite'` for an infinite query, otherwise `undefined`.\n\t* @internal\n\t* @returns The type of the query, set from the `_type` option (e.g. `'infinite'`).\n\t*/\n\tget queryType() {\n\t\treturn this.#queryType;\n\t}\n\t/**\n\t* The promise for the currently in-flight fetch, if the query is fetching.\n\t* `undefined` when the query is not fetching.\n\t* @returns The promise of the in-flight fetch, or `undefined`.\n\t*/\n\tget promise() {\n\t\treturn this.#retryer?.promise;\n\t}\n\t/**\n\t* Replaces the query's options and applies their `gcTime`. If the query has no data yet, it gets\n\t* the `initialData` from the new options, if any.\n\t* @internal\n\t* @param options - The new query options, merged on top of the query's default options.\n\t*/\n\tsetOptions(options) {\n\t\tthis.options = {\n\t\t\t...this.#defaultOptions,\n\t\t\t...options\n\t\t};\n\t\tif (options?._type) this.#queryType = options._type;\n\t\tthis.updateGcTime(this.options.gcTime);\n\t\tif (this.state && this.state.data === void 0) {\n\t\t\tconst defaultState = getDefaultState(this.options);\n\t\t\tif (defaultState.data !== void 0) {\n\t\t\t\tthis.setState(successState(defaultState.data, defaultState.dataUpdatedAt));\n\t\t\t\tthis.#initialState = defaultState;\n\t\t\t}\n\t\t}\n\t}\n\toptionalRemove() {\n\t\tif (!this.observers.length && this.state.fetchStatus === \"idle\") this.#cache.remove(this);\n\t}\n\t/**\n\t* Writes new data to the query and marks it as successfully fetched.\n\t* @internal\n\t* @param newData - The data to write. Structural sharing with the current data is applied.\n\t* @param options - Set `updatedAt` to override the timestamp, and `manual` to mark the write as\n\t* manual (e.g. from `queryClient.setQueryData`).\n\t* @returns The data that was written.\n\t*/\n\tsetData(newData, options) {\n\t\tconst data = replaceData(this.state.data, newData, this.options);\n\t\tthis.#dispatch({\n\t\t\tdata,\n\t\t\ttype: \"success\",\n\t\t\tdataUpdatedAt: options?.updatedAt,\n\t\t\tmanual: options?.manual\n\t\t});\n\t\treturn data;\n\t}\n\t/**\n\t* Merges the given partial state directly into this query's state, notifying observers. Used\n\t* by persistence and broadcast plugins to restore a state snapshot, and by devtools to let a\n\t* user manually trigger a loading/error state or edit the cached data.\n\t* @param state - The partial state to merge into the query's state.\n\t*/\n\tsetState(state) {\n\t\tthis.#dispatch({\n\t\t\ttype: \"setState\",\n\t\t\tstate\n\t\t});\n\t}\n\t/**\n\t* Cancels the query's currently in-flight fetch, if any.\n\t* - Returns a promise that resolves once the cancellation has settled.\n\t* - If no fetch is in progress, resolves immediately.\n\t* @param options - Set `revert` to restore the state from before the fetch started, and `silent`\n\t* to suppress the cancellation error when a new fetch replaces the cancelled one.\n\t* @returns A promise that resolves once the cancellation has settled.\n\t* @example\n\t* ```ts\n\t* await query.cancel()\n\t* ```\n\t*/\n\tcancel(options) {\n\t\tconst promise = this.#retryer?.promise;\n\t\tthis.#retryer?.cancel(options);\n\t\treturn promise ? promise.then(noop).catch(noop) : Promise.resolve();\n\t}\n\t/**\n\t* Clears the query's garbage collection timeout and silently cancels any\n\t* in-flight fetch. Called by `QueryCache` when the query is removed from\n\t* the cache.\n\t* @see {@link Query#cancel}\n\t*/\n\tdestroy() {\n\t\tsuper.destroy();\n\t\tthis.cancel({ silent: true });\n\t}\n\t/**\n\t* The state the query was created with.\n\t* @internal\n\t* @returns The state the query had when it was first created, used by {@link Query#reset}.\n\t*/\n\tget resetState() {\n\t\treturn this.#initialState;\n\t}\n\t/**\n\t* Resets the query back to its initial state (the state it had when it was\n\t* first created, e.g. any `initialData`), destroying it first to cancel any\n\t* in-flight fetch.\n\t*/\n\treset() {\n\t\tthis.destroy();\n\t\tthis.setState(this.resetState);\n\t}\n\t/**\n\t* Returns `true` if the query has at least one observer for which `enabled`\n\t* does not resolve to `false`.\n\t* @returns `true` if the query has an enabled observer.\n\t*/\n\tisActive() {\n\t\treturn this.observers.some((observer) => resolveQueryValue(observer.options.enabled, this) !== false);\n\t}\n\t/**\n\t* Returns `true` if the query is disabled, meaning it will not fetch\n\t* automatically.\n\t* - If the query has observers, it is disabled when none of them are active\n\t* (see `isActive`).\n\t* - If the query has no observers, it is disabled when its `queryFn` is\n\t* `skipToken` or it has never been fetched.\n\t* @returns `true` if the query is disabled.\n\t*/\n\tisDisabled() {\n\t\tif (this.getObserversCount() > 0) return !this.isActive();\n\t\treturn this.options.queryFn === skipToken || !this.isFetched();\n\t}\n\t/**\n\t* Returns `true` if the query has been fetched, i.e. it has resolved with\n\t* either data or an error at least once.\n\t* @returns `true` if the query has been fetched.\n\t*/\n\tisFetched() {\n\t\treturn this.state.dataUpdateCount + this.state.errorUpdateCount > 0;\n\t}\n\t/**\n\t* Returns `true` if the query has data and at least one observer configured with\n\t* `staleTime: 'static'`, meaning it is treated as never stale.\n\t* @returns `true` if the query is static.\n\t*/\n\tisStatic() {\n\t\tif (this.state.data === void 0) return false;\n\t\tif (this.getObserversCount() > 0) return this.observers.some((observer) => resolveQueryValue(observer.options.staleTime, this) === \"static\");\n\t\treturn false;\n\t}\n\t/**\n\t* Returns `true` if the query is stale.\n\t* - If the query has observers, defers to whether any observer's current\n\t* result reports `isStale` (which accounts for each observer's own\n\t* `staleTime` and `enabled` state).\n\t* - If the query has no observers, it is considered stale when it has no\n\t* data or has been invalidated.\n\t* @returns `true` if the query is stale.\n\t* @see {@link Query#isStaleByTime}\n\t* @example\n\t* ```ts\n\t* if (query.isStale()) {\n\t* // refetch or otherwise treat the cached data as outdated\n\t* }\n\t* ```\n\t*/\n\tisStale() {\n\t\tif (this.getObserversCount() > 0) return this.observers.some((observer) => observer.getCurrentResult().isStale);\n\t\treturn this.state.data === void 0 || this.state.isInvalidated;\n\t}\n\t/**\n\t* Returns `true` if the query's data is stale relative to the given\n\t* `staleTime` (defaults to `0`).\n\t* - A query with no data is always stale.\n\t* - `staleTime: 'static'` is never stale.\n\t* - An invalidated query is always stale.\n\t* - Otherwise, staleness is based on elapsed time since `dataUpdatedAt`.\n\t* @param staleTime - The time, in milliseconds, after which data is considered stale, or\n\t* `'static'` to never treat existing data as stale. A query without data is stale either way.\n\t* @returns `true` if the query's data is stale.\n\t* @see {@link Query#isStale}\n\t* @example\n\t* ```ts\n\t* const isStale = query.isStaleByTime(60 * 1000)\n\t* ```\n\t*/\n\tisStaleByTime(staleTime = 0) {\n\t\tif (this.state.data === void 0) return true;\n\t\tif (staleTime === \"static\") return false;\n\t\tif (this.state.isInvalidated) return true;\n\t\treturn !timeUntilStale(this.state.dataUpdatedAt, staleTime);\n\t}\n\t/**\n\t* Refetches the query when the window regains focus, if an observer wants that, and continues a\n\t* paused fetch.\n\t* @internal\n\t*/\n\tonFocus() {\n\t\tthis.observers.find((x) => x.shouldFetchOnWindowFocus())?.refetch({ cancelRefetch: false });\n\t\tthis.#retryer?.continue();\n\t}\n\t/**\n\t* Refetches the query when the app reconnects, if an observer wants that, and continues a paused\n\t* fetch.\n\t* @internal\n\t*/\n\tonOnline() {\n\t\tthis.observers.find((x) => x.shouldFetchOnReconnect())?.refetch({ cancelRefetch: false });\n\t\tthis.#retryer?.continue();\n\t}\n\t/**\n\t* Subscribes an observer to the query and stops its garbage collection.\n\t* @internal\n\t* @param observer - The observer to add. Adding an observer that is already subscribed does\n\t* nothing.\n\t*/\n\taddObserver(observer) {\n\t\tif (!this.observers.includes(observer)) {\n\t\t\tthis.observers.push(observer);\n\t\t\tthis.clearGcTimeout();\n\t\t\tthis.#cache.notify({\n\t\t\t\ttype: \"observerAdded\",\n\t\t\t\tquery: this,\n\t\t\t\tobserver\n\t\t\t});\n\t\t}\n\t}\n\t/**\n\t* Unsubscribes an observer from the query.\n\t* @internal\n\t* @param observer - The observer to remove. When the last observer is removed, the in-flight\n\t* fetch is cancelled if its abort signal was consumed (otherwise only its retries are stopped),\n\t* and garbage collection is scheduled.\n\t*/\n\tremoveObserver(observer) {\n\t\tconst index = this.observers.indexOf(observer);\n\t\tif (index !== -1) {\n\t\t\tthis.observers.splice(index, 1);\n\t\t\tif (!this.observers.length) {\n\t\t\t\tif (this.#retryer) {\n\t\t\t\t\tif (this.#abortSignalConsumed || this.state.fetchStatus === \"paused\" && this.state.status === \"pending\") this.#retryer.cancel({ revert: true });\n\t\t\t\t\telse this.#retryer.cancelRetry();\n\t\t\t\t}\n\t\t\t\tthis.scheduleGc();\n\t\t\t}\n\t\t\tthis.#cache.notify({\n\t\t\t\ttype: \"observerRemoved\",\n\t\t\t\tquery: this,\n\t\t\t\tobserver\n\t\t\t});\n\t\t}\n\t}\n\t/**\n\t* Returns the number of observers currently subscribed to this query.\n\t* @returns The number of observers.\n\t* @example\n\t* ```ts\n\t* if (query.getObserversCount() === 0) {\n\t* // no component is currently watching this query\n\t* }\n\t* ```\n\t*/\n\tgetObserversCount() {\n\t\treturn this.observers.length;\n\t}\n\t/**\n\t* Marks the query as invalidated, unless it is already invalidated. This\n\t* updates `state.isInvalidated` and notifies observers, but does not by\n\t* itself trigger a refetch.\n\t* @example\n\t* ```ts\n\t* query.invalidate()\n\t* ```\n\t*/\n\tinvalidate() {\n\t\tif (!this.state.isInvalidated) this.#dispatch({ type: \"invalidate\" });\n\t}\n\t/**\n\t* Fetches the query, i.e. runs its `queryFn` (through any configured\n\t* retryer/behavior) and updates the query's state with the result.\n\t* - If a fetch is already in flight, returns its promise instead of\n\t* starting a new one, unless `fetchOptions.cancelRefetch` is set and the\n\t* query already has data, in which case the current fetch is silently\n\t* cancelled first.\n\t* - If `options` is passed, it replaces the query's current options\n\t* before fetching.\n\t* @param options - Query options that replace the query's current options before fetching. They\n\t* are not applied when an in-flight fetch is reused.\n\t* @param fetchOptions - Set `cancelRefetch` to cancel an in-flight fetch first (only if the query\n\t* already has data), and `meta` to pass extra information to the query's behavior.\n\t* @returns A promise that resolves with the fetched data, or rejects with the fetch error. If the\n\t* fetch is cancelled with `revert` while the query has data, it resolves with the restored data\n\t* instead.\n\t*/\n\tasync fetch(options, fetchOptions) {\n\t\tif (this.state.fetchStatus !== \"idle\" && this.#retryer?.status() !== \"rejected\") {\n\t\t\tif (this.state.data !== void 0 && fetchOptions?.cancelRefetch) this.cancel({ silent: true });\n\t\t\telse if (this.#retryer && this.#fetchPromise) {\n\t\t\t\tthis.#retryer.continueRetry();\n\t\t\t\treturn this.#fetchPromise;\n\t\t\t}\n\t\t}\n\t\tif (options) this.setOptions(options);\n\t\tif (!this.options.queryFn) {\n\t\t\tconst observer = this.observers.find((x) => x.options.queryFn);\n\t\t\tif (observer) this.setOptions(observer.options);\n\t\t}\n\t\tif (process.env.NODE_ENV !== \"production\") {\n\t\t\tif (!Array.isArray(this.options.queryKey)) console.error(`As of v4, queryKey needs to be an Array. If you are using a string like 'repoData', please change it to an Array, e.g. ['repoData']`);\n\t\t}\n\t\tconst abortController = new AbortController();\n\t\tconst addSignalProperty = (object) => {\n\t\t\tObject.defineProperties(object, {\n\t\t\t\t[fetchSignal]: {\n\t\t\t\t\tvalue: abortController.signal,\n\t\t\t\t\tenumerable: true\n\t\t\t\t},\n\t\t\t\tsignal: {\n\t\t\t\t\tenumerable: true,\n\t\t\t\t\tget: () => {\n\t\t\t\t\t\tthis.#abortSignalConsumed = true;\n\t\t\t\t\t\treturn abortController.signal;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\t\t};\n\t\tconst fetchFn = () => {\n\t\t\tconst queryFn = ensureQueryFn(this.options, fetchOptions);\n\t\t\tconst createQueryFnContext = () => {\n\t\t\t\tconst queryFnContext = {\n\t\t\t\t\tclient: this.#client,\n\t\t\t\t\tqueryKey: this.queryKey,\n\t\t\t\t\tmeta: this.meta\n\t\t\t\t};\n\t\t\t\taddSignalProperty(queryFnContext);\n\t\t\t\treturn queryFnContext;\n\t\t\t};\n\t\t\tconst queryFnContext = createQueryFnContext();\n\t\t\tthis.#abortSignalConsumed = false;\n\t\t\tif (this.options.persister) return this.options.persister(queryFn, queryFnContext, this);\n\t\t\treturn queryFn(queryFnContext);\n\t\t};\n\t\tconst createFetchContext = () => {\n\t\t\tconst context = {\n\t\t\t\tfetchOptions,\n\t\t\t\toptions: this.options,\n\t\t\t\tqueryKey: this.queryKey,\n\t\t\t\tclient: this.#client,\n\t\t\t\tstate: this.state,\n\t\t\t\tfetchFn\n\t\t\t};\n\t\t\taddSignalProperty(context);\n\t\t\treturn context;\n\t\t};\n\t\tconst context = createFetchContext();\n\t\t(this.#queryType === \"infinite\" ? infiniteQueryBehavior(this.options.pages) : this.options.behavior)?.onFetch(context, this);\n\t\tthis.#revertState = this.state;\n\t\tif (this.state.fetchStatus === \"idle\" || this.state.fetchMeta !== context.fetchOptions?.meta) this.#dispatch({\n\t\t\ttype: \"fetch\",\n\t\t\tmeta: context.fetchOptions?.meta\n\t\t});\n\t\tconst retryer = this.#retryer = createRetryer({\n\t\t\tinitialPromise: fetchOptions?.initialPromise,\n\t\t\tfn: context.fetchFn,\n\t\t\tonCancel: (error) => {\n\t\t\t\tif (error instanceof CancelledError && error.revert) this.setState({\n\t\t\t\t\t...this.#revertState,\n\t\t\t\t\tfetchStatus: \"idle\"\n\t\t\t\t});\n\t\t\t\tabortController.abort();\n\t\t\t},\n\t\t\tonFail: (failureCount, error) => {\n\t\t\t\tthis.#dispatch({\n\t\t\t\t\ttype: \"failed\",\n\t\t\t\t\tfailureCount,\n\t\t\t\t\terror\n\t\t\t\t});\n\t\t\t},\n\t\t\tonPause: () => {\n\t\t\t\tthis.#dispatch({ type: \"pause\" });\n\t\t\t},\n\t\t\tonContinue: () => {\n\t\t\t\tthis.#dispatch({ type: \"continue\" });\n\t\t\t},\n\t\t\tretry: context.options.retry,\n\t\t\tretryDelay: context.options.retryDelay,\n\t\t\tnetworkMode: context.options.networkMode,\n\t\t\tcanRun: () => true\n\t\t});\n\t\tconst fetchPromise = (async () => {\n\t\t\ttry {\n\t\t\t\tconst data = await retryer.promise;\n\t\t\t\tif (data === void 0) {\n\t\t\t\t\tif (process.env.NODE_ENV !== \"production\") console.error(`Query data cannot be undefined. Please make sure to return a value other than undefined from your query function. Affected query key: ${this.queryHash}`);\n\t\t\t\t\tthrow new Error(`${this.queryHash} data is undefined`);\n\t\t\t\t}\n\t\t\t\tthis.setData(data);\n\t\t\t\tthis.#cache.config.onSuccess?.(data, this);\n\t\t\t\tthis.#cache.config.onSettled?.(data, this.state.error, this);\n\t\t\t\treturn data;\n\t\t\t} catch (error) {\n\t\t\t\tif (error instanceof CancelledError) {\n\t\t\t\t\tif (error.silent) {\n\t\t\t\t\t\tif (this.#retryer !== retryer && this.#fetchPromise) return this.#fetchPromise;\n\t\t\t\t\t\tthrow error;\n\t\t\t\t\t} else if (error.revert) {\n\t\t\t\t\t\tif (this.state.data === void 0) throw error;\n\t\t\t\t\t\treturn this.state.data;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tthis.#dispatch({\n\t\t\t\t\ttype: \"error\",\n\t\t\t\t\terror\n\t\t\t\t});\n\t\t\t\tthis.#cache.config.onError?.(error, this);\n\t\t\t\tthis.#cache.config.onSettled?.(this.state.data, error, this);\n\t\t\t\tthrow error;\n\t\t\t} finally {\n\t\t\t\tif (this.#retryer === retryer) {\n\t\t\t\t\tthis.#retryer = void 0;\n\t\t\t\t\tthis.#fetchPromise = void 0;\n\t\t\t\t}\n\t\t\t\tthis.scheduleGc();\n\t\t\t}\n\t\t})();\n\t\tthis.#fetchPromise = fetchPromise;\n\t\tretryer.start();\n\t\treturn fetchPromise;\n\t}\n\t#dispatch(action) {\n\t\tconst reducer = (state) => {\n\t\t\tswitch (action.type) {\n\t\t\t\tcase \"failed\": return {\n\t\t\t\t\t...state,\n\t\t\t\t\tfetchFailureCount: action.failureCount,\n\t\t\t\t\tfetchFailureReason: action.error\n\t\t\t\t};\n\t\t\t\tcase \"pause\": return {\n\t\t\t\t\t...state,\n\t\t\t\t\tfetchStatus: \"paused\"\n\t\t\t\t};\n\t\t\t\tcase \"continue\": return {\n\t\t\t\t\t...state,\n\t\t\t\t\tfetchStatus: \"fetching\"\n\t\t\t\t};\n\t\t\t\tcase \"fetch\": return {\n\t\t\t\t\t...state,\n\t\t\t\t\t...fetchState(state.data, this.options),\n\t\t\t\t\tfetchMeta: action.meta ?? null\n\t\t\t\t};\n\t\t\t\tcase \"success\":\n\t\t\t\t\tconst newState = {\n\t\t\t\t\t\t...state,\n\t\t\t\t\t\t...successState(action.data, action.dataUpdatedAt),\n\t\t\t\t\t\tdataUpdateCount: state.dataUpdateCount + 1,\n\t\t\t\t\t\t...!action.manual && {\n\t\t\t\t\t\t\tfetchStatus: \"idle\",\n\t\t\t\t\t\t\tfetchFailureCount: 0,\n\t\t\t\t\t\t\tfetchFailureReason: null\n\t\t\t\t\t\t}\n\t\t\t\t\t};\n\t\t\t\t\tthis.#revertState = action.manual ? newState : void 0;\n\t\t\t\t\treturn newState;\n\t\t\t\tcase \"error\":\n\t\t\t\t\tconst error = action.error;\n\t\t\t\t\treturn {\n\t\t\t\t\t\t...state,\n\t\t\t\t\t\terror,\n\t\t\t\t\t\terrorUpdateCount: state.errorUpdateCount + 1,\n\t\t\t\t\t\terrorUpdatedAt: Date.now(),\n\t\t\t\t\t\tfetchFailureCount: state.fetchFailureCount + 1,\n\t\t\t\t\t\tfetchFailureReason: error,\n\t\t\t\t\t\tfetchStatus: \"idle\",\n\t\t\t\t\t\tstatus: \"error\",\n\t\t\t\t\t\tisInvalidated: true\n\t\t\t\t\t};\n\t\t\t\tcase \"invalidate\": return {\n\t\t\t\t\t...state,\n\t\t\t\t\tisInvalidated: true\n\t\t\t\t};\n\t\t\t\tcase \"setState\": return {\n\t\t\t\t\t...state,\n\t\t\t\t\t...action.state\n\t\t\t\t};\n\t\t\t}\n\t\t};\n\t\tthis.state = reducer(this.state);\n\t\tnotifyManager.batch(() => {\n\t\t\tthis.observers.slice().forEach((observer) => {\n\t\t\t\tobserver.onQueryUpdate();\n\t\t\t});\n\t\t\tthis.#cache.notify({\n\t\t\t\tquery: this,\n\t\t\t\ttype: \"updated\",\n\t\t\t\taction\n\t\t\t});\n\t\t});\n\t}\n};\n/**\n* Returns the state changes applied when a query starts fetching.\n* @param data - The query's current data. If it is `undefined`, the query is also reset to\n* `'pending'` with no error.\n* @param options - The query options, whose `networkMode` decides whether the query is `'fetching'`\n* or `'paused'`.\n* @returns The partial query state for a starting fetch.\n*/\nfunction fetchState(data, options) {\n\treturn {\n\t\tfetchFailureCount: 0,\n\t\tfetchFailureReason: null,\n\t\tfetchStatus: canFetch(options.networkMode) ? \"fetching\" : \"paused\",\n\t\t...data === void 0 && {\n\t\t\terror: null,\n\t\t\tstatus: \"pending\"\n\t\t}\n\t};\n}\n/**\n* Returns the state changes applied when a query receives data.\n* @param data - The new data.\n* @param dataUpdatedAt - The timestamp the data is recorded with. Defaults to the current time.\n* @returns The partial query state for a successful update.\n*/\nfunction successState(data, dataUpdatedAt) {\n\treturn {\n\t\tdata,\n\t\tdataUpdatedAt: dataUpdatedAt ?? Date.now(),\n\t\terror: null,\n\t\tisInvalidated: false,\n\t\tstatus: \"success\"\n\t};\n}\n/**\n* Returns the initial state of a query, based on its `initialData` and `initialDataUpdatedAt`\n* options.\n* @param options - The query options.\n* @returns The initial query state: `'success'` if `initialData` is set, otherwise `'pending'`.\n*/\nfunction getDefaultState(options) {\n\tconst data = typeof options.initialData === \"function\" ? options.initialData() : options.initialData;\n\tconst hasData = data !== void 0;\n\tconst initialDataUpdatedAt = hasData ? typeof options.initialDataUpdatedAt === \"function\" ? options.initialDataUpdatedAt() : options.initialDataUpdatedAt : 0;\n\treturn {\n\t\tdata,\n\t\tdataUpdateCount: 0,\n\t\tdataUpdatedAt: hasData ? initialDataUpdatedAt ?? Date.now() : 0,\n\t\terror: null,\n\t\terrorUpdateCount: 0,\n\t\terrorUpdatedAt: 0,\n\t\tfetchFailureCount: 0,\n\t\tfetchFailureReason: null,\n\t\tfetchMeta: null,\n\t\tisInvalidated: false,\n\t\tstatus: hasData ? \"success\" : \"pending\",\n\t\tfetchStatus: \"idle\"\n\t};\n}\nexport { Query, fetchState };\n\n//# sourceMappingURL=query.js.map","import { timeoutManager } from \"./timeoutManager.js\";\nimport { isValidTimeout, noop, replaceData, resolveQueryValue, shallowEqualObjects, timeUntilStale } from \"./utils.js\";\nimport { isServer } from \"./environmentManager.js\";\nimport { Subscribable } from \"./subscribable.js\";\nimport { focusManager } from \"./focusManager.js\";\nimport { notifyManager } from \"./notifyManager.js\";\nimport { fetchState } from \"./query.js\";\n// src/queryObserver.ts\n/**\n* A `QueryObserver` watches a single query in the `QueryCache` and computes a\n* `QueryObserverResult` from its state, recomputing and notifying subscribers\n* whenever the underlying query (or the observer's options) changes. It is\n* the primitive that framework adapters (e.g. `useQuery`) build their hooks\n* on top of, but it can also be used directly to observe and switch between\n* queries outside of any framework.\n* @example\n* ```ts\n* const observer = new QueryObserver(queryClient, {\n* queryKey: ['posts'],\n* queryFn: fetchPosts,\n* })\n*\n* const unsubscribe = observer.subscribe((result) => {\n* console.log(result.data)\n* })\n* ```\n*/\nvar QueryObserver = class extends Subscribable {\n\t#client;\n\t#currentQuery = void 0;\n\t#currentQueryInitialState = void 0;\n\t#currentResult = void 0;\n\t#currentResultState;\n\t#currentResultOptions;\n\t#selectError;\n\t#selectFn;\n\t#selectResult;\n\t#lastQueryWithDefinedData;\n\t#staleTimeoutId;\n\t#refetchIntervalId;\n\t#currentRefetchInterval;\n\t#trackedProps = /* @__PURE__ */ new Set();\n\tconstructor(client, options) {\n\t\tsuper();\n\t\tthis.options = options;\n\t\tthis.#client = client;\n\t\tthis.#selectError = null;\n\t\tthis.bindMethods();\n\t\tthis.setOptions(options);\n\t}\n\t/**\n\t* Binds the methods of the result (`refetch`) to the observer, so they keep working when destructured\n\t* from it. Subclasses override it to bind their own result methods as well.\n\t*/\n\tbindMethods() {\n\t\tthis.refetch = this.refetch.bind(this);\n\t}\n\tonSubscribe() {\n\t\tif (this.listeners.size === 1) {\n\t\t\tthis.#currentQuery.addObserver(this);\n\t\t\tif (shouldFetchOnMount(this.#currentQuery, this.options)) this.#executeFetch();\n\t\t\telse this.updateResult();\n\t\t\tthis.#updateTimers();\n\t\t}\n\t}\n\tonUnsubscribe() {\n\t\tif (!this.hasListeners()) this.destroy();\n\t}\n\t/**\n\t* Returns whether the observed query is currently stale and configured\n\t* (via the `refetchOnReconnect` option) to refetch when the network\n\t* reconnects.\n\t* @returns `true` if the observer should refetch the query on reconnect.\n\t*/\n\tshouldFetchOnReconnect() {\n\t\treturn shouldFetchOn(this.#currentQuery, this.options, this.options.refetchOnReconnect);\n\t}\n\t/**\n\t* Returns whether the observed query is currently stale and configured\n\t* (via the `refetchOnWindowFocus` option) to refetch when the window\n\t* regains focus.\n\t* @returns `true` if the observer should refetch the query on window focus.\n\t*/\n\tshouldFetchOnWindowFocus() {\n\t\treturn shouldFetchOn(this.#currentQuery, this.options, this.options.refetchOnWindowFocus);\n\t}\n\t/**\n\t* Stops observing the current query: clears all listeners, cancels the\n\t* stale and refetch-interval timers, and removes this observer from the\n\t* query it was observing.\n\t*/\n\tdestroy() {\n\t\tthis.listeners = /* @__PURE__ */ new Set();\n\t\tthis.#clearStaleTimeout();\n\t\tthis.#clearRefetchInterval();\n\t\tthis.#currentQuery.removeObserver(this);\n\t}\n\t/**\n\t* Updates the observer's options. This will re-resolve the query being\n\t* observed (switching to a different query if the `queryKey` changed),\n\t* trigger a fetch if the new options require one and the observer has\n\t* subscribers, recompute the current result, and reschedule the stale and\n\t* refetch-interval timers as needed.\n\t* @param options - The new observer options. They are defaulted with {@link\n\t* QueryClient#defaultQueryOptions} before being applied.\n\t* @throws {Error} If `enabled` is neither a boolean nor a function.\n\t* @example\n\t* ```ts\n\t* observer.setOptions({ queryKey: ['posts', 1], queryFn: () => fetchPost(1) })\n\t* // later: switch to a different query, reusing the same observer\n\t* observer.setOptions({ queryKey: ['posts', 2], queryFn: () => fetchPost(2) })\n\t* ```\n\t*/\n\tsetOptions(options) {\n\t\tconst prevOptions = this.options;\n\t\tconst prevQuery = this.#currentQuery;\n\t\tthis.options = this.#client.defaultQueryOptions(options);\n\t\tif (this.options.enabled !== void 0 && typeof this.options.enabled !== \"boolean\" && typeof this.options.enabled !== \"function\" && typeof resolveQueryValue(this.options.enabled, this.#currentQuery) !== \"boolean\") throw new Error(\"Expected enabled to be a boolean or a callback that returns a boolean\");\n\t\tthis.#updateQuery();\n\t\tthis.#currentQuery.setOptions(this.options);\n\t\tif (prevOptions._defaulted && !shallowEqualObjects(this.options, prevOptions)) this.#client.getQueryCache().notify({\n\t\t\ttype: \"observerOptionsUpdated\",\n\t\t\tquery: this.#currentQuery,\n\t\t\tobserver: this\n\t\t});\n\t\tconst mounted = this.hasListeners();\n\t\tif (mounted && shouldFetchOptionally(this.#currentQuery, prevQuery, this.options, prevOptions)) this.#executeFetch();\n\t\tthis.updateResult();\n\t\tif (mounted && (this.#currentQuery !== prevQuery || resolveQueryValue(this.options.enabled, this.#currentQuery) !== resolveQueryValue(prevOptions.enabled, this.#currentQuery) || resolveQueryValue(this.options.staleTime, this.#currentQuery) !== resolveQueryValue(prevOptions.staleTime, this.#currentQuery))) this.#updateStaleTimeout();\n\t\tconst nextRefetchInterval = this.#computeRefetchInterval();\n\t\tif (mounted && (this.#currentQuery !== prevQuery || resolveQueryValue(this.options.enabled, this.#currentQuery) !== resolveQueryValue(prevOptions.enabled, this.#currentQuery) || nextRefetchInterval !== this.#currentRefetchInterval)) this.#updateRefetchInterval(nextRefetchInterval);\n\t}\n\t/**\n\t* Computes the result the observer would produce for the given (already-defaulted) options\n\t* right now, building the underlying `Query` if it doesn't exist yet, without waiting for a\n\t* subscription callback. Called by framework adapters on every render (e.g. `useQuery`) so the\n\t* returned value is available synchronously, ahead of `setOptions` triggering an actual fetch.\n\t* @param options - The defaulted observer options to compute the result for.\n\t* @returns The result for the given options.\n\t*/\n\tgetOptimisticResult(options) {\n\t\tconst query = this.#client.getQueryCache().build(this.#client, options);\n\t\tconst result = this.createResult(query, options);\n\t\tif (!shallowEqualObjects(this.getCurrentResult(), result)) {\n\t\t\tthis.#currentResult = result;\n\t\t\tthis.#currentResultOptions = this.options;\n\t\t\tthis.#currentResultState = this.#currentQuery.state;\n\t\t}\n\t\treturn result;\n\t}\n\t/**\n\t* Returns the most recently computed `QueryObserverResult` for the\n\t* observed query. This is a point-in-time read; to be notified of updates\n\t* as they happen, subscribe to the observer instead (its inherited\n\t* `subscribe` method).\n\t* @returns The observer's latest result.\n\t* @example\n\t* ```ts\n\t* const result = observer.getCurrentResult()\n\t* console.log(result.status, result.data)\n\t* ```\n\t*/\n\tgetCurrentResult() {\n\t\treturn this.#currentResult;\n\t}\n\t/**\n\t* Wraps a `QueryObserverResult` in a `Proxy` that records which properties are read, via\n\t* {@link QueryObserver#trackProp} (and an optional `onPropTracked` callback). Used by framework\n\t* adapters when `notifyOnChangeProps` is not set, to implement its default \"only re-render on\n\t* properties you actually read\" behavior.\n\t* @param result - The result to wrap.\n\t* @param onPropTracked - Called with the name of each property that is read.\n\t* @returns A proxy of `result` that tracks property reads.\n\t*/\n\ttrackResult(result, onPropTracked) {\n\t\treturn new Proxy(result, { get: (target, key) => {\n\t\t\tthis.trackProp(key);\n\t\t\tonPropTracked?.(key);\n\t\t\treturn Reflect.get(target, key);\n\t\t} });\n\t}\n\t/**\n\t* Records that the given `QueryObserverResult` property was read, so a subsequent update only\n\t* notifies this observer if a tracked property actually changed. Normally called indirectly via\n\t* {@link QueryObserver#trackResult}'s proxy; exposed directly for adapters that track property\n\t* access themselves (e.g. through their own reactivity system) instead of via the proxy.\n\t* @param key - The name of the property that was read.\n\t*/\n\ttrackProp(key) {\n\t\tthis.#trackedProps.add(key);\n\t}\n\t/**\n\t* Returns the `Query` instance this observer is currently observing.\n\t* @returns The observed query.\n\t*/\n\tgetCurrentQuery() {\n\t\treturn this.#currentQuery;\n\t}\n\t/**\n\t* Refetches the observed query and returns a promise that resolves with\n\t* the resulting `QueryObserverResult`.\n\t* @param options - Set `cancelRefetch` to `false` to keep a running fetch instead of cancelling\n\t* it, and `throwOnError` to `true` to reject when the refetch fails.\n\t* @returns A promise that resolves with the result after the refetch.\n\t* @example\n\t* ```ts\n\t* const result = await observer.refetch({ cancelRefetch: false })\n\t* console.log(result.data)\n\t* ```\n\t*/\n\trefetch({ ...options } = {}) {\n\t\treturn this.fetch({ ...options });\n\t}\n\t/**\n\t* Fetches a query defined by the given options without affecting this\n\t* observer's own tracked query or result, and returns a promise that\n\t* resolves with the `QueryObserverResult` for that fetch. This is useful\n\t* for prefetching data that another observer (e.g. a query about to be\n\t* navigated to) will need, ahead of time.\n\t* @param options - The observer options of the query to fetch.\n\t* @returns A promise that resolves with the result for the fetched query.\n\t* @example\n\t* ```ts\n\t* const result = await observer.fetchOptimistic({\n\t* queryKey: ['posts', 2],\n\t* queryFn: () => fetchPost(2),\n\t* })\n\t* console.log(result.data)\n\t* ```\n\t*/\n\tfetchOptimistic(options) {\n\t\tconst defaultedOptions = this.#client.defaultQueryOptions(options);\n\t\tconst query = this.#client.getQueryCache().build(this.#client, defaultedOptions);\n\t\tlet unsubscribe = () => {};\n\t\tlet resolveEarly;\n\t\tconst cachePromise = new Promise((resolve) => {\n\t\t\tresolveEarly = resolve;\n\t\t\tunsubscribe = this.#client.getQueryCache().subscribe((event) => {\n\t\t\t\tif (event.type === \"updated\" && event.query.queryHash === query.queryHash && query.state.data !== void 0) {\n\t\t\t\t\tunsubscribe();\n\t\t\t\t\tresolve(this.createResult(query, defaultedOptions));\n\t\t\t\t}\n\t\t\t});\n\t\t});\n\t\treturn Promise.race([query.fetch(defaultedOptions).then(() => {\n\t\t\tconst result = this.createResult(query, defaultedOptions);\n\t\t\tresolveEarly?.(result);\n\t\t\treturn result;\n\t\t}).finally(() => {\n\t\t\tunsubscribe();\n\t\t}), cachePromise]);\n\t}\n\t/**\n\t* Fetches the observed query and updates the result once the fetch settles. Used by `refetch` and,\n\t* in `InfiniteQueryObserver`, to fetch more pages.\n\t* @param fetchOptions - Options for this fetch. `cancelRefetch` defaults to `true`.\n\t* @returns A promise that resolves with the updated result.\n\t*/\n\tfetch(fetchOptions) {\n\t\treturn this.#executeFetch({\n\t\t\t...fetchOptions,\n\t\t\tcancelRefetch: fetchOptions.cancelRefetch ?? true\n\t\t}).then(() => {\n\t\t\tthis.updateResult();\n\t\t\treturn this.#currentResult;\n\t\t});\n\t}\n\t#executeFetch(fetchOptions) {\n\t\tthis.#updateQuery();\n\t\tlet promise = this.#currentQuery.fetch(this.options, fetchOptions);\n\t\tif (!fetchOptions?.throwOnError) promise = promise.catch(noop);\n\t\treturn promise;\n\t}\n\t#shouldScheduleTimer(timeout) {\n\t\treturn !isServer() && resolveQueryValue(this.options.enabled, this.#currentQuery) !== false && isValidTimeout(timeout);\n\t}\n\t#updateStaleTimeout() {\n\t\tthis.#clearStaleTimeout();\n\t\tconst staleTime = resolveQueryValue(this.options.staleTime, this.#currentQuery);\n\t\tif (this.#currentResult.isStale || !this.#shouldScheduleTimer(staleTime)) return;\n\t\tconst timeout = timeUntilStale(this.#currentResult.dataUpdatedAt, staleTime) + 1;\n\t\tthis.#staleTimeoutId = timeoutManager.setTimeout(() => {\n\t\t\tif (!this.#currentResult.isStale) this.updateResult();\n\t\t}, timeout);\n\t}\n\t#computeRefetchInterval() {\n\t\treturn resolveQueryValue(this.options.refetchInterval, this.#currentQuery) ?? false;\n\t}\n\t#updateRefetchInterval(nextInterval) {\n\t\tthis.#clearRefetchInterval();\n\t\tthis.#currentRefetchInterval = nextInterval;\n\t\tif (this.#currentRefetchInterval === 0 || !this.#shouldScheduleTimer(this.#currentRefetchInterval)) return;\n\t\tthis.#refetchIntervalId = timeoutManager.setInterval(() => {\n\t\t\tif (this.options.refetchIntervalInBackground || focusManager.isFocused()) this.#executeFetch();\n\t\t}, this.#currentRefetchInterval);\n\t}\n\t#updateTimers() {\n\t\tthis.#updateStaleTimeout();\n\t\tthis.#updateRefetchInterval(this.#computeRefetchInterval());\n\t}\n\t#clearStaleTimeout() {\n\t\tif (this.#staleTimeoutId !== void 0) {\n\t\t\ttimeoutManager.clearTimeout(this.#staleTimeoutId);\n\t\t\tthis.#staleTimeoutId = void 0;\n\t\t}\n\t}\n\t#clearRefetchInterval() {\n\t\tif (this.#refetchIntervalId !== void 0) {\n\t\t\ttimeoutManager.clearInterval(this.#refetchIntervalId);\n\t\t\tthis.#refetchIntervalId = void 0;\n\t\t}\n\t}\n\t/**\n\t* Computes the result for a query and options from the query's state, applying `select`,\n\t* `placeholderData`, and the derived flags. Subclasses override it to add their own fields.\n\t* @param query - The query to compute the result for.\n\t* @param options - The observer options to compute the result with.\n\t* @returns The computed result.\n\t*/\n\tcreateResult(query, options) {\n\t\tconst prevQuery = this.#currentQuery;\n\t\tconst prevOptions = this.options;\n\t\tconst prevResult = this.#currentResult;\n\t\tconst prevResultState = this.#currentResultState;\n\t\tconst prevResultOptions = this.#currentResultOptions;\n\t\tconst queryInitialState = query !== prevQuery ? query.state : this.#currentQueryInitialState;\n\t\tconst { state } = query;\n\t\tlet newState = { ...state };\n\t\tlet isPlaceholderData = false;\n\t\tlet data;\n\t\tif (options._optimisticResults) {\n\t\t\tconst mounted = this.hasListeners();\n\t\t\tconst fetchOnMount = !mounted && shouldFetchOnMount(query, options);\n\t\t\tconst fetchOptionally = mounted && shouldFetchOptionally(query, prevQuery, options, prevOptions);\n\t\t\tif (fetchOnMount || fetchOptionally) newState = {\n\t\t\t\t...newState,\n\t\t\t\t...fetchState(state.data, query.options)\n\t\t\t};\n\t\t\tif (options._optimisticResults === \"isRestoring\") newState.fetchStatus = \"idle\";\n\t\t}\n\t\tlet { error, errorUpdatedAt, status } = newState;\n\t\tdata = newState.data;\n\t\tlet skipSelect = false;\n\t\tif (options.placeholderData !== void 0 && data === void 0 && status === \"pending\") {\n\t\t\tlet placeholderData;\n\t\t\tif (prevResult?.isPlaceholderData && options.placeholderData === prevResultOptions?.placeholderData) {\n\t\t\t\tplaceholderData = prevResult.data;\n\t\t\t\tskipSelect = true;\n\t\t\t} else placeholderData = typeof options.placeholderData === \"function\" ? options.placeholderData(this.#lastQueryWithDefinedData?.state.data, this.#lastQueryWithDefinedData) : options.placeholderData;\n\t\t\tif (placeholderData !== void 0) {\n\t\t\t\tstatus = \"success\";\n\t\t\t\tdata = replaceData(prevResult?.data, placeholderData, options);\n\t\t\t\tisPlaceholderData = true;\n\t\t\t}\n\t\t}\n\t\tif (options.select && data !== void 0 && !skipSelect) {\n\t\t\tif (prevResult && data === prevResultState?.data && options.select === this.#selectFn) data = this.#selectResult;\n\t\t\telse try {\n\t\t\t\tthis.#selectFn = options.select;\n\t\t\t\tdata = options.select(data);\n\t\t\t\tdata = replaceData(prevResult?.data, data, options);\n\t\t\t\tthis.#selectResult = data;\n\t\t\t\tthis.#selectError = null;\n\t\t\t} catch (selectError) {\n\t\t\t\tthis.#selectError = selectError;\n\t\t\t}\n\t\t} else if (data === void 0) this.#selectError = null;\n\t\tif (this.#selectError) {\n\t\t\terror = this.#selectError;\n\t\t\tdata = this.#selectResult;\n\t\t\terrorUpdatedAt = Date.now();\n\t\t\tstatus = \"error\";\n\t\t\tisPlaceholderData = false;\n\t\t}\n\t\tconst isFetching = newState.fetchStatus === \"fetching\";\n\t\tconst isPending = status === \"pending\";\n\t\tconst isError = status === \"error\";\n\t\tconst isLoading = isPending && isFetching;\n\t\tconst hasData = data !== void 0;\n\t\treturn {\n\t\t\tstatus,\n\t\t\tfetchStatus: newState.fetchStatus,\n\t\t\tisPending,\n\t\t\tisSuccess: status === \"success\",\n\t\t\tisError,\n\t\t\tisInitialLoading: isLoading,\n\t\t\tisLoading,\n\t\t\tdata,\n\t\t\tdataUpdatedAt: newState.dataUpdatedAt,\n\t\t\terror,\n\t\t\terrorUpdatedAt,\n\t\t\tfailureCount: newState.fetchFailureCount,\n\t\t\tfailureReason: newState.fetchFailureReason,\n\t\t\terrorUpdateCount: newState.errorUpdateCount,\n\t\t\tisFetched: query.isFetched(),\n\t\t\tisFetchedAfterMount: newState.dataUpdateCount > queryInitialState.dataUpdateCount || newState.errorUpdateCount > queryInitialState.errorUpdateCount,\n\t\t\tisFetching,\n\t\t\tisRefetching: isFetching && !isPending,\n\t\t\tisLoadingError: isError && !hasData,\n\t\t\tisPaused: newState.fetchStatus === \"paused\",\n\t\t\tisPlaceholderData,\n\t\t\tisRefetchError: isError && hasData,\n\t\t\tisStale: isStale(query, options),\n\t\t\trefetch: this.refetch,\n\t\t\tisEnabled: resolveQueryValue(options.enabled, query) !== false\n\t\t};\n\t}\n\t/**\n\t* Recomputes and stores the current result from the current query/options, notifying listeners\n\t* if it changed. Framework adapters call this right after subscribing to make sure no query\n\t* update was missed in the gap between creating the observer and subscribing to it.\n\t*/\n\tupdateResult() {\n\t\tconst prevResult = this.#currentResult;\n\t\tconst nextResult = this.createResult(this.#currentQuery, this.options);\n\t\tthis.#currentResultState = this.#currentQuery.state;\n\t\tthis.#currentResultOptions = this.options;\n\t\tif (this.#currentResultState.data !== void 0) this.#lastQueryWithDefinedData = this.#currentQuery;\n\t\tif (shallowEqualObjects(nextResult, prevResult)) return;\n\t\tthis.#currentResult = nextResult;\n\t\tconst shouldNotifyListeners = () => {\n\t\t\tif (!prevResult) return true;\n\t\t\tconst { notifyOnChangeProps } = this.options;\n\t\t\tconst notifyOnChangePropsValue = typeof notifyOnChangeProps === \"function\" ? notifyOnChangeProps() : notifyOnChangeProps;\n\t\t\tif (notifyOnChangePropsValue === \"all\" || !notifyOnChangePropsValue && !this.#trackedProps.size) return true;\n\t\t\tif (this.options.throwOnError && this.#currentResult.error !== prevResult.error) return true;\n\t\t\tfor (const key of notifyOnChangePropsValue ?? this.#trackedProps) if (this.#currentResult[key] !== prevResult[key]) return true;\n\t\t\treturn false;\n\t\t};\n\t\tconst notifyListeners = shouldNotifyListeners();\n\t\tnotifyManager.batch(() => {\n\t\t\tif (notifyListeners) this.listeners.forEach((listener) => {\n\t\t\t\tlistener(this.#currentResult);\n\t\t\t});\n\t\t\tthis.#client.getQueryCache().notify({\n\t\t\t\tquery: this.#currentQuery,\n\t\t\t\ttype: \"observerResultsUpdated\"\n\t\t\t});\n\t\t});\n\t}\n\t#updateQuery() {\n\t\tconst query = this.#client.getQueryCache().build(this.#client, this.options);\n\t\tif (query === this.#currentQuery) return;\n\t\tconst prevQuery = this.#currentQuery;\n\t\tthis.#currentQuery = query;\n\t\tthis.#currentQueryInitialState = query.state;\n\t\tif (this.hasListeners()) {\n\t\t\tprevQuery?.removeObserver(this);\n\t\t\tquery.addObserver(this);\n\t\t}\n\t}\n\t/**\n\t* Updates the observer's result when the observed query changes, and reschedules its timers if it\n\t* has listeners.\n\t* @internal\n\t*/\n\tonQueryUpdate() {\n\t\tthis.updateResult();\n\t\tif (this.hasListeners()) this.#updateTimers();\n\t}\n};\n/**\n* Checks whether a query has no data yet and should do its initial load when an observer mounts.\n* @param query - The query to check.\n* @param options - The observer options.\n* @returns `true` if the query is enabled, has no data, and isn't in an error state with\n* `retryOnMount: false`.\n*/\nfunction shouldLoadOnMount(query, options) {\n\treturn resolveQueryValue(options.enabled, query) !== false && query.state.data === void 0 && !(query.state.status === \"error\" && resolveQueryValue(options.retryOnMount, query) === false);\n}\n/**\n* Checks whether a query should fetch when an observer mounts: either for its initial load, or\n* because it has data and `refetchOnMount` asks for a refetch.\n* @param query - The query to check.\n* @param options - The observer options.\n* @returns `true` if the query should fetch on mount.\n*/\nfunction shouldFetchOnMount(query, options) {\n\treturn shouldLoadOnMount(query, options) || query.state.data !== void 0 && shouldFetchOn(query, options, options.refetchOnMount);\n}\n/**\n* Checks whether a query should fetch for a `refetchOnMount`, `refetchOnWindowFocus`, or\n* `refetchOnReconnect` option.\n* @param query - The query to check.\n* @param options - The observer options.\n* @param field - The value of the option to check.\n* @returns `true` if the query is enabled, not static, and the option is `'always'`, or is not\n* `false` and the query is stale.\n*/\nfunction shouldFetchOn(query, options, field) {\n\tif (resolveQueryValue(options.enabled, query) !== false && resolveQueryValue(options.staleTime, query) !== \"static\") {\n\t\tconst value = resolveQueryValue(field, query);\n\t\treturn value === \"always\" || value !== false && isStale(query, options);\n\t}\n\treturn false;\n}\n/**\n* Checks whether a query should fetch after the observer's options change.\n* @param query - The query observed with the new options.\n* @param prevQuery - The query observed with the previous options.\n* @param options - The new observer options.\n* @param prevOptions - The previous observer options.\n* @returns `true` if the query changed or was disabled before, it isn't a suspense query in an\n* error state, and it is stale.\n*/\nfunction shouldFetchOptionally(query, prevQuery, options, prevOptions) {\n\treturn (query !== prevQuery || resolveQueryValue(prevOptions.enabled, query) === false) && (!options.suspense || query.state.status !== \"error\") && isStale(query, options);\n}\n/**\n* Checks whether a query is stale for the given observer options.\n* @param query - The query to check.\n* @param options - The observer options, whose `enabled` and `staleTime` are used.\n* @returns `true` if the query is enabled and its data is stale for `staleTime`.\n*/\nfunction isStale(query, options) {\n\treturn resolveQueryValue(options.enabled, query) !== false && query.isStaleByTime(resolveQueryValue(options.staleTime, query));\n}\nexport { QueryObserver };\n\n//# sourceMappingURL=queryObserver.js.map","import { hasNextPage, hasPreviousPage } from \"./infiniteQueryBehavior.js\";\nimport { QueryObserver } from \"./queryObserver.js\";\n// src/infiniteQueryObserver.ts\n/**\n* An `InfiniteQueryObserver` extends `QueryObserver` to observe and switch\n* between infinite queries. It augments the base `QueryObserverResult` with\n* infinite-query-specific fields and methods, such as `hasNextPage` and\n* `fetchNextPage`, and is the primitive that framework adapters (e.g.\n* `useInfiniteQuery`) build their hooks on top of.\n* @example\n* ```ts\n* const observer = new InfiniteQueryObserver(queryClient, {\n* queryKey: ['projects'],\n* queryFn: ({ pageParam }) => fetchProjects(pageParam),\n* initialPageParam: 0,\n* getNextPageParam: (lastPage) => lastPage.nextCursor,\n* })\n*\n* const unsubscribe = observer.subscribe((result) => console.log(result))\n* ```\n*/\nvar InfiniteQueryObserver = class extends QueryObserver {\n\tconstructor(client, options) {\n\t\tsuper(client, options);\n\t}\n\tbindMethods() {\n\t\tsuper.bindMethods();\n\t\tthis.fetchNextPage = this.fetchNextPage.bind(this);\n\t\tthis.fetchPreviousPage = this.fetchPreviousPage.bind(this);\n\t}\n\t/**\n\t* Updates the observer's options. Behaves the same as\n\t* `QueryObserver.setOptions`, additionally marking the options as\n\t* belonging to an infinite query before delegating to the base\n\t* implementation.\n\t* @param options - The new infinite query observer options.\n\t*/\n\tsetOptions(options) {\n\t\toptions._type = \"infinite\";\n\t\tsuper.setOptions(options);\n\t}\n\t/**\n\t* The infinite-query counterpart of {@link QueryObserver#getOptimisticResult}, marking the\n\t* options as an infinite query before delegating to it. Called by framework adapters (e.g.\n\t* `useInfiniteQuery`) ahead of subscribing, to compute the current `InfiniteQueryObserverResult`\n\t* synchronously.\n\t* @param options - The defaulted infinite query observer options to compute the result for.\n\t* @returns The result for the given options.\n\t*/\n\tgetOptimisticResult(options) {\n\t\toptions._type = \"infinite\";\n\t\treturn super.getOptimisticResult(options);\n\t}\n\t/**\n\t* Fetches the next page of the infinite query and returns a promise that\n\t* resolves with the resulting `InfiniteQueryObserverResult`. The page\n\t* param used for the fetch is determined by `getNextPageParam`, which\n\t* receives the current pages/page params and whose result also determines\n\t* `hasNextPage`.\n\t* @param options - Set `cancelRefetch` to `false` to ignore the call while a fetch is running,\n\t* and `throwOnError` to `true` to reject when the fetch fails.\n\t* @returns A promise that resolves with the result after the next page is fetched. With\n\t* `cancelRefetch: false`, a running fetch is reused instead, so the next page may not be fetched.\n\t* @see {@link InfiniteQueryObserver#fetchPreviousPage}\n\t* @example\n\t* ```ts\n\t* const { hasNextPage } = observer.getCurrentResult()\n\t*\n\t* if (hasNextPage) {\n\t* await observer.fetchNextPage()\n\t* }\n\t* ```\n\t*/\n\tfetchNextPage(options) {\n\t\treturn this.fetch({\n\t\t\t...options,\n\t\t\tmeta: { fetchMore: { direction: \"forward\" } }\n\t\t});\n\t}\n\t/**\n\t* Fetches the previous page of the infinite query and returns a promise\n\t* that resolves with the resulting `InfiniteQueryObserverResult`. The page\n\t* param used for the fetch is determined by `getPreviousPageParam`, which\n\t* receives the current pages/page params and whose result also determines\n\t* `hasPreviousPage`.\n\t* @param options - Set `cancelRefetch` to `false` to ignore the call while a fetch is running,\n\t* and `throwOnError` to `true` to reject when the fetch fails.\n\t* @returns A promise that resolves with the result after the previous page is fetched. With\n\t* `cancelRefetch: false`, a running fetch is reused instead, so the previous page may not be fetched.\n\t* @see {@link InfiniteQueryObserver#fetchNextPage}\n\t* @example\n\t* ```ts\n\t* const { hasPreviousPage } = observer.getCurrentResult()\n\t*\n\t* if (hasPreviousPage) {\n\t* await observer.fetchPreviousPage()\n\t* }\n\t* ```\n\t*/\n\tfetchPreviousPage(options) {\n\t\treturn this.fetch({\n\t\t\t...options,\n\t\t\tmeta: { fetchMore: { direction: \"backward\" } }\n\t\t});\n\t}\n\tcreateResult(query, options) {\n\t\tconst { state } = query;\n\t\tconst parentResult = super.createResult(query, options);\n\t\tconst { isFetching, isRefetching, isError, isRefetchError } = parentResult;\n\t\tconst fetchDirection = state.fetchMeta?.fetchMore?.direction;\n\t\tconst isFetchNextPageError = isError && fetchDirection === \"forward\";\n\t\tconst isFetchingNextPage = isFetching && fetchDirection === \"forward\";\n\t\tconst isFetchPreviousPageError = isError && fetchDirection === \"backward\";\n\t\tconst isFetchingPreviousPage = isFetching && fetchDirection === \"backward\";\n\t\treturn {\n\t\t\t...parentResult,\n\t\t\tfetchNextPage: this.fetchNextPage,\n\t\t\tfetchPreviousPage: this.fetchPreviousPage,\n\t\t\thasNextPage: hasNextPage(options, state.data),\n\t\t\thasPreviousPage: hasPreviousPage(options, state.data),\n\t\t\tisFetchNextPageError,\n\t\t\tisFetchingNextPage,\n\t\t\tisFetchPreviousPageError,\n\t\t\tisFetchingPreviousPage,\n\t\t\tisRefetchError: isRefetchError && !isFetchNextPageError && !isFetchPreviousPageError,\n\t\t\tisRefetching: isRefetching && !isFetchingNextPage && !isFetchingPreviousPage\n\t\t};\n\t}\n};\nexport { InfiniteQueryObserver };\n\n//# sourceMappingURL=infiniteQueryObserver.js.map","import { notifyManager } from \"./notifyManager.js\";\nimport { createRetryer } from \"./retryer.js\";\nimport { Removable } from \"./removable.js\";\n// src/mutation.ts\n/**\n* Represents a single mutation attempt. A `Mutation` holds the mutation's\n* options, state (data/error/status), and the `MutationObserver`s currently\n* subscribed to it.\n*\n* Instances are created and managed internally by `MutationCache`; application\n* code typically interacts with mutations indirectly through `QueryClient` or\n* a framework hook like `useMutation`. Direct access to a `Mutation` instance\n* is possible via `mutationCache.find()`/`getAll()` for inspecting cache state.\n* @example\n* ```ts\n* const mutationCache = queryClient.getMutationCache()\n*\n* const mutation = mutationCache.find({ mutationKey: ['addPost'] })\n* ```\n*/\nvar Mutation = class extends Removable {\n\t#client;\n\t#observers;\n\t#mutationCache;\n\t#retryer;\n\tconstructor(config) {\n\t\tsuper();\n\t\tthis.#client = config.client;\n\t\tthis.mutationId = config.mutationId;\n\t\tthis.#mutationCache = config.mutationCache;\n\t\tthis.#observers = [];\n\t\tthis.state = config.state || getDefaultState();\n\t\tthis.setOptions(config.options);\n\t\tthis.scheduleGc();\n\t}\n\t/**\n\t* Replaces the mutation's options and applies their `gcTime`.\n\t* @internal\n\t* @param options - The new mutation options.\n\t*/\n\tsetOptions(options) {\n\t\tthis.options = options;\n\t\tthis.updateGcTime(this.options.gcTime);\n\t}\n\t/**\n\t* The `meta` object passed in the mutation's options, if any.\n\t* @returns The mutation's `meta`, or `undefined` if none was set.\n\t*/\n\tget meta() {\n\t\treturn this.options.meta;\n\t}\n\t/**\n\t* Subscribes an observer to the mutation and stops its garbage collection.\n\t* @internal\n\t* @param observer - The observer to add. Adding an observer that is already subscribed does\n\t* nothing.\n\t*/\n\taddObserver(observer) {\n\t\tif (!this.#observers.includes(observer)) {\n\t\t\tthis.#observers.push(observer);\n\t\t\tthis.clearGcTimeout();\n\t\t\tthis.#mutationCache.notify({\n\t\t\t\ttype: \"observerAdded\",\n\t\t\t\tmutation: this,\n\t\t\t\tobserver\n\t\t\t});\n\t\t}\n\t}\n\t/**\n\t* Unsubscribes an observer from the mutation.\n\t* @internal\n\t* @param observer - The observer to remove. Garbage collection is scheduled afterwards.\n\t*/\n\tremoveObserver(observer) {\n\t\tthis.#observers = this.#observers.filter((x) => x !== observer);\n\t\tthis.scheduleGc();\n\t\tthis.#mutationCache.notify({\n\t\t\ttype: \"observerRemoved\",\n\t\t\tmutation: this,\n\t\t\tobserver\n\t\t});\n\t}\n\toptionalRemove() {\n\t\tif (!this.#observers.length) {\n\t\t\tif (this.state.status === \"pending\") this.scheduleGc();\n\t\t\telse this.#mutationCache.remove(this);\n\t\t}\n\t}\n\t/**\n\t* Resumes a mutation that is currently paused or was restored from a\n\t* dehydrated, still-`pending` state.\n\t*\n\t* - If this mutation has an active retryer (it paused mid-attempt, e.g. due\n\t* to the network mode or scope-based queuing), its retryer is resumed.\n\t* - Otherwise, if the mutation's status is still `pending` (e.g. it was\n\t* dehydrated while an attempt was in flight and never got a retryer in\n\t* this instance), `execute` is called again with the last known variables.\n\t* - Otherwise the mutation has already settled and this resolves immediately\n\t* without running anything again.\n\t* @returns A promise that settles with the resumed mutation: it rejects if the mutation fails.\n\t* It resolves immediately if the mutation has already settled.\n\t* @see {@link Mutation#execute}\n\t* @example\n\t* ```ts\n\t* // typically driven by reconnect handling, e.g. queryClient.resumePausedMutations()\n\t* const mutation = mutationCache.find({ mutationKey: ['addPost'] })\n\t* await mutation?.continue()\n\t* ```\n\t*/\n\tcontinue() {\n\t\treturn this.#retryer?.continue() ?? (this.state.status === \"pending\" ? this.execute(this.state.variables) : Promise.resolve());\n\t}\n\t/**\n\t* Runs the mutation function for the given variables through a retryer, and\n\t* drives the mutation's state and lifecycle callbacks through to settlement.\n\t*\n\t* If this mutation's state is already `pending` when `execute` is called\n\t* (i.e. it was restored, still in-flight, from a dehydrated state), the\n\t* `onMutate` step is skipped and a `continue` action is dispatched to\n\t* unpause it; otherwise a `pending` action is dispatched first, then the\n\t* mutation cache's `onMutate` and the mutation's own `onMutate` option are\n\t* awaited in that order, and the resulting context is stored.\n\t*\n\t* The mutation function is then run (subject to `retry`/`retryDelay`/\n\t* `networkMode`, and to the mutation cache's scope-based serialization).\n\t* On success, the cache's `onSuccess`/`onSettled` callbacks run before the\n\t* mutation's own `onSuccess`/`onSettled` options, a `success` action is\n\t* dispatched, and the resolved data is returned. On failure, the same\n\t* cache-then-option ordering is used for `onError`/`onSettled`, but each of\n\t* those four callbacks is individually caught so that a throwing callback\n\t* cannot mask the original error; an `error` action is then dispatched and\n\t* the original error is re-thrown.\n\t* @param variables - The variables passed to the `mutationFn`.\n\t* @returns A promise that resolves with the mutation's data, or rejects with its error.\n\t* @see {@link Mutation#continue}\n\t* @example\n\t* ```ts\n\t* // Called internally by `MutationObserver.mutate` and `Mutation.continue` —\n\t* // applications normally trigger mutations through those, not this method.\n\t* const data = await mutation.execute(variables)\n\t* ```\n\t*/\n\tasync execute(variables) {\n\t\tconst onContinue = () => {\n\t\t\tthis.#dispatch({ type: \"continue\" });\n\t\t};\n\t\tconst mutationFnContext = {\n\t\t\tclient: this.#client,\n\t\t\tmeta: this.options.meta,\n\t\t\tmutationKey: this.options.mutationKey\n\t\t};\n\t\tconst retryer = this.#retryer = createRetryer({\n\t\t\tfn: () => {\n\t\t\t\tif (!this.options.mutationFn) return Promise.reject(/* @__PURE__ */ new Error(\"No mutationFn found\"));\n\t\t\t\treturn this.options.mutationFn(variables, mutationFnContext);\n\t\t\t},\n\t\t\tonFail: (failureCount, error) => {\n\t\t\t\tthis.#dispatch({\n\t\t\t\t\ttype: \"failed\",\n\t\t\t\t\tfailureCount,\n\t\t\t\t\terror\n\t\t\t\t});\n\t\t\t},\n\t\t\tonPause: () => {\n\t\t\t\tthis.#dispatch({ type: \"pause\" });\n\t\t\t},\n\t\t\tonContinue,\n\t\t\tretry: this.options.retry ?? 0,\n\t\t\tretryDelay: this.options.retryDelay,\n\t\t\tnetworkMode: this.options.networkMode,\n\t\t\tcanRun: () => this.#mutationCache.canRun(this)\n\t\t});\n\t\tconst restored = this.state.status === \"pending\";\n\t\tconst isPaused = !retryer.canStart();\n\t\ttry {\n\t\t\tif (restored) onContinue();\n\t\t\telse {\n\t\t\t\tthis.#dispatch({\n\t\t\t\t\ttype: \"pending\",\n\t\t\t\t\tvariables,\n\t\t\t\t\tisPaused\n\t\t\t\t});\n\t\t\t\tif (this.#mutationCache.config.onMutate) await this.#mutationCache.config.onMutate(variables, this, mutationFnContext);\n\t\t\t\tconst context = await this.options.onMutate?.(variables, mutationFnContext);\n\t\t\t\tif (context !== this.state.context) this.#dispatch({\n\t\t\t\t\ttype: \"pending\",\n\t\t\t\t\tcontext,\n\t\t\t\t\tvariables,\n\t\t\t\t\tisPaused\n\t\t\t\t});\n\t\t\t}\n\t\t\tif (this.state.isPaused && retryer.canStart()) onContinue();\n\t\t\tconst data = await retryer.start();\n\t\t\tawait this.#mutationCache.config.onSuccess?.(data, variables, this.state.context, this, mutationFnContext);\n\t\t\tawait this.options.onSuccess?.(data, variables, this.state.context, mutationFnContext);\n\t\t\tawait this.#mutationCache.config.onSettled?.(data, null, this.state.variables, this.state.context, this, mutationFnContext);\n\t\t\tawait this.options.onSettled?.(data, null, variables, this.state.context, mutationFnContext);\n\t\t\tthis.#dispatch({\n\t\t\t\ttype: \"success\",\n\t\t\t\tdata\n\t\t\t});\n\t\t\treturn data;\n\t\t} catch (error) {\n\t\t\ttry {\n\t\t\t\tawait this.#mutationCache.config.onError?.(error, variables, this.state.context, this, mutationFnContext);\n\t\t\t} catch (e) {\n\t\t\t\tPromise.reject(e);\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tawait this.options.onError?.(error, variables, this.state.context, mutationFnContext);\n\t\t\t} catch (e) {\n\t\t\t\tPromise.reject(e);\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tawait this.#mutationCache.config.onSettled?.(void 0, error, this.state.variables, this.state.context, this, mutationFnContext);\n\t\t\t} catch (e) {\n\t\t\t\tPromise.reject(e);\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tawait this.options.onSettled?.(void 0, error, variables, this.state.context, mutationFnContext);\n\t\t\t} catch (e) {\n\t\t\t\tPromise.reject(e);\n\t\t\t}\n\t\t\tthis.#dispatch({\n\t\t\t\ttype: \"error\",\n\t\t\t\terror\n\t\t\t});\n\t\t\tthrow error;\n\t\t} finally {\n\t\t\tif (this.#retryer === retryer) this.#retryer = void 0;\n\t\t\tthis.#mutationCache.runNext(this);\n\t\t}\n\t}\n\t#dispatch(action) {\n\t\tconst reducer = (state) => {\n\t\t\tswitch (action.type) {\n\t\t\t\tcase \"failed\": return {\n\t\t\t\t\t...state,\n\t\t\t\t\tfailureCount: action.failureCount,\n\t\t\t\t\tfailureReason: action.error\n\t\t\t\t};\n\t\t\t\tcase \"pause\": return {\n\t\t\t\t\t...state,\n\t\t\t\t\tisPaused: true\n\t\t\t\t};\n\t\t\t\tcase \"continue\": return {\n\t\t\t\t\t...state,\n\t\t\t\t\tisPaused: false\n\t\t\t\t};\n\t\t\t\tcase \"pending\": return {\n\t\t\t\t\t...state,\n\t\t\t\t\tcontext: action.context,\n\t\t\t\t\tdata: void 0,\n\t\t\t\t\tfailureCount: 0,\n\t\t\t\t\tfailureReason: null,\n\t\t\t\t\terror: null,\n\t\t\t\t\tisPaused: action.isPaused,\n\t\t\t\t\tstatus: \"pending\",\n\t\t\t\t\tvariables: action.variables,\n\t\t\t\t\tsubmittedAt: Date.now()\n\t\t\t\t};\n\t\t\t\tcase \"success\": return {\n\t\t\t\t\t...state,\n\t\t\t\t\tdata: action.data,\n\t\t\t\t\tfailureCount: 0,\n\t\t\t\t\tfailureReason: null,\n\t\t\t\t\terror: null,\n\t\t\t\t\tstatus: \"success\",\n\t\t\t\t\tisPaused: false\n\t\t\t\t};\n\t\t\t\tcase \"error\": return {\n\t\t\t\t\t...state,\n\t\t\t\t\tdata: void 0,\n\t\t\t\t\terror: action.error,\n\t\t\t\t\tfailureCount: state.failureCount + 1,\n\t\t\t\t\tfailureReason: action.error,\n\t\t\t\t\tisPaused: false,\n\t\t\t\t\tstatus: \"error\"\n\t\t\t\t};\n\t\t\t}\n\t\t};\n\t\tthis.state = reducer(this.state);\n\t\tnotifyManager.batch(() => {\n\t\t\tthis.#observers.forEach((observer) => {\n\t\t\t\tobserver.onMutationUpdate(action);\n\t\t\t});\n\t\t\tthis.#mutationCache.notify({\n\t\t\t\tmutation: this,\n\t\t\t\ttype: \"updated\",\n\t\t\t\taction\n\t\t\t});\n\t\t});\n\t}\n};\n/**\n* Returns the initial state of a mutation: `'idle'`, with no data, error, or variables.\n* @returns The initial mutation state.\n*/\nfunction getDefaultState() {\n\treturn {\n\t\tcontext: void 0,\n\t\tdata: void 0,\n\t\terror: null,\n\t\tfailureCount: 0,\n\t\tfailureReason: null,\n\t\tisPaused: false,\n\t\tstatus: \"idle\",\n\t\tvariables: void 0,\n\t\tsubmittedAt: 0\n\t};\n}\nexport { Mutation, getDefaultState };\n\n//# sourceMappingURL=mutation.js.map","import { hashKey, shallowEqualObjects } from \"./utils.js\";\nimport { Subscribable } from \"./subscribable.js\";\nimport { notifyManager } from \"./notifyManager.js\";\nimport { getDefaultState } from \"./mutation.js\";\n// src/mutationObserver.ts\n/**\n* Observes a single mutation and derives a `MutationObserverResult` from it.\n* A framework hook like `useMutation` creates one `MutationObserver` per hook\n* call, keeps it stable across re-renders, calls `setOptions` when the options\n* passed to the hook change, subscribes to it to re-render on updates, and\n* reads `getCurrentResult()` for the value to return. Calling `mutate()`\n* builds a new underlying `Mutation` in the `MutationCache` and executes it.\n* @example\n* ```ts\n* const observer = new MutationObserver(queryClient, {\n* mutationFn: (variables: { title: string }) => addPost(variables),\n* })\n* ```\n*/\nvar MutationObserver = class extends Subscribable {\n\t#client;\n\t#currentResult = void 0;\n\t#currentMutation;\n\t#mutateOptions;\n\tconstructor(client, options) {\n\t\tsuper();\n\t\tthis.#client = client;\n\t\tthis.setOptions(options);\n\t\tthis.bindMethods();\n\t\tthis.#updateResult();\n\t}\n\t/**\n\t* Binds the methods of the result (`mutate` and `reset`) to the observer, so they keep working when\n\t* destructured from it.\n\t*/\n\tbindMethods() {\n\t\tthis.mutate = this.mutate.bind(this);\n\t\tthis.reset = this.reset.bind(this);\n\t}\n\t/**\n\t* Updates the observer's options.\n\t*\n\t* If the new `mutationKey` differs from the previous one (and both were\n\t* defined), the observer is reset, detaching it from the mutation it was\n\t* observing. Otherwise, if the currently observed mutation is still\n\t* `pending`, its options are updated in place as well.\n\t* @param options - The new mutation observer options. They are defaulted with {@link\n\t* QueryClient#defaultMutationOptions} before being applied.\n\t* @example\n\t* ```ts\n\t* observer.setOptions({\n\t* mutationFn: (variables: { title: string }) => addPost(variables),\n\t* onSuccess: (data) => console.log(data),\n\t* })\n\t* ```\n\t*/\n\tsetOptions(options) {\n\t\tconst prevOptions = this.options;\n\t\tthis.options = this.#client.defaultMutationOptions(options);\n\t\tif (!shallowEqualObjects(this.options, prevOptions)) this.#client.getMutationCache().notify({\n\t\t\ttype: \"observerOptionsUpdated\",\n\t\t\tmutation: this.#currentMutation,\n\t\t\tobserver: this\n\t\t});\n\t\tif (prevOptions?.mutationKey && this.options.mutationKey && hashKey(prevOptions.mutationKey) !== hashKey(this.options.mutationKey)) this.reset();\n\t\telse if (this.#currentMutation?.state.status === \"pending\") this.#currentMutation.setOptions(this.options);\n\t}\n\tonSubscribe() {\n\t\tif (this.listeners.size === 1 && this.#currentMutation) {\n\t\t\tthis.#currentMutation.addObserver(this);\n\t\t\tthis.#updateResult();\n\t\t}\n\t}\n\tonUnsubscribe() {\n\t\tif (!this.hasListeners()) this.#currentMutation?.removeObserver(this);\n\t}\n\t/**\n\t* Updates the observer's result when the observed mutation changes, and notifies its listeners.\n\t* @internal\n\t* @param action - The action that updated the observed mutation, passed on to the observer's\n\t* callbacks.\n\t*/\n\tonMutationUpdate(action) {\n\t\tthis.#updateResult();\n\t\tthis.#notify(action);\n\t}\n\t/**\n\t* Returns the observer's current result, derived from the observed\n\t* mutation's state (or the default, `idle` state if no mutation has been\n\t* built yet, e.g. before the first `mutate()` call or after `reset()`).\n\t* @returns The observer's latest result.\n\t*/\n\tgetCurrentResult() {\n\t\treturn this.#currentResult;\n\t}\n\t/**\n\t* Detaches the observer from the mutation it is currently observing (if\n\t* any) and resets the observed result back to its default, `idle` state.\n\t*\n\t* This does not cancel an in-flight mutation; the mutation itself keeps\n\t* running to completion and its own callbacks still fire, but this\n\t* observer stops reflecting its state and a subsequent `mutate()` call\n\t* will build a brand new mutation.\n\t* @see {@link MutationObserver#mutate}\n\t* @example\n\t* ```ts\n\t* observer.reset()\n\t* ```\n\t*/\n\treset() {\n\t\tthis.#currentMutation?.removeObserver(this);\n\t\tthis.#currentMutation = void 0;\n\t\tthis.#updateResult();\n\t\tthis.#notify();\n\t}\n\t/**\n\t* Builds a new `Mutation` in the `MutationCache` using the observer's\n\t* current options, detaches this observer from any previously observed\n\t* mutation, attaches it to the new one, and executes it with the given\n\t* variables.\n\t*\n\t* The optional per-call `options` (`onSuccess`/`onError`/`onSettled`) are\n\t* invoked once the mutation settles, in addition to any callbacks defined\n\t* on the observer's own options.\n\t* @param variables - The variables passed to the `mutationFn`.\n\t* @param options - Per-call `onSuccess`, `onError`, and `onSettled` callbacks.\n\t* @returns A promise that resolves with the mutation's data, or rejects with its error.\n\t* @example\n\t* ```ts\n\t* await observer.mutate(\n\t* { title: 'New post' },\n\t* { onSuccess: (data) => console.log(data) },\n\t* )\n\t* ```\n\t*/\n\tmutate(variables, options) {\n\t\tthis.#mutateOptions = options;\n\t\tthis.#currentMutation?.removeObserver(this);\n\t\tthis.#currentMutation = this.#client.getMutationCache().build(this.#client, this.options);\n\t\tthis.#currentMutation.addObserver(this);\n\t\treturn this.#currentMutation.execute(variables);\n\t}\n\t#updateResult() {\n\t\tconst state = this.#currentMutation?.state ?? getDefaultState();\n\t\tthis.#currentResult = {\n\t\t\t...state,\n\t\t\tisPending: state.status === \"pending\",\n\t\t\tisSuccess: state.status === \"success\",\n\t\t\tisError: state.status === \"error\",\n\t\t\tisIdle: state.status === \"idle\",\n\t\t\tmutate: this.mutate,\n\t\t\treset: this.reset\n\t\t};\n\t}\n\t#notify(action) {\n\t\tnotifyManager.batch(() => {\n\t\t\tconst mutateOptions = this.#mutateOptions;\n\t\t\tif (mutateOptions && this.hasListeners()) {\n\t\t\t\tconst variables = this.#currentResult.variables;\n\t\t\t\tconst onMutateResult = this.#currentResult.context;\n\t\t\t\tconst context = {\n\t\t\t\t\tclient: this.#client,\n\t\t\t\t\tmeta: this.options.meta,\n\t\t\t\t\tmutationKey: this.options.mutationKey\n\t\t\t\t};\n\t\t\t\tif (action?.type === \"success\") {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tmutateOptions.onSuccess?.(action.data, variables, onMutateResult, context);\n\t\t\t\t\t} catch (e) {\n\t\t\t\t\t\tPromise.reject(e);\n\t\t\t\t\t}\n\t\t\t\t\ttry {\n\t\t\t\t\t\tmutateOptions.onSettled?.(action.data, null, variables, onMutateResult, context);\n\t\t\t\t\t} catch (e) {\n\t\t\t\t\t\tPromise.reject(e);\n\t\t\t\t\t}\n\t\t\t\t} else if (action?.type === \"error\") {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tmutateOptions.onError?.(action.error, variables, onMutateResult, context);\n\t\t\t\t\t} catch (e) {\n\t\t\t\t\t\tPromise.reject(e);\n\t\t\t\t\t}\n\t\t\t\t\ttry {\n\t\t\t\t\t\tmutateOptions.onSettled?.(void 0, action.error, variables, onMutateResult, context);\n\t\t\t\t\t} catch (e) {\n\t\t\t\t\t\tPromise.reject(e);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tthis.listeners.forEach((listener) => {\n\t\t\t\tlistener(this.#currentResult);\n\t\t\t});\n\t\t});\n\t}\n};\nexport { MutationObserver };\n\n//# sourceMappingURL=mutationObserver.js.map","\"use client\";\nimport * as React from \"react\";\n// src/IsRestoringProvider.ts\nconst IsRestoringContext = React.createContext(false);\n/**\n* If you are using `PersistQueryClientProvider`, you can also use the `useIsRestoring` hook alongside it to\n* check if a restore is currently in progress. `useQuery` and friends also check this internally to avoid\n* race conditions between the restore and mounting queries.\n* @returns `true` while a persisted client is being restored, `false` otherwise.\n*/\nconst useIsRestoring = () => React.useContext(IsRestoringContext);\n/**\n* The Provider that `PersistQueryClientProvider` uses to signal whether a persisted client is currently\n* being restored, read by `useIsRestoring`.\n*/\nconst IsRestoringProvider = IsRestoringContext.Provider;\nexport { IsRestoringProvider, useIsRestoring };\n\n//# sourceMappingURL=IsRestoringProvider.js.map","\"use client\";\nimport * as React from \"react\";\nimport { jsx } from \"react/jsx-runtime\";\n// src/QueryErrorResetBoundary.tsx\n/**\n* Creates the value shared through the boundary's context, which tracks whether a reset was\n* requested.\n* @returns The `clearReset`, `isReset`, and `reset` functions of the boundary.\n*/\nfunction createValue() {\n\tlet isReset = false;\n\treturn {\n\t\t/**\n\t\t* Clears the reset state, so queries know not to try again until the boundary is reset again.\n\t\t*/\n\t\tclearReset: () => {\n\t\t\tisReset = false;\n\t\t},\n\t\t/**\n\t\t* Resets any query errors within the boundary, so queries know they can try again.\n\t\t*/\n\t\treset: () => {\n\t\t\tisReset = true;\n\t\t},\n\t\t/**\n\t\t* Returns whether the boundary has been reset and not yet cleared.\n\t\t* @returns `true` if the boundary has been reset and not yet cleared.\n\t\t*/\n\t\tisReset: () => {\n\t\t\treturn isReset;\n\t\t}\n\t};\n}\nconst QueryErrorResetBoundaryContext = React.createContext(createValue());\n/**\n* This hook will reset any query errors within the closest `QueryErrorResetBoundary`. If there is no boundary\n* defined it will reset them globally.\n* @returns The boundary's {@link QueryErrorResetBoundaryValue}.\n* @example\n* ```tsx\n* import { ErrorBoundary } from 'react-error-boundary'\n* import { useQueryErrorResetBoundary } from '@tanstack/react-query'\n*\n* function App({ children }: { children: React.ReactNode }) {\n* const { reset } = useQueryErrorResetBoundary()\n*\n* return (\n* <ErrorBoundary\n* onReset={reset}\n* fallbackRender={({ resetErrorBoundary }) => (\n* <div>\n* There was an error!\n* <button onClick={() => resetErrorBoundary()}>Try again</button>\n* </div>\n* )}\n* >\n* {children}\n* </ErrorBoundary>\n* )\n* }\n* ```\n*/\nconst useQueryErrorResetBoundary = () => React.useContext(QueryErrorResetBoundaryContext);\n/**\n* When using `suspense` or `throwOnError` in your queries, you need a way to let queries know that you want to\n* try again when re-rendering after some error occurred. With the `QueryErrorResetBoundary` component you can\n* reset any query errors within the boundaries of the component.\n* @param props - The `children` to render.\n* @returns The `children`, rendered as-is, or called with the boundary's {@link QueryErrorResetBoundaryValue}\n* if `children` is a function.\n* @example\n* ```tsx\n* import { ErrorBoundary } from 'react-error-boundary'\n* import { QueryErrorResetBoundary } from '@tanstack/react-query'\n*\n* function App() {\n* return (\n* <QueryErrorResetBoundary>\n* {({ reset }) => (\n* <ErrorBoundary\n* onReset={reset}\n* fallbackRender={({ resetErrorBoundary }) => (\n* <div>\n* There was an error!\n* <button onClick={() => resetErrorBoundary()}>Try again</button>\n* </div>\n* )}\n* >\n* <Page />\n* </ErrorBoundary>\n* )}\n* </QueryErrorResetBoundary>\n* )\n* }\n* ```\n*/\nconst QueryErrorResetBoundary = ({ children }) => {\n\tconst [value] = React.useState(() => createValue());\n\treturn /* @__PURE__ */ jsx(QueryErrorResetBoundaryContext.Provider, {\n\t\tvalue,\n\t\tchildren: typeof children === \"function\" ? children(value) : children\n\t});\n};\nexport { QueryErrorResetBoundary, useQueryErrorResetBoundary };\n\n//# sourceMappingURL=QueryErrorResetBoundary.js.map","\"use client\";\nimport * as React from \"react\";\nimport { shouldThrowError } from \"@tanstack/query-core\";\n// src/errorBoundaryUtils.ts\n/**\n* Turns off `retryOnMount` for a query that throws its errors (with `suspense` or `throwOnError`),\n* unless the error boundary has been reset, so a remount doesn't retry the failed query before the\n* user resets the boundary. Mutates the options.\n* @param options - The defaulted query options to adjust.\n* @param errorResetBoundary - The value of the nearest `QueryErrorResetBoundary`.\n* @param query - The query, used to evaluate a `throwOnError` function against its error.\n*/\nconst ensurePreventErrorBoundaryRetry = (options, errorResetBoundary, query) => {\n\tconst throwOnError = query?.state.status === \"error\" && typeof options.throwOnError === \"function\" ? shouldThrowError(options.throwOnError, [query.state.error, query]) : options.throwOnError;\n\tif (options.suspense || throwOnError) {\n\t\tif (!errorResetBoundary.isReset()) options.retryOnMount = false;\n\t}\n};\n/**\n* Clears the reset state of the error boundary after the component mounts, so later errors are\n* thrown to the boundary again.\n* @param errorResetBoundary - The value of the nearest `QueryErrorResetBoundary`.\n*/\nconst useClearResetErrorBoundary = (errorResetBoundary) => {\n\tReact.useEffect(() => {\n\t\terrorResetBoundary.clearReset();\n\t}, [errorResetBoundary]);\n};\n/**\n* Checks whether the query error should be thrown to the nearest error boundary: the query errored\n* and isn't fetching, the boundary hasn't been reset, and either `suspense` is enabled with no data\n* or `throwOnError` says so.\n* @param params - The observer `result`, the `errorResetBoundary`, the `throwOnError` option, the\n* `query`, and the `suspense` option.\n* @returns `true` if the error should be thrown.\n*/\nconst getHasError = ({ result, errorResetBoundary, throwOnError, query, suspense }) => {\n\treturn result.isError && !errorResetBoundary.isReset() && !result.isFetching && query && (suspense && result.data === void 0 || shouldThrowError(throwOnError, [result.error, query]));\n};\nexport { ensurePreventErrorBoundaryRetry, getHasError, useClearResetErrorBoundary };\n\n//# sourceMappingURL=errorBoundaryUtils.js.map","// src/suspense.ts\n/**\n* The default `throwOnError` of the suspense hooks: throws the error to the nearest error boundary\n* only if the query has no data to show.\n* @param _error - The error of the query. Unused.\n* @param query - The query that errored.\n* @returns `true` if the query has no data.\n*/\nconst defaultThrowOnError = (_error, query) => query.state.data === void 0;\n/**\n* Raises `staleTime` and a numeric `gcTime` to at least 1000ms when `suspense` is enabled, so a\n* component that remounts after suspending doesn't refetch right away or find the query garbage\n* collected. A `'static'` `staleTime` is kept as is. Mutates the options.\n* @param defaultedOptions - The defaulted query options to adjust.\n*/\nconst ensureSuspenseTimers = (defaultedOptions) => {\n\tif (defaultedOptions.suspense) {\n\t\tconst MIN_SUSPENSE_TIME_MS = 1e3;\n\t\tconst clamp = (value) => value === \"static\" ? value : Math.max(value ?? MIN_SUSPENSE_TIME_MS, MIN_SUSPENSE_TIME_MS);\n\t\tconst originalStaleTime = defaultedOptions.staleTime;\n\t\tdefaultedOptions.staleTime = typeof originalStaleTime === \"function\" ? (...args) => clamp(originalStaleTime(...args)) : clamp(originalStaleTime);\n\t\tif (typeof defaultedOptions.gcTime === \"number\") defaultedOptions.gcTime = Math.max(defaultedOptions.gcTime, MIN_SUSPENSE_TIME_MS);\n\t}\n};\n/**\n* Checks whether a query should suspend: `suspense` is enabled and the result is still `pending`.\n* @param defaultedOptions - The defaulted query options, if any.\n* @param result - The current result of the observer.\n* @returns `true` if the component should suspend.\n*/\nconst shouldSuspend = (defaultedOptions, result) => defaultedOptions?.suspense && result.isPending;\n/**\n* Fetches the query for a suspending component, without affecting the observer's own result. If\n* the fetch fails, the reset state of the error boundary is cleared, so the error is thrown to it.\n* @param defaultedOptions - The defaulted query options to fetch with.\n* @param observer - The observer of the query.\n* @param errorResetBoundary - The value of the nearest `QueryErrorResetBoundary`.\n* @returns A promise that resolves once the fetch settles. It never rejects.\n*/\nconst fetchOptimistic = (defaultedOptions, observer, errorResetBoundary) => observer.fetchOptimistic(defaultedOptions).catch(() => {\n\terrorResetBoundary.clearReset();\n});\nexport { defaultThrowOnError, ensureSuspenseTimers, fetchOptimistic, shouldSuspend };\n\n//# sourceMappingURL=suspense.js.map","\"use client\";\nimport { useQueryClient } from \"./QueryClientProvider.js\";\nimport { useIsRestoring } from \"./IsRestoringProvider.js\";\nimport { useQueryErrorResetBoundary } from \"./QueryErrorResetBoundary.js\";\nimport { ensurePreventErrorBoundaryRetry, getHasError, useClearResetErrorBoundary } from \"./errorBoundaryUtils.js\";\nimport { ensureSuspenseTimers, fetchOptimistic, shouldSuspend } from \"./suspense.js\";\nimport * as React from \"react\";\nimport { noop, notifyManager } from \"@tanstack/query-core\";\n// src/useBaseQuery.ts\n/**\n* Base implementation shared by `useQuery`, `useInfiniteQuery`, `useSuspenseQuery`, and\n* `useSuspenseInfiniteQuery`.\n* @param options - The options passed to the calling hook.\n* @param Observer - The observer class from query-core (`QueryObserver` or\n* `InfiniteQueryObserver`).\n* @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest\n* context will be used.\n* @returns The query result, tracking which properties are read unless `notifyOnChangeProps` is\n* set.\n* @throws {Error} If `options` is not an object (outside production), or the query error when it should be\n* thrown to the nearest error boundary (see `throwOnError`). While suspending, it throws a promise instead.\n*/\nfunction useBaseQuery(options, Observer, queryClient) {\n\tif (process.env.NODE_ENV !== \"production\") {\n\t\tif (typeof options !== \"object\" || Array.isArray(options)) throw new Error(\"Bad argument type. Starting with v5, only the \\\"Object\\\" form is allowed when calling query related functions. Please use the error stack to find the culprit call. More info here: https://tanstack.com/query/latest/docs/react/guides/migrating-to-v5#supports-a-single-signature-one-object\");\n\t}\n\tconst isRestoring = useIsRestoring();\n\tconst errorResetBoundary = useQueryErrorResetBoundary();\n\tconst client = useQueryClient(queryClient);\n\tconst defaultedOptions = client.defaultQueryOptions(options);\n\tconst query = client.getQueryCache().get(defaultedOptions.queryHash);\n\tif (process.env.NODE_ENV !== \"production\") {\n\t\tif (!defaultedOptions.queryFn) console.error(`[${defaultedOptions.queryHash}]: No queryFn was passed as an option, and no default queryFn was found. The queryFn parameter is only optional when using a default queryFn. More info here: https://tanstack.com/query/latest/docs/framework/react/guides/default-query-function`);\n\t}\n\tconst subscribed = options.subscribed !== false;\n\tdefaultedOptions._optimisticResults = isRestoring ? \"isRestoring\" : subscribed ? \"optimistic\" : void 0;\n\tensureSuspenseTimers(defaultedOptions);\n\tensurePreventErrorBoundaryRetry(defaultedOptions, errorResetBoundary, query);\n\tuseClearResetErrorBoundary(errorResetBoundary);\n\tconst [observer] = React.useState(() => new Observer(client, defaultedOptions));\n\tconst result = observer.getOptimisticResult(defaultedOptions);\n\tReact.useEffect(() => {\n\t\tobserver.setOptions(defaultedOptions);\n\t}, [defaultedOptions, observer]);\n\tconst shouldSubscribe = !isRestoring && subscribed;\n\tReact.useSyncExternalStore(React.useCallback((onStoreChange) => {\n\t\tconst unsubscribe = shouldSubscribe ? observer.subscribe(notifyManager.batchCalls(onStoreChange)) : noop;\n\t\tobserver.updateResult();\n\t\treturn unsubscribe;\n\t}, [observer, shouldSubscribe]), () => observer.getCurrentResult(), () => observer.getCurrentResult());\n\tif (shouldSuspend(defaultedOptions, result)) throw fetchOptimistic(defaultedOptions, observer, errorResetBoundary);\n\tif (getHasError({\n\t\tresult,\n\t\terrorResetBoundary,\n\t\tthrowOnError: defaultedOptions.throwOnError,\n\t\tquery,\n\t\tsuspense: defaultedOptions.suspense\n\t})) throw result.error;\n\treturn !defaultedOptions.notifyOnChangeProps ? observer.trackResult(result) : result;\n}\nexport { useBaseQuery };\n\n//# sourceMappingURL=useBaseQuery.js.map","\"use client\";\nimport { useBaseQuery } from \"./useBaseQuery.js\";\nimport { QueryObserver } from \"@tanstack/query-core\";\n// src/useQuery.ts\nfunction useQuery(options, queryClient) {\n\treturn useBaseQuery(options, QueryObserver, queryClient);\n}\nexport { useQuery };\n\n//# sourceMappingURL=useQuery.js.map","\"use client\";\nimport { useQueryClient } from \"./QueryClientProvider.js\";\nimport * as React from \"react\";\nimport { MutationObserver, noop, notifyManager, shouldThrowError } from \"@tanstack/query-core\";\n// src/useMutation.ts\n/**\n* Unlike queries, mutations are typically used to create/update/delete data or perform server side-effects.\n* `useMutation` is the hook for that.\n* @param options - The {@link UseMutationOptions} to use — everything you can pass to `useMutation`.\n* @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will\n* be used.\n* @returns `mutate`/`mutateAsync` also accept per-call `onSuccess`/`onError`/`onSettled` callbacks as a second\n* argument, useful for triggering call-site side effects (e.g. navigation) without coupling them to the shared\n* mutation definition. Hook-level callbacks (passed to `options`) fire for every mutation; per-call callbacks\n* fire only for the latest call you've made, and only while the component is still mounted — unmounting before\n* the mutation settles removes the subscription and prevents them from firing.\n* @throws {Error} The mutation error, when `throwOnError` is `true` or returns `true` for it, so that it is\n* thrown to the nearest error boundary.\n* @see {@link mutationOptions} to share these options across multiple `useMutation` call sites, or to look\n* the mutation up elsewhere via its `mutationKey` (e.g. with `useMutationState`).\n* @example\n* ```tsx\n* import { useMutation, useQueryClient } from '@tanstack/react-query'\n*\n* function AddTodo() {\n* const queryClient = useQueryClient()\n*\n* const addMutation = useMutation({\n* mutationFn: addTodo,\n* onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),\n* })\n*\n* return (\n* <button\n* onClick={() =>\n* addMutation.mutate('Item', {\n* onError: (error) => console.error('Failed to add item:', error),\n* })\n* }\n* >\n* Add\n* </button>\n* )\n* }\n* ```\n* @example\n* Rendering the mutation's own state, rather than just firing it off:\n* ```tsx\n* import { useMutation, useQueryClient } from '@tanstack/react-query'\n*\n* function AddTodo() {\n* const queryClient = useQueryClient()\n*\n* const addMutation = useMutation({\n* mutationFn: addTodo,\n* onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),\n* })\n*\n* return (\n* <div>\n* {addMutation.isPending ? (\n* 'Adding todo...'\n* ) : (\n* <>\n* {addMutation.isError ? (\n* <div>An error occurred: {addMutation.error.message}</div>\n* ) : null}\n* <button onClick={() => addMutation.mutate('Item')}>Add</button>\n* </>\n* )}\n* </div>\n* )\n* }\n* ```\n* @example\n* Optimistic update via `onMutate`, rolling back on `onError`:\n* ```tsx\n* import { useMutation, useQueryClient } from '@tanstack/react-query'\n*\n* function AddTodo() {\n* const queryClient = useQueryClient()\n*\n* const addMutation = useMutation({\n* mutationFn: addTodo,\n* onMutate: async (newTodo) => {\n* await queryClient.cancelQueries({ queryKey: ['todos'] })\n* const previousTodos = queryClient.getQueryData<Array<string>>(['todos'])\n*\n* queryClient.setQueryData<Array<string>>(['todos'], (old) => [\n* ...(old ?? []),\n* newTodo,\n* ])\n*\n* // Passed to `onError` as `onMutateResult` if the mutation fails.\n* return { previousTodos }\n* },\n* onError: (_err, _newTodo, onMutateResult) => {\n* queryClient.setQueryData(['todos'], onMutateResult?.previousTodos)\n* },\n* onSettled: () => {\n* queryClient.invalidateQueries({ queryKey: ['todos'] })\n* },\n* })\n*\n* return (\n* <button onClick={() => addMutation.mutate('Item')}>Add</button>\n* )\n* }\n* ```\n* @example\n* Callbacks passed per call to `mutate` only fire for the last call — `mutateAsync` gives you a\n* promise per call instead, so you can wait for all of them when they succeed:\n* ```tsx\n* import { useMutation, useQueryClient } from '@tanstack/react-query'\n*\n* function AddTodos() {\n* const queryClient = useQueryClient()\n*\n* const addMutation = useMutation({\n* mutationFn: addTodo,\n* onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),\n* })\n*\n* async function handleAddAll(todos: Array<string>) {\n* try {\n* await Promise.all(todos.map((todo) => addMutation.mutateAsync(todo)))\n* } catch (error) {\n* console.error('Failed to add todos:', error)\n* }\n* }\n*\n* return (\n* <button onClick={() => handleAddAll(['Todo 1', 'Todo 2', 'Todo 3'])}>\n* Add all\n* </button>\n* )\n* }\n* ```\n* @example\n* If some of the mutations above can fail independently of the others, and you want to know which ones\n* did — rather than losing that information the moment the first one rejects — swap `Promise.all` for\n* `Promise.allSettled`:\n* ```tsx\n* import { useMutation, useQueryClient } from '@tanstack/react-query'\n*\n* function AddTodos() {\n* const queryClient = useQueryClient()\n*\n* const addMutation = useMutation({\n* mutationFn: addTodo,\n* onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),\n* })\n*\n* async function handleAddAll(todos: Array<string>) {\n* const addResults = await Promise.allSettled(\n* todos.map((todo) => addMutation.mutateAsync(todo)),\n* )\n*\n* addResults.forEach((addResult, index) => {\n* if (addResult.status === 'rejected') {\n* console.error(`Failed to add \"${todos[index]}\":`, addResult.reason)\n* }\n* })\n* }\n*\n* return (\n* <button onClick={() => handleAddAll(['Todo 1', 'Todo 2', 'Todo 3'])}>\n* Add all\n* </button>\n* )\n* }\n* ```\n*/\nfunction useMutation(options, queryClient) {\n\tconst client = useQueryClient(queryClient);\n\tconst [observer] = React.useState(() => new MutationObserver(client, options));\n\tReact.useEffect(() => {\n\t\tobserver.setOptions(options);\n\t}, [observer, options]);\n\tconst result = React.useSyncExternalStore(React.useCallback((onStoreChange) => observer.subscribe(notifyManager.batchCalls(onStoreChange)), [observer]), () => observer.getCurrentResult(), () => observer.getCurrentResult());\n\tconst mutate = React.useCallback((...args) => {\n\t\tobserver.mutate(args[0], args[1]).catch(noop);\n\t}, [observer]);\n\tif (result.error && shouldThrowError(observer.options.throwOnError, [result.error])) throw result.error;\n\treturn {\n\t\t...result,\n\t\tmutate,\n\t\tmutateAsync: result.mutate\n\t};\n}\nexport { useMutation };\n\n//# sourceMappingURL=useMutation.js.map","\"use client\";\nimport { useBaseQuery } from \"./useBaseQuery.js\";\nimport { InfiniteQueryObserver } from \"@tanstack/query-core\";\n// src/useInfiniteQuery.ts\nfunction useInfiniteQuery(options, queryClient) {\n\treturn useBaseQuery(options, InfiniteQueryObserver, queryClient);\n}\nexport { useInfiniteQuery };\n\n//# sourceMappingURL=useInfiniteQuery.js.map","'use strict';\n\n/**\n * Create a bound version of a function with a specified `this` context\n *\n * @param {Function} fn - The function to bind\n * @param {*} thisArg - The value to be passed as the `this` parameter\n * @returns {Function} A new function that will call the original function with the specified `this` context\n */\nexport default function bind(fn, thisArg) {\n return function wrap() {\n return fn.apply(thisArg, arguments);\n };\n}\n","'use strict';\n\nimport bind from './helpers/bind.js';\n\n// utils is a library of generic helper functions non-specific to axios\n\nconst { toString } = Object.prototype;\nconst { getPrototypeOf } = Object;\nconst { iterator, toStringTag } = Symbol;\n\n/* Creating a function that will check if an object has a property. */\nconst hasOwnProperty = (\n ({ hasOwnProperty }) =>\n (obj, prop) =>\n hasOwnProperty.call(obj, prop)\n)(Object.prototype);\n\nconst isUnsafeObjectKey = (prop) =>\n typeof prop === 'string' &&\n (prop === '__proto__' || prop === 'constructor' || prop === 'prototype');\n\n/**\n * Determine whether an inherited object must be treated as a shared-prototype\n * boundary. Cross-realm Object.prototype objects cannot be distinguished\n * reliably from application-created null-prototype objects because their\n * properties are mutable, so all inherited terminal prototypes are excluded\n * as a fail-closed boundary. A null-prototype source still keeps its own\n * properties, as produced by mergeConfig and other safe materialization paths.\n *\n * @param {*} obj The object to inspect\n * @param {*} prototype The object's prototype\n * @param {boolean} source Whether obj is the original traversal source\n *\n * @returns {boolean} True when obj is a safe prototype traversal boundary\n */\nconst isPrototypeBoundary = (obj, prototype, source) =>\n obj === Object.prototype || (!source && prototype === null);\n\n/**\n * Determine whether an object can retain its identity through code paths that\n * add, replace, and remove config properties without bypassing unsafe-key\n * filtering. Immutable objects, unsafe-key-bearing objects, and objects with\n * accessor or restricted data properties must be materialized instead.\n *\n * @param {*} obj The object to inspect\n *\n * @returns {boolean} True when every own property is safe and fully mutable\n */\nconst isSafeAndFullyMutable = (obj) => {\n if (!Object.isExtensible(obj)) {\n return false;\n }\n\n const props = Object.getOwnPropertyNames(obj);\n\n if (Object.getOwnPropertySymbols) {\n props.push(...Object.getOwnPropertySymbols(obj));\n }\n\n return props.every((prop) => {\n if (isUnsafeObjectKey(prop)) {\n return false;\n }\n\n const descriptor = Object.getOwnPropertyDescriptor(obj, prop);\n\n return !!descriptor && descriptor.configurable && descriptor.writable === true;\n });\n};\n\n/**\n * Walk the prototype chain (excluding the source realm's Object.prototype)\n * looking for an own `prop`. This distinguishes genuine own/inherited members\n * — including class accessors and template prototypes — from members injected\n * via Object.prototype pollution (e.g. `Object.prototype.username = '...'`),\n * which live on Object.prototype itself and are therefore never matched.\n *\n * @param {*} thing The value whose chain to inspect\n * @param {string|symbol} prop The property key to look for\n *\n * @returns {boolean} True when `prop` is owned below Object.prototype\n */\nconst hasOwnInPrototypeChain = (thing, prop) => {\n let obj = thing;\n const seen = [];\n\n while (obj != null) {\n if (seen.indexOf(obj) !== -1) {\n return false;\n }\n seen.push(obj);\n\n const prototype = getPrototypeOf(obj);\n\n if (isPrototypeBoundary(obj, prototype, obj === thing)) {\n return false;\n }\n\n if (hasOwnProperty(obj, prop)) {\n return true;\n }\n obj = prototype;\n }\n return false;\n};\n\n/**\n * Read `obj[prop]` only when it is safe from Object.prototype pollution. Own\n * properties and members inherited from a non-Object.prototype source (a class\n * instance or template object) are honored; a value reachable only through a\n * polluted Object.prototype is ignored and `undefined` is returned.\n *\n * @param {*} obj The source object\n * @param {string|symbol} prop The property key to read\n *\n * @returns {*} The resolved value, or undefined when unsafe/absent\n */\nconst getSafeProp = (obj, prop) =>\n obj != null && hasOwnInPrototypeChain(obj, prop) ? obj[prop] : undefined;\n\n/**\n * Flatten an object and its application-defined prototype chain into a\n * null-prototype object. Members inherited only from the source realm's\n * Object.prototype are deliberately excluded, while class/template members\n * below that boundary are preserved.\n *\n * @param {*} thing The value to flatten\n *\n * @returns {*} A null-prototype copy, or the original value when it is already\n * structurally safe or is not an object\n */\nconst toSafeFlatObject = (thing) => {\n if (thing == null || (typeof thing !== 'object' && typeof thing !== 'function')) {\n return thing;\n }\n\n const sourcePrototype = getPrototypeOf(thing);\n\n if (sourcePrototype === null && isSafeAndFullyMutable(thing)) {\n return thing;\n }\n\n const result = Object.create(null);\n const merged = Object.create(null);\n const seen = [];\n let current = thing;\n\n while (current != null) {\n if (seen.indexOf(current) !== -1) {\n break;\n }\n\n seen.push(current);\n\n const prototype = current === thing ? sourcePrototype : getPrototypeOf(current);\n\n if (isPrototypeBoundary(current, prototype, current === thing)) {\n break;\n }\n\n const props = Object.getOwnPropertyNames(current);\n\n if (Object.getOwnPropertySymbols) {\n props.push(...Object.getOwnPropertySymbols(current));\n }\n\n for (const prop of props) {\n if (isUnsafeObjectKey(prop)) {\n continue;\n }\n\n if (!hasOwnProperty(merged, prop)) {\n result[prop] = thing[prop];\n merged[prop] = true;\n }\n }\n\n current = prototype;\n }\n\n return result;\n};\n\nconst kindOf = ((cache) => (thing) => {\n const str = toString.call(thing);\n return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase());\n})(Object.create(null));\n\nconst kindOfTest = (type) => {\n type = type.toLowerCase();\n return (thing) => kindOf(thing) === type;\n};\n\nconst typeOfTest = (type) => (thing) => typeof thing === type;\n\n/**\n * Determine if a value is a non-null object\n *\n * @param {Object} val The value to test\n *\n * @returns {boolean} True if value is an Array, otherwise false\n */\nconst { isArray } = Array;\n\n/**\n * Determine if a value is undefined\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if the value is undefined, otherwise false\n */\nconst isUndefined = typeOfTest('undefined');\n\n/**\n * Determine if a value is a Buffer\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a Buffer, otherwise false\n */\nfunction isBuffer(val) {\n return (\n val !== null &&\n !isUndefined(val) &&\n val.constructor !== null &&\n !isUndefined(val.constructor) &&\n isFunction(val.constructor.isBuffer) &&\n val.constructor.isBuffer(val)\n );\n}\n\n/**\n * Determine if a value is an ArrayBuffer\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is an ArrayBuffer, otherwise false\n */\nconst isArrayBuffer = kindOfTest('ArrayBuffer');\n\n/**\n * Determine if a value is a view on an ArrayBuffer\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false\n */\nfunction isArrayBufferView(val) {\n let result;\n if (typeof ArrayBuffer !== 'undefined' && ArrayBuffer.isView) {\n result = ArrayBuffer.isView(val);\n } else {\n result = val && val.buffer && isArrayBuffer(val.buffer);\n }\n return result;\n}\n\n/**\n * Determine if a value is a String\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a String, otherwise false\n */\nconst isString = typeOfTest('string');\n\n/**\n * Determine if a value is a Function\n *\n * @param {*} val The value to test\n * @returns {boolean} True if value is a Function, otherwise false\n */\nconst isFunction = typeOfTest('function');\n\n/**\n * Determine if a value is a Number\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a Number, otherwise false\n */\nconst isNumber = typeOfTest('number');\n\n/**\n * Determine if a value is an Object\n *\n * @param {*} thing The value to test\n *\n * @returns {boolean} True if value is an Object, otherwise false\n */\nconst isObject = (thing) => thing !== null && typeof thing === 'object';\n\n/**\n * Determine if a value is a Boolean\n *\n * @param {*} thing The value to test\n * @returns {boolean} True if value is a Boolean, otherwise false\n */\nconst isBoolean = (thing) => thing === true || thing === false;\n\n/**\n * Determine if a value is a plain Object\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a plain Object, otherwise false\n */\nconst isPlainObject = (val) => {\n if (!isObject(val)) {\n return false;\n }\n\n const prototype = getPrototypeOf(val);\n return (\n (prototype === null || prototype === Object.prototype || getPrototypeOf(prototype) === null) &&\n // Treat own Symbol.toStringTag or Symbol.iterator members as evidence the\n // value is tagged/iterable, ignoring members reachable only through shared\n // or terminal prototype boundaries. This is exactly what\n // hasOwnInPrototypeChain(val, prop) computes here: every prototype admitted\n // above (null, Object.prototype, or a terminal null-prototype template) is\n // a boundary, so the walk never inspects anything but `val`'s own members,\n // and stops before even those when `val` is itself the boundary\n // Object.prototype. Checking that inline avoids allocating the walker's\n // `seen` list twice per call on the mergeConfig / merge hot path.\n (isPrototypeBoundary(val, prototype, true) ||\n (!hasOwnProperty(val, toStringTag) && !hasOwnProperty(val, iterator)))\n );\n};\n\n/**\n * Determine if a value is an empty object (safely handles Buffers)\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is an empty object, otherwise false\n */\nconst isEmptyObject = (val) => {\n // Early return for non-objects or Buffers to prevent RangeError\n if (!isObject(val) || isBuffer(val)) {\n return false;\n }\n\n try {\n return Object.keys(val).length === 0 && Object.getPrototypeOf(val) === Object.prototype;\n } catch (e) {\n // Fallback for any other objects that might cause RangeError with Object.keys()\n return false;\n }\n};\n\n/**\n * Determine if a value is a Date\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a Date, otherwise false\n */\nconst isDate = kindOfTest('Date');\n\n/**\n * Determine if a value is a File\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a File, otherwise false\n */\nconst isFile = kindOfTest('File');\n\n/**\n * Determine if a value is a React Native Blob\n * React Native \"blob\": an object with a `uri` attribute. Optionally, it can\n * also have a `name` and `type` attribute to specify filename and content type\n *\n * @see https://github.com/facebook/react-native/blob/26684cf3adf4094eb6c405d345a75bf8c7c0bf88/Libraries/Network/FormData.js#L68-L71\n *\n * @param {*} value The value to test\n *\n * @returns {boolean} True if value is a React Native Blob, otherwise false\n */\nconst isReactNativeBlob = (value) => {\n return !!(value && typeof value.uri !== 'undefined');\n};\n\n/**\n * Determine if environment is React Native\n * ReactNative `FormData` has a non-standard `getParts()` method\n *\n * @param {*} formData The formData to test\n *\n * @returns {boolean} True if environment is React Native, otherwise false\n */\nconst isReactNative = (formData) => formData && typeof formData.getParts !== 'undefined';\n\n/**\n * Determine if a value is a Blob\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a Blob, otherwise false\n */\nconst isBlob = kindOfTest('Blob');\n\n/**\n * Determine if a value is a FileList\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a FileList, otherwise false\n */\nconst isFileList = kindOfTest('FileList');\nconst isSet = kindOfTest('Set');\n\n/**\n * Determine if a value is a Stream\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a Stream, otherwise false\n */\nconst isStream = (val) => isObject(val) && isFunction(val.pipe);\n\n/**\n * Determine if a value is a FormData\n *\n * @param {*} thing The value to test\n *\n * @returns {boolean} True if value is an FormData, otherwise false\n */\nfunction getGlobal() {\n if (typeof globalThis !== 'undefined') return globalThis;\n if (typeof self !== 'undefined') return self;\n if (typeof window !== 'undefined') return window;\n if (typeof global !== 'undefined') return global;\n return {};\n}\n\nconst G = getGlobal();\nconst FormDataCtor = typeof G.FormData !== 'undefined' ? G.FormData : undefined;\n\nconst isFormData = (thing) => {\n if (!thing) return false;\n if (FormDataCtor && thing instanceof FormDataCtor) return true;\n // Reject plain objects inheriting directly from Object.prototype so prototype-pollution gadgets can't spoof FormData.\n const proto = getPrototypeOf(thing);\n if (!proto || proto === Object.prototype) return false;\n if (!isFunction(thing.append)) return false;\n const kind = kindOf(thing);\n return (\n kind === 'formdata' ||\n // detect form-data instance\n (kind === 'object' && isFunction(thing.toString) && thing.toString() === '[object FormData]')\n );\n};\n\n/**\n * Determine if a value is a URLSearchParams object\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a URLSearchParams object, otherwise false\n */\nconst isURLSearchParams = kindOfTest('URLSearchParams');\n\nconst [isReadableStream, isRequest, isResponse, isHeaders] = [\n 'ReadableStream',\n 'Request',\n 'Response',\n 'Headers',\n].map(kindOfTest);\n\n/**\n * Trim excess whitespace off the beginning and end of a string\n *\n * @param {String} str The String to trim\n *\n * @returns {String} The String freed of excess whitespace\n */\nconst trim = (str) => {\n return str.trim ? str.trim() : str.replace(/^[\\s\\uFEFF\\xA0]+|[\\s\\uFEFF\\xA0]+$/g, '');\n};\n/**\n * Iterate over an Array or an Object invoking a function for each item.\n *\n * If `obj` is an Array callback will be called passing\n * the value, index, and complete array for each item.\n *\n * If 'obj' is an Object callback will be called passing\n * the value, key, and complete object for each property.\n *\n * @param {Object|Array<unknown>} obj The object to iterate\n * @param {Function} fn The callback to invoke for each item\n *\n * @param {Object} [options]\n * @param {Boolean} [options.allOwnKeys = false]\n * @returns {any}\n */\nfunction forEach(obj, fn, { allOwnKeys = false } = {}) {\n // Don't bother if no value provided\n if (obj === null || typeof obj === 'undefined') {\n return;\n }\n\n let i;\n let l;\n\n // Force an array if not already something iterable\n if (typeof obj !== 'object') {\n /*eslint no-param-reassign:0*/\n obj = [obj];\n }\n\n if (isArray(obj)) {\n // Iterate over array values\n for (i = 0, l = obj.length; i < l; i++) {\n fn.call(null, obj[i], i, obj);\n }\n } else {\n // Buffer check\n if (isBuffer(obj)) {\n return;\n }\n\n // Iterate over object keys\n const keys = allOwnKeys ? Object.getOwnPropertyNames(obj) : Object.keys(obj);\n const len = keys.length;\n let key;\n\n for (i = 0; i < len; i++) {\n key = keys[i];\n fn.call(null, obj[key], key, obj);\n }\n }\n}\n\n/**\n * Finds a key in an object, case-insensitive, returning the actual key name.\n * Returns null if the object is a Buffer or if no match is found.\n *\n * @param {Object} obj - The object to search.\n * @param {string} key - The key to find (case-insensitive).\n * @returns {?string} The actual key name if found, otherwise null.\n */\nfunction findKey(obj, key) {\n if (isBuffer(obj)) {\n return null;\n }\n\n key = key.toLowerCase();\n const keys = Object.keys(obj);\n let i = keys.length;\n let _key;\n while (i-- > 0) {\n _key = keys[i];\n if (key === _key.toLowerCase()) {\n return _key;\n }\n }\n return null;\n}\n\nconst _global = (() => {\n /*eslint no-undef:0*/\n if (typeof globalThis !== 'undefined') return globalThis;\n return typeof self !== 'undefined' ? self : typeof window !== 'undefined' ? window : global;\n})();\n\nconst isContextDefined = (context) => !isUndefined(context) && context !== _global;\n\n/**\n * Accepts varargs expecting each argument to be an object, then\n * immutably merges the properties of each object and returns result.\n *\n * When multiple objects contain the same key the later object in\n * the arguments list will take precedence.\n *\n * Example:\n *\n * ```js\n * const result = merge({foo: 123}, {foo: 456});\n * console.log(result.foo); // outputs 456\n * ```\n *\n * @param {Object} obj1 Object to merge\n *\n * @returns {Object} Result of all merge properties\n */\nfunction merge(...objs) {\n const { caseless, skipUndefined } = (isContextDefined(this) && this) || {};\n const result = {};\n // Caseless lookup only applies to string keys — symbol keys are\n // identity-matched. Every string key that reaches `result` passes through\n // this index first, so it can never hold two case variants of one key and a\n // lowercase -> key map is exactly what findKey(result, key) would rescan\n // Object.keys(result) for on each assignment.\n const lowerCaseKeys = caseless ? Object.create(null) : null;\n const assignValue = (val, key) => {\n // Skip dangerous property names to prevent prototype pollution\n if (key === '__proto__' || key === 'constructor' || key === 'prototype') {\n return;\n }\n\n let targetKey = key;\n if (lowerCaseKeys && typeof key === 'string') {\n const lowerKey = key.toLowerCase();\n const knownKey = lowerCaseKeys[lowerKey];\n // A key recorded but absent from `result` was skipped by skipUndefined;\n // the later spelling wins then, as it does for findKey.\n if (knownKey !== undefined && hasOwnProperty(result, knownKey)) {\n targetKey = knownKey;\n } else {\n lowerCaseKeys[lowerKey] = key;\n }\n }\n // Read via own-prop only — a bare `result[targetKey]` walks the prototype\n // chain, so a polluted Object.prototype value could surface here and get\n // copied into the merged result.\n const existing = hasOwnProperty(result, targetKey) ? result[targetKey] : undefined;\n if (isPlainObject(existing) && isPlainObject(val)) {\n result[targetKey] = merge(existing, val);\n } else if (isPlainObject(val)) {\n result[targetKey] = merge({}, val);\n } else if (isArray(val)) {\n result[targetKey] = val.slice();\n } else if (!skipUndefined || !isUndefined(val)) {\n result[targetKey] = val;\n }\n };\n\n for (let i = 0, l = objs.length; i < l; i++) {\n const source = objs[i];\n if (!source || isBuffer(source)) {\n continue;\n }\n\n forEach(source, assignValue);\n\n if (typeof source !== 'object' || isArray(source) || !Object.getOwnPropertySymbols) {\n continue;\n }\n\n const symbols = Object.getOwnPropertySymbols(source);\n for (let j = 0; j < symbols.length; j++) {\n const symbol = symbols[j];\n if (propertyIsEnumerable.call(source, symbol)) {\n assignValue(source[symbol], symbol);\n }\n }\n }\n return result;\n}\n\n/**\n * Extends object a by mutably adding to it the properties of object b.\n *\n * @param {Object} a The object to be extended\n * @param {Object} b The object to copy properties from\n * @param {Object} thisArg The object to bind function to\n *\n * @param {Object} [options]\n * @param {Boolean} [options.allOwnKeys]\n * @returns {Object} The resulting value of object a\n */\nconst extend = (a, b, thisArg, { allOwnKeys } = {}) => {\n forEach(\n b,\n (val, key) => {\n if (thisArg && isFunction(val)) {\n Object.defineProperty(a, key, {\n // Null-proto descriptor so a polluted Object.prototype.get cannot\n // hijack defineProperty's accessor-vs-data resolution.\n __proto__: null,\n value: bind(val, thisArg),\n writable: true,\n enumerable: true,\n configurable: true,\n });\n } else {\n Object.defineProperty(a, key, {\n __proto__: null,\n value: val,\n writable: true,\n enumerable: true,\n configurable: true,\n });\n }\n },\n { allOwnKeys }\n );\n return a;\n};\n\n/**\n * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)\n *\n * @param {string} content with BOM\n *\n * @returns {string} content value without BOM\n */\nconst stripBOM = (content) => {\n if (content.charCodeAt(0) === 0xfeff) {\n content = content.slice(1);\n }\n return content;\n};\n\n/**\n * Inherit the prototype methods from one constructor into another\n * @param {function} constructor\n * @param {function} superConstructor\n * @param {object} [props]\n * @param {object} [descriptors]\n *\n * @returns {void}\n */\nconst inherits = (constructor, superConstructor, props, descriptors) => {\n constructor.prototype = Object.create(superConstructor.prototype, descriptors);\n Object.defineProperty(constructor.prototype, 'constructor', {\n __proto__: null,\n value: constructor,\n writable: true,\n enumerable: false,\n configurable: true,\n });\n Object.defineProperty(constructor, 'super', {\n __proto__: null,\n value: superConstructor.prototype,\n });\n props && Object.assign(constructor.prototype, props);\n};\n\n/**\n * Resolve object with deep prototype chain to a flat object\n * @param {Object} sourceObj source object\n * @param {Object} [destObj]\n * @param {Function|Boolean} [filter]\n * @param {Function} [propFilter]\n *\n * @returns {Object}\n */\nconst toFlatObject = (sourceObj, destObj, filter, propFilter) => {\n let props;\n let i;\n let prop;\n const merged = {};\n\n destObj = destObj || {};\n // eslint-disable-next-line no-eq-null,eqeqeq\n if (sourceObj == null) return destObj;\n\n do {\n props = Object.getOwnPropertyNames(sourceObj);\n i = props.length;\n while (i-- > 0) {\n prop = props[i];\n if ((!propFilter || propFilter(prop, sourceObj, destObj)) && !merged[prop]) {\n destObj[prop] = sourceObj[prop];\n merged[prop] = true;\n }\n }\n sourceObj = filter !== false && getPrototypeOf(sourceObj);\n } while (sourceObj && (!filter || filter(sourceObj, destObj)) && sourceObj !== Object.prototype);\n\n return destObj;\n};\n\n/**\n * Determines whether a string ends with the characters of a specified string\n *\n * @param {String} str\n * @param {String} searchString\n * @param {Number} [position= 0]\n *\n * @returns {boolean}\n */\nconst endsWith = (str, searchString, position) => {\n str = String(str);\n if (position === undefined || position > str.length) {\n position = str.length;\n }\n position -= searchString.length;\n const lastIndex = str.indexOf(searchString, position);\n return lastIndex !== -1 && lastIndex === position;\n};\n\n/**\n * Returns new array from array like object or null if failed\n *\n * @param {*} [thing]\n *\n * @returns {?Array}\n */\nconst toArray = (thing) => {\n if (!thing) return null;\n if (isArray(thing)) return thing;\n let i = thing.length;\n if (!Number.isSafeInteger(i) || i < 0 || i > 0xffffffff) return null;\n\n // Bound the copy by actual indexed properties, including hidden and inherited\n // members of array-like collections, rather than by the declared length alone.\n const indexes = new Set();\n const seen = new Set();\n let source = thing;\n\n while (source != null && indexes.size < i) {\n if (seen.has(source)) return null;\n seen.add(source);\n\n const prototype = getPrototypeOf(source);\n if (isPrototypeBoundary(source, prototype, source === thing)) break;\n\n Object.getOwnPropertyNames(source).forEach((key) => {\n const index = +key;\n if (\n Number.isInteger(index) &&\n index >= 0 &&\n index < i &&\n String(index) === key &&\n hasOwnProperty(source, key)\n ) {\n indexes.add(index);\n }\n });\n source = prototype;\n }\n\n if (indexes.size !== i) return null;\n const arr = new Array(i);\n while (i-- > 0) {\n arr[i] = thing[i];\n }\n return arr;\n};\n\n/**\n * Checking if the Uint8Array exists and if it does, it returns a function that checks if the\n * thing passed in is an instance of Uint8Array\n *\n * @param {TypedArray}\n *\n * @returns {Array}\n */\n// eslint-disable-next-line func-names\nconst isTypedArray = ((TypedArray) => {\n // eslint-disable-next-line func-names\n return (thing) => {\n return TypedArray && thing instanceof TypedArray;\n };\n})(typeof Uint8Array !== 'undefined' && getPrototypeOf(Uint8Array));\n\n/**\n * For each entry in the object, call the function with the key and value.\n *\n * @param {Object<any, any>} obj - The object to iterate over.\n * @param {Function} fn - The function to call for each entry.\n *\n * @returns {void}\n */\nconst forEachEntry = (obj, fn) => {\n const generator = obj && obj[iterator];\n\n const _iterator = generator.call(obj);\n\n let result;\n\n while ((result = _iterator.next()) && !result.done) {\n const pair = result.value;\n fn.call(obj, pair[0], pair[1]);\n }\n};\n\n/**\n * It takes a regular expression and a string, and returns an array of all the matches\n *\n * @param {string} regExp - The regular expression to match against.\n * @param {string} str - The string to search.\n *\n * @returns {Array<boolean>}\n */\nconst matchAll = (regExp, str) => {\n let matches;\n const arr = [];\n\n while ((matches = regExp.exec(str)) !== null) {\n arr.push(matches);\n }\n\n return arr;\n};\n\n/* Checking if the kindOfTest function returns true when passed an HTMLFormElement. */\nconst isHTMLForm = kindOfTest('HTMLFormElement');\n\nconst toCamelCase = (str) => {\n return str.toLowerCase().replace(/[-_\\s]([a-z\\d])(\\w*)/g, function replacer(m, p1, p2) {\n return p1.toUpperCase() + p2;\n });\n};\n\nconst { propertyIsEnumerable } = Object.prototype;\n\n/**\n * Determine if a value is a RegExp object\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a RegExp object, otherwise false\n */\nconst isRegExp = kindOfTest('RegExp');\n\nconst reduceDescriptors = (obj, reducer) => {\n const descriptors = Object.getOwnPropertyDescriptors(obj);\n const reducedDescriptors = {};\n\n forEach(descriptors, (descriptor, name) => {\n let ret;\n if ((ret = reducer(descriptor, name, obj)) !== false) {\n reducedDescriptors[name] = ret || descriptor;\n }\n });\n\n Object.defineProperties(obj, reducedDescriptors);\n};\n\n/**\n * Makes all methods read-only\n * @param {Object} obj\n */\n\nconst freezeMethods = (obj) => {\n reduceDescriptors(obj, (descriptor, name) => {\n // skip restricted props in strict mode\n if (isFunction(obj) && ['arguments', 'caller', 'callee'].includes(name)) {\n return false;\n }\n\n const value = obj[name];\n\n if (!isFunction(value)) return;\n\n descriptor.enumerable = false;\n\n if ('writable' in descriptor) {\n descriptor.writable = false;\n return;\n }\n\n if (!descriptor.set) {\n descriptor.set = () => {\n throw Error(\"Can not rewrite read-only method '\" + name + \"'\");\n };\n }\n });\n};\n\n/**\n * Converts an array or a delimited string into an object set with values as keys and true as values.\n * Useful for fast membership checks.\n *\n * @param {Array|string} arrayOrString - The array or string to convert.\n * @param {string} delimiter - The delimiter to use if input is a string.\n * @returns {Object} An object with keys from the array or string, values set to true.\n */\nconst toObjectSet = (arrayOrString, delimiter) => {\n const obj = {};\n\n const define = (arr) => {\n arr.forEach((value) => {\n obj[value] = true;\n });\n };\n\n isArray(arrayOrString) ? define(arrayOrString) : define(String(arrayOrString).split(delimiter));\n\n return obj;\n};\n\nconst noop = () => {};\n\nconst toFiniteNumber = (value, defaultValue) => {\n return value != null && Number.isFinite((value = +value)) ? value : defaultValue;\n};\n\n/**\n * If the thing is a FormData object, return true, otherwise return false.\n *\n * @param {unknown} thing - The thing to check.\n *\n * @returns {boolean}\n */\nfunction isSpecCompliantForm(thing) {\n return !!(\n thing &&\n isFunction(thing.append) &&\n thing[toStringTag] === 'FormData' &&\n thing[iterator]\n );\n}\n\n/**\n * Recursively converts an object to a JSON-compatible object, handling circular references and Buffers.\n *\n * @param {Object} obj - The object to convert.\n * @returns {Object} The JSON-compatible object.\n */\nconst toJSONObject = (obj) => {\n const visited = new WeakSet();\n\n const visit = (source) => {\n if (isObject(source)) {\n if (visited.has(source)) {\n return;\n }\n\n //Buffer check\n if (isBuffer(source)) {\n return source;\n }\n\n if (!('toJSON' in source)) {\n // add-on descent / delete-on-ascent: preserves path semantics, so DAG nodes serialise at every occurrence (see #7230).\n visited.add(source);\n\n let target;\n\n if (isSet(source)) {\n target = [];\n for (const value of source) {\n const reducedValue = visit(value);\n !isUndefined(reducedValue) && target.push(reducedValue);\n }\n } else {\n target = isArray(source) ? [] : {};\n\n forEach(source, (value, key) => {\n const reducedValue = visit(value);\n !isUndefined(reducedValue) && (target[key] = reducedValue);\n });\n }\n\n visited.delete(source);\n\n return target;\n }\n }\n\n return source;\n };\n\n return visit(obj);\n};\n\n/**\n * Determines if a value is an async function.\n *\n * @param {*} thing - The value to test.\n * @returns {boolean} True if value is an async function, otherwise false.\n */\nconst isAsyncFn = kindOfTest('AsyncFunction');\n\n/**\n * Determines if a value is thenable (has then and catch methods).\n *\n * @param {*} thing - The value to test.\n * @returns {boolean} True if value is thenable, otherwise false.\n */\nconst isThenable = (thing) =>\n thing &&\n (isObject(thing) || isFunction(thing)) &&\n isFunction(thing.then) &&\n isFunction(thing.catch);\n\n// original code\n// https://github.com/DigitalBrainJS/AxiosPromise/blob/16deab13710ec09779922131f3fa5954320f83ab/lib/utils.js#L11-L34\n\n/**\n * Provides a cross-platform setImmediate implementation.\n * Uses native setImmediate if available, otherwise falls back to postMessage or setTimeout.\n *\n * @param {boolean} setImmediateSupported - Whether setImmediate is supported.\n * @param {boolean} postMessageSupported - Whether postMessage is supported.\n * @returns {Function} A function to schedule a callback asynchronously.\n */\nconst _setImmediate = ((setImmediateSupported, postMessageSupported) => {\n if (setImmediateSupported) {\n return setImmediate;\n }\n\n return postMessageSupported\n ? ((token, callbacks) => {\n _global.addEventListener(\n 'message',\n ({ source, data }) => {\n if (source === _global && data === token) {\n callbacks.length && callbacks.shift()();\n }\n },\n false\n );\n\n return (cb) => {\n callbacks.push(cb);\n _global.postMessage(token, '*');\n };\n })(`axios@${Math.random()}`, [])\n : (cb) => setTimeout(cb);\n})(typeof setImmediate === 'function', isFunction(_global.postMessage));\n\n/**\n * Schedules a microtask or asynchronous callback as soon as possible.\n * Uses queueMicrotask if available, otherwise falls back to process.nextTick or _setImmediate.\n *\n * @type {Function}\n */\nconst asap =\n typeof queueMicrotask !== 'undefined'\n ? queueMicrotask.bind(_global)\n : (typeof process !== 'undefined' && process.nextTick) || _setImmediate;\n\n// *********************\n\nconst isIterable = (thing) => thing != null && isFunction(thing[iterator]);\n\n/**\n * Determine if a value is iterable via an iterator that is NOT sourced solely\n * from a polluted Object.prototype. Use this instead of `isIterable` whenever\n * the iterable comes from untrusted input (e.g. user-supplied header sources),\n * so `Object.prototype[Symbol.iterator] = ...` cannot turn an ordinary object\n * into an attacker-controlled entries iterator.\n *\n * @param {*} thing The value to test\n *\n * @returns {boolean} True if value has a non-polluted iterator\n */\nconst isSafeIterable = (thing) =>\n thing != null && hasOwnInPrototypeChain(thing, iterator) && isIterable(thing);\n\nexport default {\n isArray,\n isArrayBuffer,\n isBuffer,\n isFormData,\n isArrayBufferView,\n isString,\n isNumber,\n isBoolean,\n isObject,\n isPlainObject,\n isEmptyObject,\n isReadableStream,\n isRequest,\n isResponse,\n isHeaders,\n isUndefined,\n isDate,\n isFile,\n isReactNativeBlob,\n isReactNative,\n isBlob,\n isRegExp,\n isFunction,\n isStream,\n isURLSearchParams,\n isTypedArray,\n isFileList,\n forEach,\n merge,\n extend,\n trim,\n stripBOM,\n inherits,\n toFlatObject,\n kindOf,\n kindOfTest,\n endsWith,\n toArray,\n forEachEntry,\n matchAll,\n isHTMLForm,\n hasOwnProperty,\n hasOwnProp: hasOwnProperty, // an alias to avoid ESLint no-prototype-builtins detection\n hasOwnInPrototypeChain,\n getSafeProp,\n toSafeFlatObject,\n reduceDescriptors,\n freezeMethods,\n toObjectSet,\n toCamelCase,\n noop,\n toFiniteNumber,\n findKey,\n global: _global,\n isContextDefined,\n isSpecCompliantForm,\n toJSONObject,\n isAsyncFn,\n isThenable,\n setImmediate: _setImmediate,\n asap,\n isIterable,\n isSafeIterable,\n};\n","'use strict';\n\nimport utils from '../utils.js';\n\n// RawAxiosHeaders whose duplicates are ignored by node\n// c.f. https://nodejs.org/api/http.html#http_message_headers\nconst ignoreDuplicateOf = utils.toObjectSet([\n 'age',\n 'authorization',\n 'content-length',\n 'content-type',\n 'etag',\n 'expires',\n 'from',\n 'host',\n 'if-modified-since',\n 'if-unmodified-since',\n 'last-modified',\n 'location',\n 'max-forwards',\n 'proxy-authorization',\n 'referer',\n 'retry-after',\n 'user-agent',\n]);\n\n/**\n * Parse headers into an object\n *\n * ```\n * Date: Wed, 27 Aug 2014 08:58:49 GMT\n * Content-Type: application/json\n * Connection: keep-alive\n * Transfer-Encoding: chunked\n * ```\n *\n * @param {String} rawHeaders Headers needing to be parsed\n *\n * @returns {Object} Headers parsed into an object\n */\nexport default (rawHeaders) => {\n // Header names are data, including __proto__; avoid inherited setters.\n const parsed = Object.create(null);\n let key;\n let val;\n let i;\n\n rawHeaders &&\n rawHeaders.split('\\n').forEach(function parser(line) {\n i = line.indexOf(':');\n key = line.substring(0, i).trim().toLowerCase();\n val = line.substring(i + 1).trim();\n\n const hasKey = utils.hasOwnProp(parsed, key);\n\n if (!key || (hasKey && utils.hasOwnProp(ignoreDuplicateOf, key))) {\n return;\n }\n\n if (key === 'set-cookie') {\n if (hasKey) {\n parsed[key].push(val);\n } else {\n parsed[key] = [val];\n }\n } else {\n parsed[key] = hasKey ? parsed[key] + ', ' + val : val;\n }\n });\n\n return parsed;\n};\n","'use strict';\n\nimport utils from '../utils.js';\n\nfunction trimSPorHTAB(str) {\n let start = 0;\n let end = str.length;\n\n while (start < end) {\n const code = str.charCodeAt(start);\n\n if (code !== 0x09 && code !== 0x20) {\n break;\n }\n\n start += 1;\n }\n\n while (end > start) {\n const code = str.charCodeAt(end - 1);\n\n if (code !== 0x09 && code !== 0x20) {\n break;\n }\n\n end -= 1;\n }\n\n return start === 0 && end === str.length ? str : str.slice(start, end);\n}\n\n// The control-code ranges are intentional: header sanitization strips C0/DEL bytes.\n// eslint-disable-next-line no-control-regex\nconst INVALID_UNICODE_HEADER_VALUE_CHARS = new RegExp('[\\\\u0000-\\\\u0008\\\\u000a-\\\\u001f\\\\u007f]+', 'g');\n// eslint-disable-next-line no-control-regex\nconst INVALID_BYTE_STRING_HEADER_VALUE_CHARS = new RegExp('[^\\\\u0009\\\\u0020-\\\\u007e\\\\u0080-\\\\u00ff]+', 'g');\n\nfunction sanitizeValue(value, invalidChars) {\n if (utils.isArray(value)) {\n return value.map((item) => sanitizeValue(item, invalidChars));\n }\n\n return trimSPorHTAB(String(value).replace(invalidChars, ''));\n}\n\nexport const sanitizeHeaderValue = (value) =>\n sanitizeValue(value, INVALID_UNICODE_HEADER_VALUE_CHARS);\n\nexport const sanitizeByteStringHeaderValue = (value) =>\n sanitizeValue(value, INVALID_BYTE_STRING_HEADER_VALUE_CHARS);\n\nexport function toByteStringHeaderObject(headers) {\n const byteStringHeaders = Object.create(null);\n\n utils.forEach(headers.toJSON(), (value, header) => {\n byteStringHeaders[header] = sanitizeByteStringHeaderValue(value);\n });\n\n return byteStringHeaders;\n}\n","'use strict';\n\nimport utils from '../utils.js';\nimport parseHeaders from '../helpers/parseHeaders.js';\nimport { sanitizeHeaderValue } from '../helpers/sanitizeHeaderValue.js';\n\nconst $internals = Symbol('internals');\n\nfunction normalizeHeader(header) {\n return header && String(header).trim().toLowerCase();\n}\n\nfunction normalizeValue(value) {\n if (value === false || value == null) {\n return value;\n }\n\n return utils.isArray(value) ? value.map(normalizeValue) : sanitizeHeaderValue(String(value));\n}\n\nfunction parseTokens(str) {\n const tokens = Object.create(null);\n const tokensRE = /([^\\s,;=]+)\\s*(?:=\\s*([^,;]+))?/g;\n let match;\n\n while ((match = tokensRE.exec(str))) {\n tokens[match[1]] = match[2];\n }\n\n return tokens;\n}\n\nconst parameterNameRE = /^[!#$%&'*+\\-.^_`|~0-9A-Za-z]+$/;\n\nfunction trimOWS(value) {\n let start = 0;\n let end = value.length;\n\n while (start < end) {\n const code = value.charCodeAt(start);\n\n if (code !== 0x09 && code !== 0x20) {\n break;\n }\n\n start += 1;\n }\n\n while (end > start) {\n const code = value.charCodeAt(end - 1);\n\n if (code !== 0x09 && code !== 0x20) {\n break;\n }\n\n end -= 1;\n }\n\n return start === 0 && end === value.length ? value : value.slice(start, end);\n}\n\nfunction decodeQuotedString(value) {\n const last = value.length - 1;\n\n if (last < 1 || value.charCodeAt(0) !== 0x22 || value.charCodeAt(last) !== 0x22) {\n return value;\n }\n\n let decoded = '';\n\n for (let i = 1; i < last; i++) {\n const code = value.charCodeAt(i);\n\n if (code === 0x22) {\n return value;\n }\n\n if (code === 0x5c) {\n i += 1;\n\n if (i >= last) {\n return value;\n }\n }\n\n decoded += value[i];\n }\n\n return decoded;\n}\n\nfunction parseParameters(value) {\n const parameters = Object.create(null);\n const str = String(value);\n let start = 0;\n let quoted = false;\n let escaped = false;\n\n function parseParameter(end) {\n const part = trimOWS(str.slice(start, end));\n const equals = part.indexOf('=');\n\n if (equals < 1) {\n return;\n }\n\n const name = trimOWS(part.slice(0, equals));\n\n if (!parameterNameRE.test(name)) {\n return;\n }\n\n const normalizedName = name.toLowerCase();\n\n if (\n normalizedName === '__proto__' ||\n normalizedName === 'constructor' ||\n normalizedName === 'prototype'\n ) {\n return;\n }\n\n const parameterValue = trimOWS(part.slice(equals + 1));\n parameters[normalizedName] = decodeQuotedString(parameterValue);\n }\n\n for (let i = 0; i < str.length; i++) {\n const code = str.charCodeAt(i);\n\n if (quoted) {\n if (escaped) {\n escaped = false;\n } else if (code === 0x5c) {\n escaped = true;\n } else if (code === 0x22) {\n quoted = false;\n }\n } else if (code === 0x22) {\n quoted = true;\n } else if (code === 0x2c || code === 0x3b) {\n parseParameter(i);\n start = i + 1;\n }\n }\n\n parseParameter(str.length);\n\n return parameters;\n}\n\nconst isValidHeaderName = (str) => /^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(str.trim());\n\n// `__proto__` is a valid field name, and the one name the uppercase mapping at\n// the bottom of this file cannot reach: it is inherited from Object.prototype\n// instead of being declared on AxiosHeaders.prototype, so `self.__proto__ = v`\n// runs the inherited setter. That silently discards the header, and an array\n// value replaces the instance prototype, taking every method with it.\n// Store it under the same kind of case variant that mapping uses for `set` and\n// `constructor`. Header lookup is caseless, so it reads back under either\n// spelling, and no own `__proto__` slot is ever created for a later\n// `Object.assign` to copy onto a plain object through the same setter.\nconst PROTO_HEADER_SLOT = '__Proto__';\n\nconst headerSlot = (name) => (name === '__proto__' ? PROTO_HEADER_SLOT : name);\n\nfunction matchHeaderValue(context, value, header, filter, isHeaderNameFilter) {\n if (utils.isFunction(filter)) {\n return filter.call(context, value, header);\n }\n\n if (isHeaderNameFilter) {\n value = header;\n }\n\n if (!utils.isString(value)) return;\n\n if (utils.isString(filter)) {\n return value.indexOf(filter) !== -1;\n }\n\n if (utils.isRegExp(filter)) {\n return filter.test(value);\n }\n}\n\nfunction formatHeader(header) {\n return header\n .trim()\n .toLowerCase()\n .replace(/([a-z\\d])(\\w*)/g, (w, char, str) => {\n return char.toUpperCase() + str;\n });\n}\n\nfunction buildAccessors(obj, header) {\n const accessorName = utils.toCamelCase(' ' + header);\n\n ['get', 'set', 'has'].forEach((methodName) => {\n Object.defineProperty(obj, methodName + accessorName, {\n // Null-proto descriptor so a polluted Object.prototype.get cannot turn\n // this data descriptor into an accessor descriptor on the way in.\n __proto__: null,\n value: function (arg1, arg2, arg3) {\n return this[methodName].call(this, header, arg1, arg2, arg3);\n },\n configurable: true,\n });\n });\n}\n\nclass AxiosHeaders {\n constructor(headers) {\n headers && this.set(headers);\n }\n\n set(header, valueOrRewrite, rewrite) {\n const self = this;\n\n function setHeader(_value, _header, _rewrite) {\n const lHeader = normalizeHeader(_header);\n\n if (!lHeader) {\n return;\n }\n\n const key = utils.findKey(self, lHeader);\n\n if (\n !key ||\n self[key] === undefined ||\n _rewrite === true ||\n (_rewrite === undefined && self[key] !== false)\n ) {\n self[headerSlot(key || _header)] = normalizeValue(_value);\n }\n }\n\n const setHeaders = (headers, _rewrite) =>\n utils.forEach(headers, (_value, _header) => setHeader(_value, _header, _rewrite));\n\n if (utils.isPlainObject(header) || header instanceof this.constructor) {\n setHeaders(header, valueOrRewrite);\n } else if (utils.isString(header) && (header = header.trim()) && !isValidHeaderName(header)) {\n setHeaders(parseHeaders(header), valueOrRewrite);\n } else if (utils.isObject(header) && utils.isSafeIterable(header)) {\n let obj = Object.create(null),\n dest,\n key;\n for (const entry of header) {\n if (!utils.isArray(entry)) {\n throw new TypeError('Object iterator must return a key-value pair');\n }\n\n key = entry[0];\n\n if (utils.hasOwnProp(obj, key)) {\n dest = obj[key];\n obj[key] = utils.isArray(dest) ? [...dest, entry[1]] : [dest, entry[1]];\n } else {\n obj[key] = entry[1];\n }\n }\n\n setHeaders(obj, valueOrRewrite);\n } else {\n header != null && setHeader(valueOrRewrite, header, rewrite);\n }\n\n return this;\n }\n\n get(header, parser) {\n header = normalizeHeader(header);\n\n if (header) {\n const key = utils.findKey(this, header);\n\n if (key) {\n const value = this[key];\n\n if (!parser) {\n return value;\n }\n\n if (parser === true) {\n return parseTokens(value);\n }\n\n if (utils.isFunction(parser)) {\n return parser.call(this, value, key);\n }\n\n if (utils.isRegExp(parser)) {\n return parser.exec(value);\n }\n\n throw new TypeError('parser must be boolean|regexp|function');\n }\n }\n }\n\n has(header, matcher) {\n header = normalizeHeader(header);\n\n if (header) {\n const key = utils.findKey(this, header);\n\n return !!(\n key &&\n this[key] !== undefined &&\n (!matcher || matchHeaderValue(this, this[key], key, matcher))\n );\n }\n\n return false;\n }\n\n delete(header, matcher) {\n const self = this;\n let deleted = false;\n\n function deleteHeader(_header) {\n _header = normalizeHeader(_header);\n\n if (_header) {\n const key = utils.findKey(self, _header);\n\n if (key && (!matcher || matchHeaderValue(self, self[key], key, matcher))) {\n delete self[key];\n\n deleted = true;\n }\n }\n }\n\n if (utils.isArray(header)) {\n header.forEach(deleteHeader);\n } else {\n deleteHeader(header);\n }\n\n return deleted;\n }\n\n clear(matcher) {\n const keys = Object.keys(this);\n let i = keys.length;\n let deleted = false;\n\n while (i--) {\n const key = keys[i];\n if (!matcher || matchHeaderValue(this, this[key], key, matcher, true)) {\n delete this[key];\n deleted = true;\n }\n }\n\n return deleted;\n }\n\n normalize(format) {\n const self = this;\n const headers = Object.create(null);\n\n utils.forEach(this, (value, header) => {\n const key = utils.findKey(headers, header);\n\n if (key) {\n self[key] = normalizeValue(value);\n delete self[header];\n return;\n }\n\n const normalized = headerSlot(format ? formatHeader(header) : String(header).trim());\n\n if (normalized !== header) {\n delete self[header];\n }\n\n self[normalized] = normalizeValue(value);\n\n headers[normalized] = true;\n });\n\n return this;\n }\n\n concat(...targets) {\n return this.constructor.concat(this, ...targets);\n }\n\n toJSON(asStrings) {\n const obj = Object.create(null);\n\n utils.forEach(this, (value, header) => {\n value != null &&\n value !== false &&\n (obj[header] = asStrings && utils.isArray(value) ? value.join(', ') : value);\n });\n\n return obj;\n }\n\n [Symbol.iterator]() {\n return Object.entries(this.toJSON())[Symbol.iterator]();\n }\n\n toString() {\n return Object.entries(this.toJSON())\n .map(([header, value]) => header + ': ' + value)\n .join('\\n');\n }\n\n getSetCookie() {\n const value = this.get('set-cookie');\n return utils.isArray(value) ? value : value == null || value === false ? [] : [value];\n }\n\n get [Symbol.toStringTag]() {\n return 'AxiosHeaders';\n }\n\n static from(thing) {\n return thing instanceof this ? thing : new this(thing);\n }\n\n static parseParameters(value) {\n return parseParameters(value);\n }\n\n static concat(first, ...targets) {\n const computed = new this(first);\n\n targets.forEach((target) => computed.set(target));\n\n return computed;\n }\n\n static accessor(header) {\n const internals =\n (this[$internals] =\n this[$internals] =\n {\n accessors: {},\n });\n\n const accessors = internals.accessors;\n const prototype = this.prototype;\n\n function defineAccessor(_header) {\n const lHeader = normalizeHeader(_header);\n\n if (!accessors[lHeader]) {\n buildAccessors(prototype, _header);\n accessors[lHeader] = true;\n }\n }\n\n utils.isArray(header) ? header.forEach(defineAccessor) : defineAccessor(header);\n\n return this;\n }\n}\n\nAxiosHeaders.accessor([\n 'Content-Type',\n 'Content-Length',\n 'Accept',\n 'Accept-Encoding',\n 'User-Agent',\n 'Authorization',\n]);\n\n// reserved names hotfix\nutils.reduceDescriptors(AxiosHeaders.prototype, ({ value }, key) => {\n let mapped = key[0].toUpperCase() + key.slice(1); // map `set` => `Set`\n return {\n get: () => value,\n set(headerValue) {\n this[mapped] = headerValue;\n },\n };\n});\n\nutils.freezeMethods(AxiosHeaders);\n\nexport default AxiosHeaders;\n","'use strict';\n\nimport utils from '../utils.js';\nimport AxiosHeaders from './AxiosHeaders.js';\n\nexport const REDACTED = '[REDACTED ****]';\n\nfunction hasOwnOrPrototypeToJSON(source) {\n if (utils.hasOwnProp(source, 'toJSON')) {\n return true;\n }\n\n let prototype = Object.getPrototypeOf(source);\n\n while (prototype && prototype !== Object.prototype) {\n if (utils.hasOwnProp(prototype, 'toJSON')) {\n return true;\n }\n\n prototype = Object.getPrototypeOf(prototype);\n }\n\n return false;\n}\n\n// Build a plain-object snapshot of `config` and replace the value of any key\n// (case-insensitive) listed in `redactKeys` with REDACTED. Walks through arrays\n// and AxiosHeaders, and short-circuits on circular references.\nfunction redactConfig(config, redactKeys) {\n const lowerKeys = new Set(redactKeys.map((k) => String(k).toLowerCase()));\n const seen = [];\n\n const visit = (source) => {\n if (source === null || typeof source !== 'object') return source;\n if (utils.isBuffer(source)) return source;\n if (seen.indexOf(source) !== -1) return undefined;\n\n if (source instanceof AxiosHeaders) {\n source = source.toJSON();\n }\n\n seen.push(source);\n\n let result;\n if (utils.isArray(source)) {\n result = [];\n source.forEach((v, i) => {\n const reducedValue = visit(v);\n if (!utils.isUndefined(reducedValue)) {\n result[i] = reducedValue;\n }\n });\n } else {\n if (!utils.isPlainObject(source) && hasOwnOrPrototypeToJSON(source)) {\n seen.pop();\n return source;\n }\n\n result = Object.create(null);\n for (const [key, value] of Object.entries(source)) {\n const reducedValue = lowerKeys.has(key.toLowerCase()) ? REDACTED : visit(value);\n if (!utils.isUndefined(reducedValue)) {\n result[key] = reducedValue;\n }\n }\n }\n\n seen.pop();\n return result;\n };\n\n return visit(config);\n}\n\nfunction stringifySafely(value) {\n try {\n return String(value);\n } catch (err) {\n return '';\n }\n}\n\nfunction aggregateErrorMessage(error) {\n const message = error.errors\n .map((entry) => {\n try {\n return entry && entry.message ? stringifySafely(entry.message) : stringifySafely(entry);\n } catch (err) {\n return '';\n }\n })\n .filter(Boolean)\n .join('; ');\n\n return message || error.name || 'AggregateError';\n}\n\n// Shared with `Axios.prototype.request`, which splices the reconstructed\n// caller frames in ahead of this marker.\nexport const CAUSED_BY_SEPARATOR = '\\nCaused by: ';\nconst $causeStack = Symbol('causeStack');\n\n// Match the section we appended, not marker-like text in an error message or\n// a replacement stack supplied by the caller. Do not re-read the cause's stack.\nexport function getCauseStackIndex(error, stack) {\n const causeStack = utils.hasOwnProp(error, $causeStack) && error[$causeStack];\n\n return causeStack && stack.endsWith(causeStack) ? stack.length - causeStack.length : -1;\n}\n\n/**\n * Append the stack of a wrapped error to `target.stack`.\n *\n * `cause` already exposes the original error for tooling that walks the standard\n * cause chain, but many error reporters read `stack` and nothing else. Inlining\n * the wrapped stack there means those reporters surface the underlying failure\n * instead of the axios frames that normalized it (see #6670).\n *\n * Every read is defensive: a custom `Error.prepareStackTrace` hook, a runtime\n * without stack support, or a replaced `stack` property can leave the value\n * missing, non-string, or read-only, and normalizing an error must not throw\n * because of that.\n *\n * @param {Error} target The AxiosError being built.\n * @param {Error} source The error being wrapped.\n *\n * @returns {void}\n */\nfunction appendCauseStack(target, source) {\n try {\n const sourceStack = source && source.stack;\n\n if (typeof sourceStack !== 'string' || !sourceStack) {\n return;\n }\n\n const targetStack = target.stack;\n\n if (typeof targetStack !== 'string' || !targetStack) {\n return;\n }\n\n // Each call to `from()` creates a fresh target. Re-wrapping includes the\n // previous stack verbatim, adding one cause section per wrap.\n const causeStack = CAUSED_BY_SEPARATOR + sourceStack;\n target.stack = targetStack + causeStack;\n Object.defineProperty(target, $causeStack, { __proto__: null, value: causeStack });\n } catch (e) {\n // Ignore failures from custom stack hooks or un-writable stack properties.\n }\n}\n\nclass AxiosError extends Error {\n static from(error, code, config, request, response, customProps) {\n // `AggregateError` (thrown by Node on dual-stack/Happy-Eyeballs connection\n // failures) has an empty `message`; its detail lives in `errors[]`. Without\n // this, the wrapped error surfaces with a blank message (see #6721).\n let message = error.message;\n if (!message && utils.isArray(error.errors) && error.errors.length) {\n message = aggregateErrorMessage(error);\n }\n\n const axiosError = new AxiosError(message, code || error.code, config, request, response);\n // Match native `Error` `cause` semantics: non-enumerable. The wrapped\n // error often carries circular internals (sockets, requests, agents), so\n // an enumerable `cause` makes structured loggers (pino/winston) and any\n // own-property walk throw \"Converting circular structure to JSON\".\n // Regression from #6982; see #7205. `__proto__: null` mirrors the\n // `message` descriptor below (prototype-pollution-safe descriptor).\n Object.defineProperty(axiosError, 'cause', {\n __proto__: null,\n value: error,\n writable: true,\n enumerable: false,\n configurable: true,\n });\n axiosError.name = error.name;\n\n // Inline the wrapped stack for reporters that read only `stack`; the `cause`\n // property above already covers cause-aware tooling.\n appendCauseStack(axiosError, error);\n\n // Preserve status from the original error if not already set from response\n if (error.status != null && axiosError.status == null) {\n axiosError.status = error.status;\n }\n\n customProps && Object.assign(axiosError, customProps);\n return axiosError;\n }\n\n /**\n * Create an Error with the specified message, config, error code, request and response.\n *\n * @param {string} message The error message.\n * @param {string} [code] The error code (for example, 'ECONNABORTED').\n * @param {Object} [config] The config.\n * @param {Object} [request] The request.\n * @param {Object} [response] The response.\n *\n * @returns {Error} The created error.\n */\n constructor(message, code, config, request, response) {\n super(message);\n\n // Make message enumerable to maintain backward compatibility\n // The native Error constructor sets message as non-enumerable,\n // but axios < v1.13.3 had it as enumerable\n Object.defineProperty(this, 'message', {\n // Null-proto descriptor so a polluted Object.prototype.get cannot turn\n // this data descriptor into an accessor descriptor on the way in.\n __proto__: null,\n value: message,\n enumerable: true,\n writable: true,\n configurable: true,\n });\n\n this.name = 'AxiosError';\n this.isAxiosError = true;\n code && (this.code = code);\n config && (this.config = config);\n request && (this.request = request);\n if (response) {\n this.response = response;\n this.status = response.status;\n }\n }\n\n toJSON() {\n // Opt-in redaction: when the request config carries a `redact` array, the\n // value of any matching key (case-insensitive, at any depth) is replaced\n // with REDACTED in the serialized snapshot. Undefined or empty leaves the\n // existing serialization behavior unchanged.\n const config = this.config;\n const redactKeys = config && utils.hasOwnProp(config, 'redact') ? config.redact : undefined;\n const serializedConfig =\n utils.isArray(redactKeys) && redactKeys.length > 0\n ? redactConfig(config, redactKeys)\n : utils.toJSONObject(config);\n\n return {\n // Standard\n message: this.message,\n name: this.name,\n // Microsoft\n description: this.description,\n number: this.number,\n // Mozilla\n fileName: this.fileName,\n lineNumber: this.lineNumber,\n columnNumber: this.columnNumber,\n stack: this.stack,\n // Axios\n config: serializedConfig,\n code: this.code,\n status: this.status,\n };\n }\n}\n\n// This can be changed to static properties as soon as the parser options in .eslint.cjs are updated.\nAxiosError.ERR_BAD_OPTION_VALUE = 'ERR_BAD_OPTION_VALUE';\nAxiosError.ERR_BAD_OPTION = 'ERR_BAD_OPTION';\nAxiosError.ECONNABORTED = 'ECONNABORTED';\nAxiosError.ETIMEDOUT = 'ETIMEDOUT';\nAxiosError.ECONNREFUSED = 'ECONNREFUSED';\nAxiosError.ERR_NETWORK = 'ERR_NETWORK';\nAxiosError.ERR_FR_TOO_MANY_REDIRECTS = 'ERR_FR_TOO_MANY_REDIRECTS';\nAxiosError.ERR_DEPRECATED = 'ERR_DEPRECATED';\nAxiosError.ERR_BAD_RESPONSE = 'ERR_BAD_RESPONSE';\nAxiosError.ERR_BAD_REQUEST = 'ERR_BAD_REQUEST';\nAxiosError.ERR_CANCELED = 'ERR_CANCELED';\nAxiosError.ERR_NOT_SUPPORT = 'ERR_NOT_SUPPORT';\nAxiosError.ERR_INVALID_URL = 'ERR_INVALID_URL';\nAxiosError.ERR_FORM_DATA_DEPTH_EXCEEDED = 'ERR_FORM_DATA_DEPTH_EXCEEDED';\n\nexport default AxiosError;\n","// eslint-disable-next-line strict\nexport default null;\n","'use strict';\n\nimport utils from '../utils.js';\nimport AxiosError from '../core/AxiosError.js';\n// temporary hotfix to avoid circular references until AxiosURLSearchParams is refactored\nimport PlatformFormData from '../platform/node/classes/FormData.js';\nimport PlatformBuffer from '../platform/node/classes/Buffer.js';\n\n// Default nesting limit shared with the inverse transform (formDataToJSON) so\n// the FormData <-> JSON round-trip stays symmetric.\nexport const DEFAULT_FORM_DATA_MAX_DEPTH = 100;\n\n/**\n * Determines if the given thing is a array or js object.\n *\n * @param {string} thing - The object or array to be visited.\n *\n * @returns {boolean}\n */\nfunction isVisitable(thing) {\n return utils.isPlainObject(thing) || utils.isArray(thing);\n}\n\n/**\n * It removes the brackets from the end of a string\n *\n * @param {string} key - The key of the parameter.\n *\n * @returns {string} the key without the brackets.\n */\nfunction removeBrackets(key) {\n return utils.endsWith(key, '[]') ? key.slice(0, -2) : key;\n}\n\n/**\n * It takes a path, a key, and a boolean, and returns a string\n *\n * @param {string} path - The path to the current key.\n * @param {string} key - The key of the current object being iterated over.\n * @param {string} dots - If true, the key will be rendered with dots instead of brackets.\n *\n * @returns {string} The path to the current key.\n */\nfunction renderKey(path, key, dots) {\n if (!path) return key;\n return path\n .concat(key)\n .map(function each(token, i) {\n // eslint-disable-next-line no-param-reassign\n token = removeBrackets(token);\n return !dots && i ? '[' + token + ']' : token;\n })\n .join(dots ? '.' : '');\n}\n\n/**\n * If the array is an array and none of its elements are visitable, then it's a flat array.\n *\n * @param {Array<any>} arr - The array to check\n *\n * @returns {boolean}\n */\nfunction isFlatArray(arr) {\n return utils.isArray(arr) && !arr.some(isVisitable);\n}\n\nconst predicates = utils.toFlatObject(utils, {}, null, function filter(prop) {\n return /^is[A-Z]/.test(prop);\n});\n\n/**\n * Convert a data object to FormData\n *\n * @param {Object} obj\n * @param {?Object} [formData]\n * @param {?Object} [options]\n * @param {Function} [options.visitor]\n * @param {Boolean} [options.metaTokens = true]\n * @param {Boolean} [options.dots = false]\n * @param {?Boolean} [options.indexes = false]\n *\n * @returns {Object}\n **/\n\n/**\n * It converts an object into a FormData object\n *\n * @param {Object<any, any>} obj - The object to convert to form data.\n * @param {string} formData - The FormData object to append to.\n * @param {Object<string, any>} options\n *\n * @returns\n */\nfunction toFormData(obj, formData, options) {\n if (!utils.isObject(obj)) {\n throw new TypeError('target must be an object');\n }\n\n // eslint-disable-next-line no-param-reassign\n formData = formData || new (PlatformFormData || FormData)();\n\n const option = (name, fallback) => {\n const value = utils.getSafeProp(options, name);\n return utils.isUndefined(value) ? fallback : value;\n };\n\n const metaTokens = option('metaTokens', true);\n // eslint-disable-next-line no-use-before-define\n const visitor = option('visitor') || defaultVisitor;\n const dots = option('dots', false);\n const indexes = option('indexes', false);\n const _Blob = option('Blob') || (typeof Blob !== 'undefined' && Blob);\n const maxDepth = option('maxDepth', DEFAULT_FORM_DATA_MAX_DEPTH);\n const useBlob = _Blob && utils.isSpecCompliantForm(formData);\n const stack = [];\n\n if (!utils.isFunction(visitor)) {\n throw new TypeError('visitor must be a function');\n }\n\n function convertValue(value) {\n if (value === null) return '';\n\n if (utils.isDate(value)) {\n return value.toISOString();\n }\n\n if (utils.isBoolean(value)) {\n return value.toString();\n }\n\n if (!useBlob && utils.isBlob(value)) {\n throw new AxiosError('Blob is not supported. Use a Buffer instead.');\n }\n\n if (utils.isArrayBuffer(value) || utils.isTypedArray(value)) {\n if (useBlob && typeof _Blob === 'function') {\n return new _Blob([value]);\n }\n if (PlatformBuffer && PlatformBuffer.isBufferAvailable()) {\n return PlatformBuffer.from(value);\n }\n throw new AxiosError(\n 'Blob is not supported. Use a Buffer instead.',\n AxiosError.ERR_NOT_SUPPORT\n );\n }\n\n return value;\n }\n\n function throwIfMaxDepthExceeded(depth) {\n if (depth > maxDepth) {\n throw new AxiosError(\n 'Object is too deeply nested (' + depth + ' levels). Max depth: ' + maxDepth,\n AxiosError.ERR_FORM_DATA_DEPTH_EXCEEDED\n );\n }\n }\n\n function stringifyWithDepthLimit(value, depth) {\n if (maxDepth === Infinity) {\n return JSON.stringify(value);\n }\n\n const ancestors = [];\n\n return JSON.stringify(value, function limitDepth(_key, currentValue) {\n if (!utils.isObject(currentValue)) {\n return currentValue;\n }\n\n while (ancestors.length && ancestors[ancestors.length - 1] !== this) {\n ancestors.pop();\n }\n\n ancestors.push(currentValue);\n throwIfMaxDepthExceeded(depth + ancestors.length - 1);\n\n return currentValue;\n });\n }\n\n /**\n * Default visitor.\n *\n * @param {*} value\n * @param {String|Number} key\n * @param {Array<String|Number>} path\n * @this {FormData}\n *\n * @returns {boolean} return true to visit the each prop of the value recursively\n */\n function defaultVisitor(value, key, path) {\n let arr = value;\n\n if (utils.isReactNative(formData) && utils.isReactNativeBlob(value)) {\n formData.append(renderKey(path, key, dots), convertValue(value));\n return false;\n }\n\n if (value && !path && typeof value === 'object') {\n if (utils.endsWith(key, '{}')) {\n // eslint-disable-next-line no-param-reassign\n key = metaTokens ? key : key.slice(0, -2);\n // eslint-disable-next-line no-param-reassign\n value = stringifyWithDepthLimit(value, 1);\n } else if (\n (utils.isArray(value) && isFlatArray(value)) ||\n ((utils.isFileList(value) || utils.endsWith(key, '[]')) && (arr = utils.toArray(value)))\n ) {\n // eslint-disable-next-line no-param-reassign\n key = removeBrackets(key);\n\n arr.forEach(function each(el, index) {\n !(utils.isUndefined(el) || el === null) &&\n formData.append(\n // eslint-disable-next-line no-nested-ternary\n indexes === true\n ? renderKey([key], index, dots)\n : indexes === null\n ? key\n : key + '[]',\n convertValue(el)\n );\n });\n return false;\n }\n }\n\n if (isVisitable(value)) {\n return true;\n }\n\n formData.append(renderKey(path, key, dots), convertValue(value));\n\n return false;\n }\n\n const exposedHelpers = Object.assign(predicates, {\n defaultVisitor,\n convertValue,\n isVisitable,\n });\n\n function build(value, path, depth = 0) {\n if (utils.isUndefined(value)) return;\n\n throwIfMaxDepthExceeded(depth);\n\n if (stack.indexOf(value) !== -1) {\n throw new Error('Circular reference detected in ' + path.join('.'));\n }\n\n stack.push(value);\n\n utils.forEach(value, function each(el, key) {\n const result =\n !(utils.isUndefined(el) || el === null) &&\n visitor.call(formData, el, utils.isString(key) ? key.trim() : key, path, exposedHelpers);\n\n if (result === true) {\n build(el, path ? path.concat(key) : [key], depth + 1);\n }\n });\n\n stack.pop();\n }\n\n if (!utils.isObject(obj)) {\n throw new TypeError('data must be an object');\n }\n\n build(obj);\n\n return formData;\n}\n\nexport default toFormData;\n","'use strict';\n\nimport toFormData from './toFormData.js';\n\n/**\n * It encodes a string by replacing all characters that are not in the unreserved set with\n * their percent-encoded equivalents\n *\n * @param {string} str - The string to encode.\n *\n * @returns {string} The encoded string.\n */\nfunction encode(str) {\n const charMap = {\n '!': '%21',\n \"'\": '%27',\n '(': '%28',\n ')': '%29',\n '~': '%7E',\n '%20': '+',\n };\n return encodeURIComponent(str).replace(/[!'()~]|%20/g, function replacer(match) {\n return charMap[match];\n });\n}\n\n/**\n * It takes a params object and converts it to a FormData object\n *\n * @param {Object<string, any>} params - The parameters to be converted to a FormData object.\n * @param {Object<string, any>} options - The options object passed to the Axios constructor.\n *\n * @returns {void}\n */\nfunction AxiosURLSearchParams(params, options) {\n this._pairs = [];\n\n params && toFormData(params, this, options);\n}\n\nconst prototype = AxiosURLSearchParams.prototype;\n\nprototype.append = function append(name, value) {\n this._pairs.push([name, value]);\n};\n\nprototype.toString = function toString(encoder) {\n const _encode = encoder\n ? (value) => encoder.call(this, value, encode)\n : encode;\n\n return this._pairs\n .map(function each(pair) {\n return _encode(pair[0]) + '=' + _encode(pair[1]);\n }, '')\n .join('&');\n};\n\nexport default AxiosURLSearchParams;\n","'use strict';\n\nimport utils from '../utils.js';\nimport AxiosURLSearchParams from './AxiosURLSearchParams.js';\n\n/**\n * It replaces URL-encoded forms of `:`, `$`, `,`, and spaces with\n * their plain counterparts (`:`, `$`, `,`, `+`).\n *\n * @param {string} val The value to be encoded.\n *\n * @returns {string} The encoded value.\n */\nexport function encode(val) {\n return encodeURIComponent(val)\n .replace(/%3A/gi, ':')\n .replace(/%24/g, '$')\n .replace(/%2C/gi, ',')\n .replace(/%20/g, '+');\n}\n\n/**\n * Build a URL by appending params to the end\n *\n * @param {string} url The base of the url (e.g., http://www.google.com)\n * @param {object} [params] The params to be appended\n * @param {?(object|Function)} options\n *\n * @returns {string} The formatted url\n */\nexport default function buildURL(url, params, options) {\n if (!params) {\n return url;\n }\n url = url || '';\n\n const _options = utils.isFunction(options)\n ? {\n serialize: options,\n }\n : options;\n\n // Read serializer options pollution-safely: own properties and methods on a\n // class/template prototype are honored, but values injected onto a polluted\n // Object.prototype are ignored.\n const _encode = utils.getSafeProp(_options, 'encode') || encode;\n const serializeFn = utils.getSafeProp(_options, 'serialize');\n\n let serializedParams;\n\n if (serializeFn) {\n serializedParams = serializeFn(params, _options);\n } else {\n serializedParams = utils.isURLSearchParams(params)\n ? params.toString()\n : new AxiosURLSearchParams(params, _options).toString(_encode);\n }\n\n if (serializedParams) {\n const hashmarkIndex = url.indexOf('#');\n\n if (hashmarkIndex !== -1) {\n url = url.slice(0, hashmarkIndex);\n }\n url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams;\n }\n\n return url;\n}\n","'use strict';\n\nimport utils from '../utils.js';\n\nconst $internals = Symbol('internals');\n\n// `handlers` is public and may be replaced with a nullish value by user code;\n// `clear()` has always tolerated that. Treat it as an empty stack rather than\n// dereferencing it.\nfunction countHandlers(handlers) {\n return handlers ? handlers.length : 0;\n}\n\nfunction trimHandlers(handlers) {\n if (!handlers) {\n return;\n }\n\n while (handlers.length && handlers[handlers.length - 1] === null) {\n handlers.pop();\n }\n}\n\n// Preserve the array-key coercion used before IDs were stored in a Map, without\n// treating null, empty strings, or noncanonical numeric strings as ID zero.\nfunction normalizeHandlerId(id) {\n if (typeof id === 'string' && id !== '' && String(Number(id)) === id) {\n return Number(id);\n }\n\n return id;\n}\n\nfunction syncHandlerEntries(manager, internals) {\n const handlers = manager.handlers;\n const length = countHandlers(handlers);\n\n if (handlers !== internals.handlersRef) {\n internals.handlersRef = handlers;\n internals.handlerEntries.clear();\n } else if (length !== internals.handlersLength) {\n if (!length) {\n internals.handlerEntries.clear();\n } else {\n internals.handlerEntries.forEach(function removeStaleEntry(entry, id) {\n if (handlers[entry.index] !== entry.handler) {\n internals.handlerEntries.delete(id);\n }\n });\n }\n }\n\n internals.handlersLength = length;\n}\n\nclass InterceptorManager {\n constructor() {\n this.handlers = [];\n this[$internals] = {\n handlersRef: this.handlers,\n handlersLength: this.handlers.length,\n handlerEntries: new Map(),\n iterationDepth: 0,\n nextId: 0,\n };\n }\n\n /**\n * Add a new interceptor to the stack\n *\n * @param {Function} fulfilled The function to handle `then` for a `Promise`\n * @param {Function} rejected The function to handle `reject` for a `Promise`\n * @param {Object} options The options for the interceptor, synchronous and runWhen\n *\n * @return {Number} An ID used to remove interceptor later\n */\n use(fulfilled, rejected, options) {\n const handler = {\n fulfilled,\n rejected,\n synchronous: options ? options.synchronous : false,\n runWhen: options ? options.runWhen : null,\n };\n const internals = this[$internals];\n\n if (this.handlers == null) {\n this.handlers = [];\n }\n\n syncHandlerEntries(this, internals);\n\n const id = internals.nextId++;\n\n this.handlers.push(handler);\n internals.handlerEntries.set(id, {\n handler,\n index: this.handlers.length - 1,\n });\n internals.handlersLength = this.handlers.length;\n\n return id;\n }\n\n /**\n * Remove an interceptor from the stack\n *\n * @param {Number} id The ID that was returned by `use`\n *\n * @returns {void}\n */\n eject(id) {\n const internals = this[$internals];\n\n syncHandlerEntries(this, internals);\n\n const handlerId = normalizeHandlerId(id);\n const entry = internals.handlerEntries.get(handlerId);\n\n if (entry) {\n internals.handlerEntries.delete(handlerId);\n\n // Ignore IDs invalidated by clear or direct replacement of handlers.\n if (this.handlers[entry.index] !== entry.handler) {\n return;\n }\n\n this.handlers[entry.index] = null;\n\n // Do not reuse an index while forEach is walking its length snapshot.\n if (!internals.iterationDepth) {\n trimHandlers(this.handlers);\n internals.handlersLength = this.handlers.length;\n }\n }\n }\n\n /**\n * Clear all interceptors from the stack\n *\n * @returns {void}\n */\n clear() {\n if (this.handlers) {\n this.handlers = [];\n syncHandlerEntries(this, this[$internals]);\n }\n }\n\n /**\n * Iterate over all the registered interceptors\n *\n * This method is particularly useful for skipping over any\n * interceptors that may have become `null` calling `eject`.\n *\n * @param {Function} fn The function to call for each interceptor\n *\n * @returns {void}\n */\n forEach(fn) {\n const internals = this[$internals];\n\n syncHandlerEntries(this, internals);\n\n internals.iterationDepth++;\n\n try {\n utils.forEach(this.handlers, function forEachHandler(h) {\n if (h !== null) {\n fn(h);\n }\n });\n } finally {\n if (!--internals.iterationDepth) {\n syncHandlerEntries(this, internals);\n trimHandlers(this.handlers);\n internals.handlersLength = countHandlers(this.handlers);\n }\n }\n }\n}\n\nexport default InterceptorManager;\n","'use strict';\n\nexport default {\n silentJSONParsing: true,\n forcedJSONParsing: true,\n clarifyTimeoutError: false,\n legacyInterceptorReqResOrdering: true,\n advertiseZstdAcceptEncoding: false,\n validateStatusUndefinedResolves: true,\n encodeBasicAuthUsername: false,\n};\n","'use strict';\n\nimport AxiosURLSearchParams from '../../../helpers/AxiosURLSearchParams.js';\nexport default typeof URLSearchParams !== 'undefined' ? URLSearchParams : AxiosURLSearchParams;\n","'use strict';\n\nexport default typeof FormData !== 'undefined' ? FormData : null;\n","'use strict';\n\nexport default typeof Blob !== 'undefined' ? Blob : null;\n","import URLSearchParams from './classes/URLSearchParams.js';\nimport FormData from './classes/FormData.js';\nimport Blob from './classes/Blob.js';\n\nexport default {\n isBrowser: true,\n classes: {\n URLSearchParams,\n FormData,\n Blob,\n },\n protocols: ['http', 'https', 'file', 'blob', 'url', 'data'],\n};\n","const hasBrowserEnv = typeof window !== 'undefined' && typeof document !== 'undefined';\n\nconst _navigator = (typeof navigator === 'object' && navigator) || undefined;\n\n/**\n * Determine if we're running in a standard browser environment\n *\n * This allows axios to run in a web worker, and react-native.\n * Both environments support XMLHttpRequest, but not fully standard globals.\n *\n * web workers:\n * typeof window -> undefined\n * typeof document -> undefined\n *\n * react-native:\n * navigator.product -> 'ReactNative'\n * nativescript\n * navigator.product -> 'NativeScript' or 'NS'\n *\n * @returns {boolean}\n */\nconst hasStandardBrowserEnv =\n hasBrowserEnv &&\n (!_navigator || ['ReactNative', 'NativeScript', 'NS'].indexOf(_navigator.product) < 0);\n\n/**\n * Determine if we're running in a standard browser webWorker environment\n *\n * Although the `isStandardBrowserEnv` method indicates that\n * `allows axios to run in a web worker`, the WebWorker will still be\n * filtered out due to its judgment standard\n * `typeof window !== 'undefined' && typeof document !== 'undefined'`.\n * This leads to a problem when axios post `FormData` in webWorker\n */\nconst hasStandardBrowserWebWorkerEnv = (() => {\n return (\n typeof WorkerGlobalScope !== 'undefined' &&\n // eslint-disable-next-line no-undef\n self instanceof WorkerGlobalScope &&\n typeof self.importScripts === 'function'\n );\n})();\n\nconst origin = (hasBrowserEnv && window.location.href) || 'http://localhost';\n\nexport {\n hasBrowserEnv,\n hasStandardBrowserWebWorkerEnv,\n hasStandardBrowserEnv,\n _navigator as navigator,\n origin,\n};\n","import platform from './node/index.js';\nimport * as utils from './common/utils.js';\n\nexport default {\n ...utils,\n ...platform,\n};\n","'use strict';\n\nimport utils from '../utils.js';\nimport toFormData from './toFormData.js';\nimport platform from '../platform/index.js';\n\nexport default function toURLEncodedForm(data, options) {\n return toFormData(data, new platform.classes.URLSearchParams(), {\n visitor: function (value, key, path, helpers) {\n if (platform.isNode && utils.isBuffer(value)) {\n this.append(key, value.toString('base64'));\n return false;\n }\n\n return helpers.defaultVisitor.apply(this, arguments);\n },\n ...options,\n });\n}\n","'use strict';\n\nimport utils from '../utils.js';\nimport AxiosError from '../core/AxiosError.js';\nimport { DEFAULT_FORM_DATA_MAX_DEPTH } from './toFormData.js';\n\nconst MAX_DEPTH = DEFAULT_FORM_DATA_MAX_DEPTH;\n\nfunction throwIfDepthExceeded(index) {\n if (index > MAX_DEPTH) {\n throw new AxiosError(\n 'FormData field is too deeply nested (' + index + ' levels). Max depth: ' + MAX_DEPTH,\n AxiosError.ERR_FORM_DATA_DEPTH_EXCEEDED\n );\n }\n}\n\n/**\n * It takes a string like `foo[x][y][z]` and returns an array like `['foo', 'x', 'y', 'z']\n *\n * @param {string} name - The name of the property to get.\n *\n * @returns An array of strings.\n */\nfunction parsePropPath(name) {\n // foo[x][y][z] -> ['foo', 'x', 'y', 'z']\n // foo.x.y.z -> ['foo', 'x', 'y', 'z']\n // A path is split on `.` and on `[...]` groups. A segment — whether written\n // in dot notation or captured inside brackets — may contain any character\n // except `.`, `[` and `]`, so a key like `user-name` or `user name` is kept\n // literal instead of being split (#5402). `.`, `[` and `]` keep their existing\n // meaning, e.g. `foo[bar.baz]` -> ['foo', 'bar', 'baz'] and `[]` is an array push.\n // Excluding `[` from the bracket group also makes the match fail fast at the\n // next `[`, so a malformed name cannot rescan to the end of the string from\n // every unmatched `[` — parsing stays linear in the length of the name.\n const path = [];\n const pattern = /[^.[\\]]+|\\[([^.[\\]]*)]/g;\n let match;\n\n while ((match = pattern.exec(name)) !== null) {\n throwIfDepthExceeded(path.length);\n path.push(match[0] === '[]' ? '' : match[1] || match[0]);\n }\n\n return path;\n}\n\n/**\n * Convert an array to an object.\n *\n * @param {Array<any>} arr - The array to convert to an object.\n *\n * @returns An object with the same keys and values as the array.\n */\nfunction arrayToObject(arr) {\n const obj = {};\n const keys = Object.keys(arr);\n let i;\n const len = keys.length;\n let key;\n for (i = 0; i < len; i++) {\n key = keys[i];\n obj[key] = arr[key];\n }\n return obj;\n}\n\nfunction normalizeArray(value) {\n if (!utils.isArray(value)) return value;\n\n const keys = Object.keys(value);\n return keys.length !== value.length || keys.some((key, index) => key !== String(index))\n ? arrayToObject(value)\n : value;\n}\n\nfunction normalizeArrays(obj) {\n const pending = [obj];\n while (pending.length) {\n const target = pending.pop();\n Object.keys(target).forEach((key) => {\n const value = (target[key] = normalizeArray(target[key]));\n if (utils.isArray(value) || utils.isPlainObject(value)) {\n pending.push(value);\n }\n });\n }\n return obj;\n}\n\n/**\n * It takes a FormData object and returns a JavaScript object\n *\n * @param {string} formData The FormData object to convert to JSON.\n *\n * @returns {Object<string, any> | null} The converted object.\n */\nfunction formDataToJSON(formData) {\n function buildPath(path, value, target, index) {\n throwIfDepthExceeded(index);\n\n let name = path[index++];\n\n if (name === '__proto__') return true;\n\n const isNumericKey = Number.isFinite(+name);\n const isLast = index >= path.length;\n name = !name && utils.isArray(target) ? target.length : name;\n\n if (isLast) {\n if (utils.hasOwnProp(target, name)) {\n target[name] = normalizeArray(target[name]);\n target[name] = utils.isArray(target[name])\n ? target[name].concat(value)\n : [target[name], value];\n } else {\n target[name] = value;\n }\n\n return !isNumericKey;\n }\n\n if (!utils.hasOwnProp(target, name) || !utils.isObject(target[name])) {\n target[name] = [];\n }\n\n const result = buildPath(path, value, target[name], index);\n\n if (result && utils.isArray(target[name])) {\n target[name] = arrayToObject(target[name]);\n }\n\n return !isNumericKey;\n }\n\n if (utils.isFormData(formData) && utils.isFunction(formData.entries)) {\n const obj = {};\n\n utils.forEachEntry(formData, (name, value) => {\n buildPath(parsePropPath(name), value, obj, 0);\n });\n\n return normalizeArrays(obj);\n }\n\n return null;\n}\n\nexport default formDataToJSON;\n","'use strict';\n\nconst methodList = Object.freeze([\n 'get',\n 'delete',\n 'head',\n 'options',\n 'post',\n 'put',\n 'patch',\n 'purge',\n 'link',\n 'unlink',\n 'query',\n]);\n\nexport default methodList;\n","'use strict';\n\nimport utils from '../utils.js';\nimport AxiosError from '../core/AxiosError.js';\nimport transitionalDefaults from './transitional.js';\nimport toFormData from '../helpers/toFormData.js';\nimport toURLEncodedForm from '../helpers/toURLEncodedForm.js';\nimport platform from '../platform/index.js';\nimport formDataToJSON from '../helpers/formDataToJSON.js';\nimport methodList from '../core/methodList.js';\n\nconst own = (obj, key) => (obj != null && utils.hasOwnProp(obj, key) ? obj[key] : undefined);\n\n/**\n * It takes a string, tries to parse it, and if it fails, it returns the stringified version\n * of the input\n *\n * @param {any} rawValue - The value to be stringified.\n * @param {Function} parser - A function that parses a string into a JavaScript object.\n * @param {Function} encoder - A function that takes a value and returns a string.\n *\n * @returns {string} A stringified version of the rawValue.\n */\nfunction stringifySafely(rawValue, parser, encoder) {\n if (utils.isString(rawValue)) {\n try {\n (parser || JSON.parse)(rawValue);\n return utils.trim(rawValue);\n } catch (e) {\n if (e.name !== 'SyntaxError') {\n throw e;\n }\n }\n }\n\n return (encoder || JSON.stringify)(rawValue);\n}\n\nconst defaults = {\n transitional: transitionalDefaults,\n\n adapter: ['xhr', 'http', 'fetch'],\n\n transformRequest: [\n function transformRequest(data, headers) {\n const contentType = headers.getContentType() || '';\n const hasJSONContentType = contentType.indexOf('application/json') > -1;\n const isObjectPayload = utils.isObject(data);\n\n if (isObjectPayload && utils.isHTMLForm(data)) {\n data = new FormData(data);\n }\n\n const isFormData = utils.isFormData(data);\n\n if (isFormData) {\n return hasJSONContentType ? JSON.stringify(formDataToJSON(data)) : data;\n }\n\n if (\n utils.isArrayBuffer(data) ||\n utils.isBuffer(data) ||\n utils.isStream(data) ||\n utils.isFile(data) ||\n utils.isBlob(data) ||\n utils.isReadableStream(data)\n ) {\n return data;\n }\n if (utils.isArrayBufferView(data)) {\n return data.buffer;\n }\n if (utils.isURLSearchParams(data)) {\n headers.setContentType('application/x-www-form-urlencoded;charset=utf-8', false);\n return data.toString();\n }\n\n let isFileList;\n\n if (isObjectPayload) {\n const formSerializer = own(this, 'formSerializer');\n if (contentType.indexOf('application/x-www-form-urlencoded') > -1) {\n return toURLEncodedForm(data, formSerializer).toString();\n }\n\n if (\n (isFileList = utils.isFileList(data)) ||\n contentType.indexOf('multipart/form-data') > -1\n ) {\n const env = own(this, 'env');\n const _FormData = env && env.FormData;\n\n return toFormData(\n isFileList ? { 'files[]': data } : data,\n _FormData && new _FormData(),\n formSerializer\n );\n }\n }\n\n if (isObjectPayload || hasJSONContentType) {\n headers.setContentType('application/json', false);\n return stringifySafely(data);\n }\n\n return data;\n },\n ],\n\n transformResponse: [\n function transformResponse(data) {\n const transitional = own(this, 'transitional') || defaults.transitional;\n const forcedJSONParsing = transitional && transitional.forcedJSONParsing;\n const responseType = own(this, 'responseType');\n const JSONRequested = responseType === 'json';\n\n if (utils.isResponse(data) || utils.isReadableStream(data)) {\n return data;\n }\n\n if (\n data &&\n utils.isString(data) &&\n ((forcedJSONParsing && !responseType) || JSONRequested)\n ) {\n const silentJSONParsing = transitional && transitional.silentJSONParsing;\n const strictJSONParsing = !silentJSONParsing && JSONRequested;\n\n try {\n return JSON.parse(data, own(this, 'parseReviver'));\n } catch (e) {\n if (strictJSONParsing) {\n if (e.name === 'SyntaxError') {\n throw AxiosError.from(e, AxiosError.ERR_BAD_RESPONSE, this, null, own(this, 'response'));\n }\n throw e;\n }\n }\n }\n\n return data;\n },\n ],\n\n /**\n * A timeout in milliseconds to abort a request. If set to 0 (default) a\n * timeout is not created.\n */\n timeout: 0,\n\n xsrfCookieName: 'XSRF-TOKEN',\n xsrfHeaderName: 'X-XSRF-TOKEN',\n\n maxContentLength: -1,\n maxBodyLength: -1,\n\n env: {\n FormData: platform.classes.FormData,\n Blob: platform.classes.Blob,\n },\n\n validateStatus: function validateStatus(status) {\n return status >= 200 && status < 300;\n },\n\n headers: {\n common: {\n Accept: 'application/json, text/plain, */*',\n 'Content-Type': undefined,\n },\n },\n};\n\nutils.forEach(methodList, (method) => {\n defaults.headers[method] = {};\n});\n\nexport default defaults;\n","'use strict';\n\nimport utils from '../utils.js';\nimport defaults from '../defaults/index.js';\nimport AxiosHeaders from '../core/AxiosHeaders.js';\n\n/**\n * Transform the data for a request or a response\n *\n * @param {Array|Function} fns A single function or Array of functions\n * @param {?Object} response The response object\n *\n * @returns {*} The resulting transformed data\n */\nexport default function transformData(fns, response) {\n const config = this || defaults;\n const context = response || config;\n const headers = AxiosHeaders.from(context.headers);\n let data = context.data;\n\n utils.forEach(fns, function transform(fn) {\n data = fn.call(config, data, headers.normalize(), response ? response.status : undefined);\n });\n\n headers.normalize();\n\n return data;\n}\n","'use strict';\n\nexport default function isCancel(value) {\n return !!(value && value.__CANCEL__);\n}\n","'use strict';\n\nimport AxiosError from '../core/AxiosError.js';\n\nclass CanceledError extends AxiosError {\n /**\n * A `CanceledError` is an object that is thrown when an operation is canceled.\n *\n * @param {string=} message The message.\n * @param {Object=} config The config.\n * @param {Object=} request The request.\n *\n * @returns {CanceledError} The created error.\n */\n constructor(message, config, request) {\n super(message == null ? 'canceled' : message, AxiosError.ERR_CANCELED, config, request);\n this.name = 'CanceledError';\n this.__CANCEL__ = true;\n }\n}\n\nexport default CanceledError;\n","'use strict';\n\nimport AxiosError from './AxiosError.js';\n\n/**\n * Resolve or reject a Promise based on response status.\n *\n * @param {Function} resolve A function that resolves the promise.\n * @param {Function} reject A function that rejects the promise.\n * @param {object} response The response.\n *\n * @returns {object} The response.\n */\nexport default function settle(resolve, reject, response) {\n const validateStatus = response.config.validateStatus;\n if (!response.status || !validateStatus || validateStatus(response.status)) {\n resolve(response);\n } else {\n reject(new AxiosError(\n 'Request failed with status code ' + response.status,\n response.status >= 400 && response.status < 500 ? AxiosError.ERR_BAD_REQUEST : AxiosError.ERR_BAD_RESPONSE,\n response.config,\n response.request,\n response\n ));\n }\n}\n","'use strict';\n\nconst urlParserControlCharacters = /[\\t\\n\\r]/g;\n\n/**\n * Match WHATWG URL preprocessing before checking a URL's protocol.\n *\n * @param {string} url\n *\n * @returns {string}\n */\nexport default function normalizeURLForProtocolCheck(url) {\n if (typeof url !== 'string') {\n return url;\n }\n\n let start = 0;\n\n while (start < url.length && url.charCodeAt(start) <= 0x20) {\n start++;\n }\n\n return url.slice(start).replace(urlParserControlCharacters, '');\n}\n","'use strict';\n\nexport default function parseProtocol(url) {\n const match = /^([-+\\w]{1,25}):(?:\\/\\/)?/.exec(url);\n return (match && match[1].toLowerCase()) || '';\n}\n","import utils from '../utils.js';\nimport platform from '../platform/index.js';\n\nconst decodeCookieValue = (value) => {\n try {\n return decodeURIComponent(value);\n } catch (e) {\n return value;\n }\n};\n\nexport default platform.hasStandardBrowserEnv\n ? // Standard browser envs support document.cookie\n {\n write(name, value, expires, path, domain, secure, sameSite) {\n if (typeof document === 'undefined') return;\n\n const cookie = [`${name}=${encodeURIComponent(value)}`];\n\n if (utils.isNumber(expires)) {\n cookie.push(`expires=${new Date(expires).toUTCString()}`);\n }\n if (utils.isString(path)) {\n cookie.push(`path=${path}`);\n }\n if (utils.isString(domain)) {\n cookie.push(`domain=${domain}`);\n }\n if (secure === true) {\n cookie.push('secure');\n }\n if (utils.isString(sameSite)) {\n cookie.push(`SameSite=${sameSite}`);\n }\n\n document.cookie = cookie.join('; ');\n },\n\n read(name) {\n if (typeof document === 'undefined') return null;\n const cookieString = document.cookie;\n if (!cookieString) return null;\n // Match name=value by splitting on the semicolon separator instead of building a\n // RegExp from `name` — interpolating an unescaped string into a RegExp would let\n // metacharacters (e.g. `.+?` in an attacker-influenced cookie name) cause ReDoS or\n // match the wrong cookie. Browsers may serialize cookie pairs as either \";\" or\n // \"; \", so ignore optional whitespace before each cookie name.\n const cookies = cookieString.split(';');\n for (let i = 0; i < cookies.length; i++) {\n const cookie = cookies[i].replace(/^\\s+/, '');\n const eq = cookie.indexOf('=');\n if (eq !== -1 && cookie.slice(0, eq) === name) {\n return decodeCookieValue(cookie.slice(eq + 1));\n }\n }\n return null;\n },\n\n async readAsync(name) {\n try {\n const store = typeof window !== 'undefined' && window.cookieStore;\n if (store && utils.isFunction(store.get)) {\n const cookie = await store.get(name);\n // Both APIs expose stored bytes; preserve Axios's existing URI decoding.\n return cookie ? decodeCookieValue(cookie.value) : null;\n }\n } catch (e) {\n // Restricted or unavailable storage retains the synchronous fallback.\n }\n\n return this.read(name);\n },\n\n remove(name) {\n this.write(name, '', Date.now() - 86400000, '/');\n },\n }\n : // Non-standard browser env (web workers, react-native) lack needed support.\n {\n write() {},\n read() {\n return null;\n },\n async readAsync() {\n return null;\n },\n remove() {},\n };\n","'use strict';\n\n/**\n * Calculate data maxRate\n * @param {Number} [samplesCount= 10]\n * @param {Number} [min= 1000]\n * @returns {Function}\n */\nfunction speedometer(samplesCount, min) {\n samplesCount = samplesCount || 10;\n const bytes = new Array(samplesCount);\n const timestamps = new Array(samplesCount);\n let head = 0;\n let tail = 0;\n let firstSampleTS;\n\n min = min !== undefined ? min : 1000;\n\n return function push(chunkLength) {\n const now = Date.now();\n\n const startedAt = timestamps[tail];\n\n if (!firstSampleTS) {\n firstSampleTS = now;\n }\n\n bytes[head] = chunkLength;\n timestamps[head] = now;\n\n let i = tail;\n let bytesCount = 0;\n\n while (i !== head) {\n bytesCount += bytes[i++];\n i = i % samplesCount;\n }\n\n head = (head + 1) % samplesCount;\n\n if (head === tail) {\n tail = (tail + 1) % samplesCount;\n }\n\n if (now - firstSampleTS < min) {\n return;\n }\n\n const passed = startedAt && now - startedAt;\n\n return passed ? Math.round((bytesCount * 1000) / passed) : undefined;\n };\n}\n\nexport default speedometer;\n","/**\n * Throttle decorator\n * @param {Function} fn\n * @param {Number} freq\n * @return {Array<Function>}\n */\nfunction throttle(fn, freq) {\n let timestamp = 0;\n let threshold = 1000 / freq;\n let lastArgs;\n let timer;\n\n const invoke = (args, now = Date.now()) => {\n timestamp = now;\n lastArgs = null;\n if (timer) {\n clearTimeout(timer);\n timer = null;\n }\n fn(...args);\n };\n\n const throttled = (...args) => {\n const now = Date.now();\n const passed = now - timestamp;\n if (passed >= threshold) {\n invoke(args, now);\n } else {\n lastArgs = args;\n if (!timer) {\n timer = setTimeout(() => {\n timer = null;\n invoke(lastArgs);\n }, threshold - passed);\n }\n }\n };\n\n const flush = () => lastArgs && invoke(lastArgs);\n const flushWith = (...args) => invoke(args);\n\n return [throttled, flush, flushWith];\n}\n\nexport default throttle;\n","import speedometer from './speedometer.js';\nimport throttle from './throttle.js';\nimport utils from '../utils.js';\n\nexport const progressEventReducer = (listener, isDownloadStream, freq = 3) => {\n let bytesNotified = 0;\n const _speedometer = speedometer(50, 250);\n\n return throttle((e) => {\n if (!e || !utils.isNumber(e.loaded)) {\n return;\n }\n const rawLoaded = e.loaded;\n const total = e.lengthComputable ? e.total : undefined;\n const loaded = Math.max(0, total != null ? Math.min(rawLoaded, total) : rawLoaded);\n const progressBytes = Math.max(0, loaded - bytesNotified);\n const rate = _speedometer(progressBytes);\n\n bytesNotified = Math.max(bytesNotified, loaded);\n\n const data = {\n loaded,\n total,\n progress: total ? loaded / total : undefined,\n bytes: progressBytes,\n rate: rate ? rate : undefined,\n estimated: rate && total ? (total - loaded) / rate : undefined,\n event: e,\n lengthComputable: total != null,\n [isDownloadStream ? 'download' : 'upload']: true,\n };\n\n listener(data);\n }, freq);\n};\n\nexport const progressEventDecorator = (total, throttled) => {\n const lengthComputable = total != null;\n\n return [\n (loaded) =>\n throttled[0]({\n lengthComputable,\n total,\n loaded,\n }),\n throttled[1],\n ];\n};\n\nexport const asyncDecorator =\n (fn, scheduler = utils.asap) =>\n (...args) =>\n scheduler(() => fn(...args));\n","import platform from '../platform/index.js';\n\nexport default platform.hasStandardBrowserEnv\n ? ((origin) => (url) => {\n url = new URL(url, document.baseURI || platform.origin);\n\n return (\n origin.protocol === url.protocol && origin.host === url.host && origin.port === url.port\n );\n })(new URL(platform.origin))\n : () => true;\n","'use strict';\n\n/**\n * Determines whether the specified URL is absolute\n *\n * @param {string} url The URL to test\n *\n * @returns {boolean} True if the specified URL is absolute, otherwise false\n */\nexport default function isAbsoluteURL(url) {\n // A URL is considered absolute if it begins with \"<scheme>://\" or \"//\" (protocol-relative URL).\n // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed\n // by any combination of letters, digits, plus, period, or hyphen.\n if (typeof url !== 'string') {\n return false;\n }\n\n return /^([a-z][a-z\\d+\\-.]*:)?\\/\\//i.test(url);\n}\n","'use strict';\n\n/**\n * Creates a new URL by combining the specified URLs\n *\n * @param {string} baseURL The base URL\n * @param {string} relativeURL The relative URL\n *\n * @returns {string} The combined URL\n */\nexport default function combineURLs(baseURL, relativeURL) {\n if (!relativeURL) {\n return baseURL;\n }\n\n let end = baseURL.length;\n\n while (end > 0 && baseURL.charCodeAt(end - 1) === 47) {\n end--;\n }\n\n return baseURL.slice(0, end) + '/' + relativeURL.replace(/^\\/+/, '');\n}\n","'use strict';\n\nimport AxiosError, { REDACTED } from './AxiosError.js';\nimport isAbsoluteURL from '../helpers/isAbsoluteURL.js';\nimport combineURLs from '../helpers/combineURLs.js';\nimport normalizeURLForProtocolCheck from '../helpers/normalizeURLForProtocolCheck.js';\n\nconst malformedHttpProtocol = /^https?:(?!\\/\\/)/i;\n\n// Redact the parts of a URL that can carry secrets before it is embedded in an\n// error message. AxiosError.toJSON() serializes `message` verbatim and errors\n// are commonly logged, while the opt-in `config.redact` model only cleans\n// config keys — it cannot reach the message. Redact only the genuinely\n// sensitive substrings — userinfo (credentials), query parameter values and\n// fragment contents — with the same REDACTED marker the config redaction uses,\n// while keeping the scheme, host, path and parameter names so the offending\n// request stays accurately identifiable.\nfunction redactFragment(fragment) {\n if (!fragment) {\n return fragment;\n }\n\n return fragment.replace(/(^|&)([^=&]*=)?[^&]+/g, (match, separator, parameterName = '') => {\n return `${separator}${parameterName}${REDACTED}`;\n });\n}\n\nfunction redactSensitiveURLParts(url) {\n const redactedURL = url.replace(/^(https?:\\/{0,2})[^/?#]*@/i, `$1${REDACTED}@`);\n const fragmentIndex = redactedURL.indexOf('#');\n const urlWithoutFragment =\n fragmentIndex === -1 ? redactedURL : redactedURL.slice(0, fragmentIndex);\n const redactedURLWithoutFragment = urlWithoutFragment.replace(\n /([?&][^=&#]*=)[^&#]*/g,\n `$1${REDACTED}`\n );\n\n if (fragmentIndex === -1) {\n return redactedURLWithoutFragment;\n }\n\n return `${redactedURLWithoutFragment}#${redactFragment(redactedURL.slice(fragmentIndex + 1))}`;\n}\n\nfunction assertValidHttpProtocolURL(url, config) {\n if (typeof url === 'string') {\n const normalizedURL = normalizeURLForProtocolCheck(url);\n if (malformedHttpProtocol.test(normalizedURL)) {\n throw new AxiosError(\n `Invalid URL ${JSON.stringify(redactSensitiveURLParts(normalizedURL))}: missing \"//\" after protocol`,\n AxiosError.ERR_INVALID_URL,\n config\n );\n }\n }\n}\n\n/**\n * Creates a new URL by combining the baseURL with the requestedURL,\n * only when the requestedURL is not already an absolute URL.\n * If the requestURL is absolute, this function returns the requestedURL untouched.\n *\n * @param {string} baseURL The base URL\n * @param {string} requestedURL Absolute or relative URL to combine\n *\n * @returns {string} The combined full path\n */\nexport default function buildFullPath(baseURL, requestedURL, allowAbsoluteUrls, config) {\n assertValidHttpProtocolURL(requestedURL, config);\n let isRelativeUrl = !isAbsoluteURL(requestedURL);\n if (baseURL && (isRelativeUrl || allowAbsoluteUrls === false)) {\n assertValidHttpProtocolURL(baseURL, config);\n return combineURLs(baseURL, requestedURL);\n }\n return requestedURL;\n}\n","'use strict';\n\nimport utils from '../utils.js';\nimport AxiosError from './AxiosError.js';\n\nexport default function assertParamsAcyclic(params) {\n const pending = [{ value: params }];\n const active = new WeakSet();\n const visited = new WeakSet();\n\n while (pending.length) {\n const { value, done } = pending.pop();\n if (!utils.isPlainObject(value) && !utils.isArray(value)) continue;\n if (done) {\n active.delete(value);\n continue;\n }\n if (active.has(value)) {\n throw new AxiosError(\n 'Circular reference detected in params',\n AxiosError.ERR_BAD_OPTION_VALUE\n );\n }\n if (visited.has(value)) continue;\n visited.add(value);\n active.add(value);\n pending.push({ value, done: true });\n\n const keys = Object.keys(value);\n if (Object.getOwnPropertySymbols && Object.getOwnPropertyDescriptor) {\n Object.getOwnPropertySymbols(value).forEach((key) => {\n const descriptor = Object.getOwnPropertyDescriptor(value, key);\n if (descriptor && descriptor.enumerable) keys.push(key);\n });\n }\n // Shallow array elements retain fields filtered during plain-object merges.\n // Inspect reserved data properties without evaluating their accessors.\n keys.forEach((key) => {\n if (key === '__proto__' || key === 'constructor' || key === 'prototype') {\n const descriptor = Object.getOwnPropertyDescriptor(value, key);\n if (descriptor && utils.hasOwnProp(descriptor, 'value')) {\n pending.push({ value: descriptor.value });\n }\n } else {\n pending.push({ value: value[key] });\n }\n });\n }\n}\n","'use strict';\n\nimport utils from '../utils.js';\nimport AxiosHeaders from './AxiosHeaders.js';\nimport assertParamsAcyclic from './assertParamsAcyclic.js';\n\nconst headersToObject = (thing) => (thing instanceof AxiosHeaders ? { ...thing } : thing);\n\nconst ownEnumerableKeys = (thing) => {\n if (Object.getOwnPropertySymbols && Object.getOwnPropertyDescriptor) {\n return Object.keys(thing).concat(\n Object.getOwnPropertySymbols(thing).filter((symbol) => {\n const descriptor = Object.getOwnPropertyDescriptor(thing, symbol);\n return descriptor && descriptor.enumerable;\n })\n );\n }\n return Object.keys(thing);\n};\n\n// Copy params without recursive merges so the serializer remains responsible\n// for its depth policy. Only visit defaults that contribute to the result.\nfunction mergeParams(a, b) {\n const pending = [];\n const copies = new WeakMap();\n const empty = {};\n\n function copy(target, source) {\n if (!utils.isPlainObject(source)) {\n return utils.isArray(source) ? source.slice() : source;\n }\n\n const base = utils.isPlainObject(target) ? target : empty;\n let bases = copies.get(source);\n if (!bases) {\n bases = new WeakMap();\n copies.set(source, bases);\n }\n if (bases.has(base)) return bases.get(base);\n\n const result = {};\n bases.set(base, result);\n pending.push({ base, source, result });\n return result;\n }\n\n const result = utils.isUndefined(b) ? copy(undefined, a) : copy(a, b);\n while (pending.length) {\n const { base, source, result: target } = pending.pop();\n const baseKeys = new Set(ownEnumerableKeys(base));\n const sourceKeys = new Set(ownEnumerableKeys(source));\n const keys = new Set([...baseKeys, ...sourceKeys]);\n\n keys.forEach((key) => {\n if (key === '__proto__' || key === 'constructor' || key === 'prototype') return;\n const hasSource = sourceKeys.has(key);\n const value = hasSource ? source[key] : undefined;\n const previous =\n (!hasSource || utils.isPlainObject(value)) && baseKeys.has(key) ? base[key] : undefined;\n target[key] = hasSource ? copy(previous, value) : copy(undefined, previous);\n });\n }\n\n assertParamsAcyclic(result);\n return result;\n}\n\nfunction getMergedValue(target, source, prop, caseless) {\n if (utils.isPlainObject(target) && utils.isPlainObject(source)) {\n return utils.merge.call({ caseless }, target, source);\n } else if (utils.isPlainObject(source)) {\n return utils.merge({}, source);\n } else if (utils.isArray(source)) {\n return source.slice();\n }\n return source;\n}\n\nfunction mergeDeepProperties(a, b, prop, caseless) {\n if (!utils.isUndefined(b)) {\n return getMergedValue(a, b, prop, caseless);\n } else if (!utils.isUndefined(a)) {\n return getMergedValue(undefined, a, prop, caseless);\n }\n}\n\n// eslint-disable-next-line consistent-return\nfunction valueFromConfig2(a, b) {\n if (!utils.isUndefined(b)) {\n return getMergedValue(undefined, b);\n }\n}\n\n// eslint-disable-next-line consistent-return\nfunction defaultToConfig2(a, b) {\n if (!utils.isUndefined(b)) {\n return getMergedValue(undefined, b);\n } else if (!utils.isUndefined(a)) {\n return getMergedValue(undefined, a);\n }\n}\n\nfunction getMergedTransitionalOption(config1, config2, prop) {\n const transitional2 = utils.hasOwnProp(config2, 'transitional')\n ? config2.transitional\n : undefined;\n\n if (!utils.isUndefined(transitional2)) {\n if (utils.isPlainObject(transitional2)) {\n if (utils.hasOwnProp(transitional2, prop)) {\n return transitional2[prop];\n }\n } else {\n return undefined;\n }\n }\n\n const transitional1 = utils.hasOwnProp(config1, 'transitional')\n ? config1.transitional\n : undefined;\n\n if (utils.isPlainObject(transitional1) && utils.hasOwnProp(transitional1, prop)) {\n return transitional1[prop];\n }\n\n return undefined;\n}\n\n// eslint-disable-next-line consistent-return\nfunction mergeDirectKeys(a, b, prop, config1, config2) {\n if (utils.hasOwnProp(config2, prop)) {\n return getMergedValue(a, b);\n } else if (utils.hasOwnProp(config1, prop)) {\n return getMergedValue(undefined, a);\n }\n}\n\nfunction mergeHeaders(a, b, prop) {\n return mergeDeepProperties(headersToObject(a), headersToObject(b), prop, true);\n}\n\n// Null-proto, frozen descriptor so a polluted Object.prototype.get cannot turn\n// this data descriptor into an accessor descriptor on the way in.\n// defineProperty only reads it, so one shared instance serves every call.\nconst hasOwnPropertyDescriptor = Object.freeze({\n __proto__: null,\n value: Object.prototype.hasOwnProperty,\n enumerable: false,\n writable: true,\n configurable: true,\n});\n\n// The strategy table and the strategies above are stateless, so they are\n// built once at module load instead of on every call: mergeConfig runs at\n// most twice per request (once from a method alias, once from `_request`).\nconst mergeMap = {\n url: valueFromConfig2,\n method: valueFromConfig2,\n data: valueFromConfig2,\n baseURL: defaultToConfig2,\n transformRequest: defaultToConfig2,\n transformResponse: defaultToConfig2,\n params: mergeParams,\n paramsSerializer: defaultToConfig2,\n timeout: defaultToConfig2,\n timeoutErrorMessage: defaultToConfig2,\n withCredentials: defaultToConfig2,\n withXSRFToken: defaultToConfig2,\n adapter: defaultToConfig2,\n responseType: defaultToConfig2,\n xsrfCookieName: defaultToConfig2,\n xsrfHeaderName: defaultToConfig2,\n onUploadProgress: defaultToConfig2,\n onDownloadProgress: defaultToConfig2,\n decompress: defaultToConfig2,\n maxContentLength: defaultToConfig2,\n maxBodyLength: defaultToConfig2,\n beforeRedirect: defaultToConfig2,\n transport: defaultToConfig2,\n httpAgent: defaultToConfig2,\n httpsAgent: defaultToConfig2,\n cancelToken: defaultToConfig2,\n socketPath: defaultToConfig2,\n allowedSocketPaths: defaultToConfig2,\n responseEncoding: defaultToConfig2,\n validateStatus: mergeDirectKeys,\n headers: mergeHeaders,\n};\n\n/**\n * Config-specific merge-function which creates a new config-object\n * by merging two configuration objects together.\n *\n * @param {Object} config1\n * @param {Object} config2\n *\n * @returns {Object} New object resulting from merging config2 to config1\n */\nexport default function mergeConfig(config1, config2) {\n // eslint-disable-next-line no-param-reassign\n config1 = config1 || {};\n config2 = config2 || {};\n\n // Use a null-prototype object so that downstream reads such as `config.auth`\n // or `config.baseURL` cannot inherit polluted values from Object.prototype.\n // `hasOwnProperty` is restored as a non-enumerable own slot to preserve\n // ergonomics for user code that relies on it.\n const config = Object.create(null);\n Object.defineProperty(config, 'hasOwnProperty', hasOwnPropertyDescriptor);\n\n const keys = ownEnumerableKeys({ ...config1, ...config2 });\n\n for (let i = 0, len = keys.length; i < len; i++) {\n const prop = keys[i];\n if (prop === '__proto__' || prop === 'constructor' || prop === 'prototype') continue;\n const merge = utils.hasOwnProp(mergeMap, prop) ? mergeMap[prop] : mergeDeepProperties;\n const a = utils.hasOwnProp(config1, prop) ? config1[prop] : undefined;\n const b = utils.hasOwnProp(config2, prop) ? config2[prop] : undefined;\n const configValue =\n merge === mergeDirectKeys ? merge(a, b, prop, config1, config2) : merge(a, b, prop);\n (utils.isUndefined(configValue) && merge !== mergeDirectKeys) || (config[prop] = configValue);\n }\n\n if (\n utils.hasOwnProp(config2, 'validateStatus') &&\n utils.isUndefined(config2.validateStatus) &&\n getMergedTransitionalOption(config1, config2, 'validateStatusUndefinedResolves') === false\n ) {\n if (utils.hasOwnProp(config1, 'validateStatus')) {\n config.validateStatus = getMergedValue(undefined, config1.validateStatus);\n } else {\n delete config.validateStatus;\n }\n }\n\n return config;\n}\n","'use strict';\n\nconst FORM_DATA_CONTENT_HEADERS = ['content-type', 'content-length'];\n\n/**\n * Apply the headers generated by a FormData implementation to the request headers,\n * honoring the `formDataHeaderPolicy` option: with 'content-only', copy only the\n * content-* headers; otherwise merge all of them.\n *\n * @param {AxiosHeaders} headers - the request headers to mutate\n * @param {Object | null | undefined} formHeaders - headers produced by the FormData implementation\n * @param {String} [policy] - the resolved `formDataHeaderPolicy` config value\n *\n * @returns {void}\n */\nexport default function setFormDataHeaders(headers, formHeaders, policy) {\n if (policy !== 'content-only') {\n headers.set(formHeaders);\n return;\n }\n\n Object.entries(formHeaders || {}).forEach(([key, val]) => {\n if (FORM_DATA_CONTENT_HEADERS.includes(key.toLowerCase())) {\n headers.set(key, val);\n }\n });\n}\n","import platform from '../platform/index.js';\nimport utils from '../utils.js';\nimport AxiosError from '../core/AxiosError.js';\nimport isURLSameOrigin from './isURLSameOrigin.js';\nimport cookies from './cookies.js';\nimport buildFullPath from '../core/buildFullPath.js';\nimport mergeConfig from '../core/mergeConfig.js';\nimport AxiosHeaders from '../core/AxiosHeaders.js';\nimport setFormDataHeaders from '../core/setFormDataHeaders.js';\nimport buildURL from './buildURL.js';\n\n/**\n * Encode a UTF-8 string to a Latin-1 byte string for use with btoa().\n * This is a modern replacement for the deprecated unescape(encodeURIComponent(str)) pattern.\n *\n * @param {string} str The string to encode\n *\n * @returns {string} UTF-8 bytes as a Latin-1 string\n */\nconst encodeUTF8 = (str) =>\n encodeURIComponent(str).replace(/%([0-9A-F]{2})/gi, (_, hex) =>\n String.fromCharCode(parseInt(hex, 16))\n );\n\nconst readCookie = (name) => cookies.read(name);\n\nfunction resolveConfig(config, readXsrfCookie = readCookie) {\n const newConfig = mergeConfig({}, config);\n\n // Read only own properties to prevent prototype pollution gadgets\n // (e.g. Object.prototype.baseURL = 'https://evil.com').\n const own = (key) => (utils.hasOwnProp(newConfig, key) ? newConfig[key] : undefined);\n\n const data = own('data');\n let withXSRFToken = own('withXSRFToken');\n const xsrfHeaderName = own('xsrfHeaderName');\n const xsrfCookieName = own('xsrfCookieName');\n let headers = own('headers');\n const auth = own('auth');\n const baseURL = own('baseURL');\n const allowAbsoluteUrls = own('allowAbsoluteUrls');\n const url = own('url');\n\n newConfig.headers = headers = AxiosHeaders.from(headers);\n\n newConfig.url = buildURL(\n buildFullPath(baseURL, url, allowAbsoluteUrls, newConfig),\n own('params'),\n own('paramsSerializer')\n );\n\n // HTTP basic authentication\n if (auth) {\n const username = utils.getSafeProp(auth, 'username') || '';\n const password = utils.getSafeProp(auth, 'password') || '';\n const transitional = own('transitional');\n const encodeUsername =\n transitional &&\n utils.hasOwnProp(transitional, 'encodeBasicAuthUsername') &&\n transitional.encodeBasicAuthUsername === true;\n\n try {\n headers.set(\n 'Authorization',\n // Preserve legacy username bytes unless the caller opts in to UTF-8.\n 'Basic ' +\n btoa(\n (encodeUsername ? encodeUTF8(username) : username) +\n ':' +\n (password ? encodeUTF8(password) : '')\n )\n );\n } catch (e) {\n throw AxiosError.from(e, AxiosError.ERR_BAD_OPTION_VALUE, config);\n }\n }\n\n if (utils.isFormData(data)) {\n const getHeaders = utils.getSafeProp(data, 'getHeaders');\n\n if (\n platform.hasStandardBrowserEnv ||\n platform.hasStandardBrowserWebWorkerEnv ||\n utils.isReactNative(data)\n ) {\n headers.setContentType(undefined); // browser/web worker/RN handles it\n } else if (utils.isFunction(getHeaders)) {\n // Node.js FormData (like form-data package)\n setFormDataHeaders(headers, getHeaders.call(data), own('formDataHeaderPolicy'));\n }\n }\n\n // Add xsrf header\n // This is only done if running in a standard browser environment.\n // Specifically not if we're in a web worker, or react-native.\n\n if (platform.hasStandardBrowserEnv) {\n if (utils.isFunction(withXSRFToken)) {\n withXSRFToken = withXSRFToken(newConfig);\n }\n\n // Strict boolean check — prevents proto-pollution gadgets (e.g. Object.prototype.withXSRFToken = 1)\n // and misconfigurations (e.g. \"false\") from short-circuiting the same-origin check and leaking\n // the XSRF token cross-origin.\n const shouldSendXSRF =\n withXSRFToken === true || (withXSRFToken == null && isURLSameOrigin(newConfig.url));\n\n if (shouldSendXSRF) {\n const xsrfValue = xsrfHeaderName && xsrfCookieName && readXsrfCookie(xsrfCookieName);\n\n if (xsrfValue) {\n headers.set(xsrfHeaderName, xsrfValue);\n }\n }\n }\n\n return newConfig;\n}\n\nexport default resolveConfig;\n","import utils from '../utils.js';\nimport settle from '../core/settle.js';\nimport transitionalDefaults from '../defaults/transitional.js';\nimport AxiosError from '../core/AxiosError.js';\nimport CanceledError from '../cancel/CanceledError.js';\nimport normalizeURLForProtocolCheck from '../helpers/normalizeURLForProtocolCheck.js';\nimport parseProtocol from '../helpers/parseProtocol.js';\nimport platform from '../platform/index.js';\nimport AxiosHeaders from '../core/AxiosHeaders.js';\nimport cookies from '../helpers/cookies.js';\nimport { progressEventReducer } from '../helpers/progressEventReducer.js';\nimport resolveConfig from '../helpers/resolveConfig.js';\nimport { toByteStringHeaderObject } from '../helpers/sanitizeHeaderValue.js';\n\nconst isXHRAdapterSupported = typeof XMLHttpRequest !== 'undefined';\n\nexport default isXHRAdapterSupported &&\n function (config) {\n return new Promise(function dispatchXhrRequest(resolve, reject) {\n let useAsyncXsrf;\n try {\n const store =\n platform.hasStandardBrowserEnv && typeof window !== 'undefined' && window.cookieStore;\n useAsyncXsrf = store && utils.isFunction(store.get);\n } catch (e) {\n // A restricted Cookie Store getter must retain the synchronous fallback.\n }\n let xsrfCookieName;\n const _config = resolveConfig(\n config,\n useAsyncXsrf\n ? (name) => {\n xsrfCookieName = name;\n return null;\n }\n : undefined\n );\n let requestData = _config.data;\n const requestHeaders = AxiosHeaders.from(_config.headers).normalize();\n let { responseType, onUploadProgress, onDownloadProgress } = _config;\n let onCanceled;\n let timeoutId;\n let uploadThrottled, downloadThrottled;\n let flushUpload, flushDownload, flushDownloadWithEvent;\n\n function done() {\n clearTimeout(timeoutId);\n // A final progress callback must not prevent the remaining cleanup.\n // Report errors asynchronously, as onloadend and the throttle timer do.\n try {\n flushUpload && flushUpload(); // flush events\n } catch (err) {\n setTimeout(() => {\n throw err;\n });\n }\n try {\n flushDownload && flushDownload(); // flush events\n } catch (err) {\n setTimeout(() => {\n throw err;\n });\n }\n\n // A flush can synchronously cancel the request and reenter done().\n // In that case the inner call has already detached these listeners.\n if (request) {\n downloadThrottled && request.removeEventListener('progress', downloadThrottled);\n if (request.upload) {\n uploadThrottled && request.upload.removeEventListener('progress', uploadThrottled);\n flushUpload && request.upload.removeEventListener('loadend', flushUpload);\n }\n }\n\n _config.cancelToken && _config.cancelToken.unsubscribe(onCanceled);\n\n _config.signal && _config.signal.removeEventListener('abort', onCanceled);\n }\n\n let request = new XMLHttpRequest();\n\n request.open(_config.method.toUpperCase(), _config.url, true);\n\n // Set the request timeout in MS\n request.timeout = _config.timeout;\n\n function onloadend(event) {\n if (!request) {\n return;\n }\n\n // Status 0 means no response was received, which onerror and onabort normally\n // reject before this runs. Firefox 152 fires only readystatechange and loadend for\n // navigation-canceled requests (https://bugzilla.mozilla.org/show_bug.cgi?id=1505389),\n // leaving settle() to resolve them as an empty success. ECONNABORTED is the error\n // onabort raised on Firefox 151. Reads over file:, which some environments report as\n // status 0 on success, are excluded by the request URL's scheme after browser-style\n // preprocessing, by the page origin's scheme for relative URLs (which inherit it), or\n // by responseURL where implemented.\n if (\n request.status === 0 &&\n (parseProtocol(normalizeURLForProtocolCheck(_config.url)) ||\n parseProtocol(platform.origin)) !== 'file' &&\n !(request.responseURL && request.responseURL.startsWith('file:'))\n ) {\n reject(new AxiosError('Request aborted', AxiosError.ECONNABORTED, config, request));\n done();\n\n // Clean up request\n request = null;\n return;\n }\n\n // When loadend is still dispatching, flushing with it gives progress\n // listeners a final delivery whose event has a live target. The legacy\n // ready-state fallback has no event, so replay its pending progress.\n // A throwing listener must not block settlement; rethrow asynchronously,\n // matching how listener errors surface on the throttle timer path.\n try {\n if (event) {\n flushDownloadWithEvent && flushDownloadWithEvent(event);\n } else {\n flushDownload && flushDownload();\n }\n } catch (err) {\n setTimeout(() => {\n throw err;\n });\n }\n\n // A final progress callback can cancel the request synchronously.\n if (!request) {\n return;\n }\n\n // Prepare the response\n const responseHeaders = AxiosHeaders.from(\n 'getAllResponseHeaders' in request && request.getAllResponseHeaders()\n );\n const responseData =\n !responseType || responseType === 'text' || responseType === 'json'\n ? request.responseText\n : request.response;\n const response = {\n data: responseData,\n status: request.status,\n statusText: request.statusText,\n headers: responseHeaders,\n config,\n request,\n };\n\n settle(\n function _resolve(value) {\n resolve(value);\n done();\n },\n function _reject(err) {\n reject(err);\n done();\n },\n response\n );\n\n // Clean up request\n request = null;\n }\n\n if ('onloadend' in request) {\n // Use onloadend if available\n request.onloadend = onloadend;\n } else {\n // Listen for ready state to emulate onloadend\n request.onreadystatechange = function handleLoad() {\n if (!request || request.readyState !== 4) {\n return;\n }\n\n // The request errored out and we didn't get a response, this will be\n // handled by onerror instead\n // With one exception: request that using file: protocol, most browsers\n // will return status as 0 even though it's a successful request\n if (\n request.status === 0 &&\n !(request.responseURL && request.responseURL.startsWith('file:'))\n ) {\n return;\n }\n // readystate handler is calling before onerror or ontimeout handlers,\n // so we should call onloadend on the next 'tick'\n setTimeout(onloadend);\n };\n }\n\n // Handle browser request cancellation (as opposed to a manual cancellation)\n request.onabort = function handleAbort() {\n if (!request) {\n return;\n }\n\n reject(new AxiosError('Request aborted', AxiosError.ECONNABORTED, config, request));\n done();\n\n // Clean up request\n request = null;\n };\n\n // Handle low level network errors\n request.onerror = function handleError(event) {\n // Browsers deliver a ProgressEvent in XHR onerror\n // (message may be empty; when present, surface it)\n // See https://developer.mozilla.org/docs/Web/API/XMLHttpRequest/error_event\n const msg = event && event.message ? event.message : 'Network Error';\n const err = new AxiosError(msg, AxiosError.ERR_NETWORK, config, request);\n // attach the underlying event for consumers who want details\n err.event = event || null;\n reject(err);\n done();\n request = null;\n };\n\n // Handle timeout\n request.ontimeout = function handleTimeout() {\n if (!request) return;\n let timeoutErrorMessage = _config.timeout\n ? 'timeout of ' + _config.timeout + 'ms exceeded'\n : 'timeout exceeded';\n const transitional = _config.transitional || transitionalDefaults;\n if (_config.timeoutErrorMessage) {\n timeoutErrorMessage = _config.timeoutErrorMessage;\n }\n reject(\n new AxiosError(\n timeoutErrorMessage,\n transitional.clarifyTimeoutError ? AxiosError.ETIMEDOUT : AxiosError.ECONNABORTED,\n config,\n request\n )\n );\n done();\n\n // Clean up request\n request = null;\n };\n\n // Remove Content-Type if data is undefined\n requestData === undefined && requestHeaders.setContentType(null);\n\n // Add withCredentials to request if needed\n if (!utils.isUndefined(_config.withCredentials)) {\n request.withCredentials = !!_config.withCredentials;\n }\n\n // Add responseType to request if needed\n if (responseType && responseType !== 'json') {\n request.responseType = _config.responseType;\n }\n\n // Handle progress if needed\n if (onDownloadProgress) {\n [downloadThrottled, flushDownload, flushDownloadWithEvent] = progressEventReducer(\n onDownloadProgress,\n true\n );\n request.addEventListener('progress', downloadThrottled);\n }\n\n // Not all browsers support upload events\n if (onUploadProgress && request.upload) {\n [uploadThrottled, flushUpload] = progressEventReducer(onUploadProgress);\n\n request.upload.addEventListener('progress', uploadThrottled);\n\n request.upload.addEventListener('loadend', flushUpload);\n }\n\n if (_config.cancelToken || _config.signal) {\n // Handle cancellation\n // eslint-disable-next-line func-names\n onCanceled = (cancel) => {\n if (!request) {\n return;\n }\n reject(!cancel || cancel.type ? new CanceledError(null, config, request) : cancel);\n const xhr = request;\n done();\n request = null;\n xhr.abort();\n };\n\n _config.cancelToken && _config.cancelToken.subscribe(onCanceled);\n if (!request) return;\n if (_config.signal) {\n _config.signal.aborted\n ? onCanceled()\n : _config.signal.addEventListener('abort', onCanceled);\n }\n }\n\n if (!request) return;\n\n const protocol = parseProtocol(_config.url);\n\n if (protocol && !platform.protocols.includes(protocol)) {\n reject(\n new AxiosError(\n 'Unsupported protocol ' + protocol + ':',\n AxiosError.ERR_BAD_REQUEST,\n config\n )\n );\n done();\n return;\n }\n\n const sendRequest = () => {\n if (!request) return;\n // Apply headers after an asynchronous XSRF read so existing headers are\n // replaced through AxiosHeaders rather than appended by the native XHR.\n if ('setRequestHeader' in request) {\n utils.forEach(\n toByteStringHeaderObject(requestHeaders),\n function setRequestHeader(val, key) {\n request.setRequestHeader(key, val);\n }\n );\n }\n request.send(requestData || null);\n };\n\n if (xsrfCookieName) {\n // Native XHR timeout starts at send(). Cover cookie preparation and the\n // subsequent request with the same budget and existing timeout handler.\n const now =\n typeof performance !== 'undefined' && utils.isFunction(performance.now)\n ? () => performance.now()\n : Date.now;\n const deadline = request.timeout > 0 ? now() + Number(request.timeout) : undefined;\n const abortOnTimeout = () => {\n if (!request) return;\n const xhr = request;\n xhr.ontimeout();\n xhr.abort();\n };\n if (deadline !== undefined) {\n const scheduleTimeout = () => {\n const remaining = deadline - now();\n if (remaining > 0) {\n // Browser timers overflow above the signed 32-bit delay limit.\n timeoutId = setTimeout(scheduleTimeout, Math.min(remaining, 0x7fffffff));\n } else {\n abortOnTimeout();\n }\n };\n scheduleTimeout();\n }\n\n cookies\n .readAsync(xsrfCookieName)\n .then((value) => {\n if (!request) return;\n // Promise callbacks may run before an overdue timer after a busy task.\n if (deadline !== undefined && now() >= deadline) {\n abortOnTimeout();\n return;\n }\n if (value) {\n const headerName =\n utils.hasOwnProp(_config, 'xsrfHeaderName') && _config.xsrfHeaderName;\n requestHeaders.set(headerName, value);\n }\n sendRequest();\n })\n .catch((error) => {\n if (!request) return;\n reject(AxiosError.from(error, null, config, request));\n done();\n request = null;\n });\n } else {\n sendRequest();\n }\n });\n };\n","import CanceledError from '../cancel/CanceledError.js';\nimport AxiosError from '../core/AxiosError.js';\nimport utils from '../utils.js';\n\nconst composeSignals = (signals, timeout) => {\n signals = signals ? signals.filter(Boolean) : [];\n\n if (!timeout && !signals.length) {\n return;\n }\n\n const controller = new AbortController();\n\n let aborted = false;\n\n const onabort = function (reason) {\n if (!aborted) {\n aborted = true;\n unsubscribe();\n const err = reason instanceof Error ? reason : this.reason;\n controller.abort(\n err instanceof AxiosError\n ? err\n : new CanceledError(err instanceof Error ? err.message : err)\n );\n }\n };\n\n let timer =\n timeout &&\n setTimeout(() => {\n timer = null;\n onabort(new AxiosError(`timeout of ${timeout}ms exceeded`, AxiosError.ETIMEDOUT));\n }, timeout);\n\n const unsubscribe = () => {\n if (!signals) {\n return;\n }\n timer && clearTimeout(timer);\n timer = null;\n signals.forEach((signal) => {\n const unsubscribeSignal = utils.getSafeProp(signal, 'unsubscribe');\n utils.isFunction(unsubscribeSignal)\n ? unsubscribeSignal.call(signal, onabort)\n : signal.removeEventListener('abort', onabort);\n });\n signals = null;\n };\n\n signals.forEach((signal) => {\n if (aborted) {\n return;\n }\n\n if (signal.aborted) {\n onabort.call(signal);\n return;\n }\n\n signal.addEventListener('abort', onabort, { once: true });\n });\n\n const { signal } = controller;\n\n signal.unsubscribe = () => utils.asap(unsubscribe);\n\n return signal;\n};\n\nexport default composeSignals;\n","export const streamChunk = function* (chunk, chunkSize) {\n let len = chunk.byteLength;\n\n if (!chunkSize || len < chunkSize) {\n yield chunk;\n return;\n }\n\n let pos = 0;\n let end;\n\n while (pos < len) {\n end = pos + chunkSize;\n yield chunk.slice(pos, end);\n pos = end;\n }\n};\n\nexport const readBytes = async function* (iterable, chunkSize) {\n for await (const chunk of readStream(iterable)) {\n yield* streamChunk(chunk, chunkSize);\n }\n};\n\nconst readStream = async function* (stream) {\n if (stream[Symbol.asyncIterator]) {\n yield* stream;\n return;\n }\n\n const reader = stream.getReader();\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) {\n break;\n }\n yield value;\n }\n } finally {\n await reader.cancel();\n }\n};\n\nexport const trackStream = (stream, chunkSize, onProgress, onFinish) => {\n const iterator = readBytes(stream, chunkSize);\n\n let bytes = 0;\n let done;\n let _onFinish = (e) => {\n if (!done) {\n done = true;\n onFinish && onFinish(e);\n }\n };\n\n return new ReadableStream(\n {\n async pull(controller) {\n try {\n const { done, value } = await iterator.next();\n\n if (done) {\n _onFinish();\n controller.close();\n return;\n }\n\n let len = value.byteLength;\n if (onProgress) {\n let loadedBytes = (bytes += len);\n onProgress(loadedBytes);\n }\n controller.enqueue(new Uint8Array(value));\n } catch (err) {\n _onFinish(err);\n throw err;\n }\n },\n cancel(reason) {\n _onFinish(reason);\n return iterator.return();\n },\n },\n {\n highWaterMark: 2,\n }\n );\n};\n","import utils from '../utils.js';\n\nconst CRLF = '\\r\\n';\nconst normalizeLines = (value) => String(value).replace(/\\r\\n|\\r|\\n/g, CRLF);\nconst escapeName = (value) =>\n String(value).replace(/[\\r\\n\"]/g, (char) =>\n char === '\\r' ? '%0D' : char === '\\n' ? '%0A' : '%22'\n );\n\n// Count UTF-8 bytes without allocating an encoded copy of a field. FormData\n// string values normalize line endings; Blob/File contents remain unchanged.\nconst stringBytes = (value, normalize) => {\n let length = 0;\n for (let i = 0; i < value.length; i++) {\n const code = value.charCodeAt(i);\n if (normalize && (code === 13 || code === 10)) {\n if (code === 13 && value.charCodeAt(i + 1) === 10) i++;\n length += 2;\n } else if (code < 0x80) {\n length++;\n } else if (code < 0x800) {\n length += 2;\n } else if (\n code >= 0xd800 &&\n code <= 0xdbff &&\n value.charCodeAt(i + 1) >= 0xdc00 &&\n value.charCodeAt(i + 1) <= 0xdfff\n ) {\n length += 4;\n i++;\n } else {\n length += 3;\n }\n }\n return length;\n};\n\n// Describe serialization failures independently of any request library.\nexport class FormDataError extends TypeError {\n constructor(message, reason) {\n super(message);\n this.name = 'FormDataError';\n this.reason = reason;\n }\n}\n\n// The caller supplies the boundary, Blob implementation, and limit error.\nexport default function formDataToBlob(form, Blob, limit, limitError, boundary) {\n if (!utils.isFunction(Blob)) {\n throw new FormDataError('Blob is not supported', 'blob');\n }\n\n if (\n !utils.isString(boundary) ||\n !/^[A-Za-z0-9'()+_,./:=? -]{1,70}$/.test(boundary) ||\n / $/.test(boundary)\n ) {\n throw new FormDataError('Invalid multipart boundary', 'boundary');\n }\n const footer = '--' + boundary + '--' + CRLF;\n let length = footer.length;\n const parts = [];\n const checkLength = (extra) => {\n if (length + extra > limit) throw limitError();\n };\n checkLength(0);\n\n for (const [name, value] of form) {\n const isString = utils.isString(value);\n const valueLength = isString ? stringBytes(value, true) : value.size;\n if (!Number.isFinite(valueLength) || valueLength < 0) {\n throw new FormDataError('Unsupported FormData part size', 'part');\n }\n // Reject large values and names before building normalized header strings.\n checkLength(\n valueLength +\n stringBytes(name, true) +\n (!isString && value.name ? stringBytes(value.name, false) : 0) +\n (!isString && value.type ? stringBytes(value.type, false) : 0)\n );\n\n let header =\n '--' +\n boundary +\n CRLF +\n 'Content-Disposition: form-data; name=\"' +\n escapeName(normalizeLines(name)) +\n '\"';\n if (!isString) {\n header +=\n '; filename=\"' +\n escapeName(utils.isString(value.name) ? value.name : 'blob') +\n '\"' +\n CRLF +\n 'Content-Type: ' +\n String(value.type || 'application/octet-stream').replace(/[\\r\\n]/g, '');\n }\n header += CRLF + CRLF;\n const partLength = stringBytes(header, false) + valueLength + CRLF.length;\n checkLength(partLength);\n length += partLength;\n parts.push({ header, value, isString });\n }\n\n // Native Blob composition retains existing Blob/File data. No file is read\n // and no complete multipart ArrayBuffer is created to determine its length.\n const blobParts = [];\n for (const part of parts) {\n blobParts.push(part.header, part.isString ? normalizeLines(part.value) : part.value, CRLF);\n }\n blobParts.push(footer);\n return new Blob(blobParts, { type: 'multipart/form-data; boundary=' + boundary });\n}\n","import utils from '../utils.js';\nimport platform from '../platform/index.js';\nimport AxiosError from './AxiosError.js';\nimport formDataToBlob, { FormDataError } from '../helpers/formDataToBlob.js';\n\nexport default function createMultipartBody(form, Blob, limit, limitError, boundary) {\n // Report missing Blob support before trying to select a random source.\n if (!utils.isFunction(Blob)) {\n throw new AxiosError('Blob is not supported', AxiosError.ERR_NOT_SUPPORT);\n }\n\n if (boundary === undefined) {\n if (utils.isFunction(platform.generateString)) {\n boundary = 'axios-' + platform.generateString(36, '0123456789abcdef');\n } else {\n const crypto = utils.global.crypto;\n if (!crypto || !utils.isFunction(crypto.getRandomValues)) {\n throw new AxiosError('Random byte generation is not supported', AxiosError.ERR_NOT_SUPPORT);\n }\n const random = new Uint8Array(18);\n crypto.getRandomValues(random);\n boundary =\n 'axios-' + Array.from(random, (value) => ('0' + value.toString(16)).slice(-2)).join('');\n }\n }\n\n try {\n return formDataToBlob(form, Blob, limit, limitError, boundary);\n } catch (error) {\n if (error instanceof FormDataError) {\n const code =\n error.reason === 'boundary' ? AxiosError.ERR_BAD_OPTION_VALUE : AxiosError.ERR_BAD_REQUEST;\n throw new AxiosError(error.message, code);\n }\n throw error;\n }\n}\n","/**\n * Estimate data: URL byte lengths *without* allocating large buffers.\n * - Fetch percent-decodes a base64 body before decoding it.\n * - Node's Buffer.from(body, 'base64') sizes its backing allocation from the\n * percent-decoded body, including ignored characters and content after padding.\n * - Non-base64 data is percent-decoded and then encoded as UTF-8.\n */\nconst isHexDigit = (charCode) =>\n (charCode >= 48 && charCode <= 57) ||\n (charCode >= 65 && charCode <= 70) ||\n (charCode >= 97 && charCode <= 102);\n\nconst isPercentEncodedByte = (str, i, len) =>\n i + 2 < len && isHexDigit(str.charCodeAt(i + 1)) && isHexDigit(str.charCodeAt(i + 2));\n\nconst hexValue = (charCode) => (charCode <= 57 ? charCode - 48 : (charCode & 0xdf) - 55);\n\nconst isBase64Char = (charCode) =>\n (charCode >= 65 && charCode <= 90) || // A-Z\n (charCode >= 97 && charCode <= 122) || // a-z\n (charCode >= 48 && charCode <= 57) || // 0-9\n charCode === 43 || // +\n charCode === 47 || // /\n charCode === 45 || // - (base64url)\n charCode === 95; // _ (base64url)\n\nconst isBase64Whitespace = (charCode) =>\n charCode === 9 || charCode === 10 || charCode === 12 || charCode === 13 || charCode === 32;\n\nconst base64Bytes = (significant) => {\n const groups = Math.floor(significant / 4);\n const remainder = significant % 4;\n return groups * 3 + (remainder === 2 ? 1 : remainder === 3 ? 2 : 0);\n};\n\n// Buffer.byteLength(body, 'base64') uses the raw string length as an allocation\n// upper bound even when Buffer.from later ignores characters or stops at '='.\nconst estimateBase64BufferAllocation = (body) => {\n const len = body.length;\n let padding = 0;\n\n if (len > 0 && body.charCodeAt(len - 1) === 61 /* '=' */) {\n padding++;\n\n if (len > 1 && body.charCodeAt(len - 2) === 61 /* '=' */) {\n padding++;\n }\n }\n\n return Math.floor(((len - padding) * 3) / 4);\n};\n\nconst estimatePercentDecodedBase64BufferAllocation = (body) => {\n // Ordinary Base64 needs only its length and trailing padding.\n if (body.indexOf('%') === -1) {\n return estimateBase64BufferAllocation(body);\n }\n\n let length = 0;\n let previous = 0;\n let last = 0;\n\n for (let i = 0, len = body.length; i < len; i++) {\n let code = body.charCodeAt(i);\n if (code === 37 /* '%' */ && isPercentEncodedByte(body, i, len)) {\n code = hexValue(body.charCodeAt(i + 1)) * 16 + hexValue(body.charCodeAt(i + 2));\n i += 2;\n }\n length++;\n previous = last;\n last = code;\n }\n\n const padding = last === 61 ? (previous === 61 ? 2 : 1) : 0;\n return Math.floor(((length - padding) * 3) / 4);\n};\n\nconst estimatePercentDecodedBase64Bytes = (body) => {\n const len = body.length;\n let significant = 0;\n let padding = 0;\n let invalid = false;\n\n for (let i = 0; i < len; i++) {\n let code = body.charCodeAt(i);\n\n if (code === 37 /* '%' */ && isPercentEncodedByte(body, i, len)) {\n code = hexValue(body.charCodeAt(i + 1)) * 16 + hexValue(body.charCodeAt(i + 2));\n i += 2;\n }\n\n if (isBase64Whitespace(code)) {\n continue;\n }\n\n if (code === 61 /* '=' */) {\n padding++;\n continue;\n }\n\n if (!isBase64Char(code) || padding > 0) {\n invalid = true;\n continue;\n }\n\n significant++;\n }\n\n // Fetch rejects malformed forgiving-base64 input. Returning the raw-size\n // allocation bound keeps that invalid input from becoming a pre-check bypass.\n if (\n invalid ||\n padding > 2 ||\n (padding > 0 && (significant + padding) % 4 !== 0) ||\n significant % 4 === 1\n ) {\n return estimateBase64BufferAllocation(body);\n }\n\n return base64Bytes(significant);\n};\n\nconst estimateDataURLBytes = (url, estimateBase64, base64Pattern) => {\n if (!url || typeof url !== 'string') return 0;\n if (!/^data:/i.test(url)) return 0;\n\n const comma = url.indexOf(',');\n if (comma < 0) return 0;\n\n const meta = url.slice(5, comma);\n const body = url.slice(comma + 1);\n const isBase64 = base64Pattern.test(meta);\n\n if (isBase64) {\n return estimateBase64(body);\n }\n\n // Compute UTF-8 byte length directly from UTF-16 code units without allocating\n // a byte buffer (TextEncoder.encode would defeat the DoS guard on large bodies).\n // Valid %XX triplets count as one decoded byte; this matches the bytes that\n // decodeURIComponent(body) would produce before Buffer re-encodes the string.\n let bytes = 0;\n for (let i = 0, len = body.length; i < len; i++) {\n const c = body.charCodeAt(i);\n if (c === 37 /* '%' */ && isPercentEncodedByte(body, i, len)) {\n bytes += 1;\n i += 2;\n } else if (c < 0x80) {\n bytes += 1;\n } else if (c < 0x800) {\n bytes += 2;\n } else if (c >= 0xd800 && c <= 0xdbff && i + 1 < len) {\n const next = body.charCodeAt(i + 1);\n if (next >= 0xdc00 && next <= 0xdfff) {\n bytes += 4;\n i++;\n } else {\n bytes += 3;\n }\n } else {\n bytes += 3;\n }\n }\n return bytes;\n};\n\n/**\n * Estimate the percent-decoded payload size used by Fetch data: URLs.\n *\n * @param {string} url\n * @returns {number}\n */\nexport default function estimateDataURLDecodedBytes(url) {\n // Fetch removes URL fragments before processing a data: URL.\n const fragmentIndex = typeof url === 'string' ? url.indexOf('#') : -1;\n\n return estimateDataURLBytes(\n fragmentIndex === -1 ? url : url.slice(0, fragmentIndex),\n estimatePercentDecodedBase64Bytes,\n /; *base64[\\t\\n\\f\\r ]*$/i\n );\n}\n\n/**\n * Estimate the Buffer backing allocation used after Node's percent-decoding step.\n *\n * @param {string} url\n * @returns {number}\n */\nexport function estimateDataURLBufferAllocation(url) {\n // Match fromDataURI's case-insensitive protocol and encoding suffix.\n return estimateDataURLBytes(url, estimatePercentDecodedBase64BufferAllocation, /;base64$/i);\n}\n","export const VERSION = \"1.21.0\";","import platform from '../platform/index.js';\nimport utils from '../utils.js';\nimport AxiosError from '../core/AxiosError.js';\nimport composeSignals from '../helpers/composeSignals.js';\nimport { trackStream } from '../helpers/trackStream.js';\nimport createMultipartBody from '../core/createMultipartBody.js';\nimport AxiosHeaders from '../core/AxiosHeaders.js';\nimport {\n progressEventReducer,\n progressEventDecorator,\n asyncDecorator,\n} from '../helpers/progressEventReducer.js';\nimport resolveConfig from '../helpers/resolveConfig.js';\nimport settle from '../core/settle.js';\nimport estimateDataURLDecodedBytes from '../helpers/estimateDataURLDecodedBytes.js';\nimport { VERSION } from '../env/data.js';\nimport { toByteStringHeaderObject } from '../helpers/sanitizeHeaderValue.js';\n\nconst DEFAULT_CHUNK_SIZE = 64 * 1024;\n\nconst DEFAULT_REQUEST_OPTIONS = {\n cache: 'default',\n redirect: 'follow',\n referrer: 'about:client',\n referrerPolicy: '',\n mode: 'cors',\n integrity: '',\n keepalive: false,\n priority: 'auto',\n window: null,\n};\n\nconst { isFunction } = utils;\n\n/**\n * Encode a UTF-8 string to a Latin-1 byte string for use with btoa().\n * This is a modern replacement for the deprecated unescape(encodeURIComponent(str)) pattern.\n *\n * @param {string} str The string to encode\n *\n * @returns {string} UTF-8 bytes as a Latin-1 string\n */\nconst encodeUTF8 = (str) =>\n encodeURIComponent(str).replace(/%([0-9A-F]{2})/gi, (_, hex) =>\n String.fromCharCode(parseInt(hex, 16))\n );\n\n// Node's WHATWG URL parser returns `username` and `password` percent-encoded.\n// Decode before composing the `auth` option so credentials such as\n// `my%40email.com:pass` are sent as `my@email.com:pass`. Falls back to the\n// original value for malformed input so a bad encoding never throws.\nconst decodeURIComponentSafe = (value) => {\n if (!utils.isString(value)) {\n return value;\n }\n\n try {\n return decodeURIComponent(value);\n } catch (error) {\n return value;\n }\n};\n\nconst test = (fn, ...args) => {\n try {\n return !!fn(...args);\n } catch (e) {\n return false;\n }\n};\n\nconst maybeWithAuthCredentials = (url) => {\n const protocolIndex = url.indexOf('://');\n let urlToCheck = url;\n if (protocolIndex !== -1) {\n urlToCheck = urlToCheck.slice(protocolIndex + 3);\n }\n return urlToCheck.includes('@') || urlToCheck.includes(':');\n};\n\nconst factory = (env) => {\n const globalObject =\n utils.global !== undefined && utils.global !== null ? utils.global : globalThis;\n const { ReadableStream, TextEncoder } = globalObject;\n\n env = utils.merge.call(\n {\n skipUndefined: true,\n },\n {\n Request: globalObject.Request,\n Response: globalObject.Response,\n Blob: globalObject.Blob,\n },\n env\n );\n\n const envFetch = utils.hasOwnProp(env, 'fetch') ? env.fetch : undefined;\n const { Request, Response, Blob } = env;\n const isFetchSupported = envFetch ? isFunction(envFetch) : typeof fetch === 'function';\n const isRequestSupported = isFunction(Request);\n const isResponseSupported = isFunction(Response);\n\n if (!isFetchSupported) {\n return false;\n }\n\n const isReadableStreamSupported = isFetchSupported && isFunction(ReadableStream);\n\n const encodeText =\n isFetchSupported &&\n (typeof TextEncoder === 'function'\n ? (\n (encoder) => (str) =>\n encoder.encode(str)\n )(new TextEncoder())\n : async (str) => new Uint8Array(await new Request(str).arrayBuffer()));\n\n const supportsRequestStream =\n isRequestSupported &&\n isReadableStreamSupported &&\n test(() => {\n let duplexAccessed = false;\n\n const request = new Request(platform.origin, {\n body: new ReadableStream(),\n method: 'POST',\n get duplex() {\n duplexAccessed = true;\n return 'half';\n },\n });\n\n const hasContentType = request.headers.has('Content-Type');\n\n if (request.body != null) {\n request.body.cancel();\n }\n\n return duplexAccessed && !hasContentType;\n });\n\n const supportsResponseStream =\n isResponseSupported &&\n isReadableStreamSupported &&\n test(() => utils.isReadableStream(new Response('').body));\n\n // Some runtimes reject every explicit cache mode. Use own defaults for both\n // probes so unrelated polluted options cannot affect cache-mode detection.\n const requestDefaults = Object.assign(Object.create(null), DEFAULT_REQUEST_OPTIONS);\n\n if (isRequestSupported && !test(() => new Request(platform.origin, requestDefaults))) {\n delete requestDefaults.cache;\n\n // Only omit cache when that makes Request construction succeed. Otherwise\n // retain the explicit default that protects supporting runtimes from pollution.\n if (!test(() => new Request(platform.origin, requestDefaults))) {\n requestDefaults.cache = DEFAULT_REQUEST_OPTIONS.cache;\n }\n }\n\n const resolvers = {\n stream: supportsResponseStream && ((res) => res.body),\n };\n\n isFetchSupported &&\n (() => {\n ['text', 'arrayBuffer', 'blob', 'formData', 'stream'].forEach((type) => {\n !resolvers[type] &&\n (resolvers[type] = (res, config) => {\n let method = res && res[type];\n\n if (method) {\n return method.call(res);\n }\n\n throw new AxiosError(\n `Response type '${type}' is not supported`,\n AxiosError.ERR_NOT_SUPPORT,\n config\n );\n });\n });\n })();\n\n const getBodyLength = async (body) => {\n if (body == null) {\n return 0;\n }\n\n if (utils.isBlob(body)) {\n return body.size;\n }\n\n if (utils.isArrayBufferView(body) || utils.isArrayBuffer(body)) {\n return body.byteLength;\n }\n\n if (utils.isURLSearchParams(body)) {\n body = body + '';\n }\n\n if (utils.isString(body)) {\n return (await encodeText(body)).byteLength;\n }\n };\n\n const resolveBodyLength = async (headers, body) => {\n const length = utils.toFiniteNumber(headers.getContentLength());\n\n return length == null ? getBodyLength(body) : length;\n };\n\n return async (config) => {\n let {\n url,\n method,\n data,\n signal,\n cancelToken,\n timeout,\n onDownloadProgress,\n onUploadProgress,\n responseType,\n headers,\n withCredentials = 'same-origin',\n fetchOptions,\n maxContentLength,\n maxBodyLength,\n maxRedirects,\n } = resolveConfig(config);\n\n const hasMaxContentLength = utils.isNumber(maxContentLength) && maxContentLength > -1;\n const hasMaxBodyLength = utils.isNumber(maxBodyLength) && maxBodyLength > -1;\n const own = (key) => (utils.hasOwnProp(config, key) ? config[key] : undefined);\n\n let _fetch = envFetch || fetch;\n\n responseType = responseType ? (responseType + '').toLowerCase() : 'text';\n\n let composedSignal = composeSignals(\n [signal, cancelToken && cancelToken.toAbortSignal()],\n timeout\n );\n\n let request = null;\n\n const unsubscribe =\n composedSignal &&\n composedSignal.unsubscribe &&\n (() => {\n composedSignal.unsubscribe();\n });\n\n let requestContentLength;\n\n // AxiosErrors we raise while request or response bodies are being streamed. Captured\n // by identity so the catch block can surface it directly, regardless of\n // how the runtime wraps the resulting fetch rejection (undici exposes it\n // as `err.cause`; some browsers drop the original error entirely).\n let pendingBodyError = null;\n let pendingResponseError = null;\n\n const maxBodyLengthError = () =>\n new AxiosError(\n 'Request body larger than maxBodyLength limit',\n AxiosError.ERR_BAD_REQUEST,\n config,\n request\n );\n\n try {\n // HTTP basic authentication\n let auth = undefined;\n const configAuth = own('auth');\n\n if (configAuth) {\n const username = utils.getSafeProp(configAuth, 'username') || '';\n const password = utils.getSafeProp(configAuth, 'password') || '';\n auth = {\n username,\n password,\n };\n }\n\n let parsedURL;\n if (maybeWithAuthCredentials(url)) {\n parsedURL = new URL(url, platform.origin);\n\n if (!auth && (parsedURL.username || parsedURL.password)) {\n const urlUsername = decodeURIComponentSafe(parsedURL.username);\n const urlPassword = decodeURIComponentSafe(parsedURL.password);\n auth = {\n username: urlUsername,\n password: urlPassword,\n };\n }\n\n if (parsedURL.username || parsedURL.password) {\n parsedURL.username = '';\n parsedURL.password = '';\n url = parsedURL.href;\n }\n }\n\n if (auth) {\n headers.delete('authorization');\n headers.set(\n 'Authorization',\n 'Basic ' + btoa(encodeUTF8((auth.username || '') + ':' + (auth.password || '')))\n );\n }\n\n // Enforce maxContentLength for data: URLs up-front so we never materialize\n // an oversized payload. The HTTP adapter applies the same check (see http.js\n // \"if (protocol === 'data:')\" branch).\n if (hasMaxContentLength && parsedURL && parsedURL.protocol === 'data:') {\n const estimated = estimateDataURLDecodedBytes(parsedURL.href);\n if (estimated > maxContentLength) {\n throw new AxiosError(\n 'maxContentLength size of ' + maxContentLength + ' exceeded',\n AxiosError.ERR_BAD_RESPONSE,\n config,\n request\n );\n }\n }\n\n const formContentType =\n utils.isSpecCompliantForm(data) && AxiosHeaders.from(own('headers')).getContentType();\n let formBoundary;\n if (\n utils.isString(formContentType) &&\n /^multipart\\/form-data(?:\\s*;|$)/i.test(formContentType.trim())\n ) {\n const parameters = AxiosHeaders.parseParameters(formContentType);\n if (utils.hasOwnProp(parameters, 'boundary')) formBoundary = parameters.boundary;\n }\n\n if (\n utils.isSpecCompliantForm(data) &&\n method !== 'get' &&\n method !== 'head' &&\n (hasMaxBodyLength ||\n (onUploadProgress && supportsRequestStream) ||\n formBoundary !== undefined)\n ) {\n data = createMultipartBody(\n data,\n Blob,\n hasMaxBodyLength ? maxBodyLength : Infinity,\n maxBodyLengthError,\n formBoundary\n );\n // Blob.type lowercases its value, including a case-sensitive boundary.\n // Retain the caller's header when an explicit boundary was serialized.\n headers.setContentType(formBoundary === undefined ? data.type : formContentType);\n requestContentLength = data.size;\n }\n\n // Enforce maxBodyLength against known-size bodies before dispatch using\n // the body's *actual* size — never a caller-declared Content-Length,\n // which could under-report to slip an oversized body past the check.\n // Unknown-size streams return undefined here and are counted per-chunk\n // below as fetch consumes them.\n if (hasMaxBodyLength && method !== 'get' && method !== 'head') {\n const outboundLength = await getBodyLength(data);\n if (typeof outboundLength === 'number' && isFinite(outboundLength)) {\n requestContentLength = outboundLength;\n if (outboundLength > maxBodyLength) {\n throw maxBodyLengthError();\n }\n }\n }\n\n // A streamed body under maxBodyLength must be counted as fetch consumes\n // it; its size is never trusted from a caller-declared Content-Length.\n const mustEnforceStreamBody =\n hasMaxBodyLength && (utils.isReadableStream(data) || utils.isStream(data));\n\n const trackRequestStream = (stream, onProgress, flush) =>\n trackStream(\n stream,\n DEFAULT_CHUNK_SIZE,\n (loadedBytes) => {\n if (hasMaxBodyLength && loadedBytes > maxBodyLength) {\n throw (pendingBodyError = maxBodyLengthError());\n }\n onProgress && onProgress(loadedBytes);\n },\n flush\n );\n\n if (\n supportsRequestStream &&\n method !== 'get' &&\n method !== 'head' &&\n (onUploadProgress || mustEnforceStreamBody)\n ) {\n requestContentLength =\n requestContentLength == null\n ? await resolveBodyLength(headers, data)\n : requestContentLength;\n\n // A declared length of 0 is only trusted to skip the wrap when we are\n // not enforcing a stream limit (which must not rely on that header).\n if (requestContentLength !== 0 || mustEnforceStreamBody) {\n let _request = new Request(url, {\n method: 'POST',\n body: data,\n duplex: 'half',\n });\n\n let contentTypeHeader;\n\n if (\n utils.isFormData(data) &&\n (contentTypeHeader = _request.headers.get('content-type'))\n ) {\n headers.setContentType(contentTypeHeader);\n }\n\n if (_request.body) {\n const [onProgress, flush] =\n (onUploadProgress &&\n progressEventDecorator(\n requestContentLength,\n progressEventReducer(asyncDecorator(onUploadProgress))\n )) ||\n [];\n\n data = trackRequestStream(_request.body, onProgress, flush);\n }\n }\n } else if (\n mustEnforceStreamBody &&\n !isRequestSupported &&\n isReadableStreamSupported &&\n method !== 'get' &&\n method !== 'head'\n ) {\n data = trackRequestStream(data);\n } else if (\n mustEnforceStreamBody &&\n isRequestSupported &&\n !supportsRequestStream &&\n method !== 'get' &&\n method !== 'head'\n ) {\n throw new AxiosError(\n 'Stream request bodies are not supported by the current fetch implementation',\n AxiosError.ERR_NOT_SUPPORT,\n config,\n request\n );\n }\n\n if (!utils.isString(withCredentials)) {\n withCredentials = withCredentials ? 'include' : 'omit';\n }\n\n // Cloudflare Workers throws when credentials are defined\n // see https://github.com/cloudflare/workerd/issues/902\n const isCredentialsSupported = isRequestSupported && 'credentials' in Request.prototype;\n\n // If data is FormData and Content-Type is multipart/form-data without boundary,\n // delete it so fetch can set it correctly with the boundary\n if (utils.isFormData(data)) {\n const contentType = headers.getContentType();\n if (\n contentType &&\n /^multipart\\/form-data/i.test(contentType) &&\n !/boundary=/i.test(contentType)\n ) {\n headers.delete('content-type');\n }\n }\n\n // Set User-Agent header if not already set (fetch defaults to 'node' in Node.js)\n headers.set('User-Agent', 'axios/' + VERSION, false);\n\n const safeFetchOptions =\n fetchOptions == null ? fetchOptions : Object.assign(Object.create(null), fetchOptions);\n\n if (safeFetchOptions) {\n // These options are owned by Axios and are already reflected in the\n // resolved Request passed to fetch.\n delete safeFetchOptions.body;\n delete safeFetchOptions.headers;\n delete safeFetchOptions.method;\n delete safeFetchOptions.signal;\n delete safeFetchOptions.duplex;\n delete safeFetchOptions.credentials;\n }\n\n const resolvedOptions = Object.assign(Object.create(null), safeFetchOptions, {\n signal: composedSignal,\n method: method.toUpperCase(),\n headers: toByteStringHeaderObject(headers.normalize()),\n body: data,\n duplex: 'half',\n credentials: isCredentialsSupported ? withCredentials : undefined,\n });\n\n if (isRequestSupported) {\n utils.forEach(requestDefaults, (value, key) => {\n if (resolvedOptions[key] === undefined) {\n resolvedOptions[key] = value;\n }\n });\n\n if (resolvedOptions.signal === undefined) {\n resolvedOptions.signal = null;\n }\n\n if (resolvedOptions.body === undefined) {\n resolvedOptions.body = null;\n }\n }\n\n if (maxRedirects === 0) {\n resolvedOptions.redirect = 'manual';\n\n if (safeFetchOptions) {\n safeFetchOptions.redirect = 'manual';\n }\n }\n\n request = isRequestSupported && new Request(url, resolvedOptions);\n\n let response = await (isRequestSupported\n ? _fetch(request, safeFetchOptions)\n : _fetch(url, resolvedOptions));\n\n const responseHeaders = AxiosHeaders.from(response.headers);\n\n // Cheap pre-check: if the server honestly declares a content-length that\n // already exceeds the cap, reject before we start streaming.\n if (hasMaxContentLength) {\n const declaredLength = utils.toFiniteNumber(responseHeaders.getContentLength());\n if (declaredLength != null && declaredLength > maxContentLength) {\n throw new AxiosError(\n 'maxContentLength size of ' + maxContentLength + ' exceeded',\n AxiosError.ERR_BAD_RESPONSE,\n config,\n request\n );\n }\n }\n\n const isStreamResponse =\n supportsResponseStream && (responseType === 'stream' || responseType === 'response');\n\n if (\n supportsResponseStream &&\n response.body &&\n (onDownloadProgress || hasMaxContentLength || (isStreamResponse && unsubscribe))\n ) {\n const options = {};\n\n ['status', 'statusText', 'headers'].forEach((prop) => {\n options[prop] = response[prop];\n });\n\n const responseContentLength = utils.toFiniteNumber(responseHeaders.getContentLength());\n\n const [onProgress, flush] =\n (onDownloadProgress &&\n progressEventDecorator(\n responseContentLength,\n progressEventReducer(asyncDecorator(onDownloadProgress), true)\n )) ||\n [];\n\n let bytesRead = 0;\n const onChunkProgress = (loadedBytes) => {\n if (hasMaxContentLength) {\n bytesRead = loadedBytes;\n if (bytesRead > maxContentLength) {\n throw (pendingResponseError = new AxiosError(\n 'maxContentLength size of ' + maxContentLength + ' exceeded',\n AxiosError.ERR_BAD_RESPONSE,\n config,\n request\n ));\n }\n }\n onProgress && onProgress(loadedBytes);\n };\n\n response = new Response(\n trackStream(response.body, DEFAULT_CHUNK_SIZE, onChunkProgress, () => {\n flush && flush();\n unsubscribe && unsubscribe();\n }),\n options\n );\n }\n\n responseType = responseType || 'text';\n\n let responseData = await resolvers[utils.findKey(resolvers, responseType) || 'text'](\n response,\n config\n );\n\n // Fallback enforcement for environments without ReadableStream support\n // (legacy runtimes). Detect materialized size from typed output; skip\n // streams/Response passthrough since the user will read those themselves.\n if (hasMaxContentLength && !supportsResponseStream && !isStreamResponse) {\n let materializedSize;\n if (responseData != null) {\n if (typeof responseData.byteLength === 'number') {\n materializedSize = responseData.byteLength;\n } else if (typeof responseData.size === 'number') {\n materializedSize = responseData.size;\n } else if (typeof responseData === 'string') {\n materializedSize =\n typeof TextEncoder === 'function'\n ? new TextEncoder().encode(responseData).byteLength\n : responseData.length;\n }\n }\n if (typeof materializedSize === 'number' && materializedSize > maxContentLength) {\n throw new AxiosError(\n 'maxContentLength size of ' + maxContentLength + ' exceeded',\n AxiosError.ERR_BAD_RESPONSE,\n config,\n request\n );\n }\n }\n\n !isStreamResponse && unsubscribe && unsubscribe();\n\n return await new Promise((resolve, reject) => {\n settle(resolve, reject, {\n data: responseData,\n headers: AxiosHeaders.from(response.headers),\n status: response.status,\n statusText: response.statusText,\n config,\n request,\n });\n });\n } catch (err) {\n unsubscribe && unsubscribe();\n\n // Safari can surface fetch aborts as a DOMException-like object whose\n // branded getters throw. Prefer our composed signal reason before reading\n // the caught error, preserving timeout vs cancellation semantics.\n if (composedSignal && composedSignal.aborted && composedSignal.reason instanceof AxiosError) {\n const canceledError = composedSignal.reason;\n canceledError.config = config;\n request && (canceledError.request = request);\n if (err !== canceledError) {\n // Non-enumerable to match native Error `cause` semantics so loggers\n // don't recurse into circular fetch internals (see #7205).\n Object.defineProperty(canceledError, 'cause', {\n __proto__: null,\n value: err,\n writable: true,\n enumerable: false,\n configurable: true,\n });\n }\n throw canceledError;\n }\n\n // Surface a maxBodyLength violation we raised while the request body was\n // being streamed. Keeping the original error (rather than reading\n // `err.cause.isAxiosError`) keeps the error deterministic across runtimes\n // and avoids both prototype-pollution reads and mis-attributing a foreign\n // AxiosError that merely happened to land in `err.cause`.\n if (pendingBodyError) {\n request && !pendingBodyError.request && (pendingBodyError.request = request);\n throw pendingBodyError;\n }\n\n if (pendingResponseError) {\n throw pendingResponseError;\n }\n\n // Re-throw AxiosErrors we raised synchronously (data: URL / content-length\n // pre-checks, response size enforcement) without re-wrapping them.\n if (err instanceof AxiosError) {\n request && !err.request && (err.request = request);\n throw err;\n }\n\n if (err && err.name === 'TypeError' && /Load failed|fetch/i.test(err.message)) {\n const networkError = new AxiosError(\n 'Network Error',\n AxiosError.ERR_NETWORK,\n config,\n request,\n err && err.response\n );\n // Non-enumerable to match native Error `cause` semantics so loggers\n // don't recurse into circular fetch internals (see #7205).\n Object.defineProperty(networkError, 'cause', {\n __proto__: null,\n value: err.cause || err,\n writable: true,\n enumerable: false,\n configurable: true,\n });\n throw networkError;\n }\n\n throw AxiosError.from(err, err && err.code, config, request, err && err.response);\n }\n };\n};\n\nconst seedCache = new Map();\n\nexport const getFetch = (config) => {\n const env = Object.create(null);\n const configuredEnv = config && utils.hasOwnProp(config, 'env') && config.env;\n ['fetch', 'Request', 'Response', 'Blob'].forEach((key) => {\n if (configuredEnv && utils.hasOwnProp(configuredEnv, key)) {\n env[key] = configuredEnv[key];\n }\n });\n const { fetch, Request, Response, Blob } = env;\n const seeds = [Request, Response, fetch, Blob];\n\n let len = seeds.length,\n i = len,\n seed,\n target,\n map = seedCache;\n\n while (i--) {\n seed = seeds[i];\n target = map.get(seed);\n\n target === undefined && map.set(seed, (target = i ? new Map() : factory(env)));\n\n map = target;\n }\n\n return target;\n};\n\nconst adapter = getFetch();\n\nexport default adapter;\n","import utils from '../utils.js';\nimport httpAdapter from './http.js';\nimport xhrAdapter from './xhr.js';\nimport * as fetchAdapter from './fetch.js';\nimport AxiosError from '../core/AxiosError.js';\n\n/**\n * Known adapters mapping.\n * Provides environment-specific adapters for Axios:\n * - `http` for Node.js\n * - `xhr` for browsers\n * - `fetch` for fetch API-based requests\n *\n * @type {Object<string, Function|Object>}\n */\nconst knownAdapters = {\n http: httpAdapter,\n xhr: xhrAdapter,\n fetch: {\n get: fetchAdapter.getFetch,\n },\n};\n\n// Assign adapter names for easier debugging and identification\nutils.forEach(knownAdapters, (fn, value) => {\n if (fn) {\n try {\n // Null-proto descriptors so a polluted Object.prototype.get cannot turn\n // these data descriptors into accessor descriptors on the way in.\n Object.defineProperty(fn, 'name', { __proto__: null, value });\n } catch (e) {\n // eslint-disable-next-line no-empty\n }\n Object.defineProperty(fn, 'adapterName', { __proto__: null, value });\n }\n});\n\n/**\n * Render a rejection reason string for unknown or unsupported adapters\n *\n * @param {string} reason\n * @returns {string}\n */\nconst renderReason = (reason) => `- ${reason}`;\n\n/**\n * Check if the adapter is resolved (function, null, or false)\n *\n * @param {Function|null|false} adapter\n * @returns {boolean}\n */\nconst isResolvedHandle = (adapter) =>\n utils.isFunction(adapter) || adapter === null || adapter === false;\n\n/**\n * Get the first suitable adapter from the provided list.\n * Tries each adapter in order until a supported one is found.\n * Throws an AxiosError if no adapter is suitable.\n *\n * @param {Array<string|Function>|string|Function} adapters - Adapter(s) by name or function.\n * @param {Object} config - Axios request configuration\n * @throws {AxiosError} If no suitable adapter is available\n * @returns {Function} The resolved adapter function\n */\nfunction getAdapter(adapters, config) {\n adapters = utils.isArray(adapters) ? adapters : [adapters];\n\n const { length } = adapters;\n let nameOrAdapter;\n let adapter;\n\n const rejectedReasons = {};\n\n for (let i = 0; i < length; i++) {\n nameOrAdapter = adapters[i];\n let id;\n\n adapter = nameOrAdapter;\n\n if (!isResolvedHandle(nameOrAdapter)) {\n adapter = knownAdapters[(id = String(nameOrAdapter)).toLowerCase()];\n\n if (adapter === undefined) {\n throw new AxiosError(`Unknown adapter '${id}'`);\n }\n }\n\n if (adapter && (utils.isFunction(adapter) || (adapter = adapter.get(config)))) {\n break;\n }\n\n rejectedReasons[id || '#' + i] = adapter;\n }\n\n if (!adapter) {\n const reasons = Object.entries(rejectedReasons).map(\n ([id, state]) =>\n `adapter ${id} ` +\n (state === false ? 'is not supported by the environment' : 'is not available in the build')\n );\n\n let s = length\n ? reasons.length > 1\n ? 'since :\\n' + reasons.map(renderReason).join('\\n')\n : ' ' + renderReason(reasons[0])\n : 'as no adapter specified';\n\n throw new AxiosError(\n `There is no suitable adapter to dispatch the request ` + s,\n AxiosError.ERR_NOT_SUPPORT\n );\n }\n\n return adapter;\n}\n\n/**\n * Exports Axios adapters and utility to resolve an adapter\n */\nexport default {\n /**\n * Resolve an adapter from a list of adapter names or functions.\n * @type {Function}\n */\n getAdapter,\n\n /**\n * Exposes all known adapters\n * @type {Object<string, Function|Object>}\n */\n adapters: knownAdapters,\n};\n","'use strict';\n\nimport transformData from './transformData.js';\nimport isCancel from '../cancel/isCancel.js';\nimport defaults from '../defaults/index.js';\nimport CanceledError from '../cancel/CanceledError.js';\nimport AxiosHeaders from '../core/AxiosHeaders.js';\nimport adapters from '../adapters/adapters.js';\nimport utils from '../utils.js';\n\n/**\n * Throws a `CanceledError` if cancellation has been requested.\n *\n * @param {Object} config The config that is to be used for the request\n *\n * @returns {void}\n */\nfunction throwIfCancellationRequested(config) {\n if (config.cancelToken) {\n config.cancelToken.throwIfRequested();\n }\n\n if (config.signal && config.signal.aborted) {\n throw new CanceledError(null, config);\n }\n}\n\n/**\n * Milliseconds elapsed since `start`, floored at zero.\n *\n * Wall-clock, to match the rest of the codebase (speedometer, throttle,\n * AxiosTransformStream). A backwards clock adjustment mid-request would\n * otherwise produce a negative duration, so the result is clamped.\n *\n * @param {number} start Timestamp from `Date.now()`\n *\n * @returns {number} Non-negative elapsed milliseconds\n */\nfunction elapsedSince(start) {\n return Math.max(0, Date.now() - start);\n}\n\n/**\n * Dispatch a request to the server using the configured adapter.\n *\n * @param {object} config The config that is to be used for the request\n *\n * @returns {Promise} The Promise to be fulfilled\n */\nexport default function dispatchRequest(_config) {\n // Interceptors may replace the merged config with an ordinary object. Flatten\n // it at the dispatch boundary so shared prototype members cannot become\n // request behavior, while preserving intentional template/class members.\n const config = utils.toSafeFlatObject(_config);\n\n throwIfCancellationRequested(config);\n\n config.headers = AxiosHeaders.from(utils.getSafeProp(config, 'headers'));\n\n // Transform request data\n config.data = transformData.call(config, config.transformRequest);\n\n if (['post', 'put', 'patch'].indexOf(config.method) !== -1) {\n config.headers.setContentType('application/x-www-form-urlencoded', false);\n }\n\n const adapter = adapters.getAdapter(config.adapter || defaults.adapter, config);\n\n const start = Date.now();\n\n return adapter(config).then(\n function onAdapterResolution(response) {\n throwIfCancellationRequested(config);\n\n response.duration = elapsedSince(start);\n\n // Expose the current response on config so that transformResponse can\n // attach it to any AxiosError it throws (e.g. on JSON parse failure).\n // We clean it up afterwards to avoid polluting the config object.\n config.response = response;\n try {\n response.data = transformData.call(config, config.transformResponse, response);\n } finally {\n delete config.response;\n }\n\n response.headers = AxiosHeaders.from(response.headers);\n\n return response;\n },\n function onAdapterRejection(reason) {\n if (!isCancel(reason)) {\n throwIfCancellationRequested(config);\n\n // Transform response data\n if (reason && reason.response) {\n reason.response.duration = elapsedSince(start);\n config.response = reason.response;\n try {\n reason.response.data = transformData.call(\n config,\n config.transformResponse,\n reason.response\n );\n } finally {\n delete config.response;\n }\n reason.response.headers = AxiosHeaders.from(reason.response.headers);\n }\n }\n\n return Promise.reject(reason);\n }\n );\n}\n","'use strict';\n\nimport { VERSION } from '../env/data.js';\nimport AxiosError from '../core/AxiosError.js';\n\nconst validators = {};\n\n// eslint-disable-next-line func-names\n['object', 'boolean', 'number', 'function', 'string', 'symbol'].forEach((type, i) => {\n validators[type] = function validator(thing) {\n return typeof thing === type || 'a' + (i < 1 ? 'n ' : ' ') + type;\n };\n});\n\nconst deprecatedWarnings = {};\n\n/**\n * Transitional option validator\n *\n * @param {function|boolean?} validator - set to false if the transitional option has been removed\n * @param {string?} version - deprecated version / removed since version\n * @param {string?} message - some message with additional info\n *\n * @returns {function}\n */\nvalidators.transitional = function transitional(validator, version, message) {\n function formatMessage(opt, desc) {\n return (\n '[Axios v' +\n VERSION +\n \"] Transitional option '\" +\n opt +\n \"'\" +\n desc +\n (message ? '. ' + message : '')\n );\n }\n\n // eslint-disable-next-line func-names\n return (value, opt, opts) => {\n if (validator === false) {\n throw new AxiosError(\n formatMessage(opt, ' has been removed' + (version ? ' in ' + version : '')),\n AxiosError.ERR_DEPRECATED\n );\n }\n\n if (version && !deprecatedWarnings[opt]) {\n deprecatedWarnings[opt] = true;\n // eslint-disable-next-line no-console\n console.warn(\n formatMessage(\n opt,\n ' has been deprecated since v' + version + ' and will be removed in the near future'\n )\n );\n }\n\n return validator ? validator(value, opt, opts) : true;\n };\n};\n\nvalidators.spelling = function spelling(correctSpelling) {\n return (value, opt) => {\n // eslint-disable-next-line no-console\n console.warn(`${opt} is likely a misspelling of ${correctSpelling}`);\n return true;\n };\n};\n\n/**\n * Assert object's properties type\n *\n * @param {object} options\n * @param {object} schema\n * @param {boolean?} allowUnknown\n *\n * @returns {object}\n */\n\nfunction assertOptions(options, schema, allowUnknown) {\n if (typeof options !== 'object' || options === null) {\n throw new AxiosError('options must be an object', AxiosError.ERR_BAD_OPTION_VALUE);\n }\n const keys = Object.keys(options);\n let i = keys.length;\n while (i-- > 0) {\n const opt = keys[i];\n // Use hasOwnProperty so a polluted Object.prototype.<opt> cannot supply\n // a non-function validator and cause a TypeError.\n const validator = Object.prototype.hasOwnProperty.call(schema, opt) ? schema[opt] : undefined;\n if (validator) {\n const value = options[opt];\n const result = value === undefined || validator(value, opt, options);\n if (result !== true) {\n throw new AxiosError(\n 'option ' + opt + ' must be ' + result,\n AxiosError.ERR_BAD_OPTION_VALUE\n );\n }\n continue;\n }\n if (allowUnknown !== true) {\n throw new AxiosError('Unknown option ' + opt, AxiosError.ERR_BAD_OPTION);\n }\n }\n}\n\nexport default {\n assertOptions,\n validators,\n};\n","'use strict';\n\nimport utils from '../utils.js';\nimport buildURL from '../helpers/buildURL.js';\nimport InterceptorManager from './InterceptorManager.js';\nimport dispatchRequest from './dispatchRequest.js';\nimport mergeConfig from './mergeConfig.js';\nimport buildFullPath from './buildFullPath.js';\nimport methodList from './methodList.js';\nimport validator from '../helpers/validator.js';\nimport AxiosHeaders from './AxiosHeaders.js';\nimport transitionalDefaults from '../defaults/transitional.js';\nimport { getCauseStackIndex } from './AxiosError.js';\n\nconst validators = validator.validators;\n\n// Recognize header maps without consuming objects intended as literal values.\n// AxiosHeaders from other builds share a brand and header-container interface,\n// but not constructor identity. A tag and toJSON alone can describe a literal.\nconst isHeadersBucket = (value) => {\n if (value == null || utils.isPlainObject(value) || value instanceof AxiosHeaders) {\n return true;\n }\n\n try {\n return (\n utils.isObject(value) &&\n utils.getSafeProp(value, Symbol.toStringTag) === 'AxiosHeaders' &&\n [\n 'toJSON',\n 'set',\n 'get',\n 'has',\n 'delete',\n 'clear',\n 'normalize',\n 'concat',\n 'toString',\n Symbol.iterator,\n ].every((method) => utils.isFunction(utils.getSafeProp(value, method)))\n );\n } catch (e) {\n // A failed optional brand probe must not prevent literal header serialization.\n return false;\n }\n};\n\n/**\n * Create a new instance of Axios\n *\n * @param {Object} instanceConfig The default config for the instance\n *\n * @return {Axios} A new instance of Axios\n */\nclass Axios {\n constructor(instanceConfig) {\n this.defaults = instanceConfig || {};\n this.interceptors = {\n request: new InterceptorManager(),\n response: new InterceptorManager(),\n };\n }\n\n /**\n * Dispatch a request\n *\n * @param {String|Object} configOrUrl The config specific for this request (merged with this.defaults)\n * @param {?Object} config\n *\n * @returns {Promise} The Promise to be fulfilled\n */\n async request(configOrUrl, config) {\n try {\n return await this._request(configOrUrl, config);\n } catch (err) {\n if (err instanceof Error) {\n try {\n let dummy = {};\n\n Error.captureStackTrace ? Error.captureStackTrace(dummy) : (dummy = new Error());\n\n const dummyStack = dummy.stack;\n let stack = '';\n\n // slice off the Error: ... line\n if (typeof dummyStack === 'string') {\n const firstNewlineIndex = dummyStack.indexOf('\\n');\n\n stack = firstNewlineIndex === -1 ? '' : dummyStack.slice(firstNewlineIndex + 1);\n }\n\n if (!err.stack) {\n err.stack = stack;\n } else if (stack) {\n // Match a common suffix after the 2 top frames when available,\n // otherwise compare the full reconstructed stack.\n const firstNewlineIndex = stack.indexOf('\\n');\n const secondNewlineIndex =\n firstNewlineIndex === -1 ? -1 : stack.indexOf('\\n', firstNewlineIndex + 1);\n const duplicateCheckSuffix =\n secondNewlineIndex === -1 ? stack : stack.slice(secondNewlineIndex + 1);\n\n // `AxiosError.from()` may have already inlined the wrapped error's\n // stack under a `Caused by:` marker. Keep the reconstructed caller\n // frames ahead of that marker so stack-only reporters do not read\n // them as part of the low-level cause.\n const currentStack = String(err.stack);\n const causeIndex = getCauseStackIndex(err, currentStack);\n const stackHead = causeIndex === -1 ? currentStack : currentStack.slice(0, causeIndex);\n const causeSection = causeIndex === -1 ? '' : currentStack.slice(causeIndex);\n\n if (!stackHead.endsWith(duplicateCheckSuffix)) {\n err.stack = stackHead + '\\n' + stack + causeSection;\n }\n }\n } catch (e) {\n // Ignore failures from custom stack hooks or un-writable stack properties.\n }\n }\n\n throw err;\n }\n }\n\n _request(configOrUrl, config) {\n /*eslint no-param-reassign:0*/\n // Allow for axios('example/url'[, config]) a la fetch API\n if (typeof configOrUrl === 'string') {\n config = config || {};\n config.url = configOrUrl;\n } else {\n config = configOrUrl || {};\n }\n\n config = mergeConfig(this.defaults, config);\n\n const { transitional, paramsSerializer, headers } = config;\n\n if (transitional !== undefined) {\n validator.assertOptions(\n transitional,\n {\n silentJSONParsing: validators.transitional(validators.boolean),\n forcedJSONParsing: validators.transitional(validators.boolean),\n clarifyTimeoutError: validators.transitional(validators.boolean),\n legacyInterceptorReqResOrdering: validators.transitional(validators.boolean),\n advertiseZstdAcceptEncoding: validators.transitional(validators.boolean),\n validateStatusUndefinedResolves: validators.transitional(validators.boolean),\n encodeBasicAuthUsername: validators.transitional(validators.boolean),\n },\n false\n );\n }\n\n if (paramsSerializer != null) {\n if (utils.isFunction(paramsSerializer)) {\n config.paramsSerializer = {\n serialize: paramsSerializer,\n };\n } else {\n validator.assertOptions(\n paramsSerializer,\n {\n encode: validators.function,\n serialize: validators.function,\n },\n true\n );\n }\n }\n\n // Set config.allowAbsoluteUrls\n if (config.allowAbsoluteUrls !== undefined) {\n // do nothing\n } else if (\n utils.hasOwnProp(this.defaults, 'allowAbsoluteUrls') &&\n this.defaults.allowAbsoluteUrls !== undefined\n ) {\n config.allowAbsoluteUrls = this.defaults.allowAbsoluteUrls;\n } else {\n config.allowAbsoluteUrls = true;\n }\n\n validator.assertOptions(\n config,\n {\n baseUrl: validators.spelling('baseURL'),\n withXsrfToken: validators.spelling('withXSRFToken'),\n },\n true\n );\n\n // Set config.method\n config.method = (\n utils.getSafeProp(config, 'method') ||\n utils.getSafeProp(this.defaults, 'method') ||\n 'get'\n ).toLowerCase();\n\n // Flatten header defaults without consuming literal method-named headers.\n const commonHeaders = utils.getSafeProp(headers, 'common');\n const methodHeaders = utils.getSafeProp(headers, config.method);\n const contextHeaders =\n headers &&\n utils.merge(\n isHeadersBucket(commonHeaders) ? commonHeaders : undefined,\n isHeadersBucket(methodHeaders) ? methodHeaders : undefined\n );\n\n headers &&\n utils.forEach(methodList.concat('common'), (method) => {\n if (isHeadersBucket(utils.getSafeProp(headers, method))) {\n delete headers[method];\n }\n });\n\n config.headers = AxiosHeaders.concat(contextHeaders, headers);\n\n // filter out skipped interceptors\n const requestInterceptorChain = [];\n let synchronousRequestInterceptors = true;\n this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {\n if (typeof interceptor.runWhen === 'function' && interceptor.runWhen(config) === false) {\n return;\n }\n\n synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous;\n\n const transitional = config.transitional || transitionalDefaults;\n const legacyInterceptorReqResOrdering =\n transitional && transitional.legacyInterceptorReqResOrdering;\n\n if (legacyInterceptorReqResOrdering) {\n requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected);\n } else {\n requestInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);\n }\n });\n\n const responseInterceptorChain = [];\n this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {\n responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);\n });\n\n let promise;\n let i = 0;\n let len;\n\n if (!synchronousRequestInterceptors) {\n const chain = [dispatchRequest.bind(this), undefined];\n chain.unshift(...requestInterceptorChain);\n chain.push(...responseInterceptorChain);\n len = chain.length;\n\n promise = Promise.resolve(config);\n\n while (i < len) {\n promise = promise.then(chain[i++], chain[i++]);\n }\n\n return promise;\n }\n\n len = requestInterceptorChain.length;\n\n let newConfig = config;\n\n while (i < len) {\n const onFulfilled = requestInterceptorChain[i++];\n const onRejected = requestInterceptorChain[i++];\n try {\n newConfig = onFulfilled ? onFulfilled(newConfig) : newConfig;\n } catch (error) {\n if (!onRejected) {\n promise = Promise.reject(error);\n break;\n }\n\n try {\n const rejectedResult = onRejected.call(this, error);\n\n if (utils.isThenable(rejectedResult)) {\n promise = Promise.resolve(rejectedResult).then(() =>\n dispatchRequest.call(this, newConfig)\n );\n }\n } catch (rejectedError) {\n promise = Promise.reject(rejectedError);\n }\n\n break;\n }\n }\n\n if (!promise) {\n try {\n promise = dispatchRequest.call(this, newConfig);\n } catch (error) {\n promise = Promise.reject(error);\n }\n }\n\n i = 0;\n len = responseInterceptorChain.length;\n\n while (i < len) {\n promise = promise.then(responseInterceptorChain[i++], responseInterceptorChain[i++]);\n }\n\n return promise;\n }\n\n getUri(config) {\n config = mergeConfig(this.defaults, config);\n const fullPath = buildFullPath(config.baseURL, config.url, config.allowAbsoluteUrls, config);\n return buildURL(fullPath, config.params, config.paramsSerializer);\n }\n}\n\n// Provide aliases for supported request methods\nutils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) {\n /*eslint func-names:0*/\n Axios.prototype[method] = async function (url, config) {\n return this.request(\n mergeConfig(config || {}, {\n method,\n url,\n data: config && utils.hasOwnProp(config, 'data') ? config.data : undefined,\n })\n );\n };\n});\n\nutils.forEach(['post', 'put', 'patch', 'query'], function forEachMethodWithData(method) {\n function generateHTTPMethod(isForm) {\n return async function httpMethod(url, data, config) {\n return this.request(\n mergeConfig(config || {}, {\n method,\n headers: isForm\n ? {\n 'Content-Type': 'multipart/form-data',\n }\n : {},\n url,\n data,\n })\n );\n };\n }\n\n Axios.prototype[method] = generateHTTPMethod();\n\n // QUERY is a safe/idempotent read method; multipart form bodies don't fit\n // its semantics, so no queryForm shorthand is generated.\n if (method !== 'query') {\n Axios.prototype[method + 'Form'] = generateHTTPMethod(true);\n }\n});\n\nexport default Axios;\n","'use strict';\n\nimport CanceledError from './CanceledError.js';\n\n/**\n * A `CancelToken` is an object that can be used to request cancellation of an operation.\n *\n * @param {Function} executor The executor function.\n *\n * @returns {CancelToken}\n */\nclass CancelToken {\n constructor(executor) {\n if (typeof executor !== 'function') {\n throw new TypeError('executor must be a function.');\n }\n\n let resolvePromise;\n\n this.promise = new Promise(function promiseExecutor(resolve) {\n resolvePromise = resolve;\n });\n\n const token = this;\n\n // eslint-disable-next-line func-names\n this.promise.then((cancel) => {\n if (!token._listeners) return;\n\n let i = token._listeners.length;\n\n while (i-- > 0) {\n token._listeners[i](cancel);\n }\n token._listeners = null;\n });\n\n // eslint-disable-next-line func-names\n this.promise.then = (onfulfilled) => {\n let _resolve;\n // eslint-disable-next-line func-names\n const promise = new Promise((resolve) => {\n token.subscribe(resolve);\n _resolve = resolve;\n }).then(onfulfilled);\n\n promise.cancel = function reject() {\n token.unsubscribe(_resolve);\n };\n\n return promise;\n };\n\n executor(function cancel(message, config, request) {\n if (token.reason) {\n // Cancellation has already been requested\n return;\n }\n\n token.reason = new CanceledError(message, config, request);\n resolvePromise(token.reason);\n });\n }\n\n /**\n * Throws a `CanceledError` if cancellation has been requested.\n */\n throwIfRequested() {\n if (this.reason) {\n throw this.reason;\n }\n }\n\n /**\n * Subscribe to the cancel signal\n */\n\n subscribe(listener) {\n if (this.reason) {\n listener(this.reason);\n return;\n }\n\n if (this._listeners) {\n this._listeners.push(listener);\n } else {\n this._listeners = [listener];\n }\n }\n\n /**\n * Unsubscribe from the cancel signal\n */\n\n unsubscribe(listener) {\n if (!this._listeners) {\n return;\n }\n const index = this._listeners.indexOf(listener);\n if (index !== -1) {\n this._listeners.splice(index, 1);\n }\n }\n\n toAbortSignal() {\n const controller = new AbortController();\n\n const abort = (err) => {\n controller.abort(err);\n };\n\n this.subscribe(abort);\n\n controller.signal.unsubscribe = () => this.unsubscribe(abort);\n\n return controller.signal;\n }\n\n /**\n * Returns an object that contains a new `CancelToken` and a function that, when called,\n * cancels the `CancelToken`.\n */\n static source() {\n let cancel;\n const token = new CancelToken(function executor(c) {\n cancel = c;\n });\n return {\n token,\n cancel,\n };\n }\n}\n\nexport default CancelToken;\n","'use strict';\n\n/**\n * Syntactic sugar for invoking a function and expanding an array for arguments.\n *\n * Common use case would be to use `Function.prototype.apply`.\n *\n * ```js\n * function f(x, y, z) {}\n * const args = [1, 2, 3];\n * f.apply(null, args);\n * ```\n *\n * With `spread` this example can be re-written.\n *\n * ```js\n * spread(function(x, y, z) {})([1, 2, 3]);\n * ```\n *\n * @param {Function} callback\n *\n * @returns {Function}\n */\nexport default function spread(callback) {\n return function wrap(arr) {\n return callback.apply(null, arr);\n };\n}\n","'use strict';\n\nimport utils from '../utils.js';\n\n/**\n * Determines whether the payload is an error thrown by Axios\n *\n * @param {*} payload The value to test\n *\n * @returns {boolean} True if the payload is an error thrown by Axios, otherwise false\n */\nexport default function isAxiosError(payload) {\n return utils.isObject(payload) && payload.isAxiosError === true;\n}\n","const HttpStatusCode = {\n Continue: 100,\n SwitchingProtocols: 101,\n Processing: 102,\n EarlyHints: 103,\n Ok: 200,\n Created: 201,\n Accepted: 202,\n NonAuthoritativeInformation: 203,\n NoContent: 204,\n ResetContent: 205,\n PartialContent: 206,\n MultiStatus: 207,\n AlreadyReported: 208,\n ImUsed: 226,\n MultipleChoices: 300,\n MovedPermanently: 301,\n Found: 302,\n SeeOther: 303,\n NotModified: 304,\n UseProxy: 305,\n Unused: 306,\n TemporaryRedirect: 307,\n PermanentRedirect: 308,\n BadRequest: 400,\n Unauthorized: 401,\n PaymentRequired: 402,\n Forbidden: 403,\n NotFound: 404,\n MethodNotAllowed: 405,\n NotAcceptable: 406,\n ProxyAuthenticationRequired: 407,\n RequestTimeout: 408,\n Conflict: 409,\n Gone: 410,\n LengthRequired: 411,\n PreconditionFailed: 412,\n /**\n * @deprecated Use `ContentTooLarge` instead.\n */\n PayloadTooLarge: 413,\n ContentTooLarge: 413,\n UriTooLong: 414,\n UnsupportedMediaType: 415,\n RangeNotSatisfiable: 416,\n ExpectationFailed: 417,\n ImATeapot: 418,\n MisdirectedRequest: 421,\n /**\n * @deprecated Use `UnprocessableContent` instead.\n */\n UnprocessableEntity: 422,\n UnprocessableContent: 422,\n Locked: 423,\n FailedDependency: 424,\n TooEarly: 425,\n UpgradeRequired: 426,\n PreconditionRequired: 428,\n TooManyRequests: 429,\n RequestHeaderFieldsTooLarge: 431,\n UnavailableForLegalReasons: 451,\n InternalServerError: 500,\n NotImplemented: 501,\n BadGateway: 502,\n ServiceUnavailable: 503,\n GatewayTimeout: 504,\n HttpVersionNotSupported: 505,\n VariantAlsoNegotiates: 506,\n InsufficientStorage: 507,\n LoopDetected: 508,\n NotExtended: 510,\n NetworkAuthenticationRequired: 511,\n WebServerReturnsAnUnknownError: 520,\n WebServerIsDown: 521,\n ConnectionTimedOut: 522,\n OriginIsUnreachable: 523,\n TimeoutOccurred: 524,\n SslHandshakeFailed: 525,\n InvalidSslCertificate: 526,\n};\n\nObject.entries(HttpStatusCode).forEach(([key, value]) => {\n if (HttpStatusCode[value] === undefined) {\n HttpStatusCode[value] = key;\n }\n});\n\nexport default HttpStatusCode;\n","'use strict';\n\nimport utils from './utils.js';\nimport bind from './helpers/bind.js';\nimport Axios from './core/Axios.js';\nimport mergeConfig from './core/mergeConfig.js';\nimport defaults from './defaults/index.js';\nimport formDataToJSON from './helpers/formDataToJSON.js';\nimport CanceledError from './cancel/CanceledError.js';\nimport CancelToken from './cancel/CancelToken.js';\nimport isCancel from './cancel/isCancel.js';\nimport { VERSION } from './env/data.js';\nimport toFormData from './helpers/toFormData.js';\nimport AxiosError from './core/AxiosError.js';\nimport spread from './helpers/spread.js';\nimport isAxiosError from './helpers/isAxiosError.js';\nimport AxiosHeaders from './core/AxiosHeaders.js';\nimport adapters from './adapters/adapters.js';\nimport HttpStatusCode from './helpers/HttpStatusCode.js';\n\n/**\n * Create an instance of Axios\n *\n * @param {Object} defaultConfig The default config for the instance\n *\n * @returns {Axios} A new instance of Axios\n */\nfunction createInstance(defaultConfig) {\n const context = new Axios(defaultConfig);\n const instance = bind(Axios.prototype.request, context);\n\n // Copy axios.prototype to instance\n utils.extend(instance, Axios.prototype, context, { allOwnKeys: true });\n\n // Copy context to instance\n utils.extend(instance, context, null, { allOwnKeys: true });\n\n // Factory for creating new instances\n instance.create = function create(instanceConfig) {\n return createInstance(mergeConfig(defaultConfig, instanceConfig));\n };\n\n return instance;\n}\n\n// Create the default instance to be exported\nconst axios = createInstance(defaults);\n\n// Expose Axios class to allow class inheritance\naxios.Axios = Axios;\n\n// Expose Cancel & CancelToken\naxios.CanceledError = CanceledError;\naxios.CancelToken = CancelToken;\naxios.isCancel = isCancel;\naxios.VERSION = VERSION;\naxios.toFormData = toFormData;\n\n// Expose AxiosError class\naxios.AxiosError = AxiosError;\n\n// alias for CanceledError for backward compatibility\naxios.Cancel = axios.CanceledError;\n\n// Expose all/spread\naxios.all = function all(promises) {\n return Promise.all(promises);\n};\n\naxios.spread = spread;\n\n// Expose isAxiosError\naxios.isAxiosError = isAxiosError;\n\n// Expose mergeConfig\naxios.mergeConfig = mergeConfig;\n\naxios.AxiosHeaders = AxiosHeaders;\n\naxios.formToJSON = (thing) => formDataToJSON(utils.isHTMLForm(thing) ? new FormData(thing) : thing);\n\naxios.getAdapter = adapters.getAdapter;\n\naxios.HttpStatusCode = HttpStatusCode;\n\naxios.default = axios;\n\n// this module should only have a default export\nexport default axios;\n","import axios from './lib/axios.js';\n\n// This module is intended to unwrap Axios default export as named.\n// Keep top-level export same with static properties\n// so that it can keep same with es module or cjs\nconst {\n Axios,\n AxiosError,\n CanceledError,\n isCancel,\n CancelToken,\n VERSION,\n all,\n Cancel,\n isAxiosError,\n spread,\n toFormData,\n AxiosHeaders,\n HttpStatusCode,\n formToJSON,\n getAdapter,\n mergeConfig,\n create,\n} = axios;\n\nexport {\n axios as default,\n create,\n Axios,\n AxiosError,\n CanceledError,\n isCancel,\n CancelToken,\n VERSION,\n all,\n Cancel,\n isAxiosError,\n spread,\n toFormData,\n AxiosHeaders,\n HttpStatusCode,\n formToJSON,\n getAdapter,\n mergeConfig,\n};\n","// src/features/surveys/hooks/useTableConfig.ts\r\nimport { useQuery } from '@tanstack/react-query';\r\nimport axios from 'axios';\r\nimport type { TableConfigDto } from '../types/survey.types';\r\n\r\nconst BASE = import.meta.env.VITE_API_URL;\r\n\r\nconst getHeaders = () => ({\r\n Authorization: `Bearer ${localStorage.getItem('zelisy_access_token')}`,\r\n 'X-Organization-Id': localStorage.getItem('zelisy_org_id') ?? '',\r\n});\r\n\r\n/**\r\n * Custom hook for table config.\r\n *\r\n * @param tableName - The table name.\r\n * @returns The hook's state and actions.\r\n */\r\nexport function useTableConfig<T = any>(tableName: string) {\r\n const { data, isLoading, isError } = useQuery({\r\n queryKey: ['table-config', tableName],\r\n queryFn: async () => {\r\n const res = await axios.get<TableConfigDto>(\r\n `${BASE}/tables/${tableName}/config`,\r\n { headers: getHeaders() }\r\n );\r\n return res.data; // ← critical: unwrap AxiosResponse\r\n },\r\n staleTime: 5 * 60_000,\r\n gcTime: 10 * 60_000,\r\n retry: 2,\r\n });\r\n\r\n const columns = (data?.columns ?? []).map((col) => ({\r\n key: col.key as keyof T & string,\r\n label: col.label,\r\n cellType: col.cellType ?? undefined,\r\n align: col.align ?? 'left',\r\n width: col.width ?? undefined,\r\n minWidth: col.minWidth ?? undefined,\r\n maxWidth: col.maxWidth ?? undefined,\r\n sortable: col.sortable,\r\n hidden: col.hidden ?? false,\r\n hideBelow: col.hideBelow ?? undefined,\r\n className: col.className ?? undefined,\r\n toggleable: col.toggleable ?? true,\r\n }));\r\n\r\n const tabs = (data?.tabs ?? []).map((t) => ({\r\n key: t.key,\r\n label: t.label,\r\n count: t.count,\r\n icon: t.icon,\r\n }));\r\n\r\n const controls = (data?.controls ?? []).map((c) => ({\r\n action: c.action,\r\n label: c.label,\r\n icon: c.icon,\r\n variant: c.variant,\r\n showOnSelection: c.showOnSelection ?? false,\r\n disabled: c.disabled ?? false,\r\n onClick: undefined as (() => void) | undefined,\r\n }));\r\n\r\n return {\r\n columns,\r\n tabs,\r\n controls,\r\n defaultSortBy: data?.defaultSortBy ?? 'createdAt',\r\n defaultSortOrder: (data?.defaultSortOrder ?? 'desc') as 'asc' | 'desc',\r\n defaultPageSize: data?.defaultPageSize ?? 50,\r\n tabFilterKey: data?.tabFilterKey ?? undefined,\r\n isLoading,\r\n isError,\r\n };\r\n}\r\n\r\n\r\n","import { useCallback, useMemo, useState } from 'react';\r\nimport { useInfiniteQuery, useQueryClient } from '@tanstack/react-query';\r\nimport type { PagedResponse } from '../types/survey.types';\r\n\r\ninterface UseTableDataOptions<T> {\r\n resource: string;\r\n queryKey: (string | number | Record<string, unknown>)[];\r\n fetchFn: (params: Record<string, unknown>) => Promise<PagedResponse<T> | T[]>;\r\n pageSize?: number;\r\n defaultSortBy?: string;\r\n defaultSortOrder?: 'asc' | 'desc';\r\n}\r\n\r\n/**\r\n * Custom hook for table data.\r\n *\r\n * @param options - Options that customize the behavior.\r\n * @returns The hook's state and actions.\r\n */\r\nexport function useTableData<T extends { id: string | number }>(\r\n options: UseTableDataOptions<T>\r\n) {\r\n const {\r\n queryKey,\r\n fetchFn,\r\n pageSize = 50,\r\n defaultSortBy = 'createdAt',\r\n defaultSortOrder = 'desc',\r\n } = options;\r\n\r\n const queryClient = useQueryClient();\r\n\r\n const [search, setSearch] = useState('');\r\n const [sortBy, setSortBy] = useState(defaultSortBy);\r\n const [sortOrder, setSortOrder] = useState<'asc' | 'desc'>(defaultSortOrder);\r\n const [activeTab, setActiveTab] = useState('All');\r\n const [filters, setFilters] = useState<Record<string, string>>({});\r\n\r\n const buildParams = useCallback(\r\n (cursor?: string): Record<string, unknown> => ({\r\n pageSize,\r\n ...(cursor ? { cursor } : {}),\r\n ...(search ? { search } : {}),\r\n ...(sortBy ? { sortBy } : {}),\r\n ...(sortOrder ? { sortOrder } : {}),\r\n ...(activeTab && activeTab !== 'All' ? { tab: activeTab } : {}),\r\n ...filters,\r\n }),\r\n [pageSize, search, sortBy, sortOrder, activeTab, filters]\r\n );\r\n\r\n const {\r\n data,\r\n isLoading,\r\n isFetchingNextPage,\r\n isRefetching,\r\n isError,\r\n fetchNextPage,\r\n hasNextPage,\r\n refetch,\r\n } = useInfiniteQuery({\r\n queryKey: [...queryKey, search, sortBy, sortOrder, activeTab, filters],\r\n queryFn: async ({ pageParam }) => {\r\n const result = await fetchFn(buildParams(pageParam as string | undefined));\r\n\r\n if (Array.isArray(result)) {\r\n return {\r\n items: result,\r\n totalCount: result.length,\r\n pageSize,\r\n hasMore: false,\r\n nextCursor: null,\r\n } as PagedResponse<T>;\r\n }\r\n\r\n return result;\r\n },\r\n getNextPageParam: (lastPage: PagedResponse<T>) =>\r\n lastPage.hasMore ? lastPage.nextCursor ?? undefined : undefined,\r\n initialPageParam: undefined as string | undefined,\r\n staleTime: 30_000,\r\n });\r\n\r\n const items = useMemo<T[]>(\r\n () => data?.pages.flatMap((p) => p.items) ?? [],\r\n [data]\r\n );\r\n\r\n const totalCount = data?.pages[0]?.totalCount ?? 0;\r\n const hasMore = hasNextPage ?? false;\r\n\r\n const loadMore = useCallback(() => {\r\n if (hasMore && !isFetchingNextPage) {\r\n fetchNextPage();\r\n }\r\n }, [hasMore, isFetchingNextPage, fetchNextPage]);\r\n\r\n const handleSort = useCallback((key: string, order: 'asc' | 'desc') => {\r\n setSortBy(key);\r\n setSortOrder(order);\r\n }, []);\r\n\r\n const handleTabChange = useCallback((tab: string) => {\r\n setActiveTab(tab);\r\n }, []);\r\n\r\n const updateFilter = useCallback((key: string, value: string) => {\r\n setFilters((prev) => ({ ...prev, [key]: value }));\r\n }, []);\r\n\r\n const optimisticUpdate = useCallback(\r\n (id: string | number, updater: (item: T) => T) => {\r\n queryClient.setQueriesData(\r\n { queryKey: [...queryKey] },\r\n (old: any) => {\r\n if (!old) return old;\r\n return {\r\n ...old,\r\n pages: old.pages.map((page: any) => ({\r\n ...page,\r\n items: page.items.map((item: T) =>\r\n item.id === id ? updater(item) : item\r\n ),\r\n })),\r\n };\r\n }\r\n );\r\n },\r\n [queryClient, queryKey]\r\n );\r\n\r\n const optimisticRemove = useCallback(\r\n (id: string | number) => {\r\n queryClient.setQueriesData(\r\n { queryKey: [...queryKey] },\r\n (old: any) => {\r\n if (!old) return old;\r\n return {\r\n ...old,\r\n pages: old.pages.map((page: any) => ({\r\n ...page,\r\n items: page.items.filter((item: T) => item.id !== id),\r\n totalCount: Math.max(0, (page.totalCount ?? 1) - 1),\r\n })),\r\n };\r\n }\r\n );\r\n },\r\n [queryClient, queryKey]\r\n );\r\n\r\n return {\r\n items,\r\n totalCount,\r\n hasMore,\r\n\r\n isLoading,\r\n isFetchingNextPage,\r\n isRefetching,\r\n isError,\r\n refetch,\r\n\r\n search,\r\n setSearch,\r\n\r\n sortBy,\r\n sortOrder,\r\n setSortBy,\r\n setSortOrder,\r\n handleSort,\r\n\r\n activeTab,\r\n setActiveTab,\r\n handleTabChange,\r\n\r\n filters,\r\n updateFilter,\r\n\r\n loadMore,\r\n\r\n optimisticUpdate,\r\n optimisticRemove,\r\n };\r\n}\r\r\n\r\n","// src/services/api/surveys.api.ts\r\nimport axios from 'axios';\r\nimport type {\r\n NpsSummary,\r\n SurveyListItem,\r\n CreateSurveyDto,\r\n SurveyResponseItem,\r\n SurveyAnalyticsItem,\r\n SurveyTemplateItem,\r\n PagedResponse,\r\n TableQueryParams,\r\n} from '../../types/survey.types';\r\n\r\nconst BASE = import.meta.env.VITE_API_URL;\r\n\r\nconst getHeaders = () => ({\r\n Authorization: `Bearer ${localStorage.getItem('zelisy_access_token')}`,\r\n 'X-Organization-Id': localStorage.getItem('zelisy_org_id') ?? '',\r\n});\r\n\r\nexport const surveysApi = {\r\n // list: async (params?: TableQueryParams | Record<string, unknown>) => {\r\n // const res = await axios.get<PagedResponse<SurveyListItem>>(\r\n // `${BASE}/surveys`,\r\n // { params, headers: getHeaders() }\r\n // );\r\n // return res.data;\r\n // },\r\nlist: async (params?: TableQueryParams | Record<string, unknown>) => {\r\n const res = await axios.get<{\r\n success: boolean;\r\n data: PagedResponse<SurveyListItem>;\r\n }>('/JSON/surveys/GetSurveysQuery.json', {\r\n params,\r\n headers: getHeaders(),\r\n });\r\n return res.data.data;\r\n},\r\n // getNps: async (weeks = 12) => {\r\n // const res = await axios.get<NpsSummary>(`${BASE}/surveys/nps`, {\r\n // params: { weeks },\r\n // headers: getHeaders(),\r\n // });\r\n // return res.data;\r\n // },\r\ngetNps: async (weeks = 12) => {\r\n const res = await axios.get<{\r\n success: boolean;\r\n data: NpsSummary;\r\n }>('/JSON/surveys/GetNpsDataQuery.json', {\r\n params: { weeks },\r\n headers: getHeaders(),\r\n });\r\n return res.data.data;\r\n},\r\n // Single survey for the details page.\r\n // Mock mode: reads the list JSON and picks the row. Real API: GET `${BASE}/surveys/${id}`.\r\n getById: async (id: string) => {\r\n const page = await surveysApi.list({ pageSize: 1000 });\r\n return page.items.find((s) => s.id === id) ?? null;\r\n },\r\n\r\n create: async (body: CreateSurveyDto) => {\r\n const res = await axios.post<SurveyListItem>(`${BASE}/surveys`, body, {\r\n headers: getHeaders(),\r\n });\r\n return res.data;\r\n },\r\n\r\n delete: async (id: string) => {\r\n await axios.delete<void>(`${BASE}/surveys/${id}`, {\r\n headers: getHeaders(),\r\n });\r\n },\r\n\r\n // getResponses: async (params?: Record<string, unknown>) => {\r\n // const res = await axios.get<PagedResponse<SurveyResponseItem>>(\r\n // `${BASE}/surveys/responses`,\r\n // { params, headers: getHeaders() }\r\n // );\r\n // return res.data;\r\n // },\r\ngetResponses: async (params?: Record<string, unknown>) => {\r\n const res = await axios.get<{\r\n success: boolean;\r\n data: PagedResponse<SurveyResponseItem>;\r\n }>('/JSON/surveys/GetSurveyResponsesQuery.json', {\r\n params,\r\n headers: getHeaders(),\r\n });\r\n return res.data.data;\r\n},\r\n // getAnalytics: async () => {\r\n // const res = await axios.get<SurveyAnalyticsItem[]>(\r\n // `${BASE}/surveys/analytics`,\r\n // { headers: getHeaders() }\r\n // );\r\n // return res.data;\r\n // },\r\ngetAnalytics: async () => {\r\n const res = await axios.get<{\r\n success: boolean;\r\n data: SurveyAnalyticsItem[];\r\n }>('/JSON/surveys/GetSurveyAnalyticsQuery.json', {\r\n headers: getHeaders(),\r\n });\r\n return res.data.data;\r\n},\r\n // getTemplates: async () => {\r\n // const res = await axios.get<SurveyTemplateItem[]>(\r\n // `${BASE}/surveys/templates`,\r\n // { headers: getHeaders() }\r\n // );\r\n // return res.data;\r\n // },\r\ngetTemplates: async () => {\r\n const res = await axios.get<{\r\n success: boolean;\r\n data: SurveyTemplateItem[];\r\n }>('/JSON/surveys/GetSurveyTemplatesQuery.json', {\r\n headers: getHeaders(),\r\n });\r\n return res.data.data;\r\n},\r\n\r\n useTemplate: async (\r\n templateId: string,\r\n body: { name: string; targetResponses: number }\r\n ) => {\r\n const res = await axios.post<SurveyListItem>(\r\n `${BASE}/surveys/templates/${templateId}/use`,\r\n body,\r\n { headers: getHeaders() }\r\n );\r\n return res.data;\r\n },\r\n\r\n getNpsTrend: async () => {\r\n const res = await axios.get<\r\n Array<{ period: string; score: number; responses: number }>\r\n >(`${BASE}/surveys/nps-trend`, { headers: getHeaders() });\r\n return res.data;\r\n },\r\n};\r\n\r\n\r\n","import type { HTMLAttributes } from 'react';\n\nexport interface CardProps extends HTMLAttributes<HTMLDivElement> {}\n\nexport function Card({ className = '', children, ...props }: CardProps) {\n return (\n <div\n className={`rounded-xl border border-[var(--th-border)] bg-[var(--th-surface)] ${className}`}\n {...props}\n >\n {children}\n </div>\n );\n}\r\n\r\n\r\n","// src/modules/survey/Pages/Allsurvey/SurveyGridCard.tsx\r\nimport type { RowId } from '../../components/DataTable/types';\r\nimport { Icon } from '../../components/ui/Icon';\r\nimport React from 'react';\r\n\r\nimport { Card } from '../../components/ui/Card';\r\nimport type { SurveyListItem } from '../../types/survey.types';\r\n\r\n/** Props for the card render component. */\r\nexport interface CardRenderProps<T> {\r\n row: T;\r\n isSelected?: boolean;\r\n onSelect?: (id: RowId) => void;\r\n onRowClick?: (row: T) => void;\r\n rowIndex?: number;\r\n}\r\n\r\nconst SC: Record<string, { dot: string; bg: string; text: string }> = {\r\n active: { dot: 'bg-[#4edea3] animate-pulse', bg: 'bg-[color:color-mix(in_srgb,var(--th-success)_10%,transparent)]', text: 'text-[color:var(--th-success)]' },\r\n draft: { dot: 'bg-[#ffcc6b]', bg: 'bg-[color:color-mix(in_srgb,var(--th-warning-soft)_10%,transparent)]', text: 'text-[color:var(--th-warning-soft)]' },\r\n closed: { dot: 'bg-[#958da1]', bg: 'bg-[color:color-mix(in_srgb,var(--th-ov-base)_5%,transparent)]', text: 'text-[color:var(--th-text-3)]' },\r\n};\r\n\r\n/**\r\n * Renders the survey grid card component.\r\n *\r\n * @param props - The component props.\r\n * @param props.row - The row.\r\n * @param props.isSelected - The is selected.\r\n * @param props.onSelect - The on select.\r\n * @param props.onRowClick - The on row click.\r\n */\r\nexport const SurveyGridCard: React.FC<CardRenderProps<SurveyListItem>> = ({\r\n row,\r\n isSelected,\r\n onSelect,\r\n onRowClick,\r\n}) => {\r\n const pct = row.target > 0 ? Math.min((row.responses / row.target) * 100, 100) : 0;\r\n const sc = SC[row.status] ?? SC.draft;\r\n\r\n return (\r\n <div\r\n role=\"button\"\r\n tabIndex={0}\r\n className=\"h-full cursor-pointer\"\r\n onClick={() => onRowClick?.(row)}\r\n onKeyDown={(e) => e.key === 'Enter' && onRowClick?.(row)}\r\n >\r\n <Card\r\n className={`group relative p-5 transition-all hover:border-[#7c3aed]/20 ${isSelected ? 'border-[#7c3aed]/40 ring-1 ring-[#7c3aed]/20' : ''\r\n }`}\r\n >\r\n {onSelect && (\r\n <button\r\n onClick={(e) => {\r\n e.stopPropagation();\r\n onSelect(row.id);\r\n }}\r\n className={`absolute top-3 right-3 w-5 h-5 rounded border flex items-center justify-center transition-all ${isSelected\r\n ? 'bg-[#7c3aed] border-[#7c3aed]'\r\n : 'border-[color:color-mix(in_srgb,var(--th-ov-base)_10%,transparent)] opacity-0 group-hover:opacity-100'\r\n }`}\r\n >\r\n {isSelected && <Icon icon=\"Check\" size={11} className=\"text-white\" />}\r\n </button>\r\n )}\r\n\r\n <div className=\"flex items-center gap-2 mb-3\">\r\n <span className={`w-2 h-2 rounded-full ${sc.dot}`} />\r\n <span\r\n className={`text-[9px] px-1.5 py-0.5 rounded font-medium capitalize ${sc.bg} ${sc.text}`}\r\n >\r\n {row.status}\r\n </span>\r\n {row.npsScore !== null && row.npsScore !== undefined && (\r\n <span\r\n className={`text-[9px] px-1.5 py-0.5 rounded font-bold ${row.npsScore >= 70\r\n ? 'bg-[color:color-mix(in_srgb,var(--th-success)_10%,transparent)] text-[color:var(--th-success)]'\r\n : 'bg-[color:color-mix(in_srgb,var(--th-warning-soft)_10%,transparent)] text-[color:var(--th-warning-soft)]'\r\n }`}\r\n >\r\n NPS {row.npsScore}\r\n </span>\r\n )}\r\n </div>\r\n\r\n <h3 className=\"text-[14px] font-semibold text-white mb-1 truncate pr-6\">\r\n {row.name}\r\n </h3>\r\n\r\n {row.description && (\r\n <p className=\"text-[11px] text-[color:var(--th-text-3)] line-clamp-2 mb-3\">\r\n {row.description}\r\n </p>\r\n )}\r\n\r\n <div className=\"mt-auto pt-3 border-t border-[color:color-mix(in_srgb,var(--th-ov-base)_5%,transparent)]\">\r\n <div className=\"flex items-center justify-between text-[11px] mb-1.5\">\r\n <span className=\"text-[color:var(--th-text-3)]\">Responses</span>\r\n <span className=\"text-[color:var(--th-text-1)] font-mono tabular-nums\">\r\n {row.responses.toLocaleString()} / {row.target.toLocaleString()}\r\n </span>\r\n </div>\r\n <div className=\"h-1.5 rounded-full bg-[color:color-mix(in_srgb,var(--th-ov-base)_5%,transparent)] overflow-hidden\">\r\n <div\r\n className={`h-full rounded-full ${pct >= 80 ? 'bg-[#4edea3]' : 'bg-[#7c3aed]'\r\n }`}\r\n style={{ width: `${pct}%` }}\r\n />\r\n </div>\r\n </div>\r\n\r\n <div className=\"flex items-center justify-between mt-3 text-[10px] text-[color:var(--th-text-3)]\">\r\n <span className=\"flex items-center gap-1\">\r\n <Icon icon=\"HelpCircle\" size={10} /> {row.questionCount} questions\r\n </span>\r\n <span>{row.createdByName}</span>\r\n </div>\r\n </Card>\r\n </div>\r\n );\r\n};\r\n\r\nSurveyGridCard.displayName = 'SurveyGridCard';\r\n\r\n\r\n\r\n","import type { ColumnDef } from '../../components/DataTable/types';\r\nimport type { SurveyRow } from '../../types/survey.types';\r\n\r\n/* Fallback columns, used until GET /tables/surveys/config responds.\r\n (Same idea as queue's pendingTable.config.ts — columns live in a config file, not in the page.)\r\n `cellType` values must match the types registered in cells/SurveyCells.tsx. */\r\nexport const surveysColumns: ColumnDef<SurveyRow>[] = [\r\n { key: 'name', label: 'Survey', cellType: 'surveyName', sortable: true, minWidth: 260 },\r\n { key: 'status', label: 'Status', cellType: 'surveyStatus', sortable: true, width: 90, align: 'center' },\r\n { key: 'responses', label: 'Responses', cellType: 'responseProgress', sortable: true, width: 160 },\r\n { key: 'npsScore', label: 'NPS Score', cellType: 'npsScore', sortable: true, width: 110 },\r\n { key: 'questionCount', label: 'Questions', sortable: false, width: 100 },\r\n { key: 'createdByName', label: 'Created By', sortable: false, width: 160 },\r\n { key: 'updatedAt', label: 'Updated', sortable: true, width: 130 },\r\n];\r\n\r\n\r\n\r\n\r\n","// src/modules/survey/Pages/Allsurvey/Allsurvey.tsx\r\nimport StatCard from '../../components/StatCard/StatCard';\r\nimport { DataTable } from '../../components/DataTable/DataTable';\r\nimport type { ColumnDef, RowId } from '../../components/DataTable/types';\r\nimport { ConfirmModal } from '../../components/feedback/ConfirmModal';\r\nimport { Header } from '../../components/layout/Header';\r\nimport React, { useCallback, useMemo, useState } from 'react';\r\nimport { useNavigate } from 'react-router-dom';\r\nimport { useTableConfig } from '../../hooks/useTableConfig';\r\nimport { useTableData } from '../../hooks/useTableData';\r\nimport { surveysApi } from '../../services/api/surveys.api';\r\nimport type { SurveyRow } from '../../types/survey.types';\r\nimport styles from '../surveyPage.module.scss';\r\nimport { SurveyGridCard } from './SurveyGridCard';\r\nimport { surveysColumns } from './surveysTable.config';\r\n\r\n/** Renders the all surveys component. */\r\nexport const AllSurveys: React.FC = () => {\r\n const navigate = useNavigate();\r\n const tableConfig = useTableConfig<SurveyRow>('surveys');\r\n\r\n const {\r\n items: rawItems,\r\n totalCount,\r\n hasMore,\r\n isLoading,\r\n loadMore,\r\n handleSort,\r\n handleTabChange,\r\n sortBy,\r\n sortOrder,\r\n activeTab,\r\n optimisticRemove,\r\n } = useTableData<SurveyRow>({\r\n resource: '/surveys',\r\n queryKey: ['surveys'],\r\n fetchFn: (params) => surveysApi.list(params),\r\n pageSize: tableConfig.defaultPageSize,\r\n defaultSortBy: tableConfig.defaultSortBy,\r\n defaultSortOrder: tableConfig.defaultSortOrder,\r\n });\r\n\r\n // guard against undefined rows / missing id\r\n const rows = useMemo(() => (rawItems ?? []).filter((i): i is SurveyRow => Boolean(i?.id)), [rawItems]);\r\n\r\n const [selectedIds, setSelectedIds] = useState<Set<RowId>>(new Set());\r\n const [deleteTarget, setDeleteTarget] = useState<SurveyRow | null>(null);\r\n const [isDeleting, setIsDeleting] = useState(false);\r\n\r\n const handleDelete = useCallback(async () => {\r\n if (!deleteTarget) return;\r\n setIsDeleting(true);\r\n try {\r\n await surveysApi.delete(deleteTarget.id);\r\n optimisticRemove(deleteTarget.id);\r\n setDeleteTarget(null);\r\n } finally {\r\n setIsDeleting(false);\r\n }\r\n }, [deleteTarget, optimisticRemove]);\r\n\r\n const goCreate = useCallback(() => navigate('/app/all-surveys/create-survey'), [navigate]);\r\n\r\n const controls = useMemo(\r\n () =>\r\n (tableConfig.controls ?? []).map((c) => ({\r\n ...c,\r\n onClick: () => {\r\n if (c.action === 'create') goCreate();\r\n },\r\n })),\r\n [tableConfig.controls, goCreate]\r\n );\r\n\r\n // server config wins; typed fallback until it loads\r\n const columns = (\r\n tableConfig.columns?.length ? tableConfig.columns : surveysColumns\r\n ) as ColumnDef<SurveyRow>[];\r\n\r\n /* ── stats (derived from loaded rows) ── */\r\n const stats = useMemo(() => {\r\n const active = rows.filter((r) => r.status === 'active').length;\r\n const totalResp = rows.reduce((a, r) => a + (r.responses ?? 0), 0);\r\n const scored = rows.filter((r) => r.npsScore !== null && r.npsScore !== undefined);\r\n const avgNps = scored.length\r\n ? Math.round(scored.reduce((a, r) => a + (r.npsScore ?? 0), 0) / scored.length)\r\n : null;\r\n return { active, totalResp, avgNps };\r\n }, [rows]);\r\n\r\n return (\r\n <div className={styles.wrapper}>\r\n <Header\r\n title=\"Surveys\"\r\n subtitle=\"Analytics · manage and track user surveys.\"\r\n primaryText=\"Create Survey\"\r\n primaryIcon=\"Plus\"\r\n onPrimaryClick={goCreate}\r\n />\r\n\r\n <div className={styles.statsgrid}>\r\n <StatCard icon=\"ClipboardList\" label=\"Total surveys\" value={totalCount.toLocaleString()} trendDirection=\"neutral\" color=\"#6366f1\" />\r\n <StatCard icon=\"Activity\" label=\"Active\" value={stats.active.toLocaleString()} trendDirection=\"neutral\" color=\"#10b981\" />\r\n <StatCard icon=\"MessageSquare\" label=\"Total responses\" value={stats.totalResp.toLocaleString()} trendDirection=\"neutral\" color=\"#7c3aed\" />\r\n <StatCard icon=\"Star\" label=\"Avg NPS\" value={stats.avgNps ?? '—'} trendDirection=\"neutral\" color=\"#f59e0b\" />\r\n </div>\r\n\r\n <DataTable<SurveyRow>\r\n currentPage=\"surveys\"\r\n columns={columns}\r\n data={rows}\r\n totalCount={totalCount}\r\n isLoading={tableConfig.isLoading || isLoading}\r\n hasMore={hasMore}\r\n onLoadMore={loadMore}\r\n availableViews={['table', 'grid']}\r\n renderCard={(props) => <SurveyGridCard {...props} />}\r\n gridCols={{ sm: 1, md: 2, lg: 3 }}\r\n tabs={tableConfig.tabs}\r\n activeTab={activeTab}\r\n onTabChange={handleTabChange}\r\n controls={controls}\r\n selectable\r\n selectedIds={selectedIds}\r\n onSelectionChange={setSelectedIds}\r\n sortBy={sortBy}\r\n sortOrder={sortOrder}\r\n onSort={handleSort}\r\n onEditRow={(row) => navigate(`/app/surveys/${row.id}/edit`)}\r\n onActionClick={(row) => setDeleteTarget(row)}\r\n rowClickBehavior={{ type: 'navigate', path: (r) => `/app/surveys/${r.id}` }}\r\n height=\"calc(100vh - 250px)\"\r\n emptyMessage=\"No surveys found.\"\r\n stickyHeader\r\n />\r\n\r\n <ConfirmModal\r\n open={Boolean(deleteTarget)}\r\n onClose={() => setDeleteTarget(null)}\r\n onConfirm={handleDelete}\r\n isLoading={isDeleting}\r\n title=\"Delete Survey\"\r\n description={\r\n <>\r\n Delete <strong className=\"text-white\">{deleteTarget?.name}</strong> and all{' '}\r\n {deleteTarget?.responses ?? 0} responses?\r\n </>\r\n }\r\n confirmLabel=\"Delete Survey\"\r\n confirmTone=\"danger\"\r\n requireConfirmText={deleteTarget?.name}\r\n />\r\n </div>\r\n );\r\n};\r\n\r\nAllSurveys.displayName = 'AllSurveys';\r\n\r\n\r\n\r\n","// src/features/surveys/pages/CreateSurvey.tsx\r\nimport { Header } from '../../components/layout/Header';\r\nimport { Icon } from '../../components/ui/Icon';\r\nimport React, { useCallback, useState } from 'react';\r\nimport { useNavigate } from 'react-router-dom';\r\nimport { Card } from '../../components/ui/Card';\r\nimport { surveysApi } from '../../services/api/surveys.api';\r\n\r\ntype QType = 'nps' | 'rating' | 'multiple_choice' | 'open_text';\r\n\r\ninterface QDraft {\r\n id: string;\r\n type: QType;\r\n text: string;\r\n required: boolean;\r\n options: string[];\r\n}\r\n\r\nconst TC: Record<string, string> = {\r\n nps: 'bg-[color:color-mix(in_srgb,var(--th-success)_10%,transparent)] text-[color:var(--th-success)]',\r\n rating: 'bg-[#7c3aed]/10 text-[color:var(--th-accent-soft)]',\r\n multiple_choice: 'bg-[color:color-mix(in_srgb,var(--th-warning-soft)_10%,transparent)] text-[color:var(--th-warning-soft)]',\r\n open_text: 'bg-[color:color-mix(in_srgb,var(--th-info-soft)_10%,transparent)] text-[color:var(--th-info-soft)]',\r\n};\r\n\r\n/** Renders the create survey component. */\r\nexport const CreateSurvey: React.FC = () => {\r\n const navigate = useNavigate();\r\n const [name, setName] = useState('');\r\n const [description, setDescription] = useState('');\r\n const [target, setTarget] = useState(500);\r\n const [questions, setQuestions] = useState<QDraft[]>([\r\n {\r\n id: 'q1',\r\n type: 'nps',\r\n text: 'How likely are you to recommend Zelisy?',\r\n required: true,\r\n options: [],\r\n },\r\n {\r\n id: 'q2',\r\n type: 'rating',\r\n text: 'How satisfied are you with the product?',\r\n required: true,\r\n options: [],\r\n },\r\n {\r\n id: 'q3',\r\n type: 'multiple_choice',\r\n text: 'Which feature do you use most?',\r\n required: false,\r\n options: ['Feature Flags', 'Experiments', 'Segments', 'Audit Log'],\r\n },\r\n ]);\r\n const [submitting, setSubmitting] = useState(false);\r\n const [created, setCreated] = useState(false);\r\n const [errors, setErrors] = useState<Record<string, string>>({});\r\n\r\n const addQ = (type: QType) =>\r\n setQuestions((p) => [\r\n ...p,\r\n {\r\n id: `q${Date.now()}`,\r\n type,\r\n text: '',\r\n required: false,\r\n options: type === 'multiple_choice' ? ['Option 1', 'Option 2'] : [],\r\n },\r\n ]);\r\n\r\n const updateQ = (id: string, u: Partial<QDraft>) =>\r\n setQuestions((p) => p.map((q) => (q.id === id ? { ...q, ...u } : q)));\r\n\r\n const handleSubmit = useCallback(async () => {\r\n const errs: Record<string, string> = {};\r\n if (!name.trim()) errs.name = 'Required';\r\n if (questions.length === 0) errs.questions = 'Add at least one question';\r\n questions.forEach((q, i) => {\r\n if (!q.text.trim()) errs[`q${i}`] = `Q${i + 1} text required`;\r\n });\r\n setErrors(errs);\r\n if (Object.keys(errs).length) return;\r\n\r\n setSubmitting(true);\r\n try {\r\n await surveysApi.create({\r\n name: name.trim(),\r\n description: description.trim() || undefined,\r\n targetResponses: target,\r\n questions: questions.map((q) => ({\r\n type: q.type,\r\n question: q.text.trim(),\r\n required: q.required,\r\n options: q.options.length ? q.options : undefined,\r\n })),\r\n });\r\n setCreated(true);\r\n } catch (e: any) {\r\n if (e?.errors) setErrors(e.errors);\r\n } finally {\r\n setSubmitting(false);\r\n }\r\n }, [name, description, target, questions]);\r\n\r\n if (created)\r\n return (\r\n <div className=\"p-6 lg:p-8 max-w-[900px] mx-auto\">\r\n <Card className=\"p-12 text-center\">\r\n <div className=\"w-16 h-16 rounded-2xl bg-[color:color-mix(in_srgb,var(--th-success)_15%,transparent)] flex items-center justify-center mx-auto mb-6 glow-success\">\r\n <Icon icon=\"Check\" size={32} className=\"text-[color:var(--th-success)]\" />\r\n </div>\r\n <h2 className=\"text-[24px] font-bold text-white mb-2\">\r\n Survey Created!\r\n </h2>\r\n <p className=\"text-[14px] text-[color:var(--th-text-3)] mb-6\">\r\n Your survey is now live and collecting responses.\r\n </p>\r\n <button\r\n onClick={() => navigate('/app/surveys')}\r\n className=\"px-5 py-2.5 rounded-lg bg-[#7c3aed] hover:bg-[#8b4df0] text-white text-[13px] font-medium transition-colors\"\r\n >\r\n View All Surveys\r\n </button>\r\n </Card>\r\n </div>\r\n );\r\n\r\n return (\r\n <div className=\"p-6 lg:p-8 max-w-[900px]\">\r\n <button\r\n onClick={() => navigate(-1)}\r\n className=\"flex items-center gap-1.5 text-[13px] text-[color:var(--th-text-3)] hover:text-[color:var(--th-text-2)] transition-colors mb-6\"\r\n >\r\n <Icon icon=\"ArrowLeft\" size={15} /> Back\r\n </button>\r\n <Header title=\"Create Survey\" subtitle=\"analytics · build a new survey\" />\r\n\r\n <div className=\"space-y-6\">\r\n <Card className=\"p-6 space-y-4\">\r\n <div>\r\n <label className=\"block text-[12px] text-[color:var(--th-text-3)] mb-1.5\">\r\n Survey Name\r\n </label>\r\n <input\r\n value={name}\r\n onChange={(e) => setName(e.target.value)}\r\n placeholder=\"e.g. Q1 Product Satisfaction\"\r\n className={`w-full px-3.5 py-2.5 rounded-lg bg-[color:color-mix(in_srgb,var(--th-ov-base)_5%,transparent)] border text-[13px] text-[color:var(--th-text-1)] placeholder:text-[color:color-mix(in_srgb,var(--th-text-3)_60%,transparent)] focus:border-[#7c3aed] outline-none transition-colors ${errors.name ? 'border-[color:var(--th-danger-soft)]' : 'border-[color:color-mix(in_srgb,var(--th-ov-base)_8%,transparent)]'\r\n }`}\r\n />\r\n {errors.name && (\r\n <p className=\"text-[11px] text-[color:var(--th-danger-soft)] mt-1\">{errors.name}</p>\r\n )}\r\n </div>\r\n <div>\r\n <label className=\"block text-[12px] text-[color:var(--th-text-3)] mb-1.5\">\r\n Description\r\n </label>\r\n <textarea\r\n value={description}\r\n onChange={(e) => setDescription(e.target.value)}\r\n placeholder=\"What is this survey about?\"\r\n rows={2}\r\n className=\"w-full px-3.5 py-2.5 rounded-lg bg-[color:color-mix(in_srgb,var(--th-ov-base)_5%,transparent)] border border-[color:color-mix(in_srgb,var(--th-ov-base)_8%,transparent)] text-[13px] text-[color:var(--th-text-1)] placeholder:text-[color:color-mix(in_srgb,var(--th-text-3)_60%,transparent)] focus:border-[#7c3aed] outline-none transition-colors resize-none\"\r\n />\r\n </div>\r\n <div>\r\n <label className=\"block text-[12px] text-[color:var(--th-text-3)] mb-1.5\">\r\n Target Responses\r\n </label>\r\n <input\r\n type=\"number\"\r\n value={target}\r\n onChange={(e) => setTarget(parseInt(e.target.value, 10) || 0)}\r\n className=\"w-32 px-3.5 py-2.5 rounded-lg bg-[color:color-mix(in_srgb,var(--th-ov-base)_5%,transparent)] border border-[color:color-mix(in_srgb,var(--th-ov-base)_8%,transparent)] text-[13px] text-[color:var(--th-text-1)] font-mono focus:border-[#7c3aed] outline-none transition-colors\"\r\n />\r\n </div>\r\n </Card>\r\n\r\n <Card className=\"p-6\">\r\n <h2 className=\"text-[15px] font-semibold text-white mb-4\">\r\n Questions ({questions.length})\r\n </h2>\r\n <div className=\"space-y-3\">\r\n {questions.map((q, i) => (\r\n <div\r\n key={q.id}\r\n className=\"p-4 rounded-lg bg-[color:color-mix(in_srgb,var(--th-ov-base)_2%,transparent)] border border-[color:color-mix(in_srgb,var(--th-ov-base)_5%,transparent)] group\"\r\n >\r\n <div className=\"flex items-center gap-3 mb-3\">\r\n <Icon\r\n icon=\"GripVertical\"\r\n size={14}\r\n className=\"text-[color:color-mix(in_srgb,var(--th-text-3)_30%,transparent)] cursor-grab\"\r\n />\r\n <span className=\"text-[12px] font-semibold text-[color:var(--th-text-3)]\">\r\n Q{i + 1}\r\n </span>\r\n <span\r\n className={`text-[10px] px-2 py-0.5 rounded font-medium ${TC[q.type]\r\n }`}\r\n >\r\n {q.type.replace('_', ' ')}\r\n </span>\r\n {q.required && (\r\n <span className=\"text-[10px] text-[color:var(--th-warning-soft)]\">required</span>\r\n )}\r\n <div className=\"flex-1\" />\r\n <button\r\n onClick={() =>\r\n updateQ(q.id, { required: !q.required })\r\n }\r\n className={`text-[10px] px-2 py-0.5 rounded transition-colors ${q.required\r\n ? 'bg-[color:color-mix(in_srgb,var(--th-warning-soft)_10%,transparent)] text-[color:var(--th-warning-soft)]'\r\n : 'bg-[color:color-mix(in_srgb,var(--th-ov-base)_5%,transparent)] text-[color:var(--th-text-3)]'\r\n }`}\r\n >\r\n {q.required ? 'Required' : 'Optional'}\r\n </button>\r\n <button\r\n onClick={() =>\r\n setQuestions((p) => p.filter((x) => x.id !== q.id))\r\n }\r\n className=\"text-[color:var(--th-text-3)] hover:text-[color:var(--th-danger-soft)] transition-colors\"\r\n >\r\n <Icon icon=\"Trash2\" size={13} />\r\n </button>\r\n </div>\r\n <input\r\n value={q.text}\r\n onChange={(e) =>\r\n updateQ(q.id, { text: e.target.value })\r\n }\r\n placeholder=\"Enter your question...\"\r\n className={`w-full px-3 py-2 rounded-lg bg-[color:color-mix(in_srgb,var(--th-ov-base)_5%,transparent)] border text-[13px] text-[color:var(--th-text-1)] placeholder:text-[color:color-mix(in_srgb,var(--th-text-3)_60%,transparent)] focus:border-[#7c3aed] outline-none transition-colors ${errors[`q${i}`] ? 'border-[color:var(--th-danger-soft)]' : 'border-[color:color-mix(in_srgb,var(--th-ov-base)_8%,transparent)]'\r\n }`}\r\n />\r\n {q.options.length > 0 && (\r\n <div className=\"mt-2 space-y-1.5\">\r\n {q.options.map((opt, oi) => (\r\n <div key={oi} className=\"flex items-center gap-2\">\r\n <span className=\"text-[10px] text-[color:var(--th-text-3)]\">•</span>\r\n <input\r\n value={opt}\r\n onChange={(e) => {\r\n const opts = [...q.options];\r\n opts[oi] = e.target.value;\r\n updateQ(q.id, { options: opts });\r\n }}\r\n className=\"flex-1 px-2 py-1 rounded bg-[color:color-mix(in_srgb,var(--th-ov-base)_5%,transparent)] border border-[color:color-mix(in_srgb,var(--th-ov-base)_5%,transparent)] text-[12px] text-[color:var(--th-text-2)] focus:border-[#7c3aed] outline-none\"\r\n />\r\n </div>\r\n ))}\r\n <button\r\n onClick={() =>\r\n updateQ(q.id, {\r\n options: [\r\n ...q.options,\r\n `Option ${q.options.length + 1}`,\r\n ],\r\n })\r\n }\r\n className=\"text-[10px] text-[#7c3aed] hover:text-[#8b4df0] mt-1\"\r\n >\r\n + Add option\r\n </button>\r\n </div>\r\n )}\r\n </div>\r\n ))}\r\n </div>\r\n <div className=\"mt-4 flex items-center gap-2\">\r\n {(\r\n [\r\n 'nps',\r\n 'rating',\r\n 'multiple_choice',\r\n 'open_text',\r\n ] as QType[]\r\n ).map((t) => (\r\n <button\r\n key={t}\r\n onClick={() => addQ(t)}\r\n className=\"px-3 py-1.5 rounded-lg bg-[color:color-mix(in_srgb,var(--th-ov-base)_5%,transparent)] hover:bg-[color:color-mix(in_srgb,var(--th-ov-base)_8%,transparent)] text-[11px] text-[color:var(--th-text-3)] transition-colors\"\r\n >\r\n +{' '}\r\n {t\r\n .replace('_', ' ')\r\n .replace(/\\b\\w/g, (c) => c.toUpperCase())}\r\n </button>\r\n ))}\r\n </div>\r\n </Card>\r\n\r\n <div className=\"flex items-center justify-end gap-3\">\r\n <button\r\n onClick={() => navigate(-1)}\r\n className=\"px-5 py-2.5 rounded-lg bg-[color:color-mix(in_srgb,var(--th-ov-base)_5%,transparent)] hover:bg-[color:color-mix(in_srgb,var(--th-ov-base)_8%,transparent)] text-[color:var(--th-text-3)] text-[13px] font-medium transition-colors\"\r\n >\r\n Cancel\r\n </button>\r\n <button\r\n onClick={handleSubmit}\r\n disabled={submitting || !name.trim()}\r\n className=\"px-6 py-2.5 rounded-lg bg-[#7c3aed] hover:bg-[#8b4df0] disabled:opacity-40 text-white text-[13px] font-medium transition-colors flex items-center gap-2\"\r\n >\r\n {submitting && (\r\n <Icon icon=\"Loader2\" size={13} className=\"animate-spin\" />\r\n )}\r\n Create Survey\r\n </button>\r\n </div>\r\n </div>\r\n </div>\r\n );\r\n};\r\n\r\nCreateSurvey.displayName = 'CreateSurvey';\r\n\r\n\r\n\r\n","import { useInfiniteQuery } from '@tanstack/react-query';\r\nimport { useMemo } from 'react';\r\nimport { surveysApi } from '../services/api/surveys.api';\r\nimport type { PagedResponse, SurveyResponseItem } from '../types/survey.types';\r\n\r\n/** Cursor-paged survey responses, flattened for the DataTable. */\r\nexport function useSurveyResponses(pageSize = 50) {\r\n const query = useInfiniteQuery({\r\n queryKey: ['survey-responses'],\r\n queryFn: ({ pageParam }): Promise<PagedResponse<SurveyResponseItem>> =>\r\n surveysApi.getResponses({ cursor: pageParam, pageSize }),\r\n getNextPageParam: (last) => (last?.hasMore ? last.nextCursor ?? undefined : undefined),\r\n initialPageParam: undefined as string | undefined,\r\n staleTime: 30_000,\r\n });\r\n\r\n const items = useMemo(\r\n () =>\r\n (query.data?.pages ?? [])\r\n .flatMap((p) => (Array.isArray(p?.items) ? p.items : []))\r\n .filter((r) => Boolean(r?.id)),\r\n [query.data]\r\n );\r\n\r\n const totalCount = query.data?.pages[0]?.totalCount ?? items.length;\r\n\r\n return {\r\n items,\r\n totalCount,\r\n isLoading: query.isLoading,\r\n isError: query.isError,\r\n hasMore: query.hasNextPage ?? false,\r\n loadMore: () => {\r\n if (query.hasNextPage && !query.isFetchingNextPage) query.fetchNextPage();\r\n },\r\n };\r\n}\r\n\r\n\r\n","import type { ColumnDef, FilterConfig, SearchConfig, SortConfig } from '../../components/DataTable/types';\r\nimport type { SurveyResponseItem } from '../../types/survey.types';\r\n\r\n/* Search / Filter / Sort / Columns for the Responses table\r\n (same structure as queue's pendingTable.config.ts).\r\n cellType values must match cells/SurveyCells.tsx registrations. */\r\n\r\nconst at = (r: SurveyResponseItem) => Date.parse(r.createdAt) || 0;\r\nconst dir = (d: 'asc' | 'desc') => (d === 'asc' ? 1 : -1);\r\n\r\nexport const NPS_CATEGORIES = ['promoter', 'passive', 'detractor'] as const;\r\n\r\nexport const responsesSearchConfig: SearchConfig<SurveyResponseItem> = {\r\n placeholder: 'Search by user, survey, response…',\r\n keys: ['userId', 'surveyName', 'responseText'],\r\n debounceMs: 150,\r\n};\r\n\r\nexport const responsesSortConfig: SortConfig<SurveyResponseItem> = {\r\n defaultId: 'newest',\r\n options: [\r\n { id: 'newest', label: 'Date: Newest first', comparator: (a, b) => at(b) - at(a) },\r\n { id: 'oldest', label: 'Date: Oldest first', comparator: (a, b) => at(a) - at(b) },\r\n { id: 'nps-high', label: 'NPS: High → Low', comparator: (a, b) => (b.npsScore ?? -1) - (a.npsScore ?? -1) },\r\n { id: 'nps-low', label: 'NPS: Low → High', comparator: (a, b) => (a.npsScore ?? 99) - (b.npsScore ?? 99) },\r\n ],\r\n};\r\n\r\n/**\r\n * Builds the responses filters.\r\n *\r\n * /param surveyNames - The survey names.\r\n * /returns The `FilterConfig<SurveyResponseItem>[]` result.\r\n */\r\nexport const buildResponsesFilters = (surveyNames: string[]): FilterConfig<SurveyResponseItem>[] => [\r\n {\r\n id: 'survey',\r\n label: 'Survey',\r\n options: [{ value: 'all', label: 'All surveys' }, ...surveyNames.map((n) => ({ value: n, label: n }))],\r\n defaultValue: 'all',\r\n predicate: (row, v) => row.surveyName === v,\r\n },\r\n {\r\n id: 'category',\r\n label: 'NPS category',\r\n options: [{ value: 'all', label: 'All categories' }, ...NPS_CATEGORIES.map((c) => ({ value: c, label: c }))],\r\n defaultValue: 'all',\r\n predicate: (row, v) => row.npsCategory === v,\r\n },\r\n];\r\n\r\nexport const responsesColumns: ColumnDef<SurveyResponseItem>[] = [\r\n { key: 'userId', label: 'User', cellType: 'responseUser', sortable: true, minWidth: 200 },\r\n { key: 'surveyName', label: 'Survey', sortable: true, minWidth: 200 },\r\n {\r\n key: 'npsScore',\r\n label: 'NPS',\r\n cellType: 'npsScore',\r\n sortable: true,\r\n width: 90,\r\n sortFn: (a, b, d) => ((a.npsScore ?? -1) - (b.npsScore ?? -1)) * dir(d),\r\n },\r\n { key: 'npsCategory', label: 'Category', cellType: 'responseNpsCategory', sortable: true, width: 130 },\r\n { key: 'rating', label: 'Rating', cellType: 'responseRating', sortable: true, width: 120 },\r\n { key: 'responseText', label: 'Response', cellType: 'responseText', minWidth: 260 },\r\n {\r\n key: 'createdAt',\r\n label: 'Date',\r\n sortable: true,\r\n align: 'right',\r\n width: 130,\r\n sortFn: (a, b, d) => (at(a) - at(b)) * dir(d),\r\n },\r\n];\r\n\r\n\r\n\r\n\r\n","// src/modules/survey/Pages/Surveydetails/Surveydetails.tsx\r\nimport { DataTable } from '../../components/DataTable/DataTable';\r\nimport StatCard from '../../components/StatCard/StatCard';\r\nimport { Header } from '../../components/layout/Header';\r\nimport { Icon } from '../../components/ui/Icon';\r\nimport { useQuery } from '@tanstack/react-query';\r\nimport React, { useMemo } from 'react';\r\nimport { useNavigate, useParams } from 'react-router-dom';\r\nimport { useSurveyResponses } from '../../hooks/useSurveyResponses';\r\nimport { surveysApi } from '../../services/api/surveys.api';\r\nimport type { SurveyResponseItem } from '../../types/survey.types';\r\nimport styles from '../surveyPage.module.scss';\r\nimport {\r\n responsesColumns,\r\n responsesSearchConfig,\r\n responsesSortConfig,\r\n} from '../Responses/responsesTable.config';\r\nimport { Card } from '../../components/ui/Card';\r\n\r\n// this survey's table: same columns as Responses, minus the redundant \"Survey\" column\r\nconst detailColumns = responsesColumns.filter((c) => c.key !== 'surveyName');\r\nconst detailSearch = { ...responsesSearchConfig, placeholder: 'Search by user, response…', keys: ['userId', 'responseText'] as (keyof SurveyResponseItem)[] };\r\n\r\nconst fmtDate = (v?: string | null) => {\r\n if (!v) return '—';\r\n const d = new Date(v);\r\n return Number.isNaN(d.getTime())\r\n ? '—'\r\n : d.toLocaleDateString(undefined, { day: '2-digit', month: 'short', year: 'numeric' });\r\n};\r\n\r\nconst STATUS_STYLE: Record<string, string> = {\r\n active: 'text-[color:var(--th-success)]',\r\n draft: 'text-[color:var(--th-warning-soft)]',\r\n paused: 'text-[color:var(--th-warning-soft)]',\r\n closed: 'text-[color:var(--th-text-3)]',\r\n};\r\n\r\n/** Renders the survey details component. */\r\nexport const SurveyDetails: React.FC = () => {\r\n const navigate = useNavigate();\r\n const { surveyId } = useParams<{ surveyId: string }>();\r\n\r\n const { data: survey, isLoading } = useQuery({\r\n queryKey: ['survey', surveyId],\r\n queryFn: () => surveysApi.getById(surveyId as string),\r\n enabled: Boolean(surveyId),\r\n staleTime: 2 * 60 * 1000,\r\n });\r\n\r\n // optional extra insight for this survey (same query the Analytics page uses → shared cache)\r\n const { data: analytics } = useQuery({\r\n queryKey: ['survey-analytics'],\r\n queryFn: surveysApi.getAnalytics,\r\n staleTime: 2 * 60 * 1000,\r\n });\r\n const insight = useMemo(\r\n () => (Array.isArray(analytics) ? analytics : []).find((a) => a.surveyId === surveyId),\r\n [analytics, surveyId]\r\n );\r\n\r\n // responses for THIS survey only\r\n const resp = useSurveyResponses();\r\n const surveyResponses = useMemo(\r\n () => resp.items.filter((r) => r.surveyId === surveyId),\r\n [resp.items, surveyId]\r\n );\r\n\r\n const goBack = () => navigate('/app/all-surveys');\r\n\r\n const backButton = (\r\n <button\r\n type=\"button\"\r\n onClick={goBack}\r\n className=\"flex w-fit cursor-pointer items-center gap-1.5 text-[13px] text-[color:var(--th-text-3)] transition-colors hover:text-[color:var(--th-text-2)]\"\r\n >\r\n <Icon icon=\"ArrowLeft\" size={15} /> Back to surveys\r\n </button>\r\n );\r\n\r\n if (isLoading) {\r\n return (\r\n <div className={styles.wrapper}>\r\n {backButton}\r\n <p className=\"text-[13px] text-[color:var(--th-text-3)]\">Loading survey…</p>\r\n </div>\r\n );\r\n }\r\n\r\n if (!survey) {\r\n return (\r\n <div className={styles.wrapper}>\r\n {backButton}\r\n <Card className=\"p-8 text-center text-[13px] text-[color:var(--th-text-3)]\">\r\n Survey not found.\r\n </Card>\r\n </div>\r\n );\r\n }\r\n\r\n const pct = survey.target > 0 ? Math.min(Math.round((survey.responses / survey.target) * 100), 100) : 0;\r\n\r\n const info: [string, string][] = [\r\n ['Created by', survey.createdByName || '—'],\r\n ['Created', fmtDate(survey.createdAt)],\r\n ['Last updated', fmtDate(survey.updatedAt)],\r\n ['Ends', fmtDate(survey.endsAt)],\r\n ];\r\n\r\n return (\r\n <div className={styles.wrapper}>\r\n {backButton}\r\n\r\n <Header\r\n title={survey.name}\r\n subtitle={survey.description || 'Survey details'}\r\n primaryText=\"View Analytics\"\r\n primaryIcon=\"BarChart3\"\r\n onPrimaryClick={() => navigate(`/app/survey-analytics/${survey.id}`)}\r\n />\r\n\r\n <div className={styles.statsgrid}>\r\n <StatCard icon=\"Activity\" label=\"Status\" value={survey.status.charAt(0).toUpperCase() + survey.status.slice(1)} trendDirection=\"neutral\" color=\"#10b981\" />\r\n <StatCard icon=\"MessageSquare\" label=\"Responses\" value={survey.responses.toLocaleString()} trendDirection=\"neutral\" color=\"#7c3aed\" />\r\n <StatCard icon=\"Star\" label=\"NPS score\" value={survey.npsScore ?? '—'} trendDirection=\"neutral\" color=\"#f59e0b\" />\r\n <StatCard icon=\"HelpCircle\" label=\"Questions\" value={survey.questionCount.toLocaleString()} trendDirection=\"neutral\" color=\"#6366f1\" />\r\n </div>\r\n\r\n <div className={styles.cards}>\r\n <Card className=\"p-5\">\r\n <h2 className=\"mb-4 text-[14px] font-semibold text-white\">Overview</h2>\r\n\r\n <div className=\"mb-1.5 flex items-center justify-between text-[12px]\">\r\n <span className=\"text-[color:var(--th-text-3)]\">Response progress</span>\r\n <span className=\"font-mono tabular-nums text-[color:var(--th-text-1)]\">\r\n {survey.responses.toLocaleString()} / {survey.target.toLocaleString()} ({pct}%)\r\n </span>\r\n </div>\r\n <div className=\"mb-5 h-1.5 overflow-hidden rounded-full bg-[color:color-mix(in_srgb,var(--th-ov-base)_5%,transparent)]\">\r\n <div\r\n className={`h-full rounded-full ${pct >= 80 ? 'bg-[#4edea3]' : 'bg-[#7c3aed]'}`}\r\n style={{ width: `${pct}%` }}\r\n />\r\n </div>\r\n\r\n <dl className=\"space-y-2.5 text-[12.5px]\">\r\n <div className=\"flex justify-between gap-3\">\r\n <dt className=\"text-[color:var(--th-text-3)]\">Status</dt>\r\n <dd className={`capitalize ${STATUS_STYLE[survey.status] ?? ''}`}>{survey.status}</dd>\r\n </div>\r\n {info.map(([k, v]) => (\r\n <div key={k} className=\"flex justify-between gap-3\">\r\n <dt className=\"text-[color:var(--th-text-3)]\">{k}</dt>\r\n <dd className=\"text-right text-[color:var(--th-text-2)]\">{v}</dd>\r\n </div>\r\n ))}\r\n </dl>\r\n </Card>\r\n\r\n {insight && (\r\n <Card className=\"p-5\">\r\n <h2 className=\"mb-4 text-[14px] font-semibold text-white\">Insights</h2>\r\n <dl className=\"space-y-2.5 text-[12.5px]\">\r\n {[\r\n ['Completion rate', `${insight.completionRate ?? 0}%`],\r\n ['Avg completion time', insight.avgCompletionTime ?? '—'],\r\n ['Avg rating', (insight.averageRating ?? 0).toFixed(1)],\r\n ['Top theme', insight.topTheme ?? '—'],\r\n ['Needs improvement', insight.bottomTheme ?? '—'],\r\n ].map(([k, v]) => (\r\n <div key={k} className=\"flex justify-between gap-3\">\r\n <dt className=\"text-[color:var(--th-text-3)]\">{k}</dt>\r\n <dd className=\"text-right font-mono text-[color:var(--th-text-2)]\">{v}</dd>\r\n </div>\r\n ))}\r\n </dl>\r\n </Card>\r\n )}\r\n </div>\r\n\r\n <h2 className=\"text-[14px] font-semibold text-white\">\r\n Responses ({surveyResponses.length.toLocaleString()})\r\n </h2>\r\n <DataTable<SurveyResponseItem>\r\n currentPage=\"survey-details-responses\"\r\n columns={detailColumns}\r\n data={surveyResponses}\r\n totalCount={surveyResponses.length}\r\n isLoading={resp.isLoading}\r\n hasMore={resp.hasMore}\r\n onLoadMore={resp.loadMore}\r\n searchConfig={detailSearch}\r\n sortConfig={responsesSortConfig}\r\n rowHeight={64}\r\n stickyHeader\r\n emptyMessage=\"No responses for this survey yet.\"\r\n />\r\n </div>\r\n );\r\n};\r\n\r\nSurveyDetails.displayName = 'SurveyDetails';\r\n\r\n\r\n\r\n","// src/features/surveys/pages/SurveyTemplates.tsx\r\nimport { Header } from '../../components/layout/Header';\r\nimport { Icon } from '../../components/ui/Icon';\r\nimport { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';\r\nimport React, { useState } from 'react';\r\nimport { useNavigate } from 'react-router-dom';\r\nimport { surveysApi } from '../../services/api/surveys.api';\r\nimport type { SurveyTemplateItem } from '../../types/survey.types';\r\nimport styles from '../surveyPage.module.scss';\r\nimport { Card } from '../../components/ui/Card';\r\n\r\n/* ─── constants ─── */\r\nconst CATEGORY_STYLES: Record<string, string> = {\r\n Product: 'bg-[#7c3aed]/10 text-[color:var(--th-accent-soft)]',\r\n Loyalty: 'bg-[color:color-mix(in_srgb,var(--th-success)_10%,transparent)] text-[color:var(--th-success)]',\r\n UX: 'bg-[color:color-mix(in_srgb,var(--th-info-soft)_10%,transparent)] text-[color:var(--th-info-soft)]',\r\n Retention: 'bg-[color:color-mix(in_srgb,var(--th-warning-soft)_10%,transparent)] text-[color:var(--th-warning-soft)]',\r\n Revenue: 'bg-[color:color-mix(in_srgb,var(--th-danger-soft)_10%,transparent)] text-[color:var(--th-danger-soft)]',\r\n};\r\n\r\n/* ─── use-template modal ─── */\r\ninterface UseTemplateModalProps {\r\n template: SurveyTemplateItem;\r\n onClose: () => void;\r\n}\r\n\r\nconst UseTemplateModal = ({ template, onClose }: UseTemplateModalProps) => {\r\n const navigate = useNavigate();\r\n const queryClient = useQueryClient();\r\n const [name, setName] = useState(template.name);\r\n const [target, setTarget] = useState(500);\r\n\r\n const mutation = useMutation({\r\n mutationFn: () =>\r\n surveysApi.useTemplate(template.id, { name, targetResponses: target }),\r\n onSuccess: () => {\r\n queryClient.invalidateQueries({ queryKey: ['surveys'] });\r\n onClose();\r\n navigate('/analytics/surveys');\r\n },\r\n });\r\n\r\n const handleBackdrop = (e: React.MouseEvent<HTMLDivElement>) => {\r\n if (e.target === e.currentTarget) onClose();\r\n };\r\n\r\n return (\r\n <div\r\n className=\"fixed inset-0 z-50 flex items-center justify-center\"\r\n onClick={handleBackdrop}\r\n >\r\n <div className=\"absolute inset-0 bg-black/60 backdrop-blur-sm\" />\r\n\r\n <Card className=\"relative p-8 w-full max-w-md mx-4 shadow-2xl\">\r\n <button\r\n onClick={onClose}\r\n className=\"absolute top-4 right-4 p-1.5 rounded-lg hover:bg-[color:color-mix(in_srgb,var(--th-ov-base)_5%,transparent)]\r\n text-[color:var(--th-text-3)] hover:text-[color:var(--th-text-1)] transition-colors\"\r\n >\r\n <Icon icon=\"X\" size={16} />\r\n </button>\r\n\r\n <div className=\"flex items-center gap-3 mb-6\">\r\n <div className=\"w-10 h-10 rounded-xl bg-[#7c3aed]/20 flex items-center justify-center\">\r\n <Icon icon=\"ClipboardCopy\" size={18} className=\"text-[color:var(--th-accent-soft)]\" />\r\n </div>\r\n <div>\r\n <h2 className=\"text-[16px] font-semibold text-white\">\r\n Use Template\r\n </h2>\r\n <p className=\"text-[12px] text-[color:var(--th-text-3)]\">{template.name}</p>\r\n </div>\r\n </div>\r\n\r\n <div className=\"space-y-4\">\r\n <div>\r\n <label className=\"block text-[12px] text-[color:var(--th-text-3)] mb-1.5\">\r\n Survey Name\r\n </label>\r\n <input\r\n value={name}\r\n onChange={(e) => setName(e.target.value)}\r\n placeholder=\"My survey\"\r\n className=\"w-full px-3.5 py-2.5 rounded-lg bg-[color:color-mix(in_srgb,var(--th-ov-base)_5%,transparent)] border border-[color:color-mix(in_srgb,var(--th-ov-base)_8%,transparent)]\r\n text-[13px] text-[color:var(--th-text-1)] placeholder:text-[color:color-mix(in_srgb,var(--th-text-3)_60%,transparent)]\r\n focus:border-[#7c3aed] outline-none transition-colors\"\r\n />\r\n </div>\r\n <div>\r\n <label className=\"block text-[12px] text-[color:var(--th-text-3)] mb-1.5\">\r\n Target Responses\r\n </label>\r\n <input\r\n type=\"number\"\r\n value={target}\r\n onChange={(e) => setTarget(parseInt(e.target.value) || 500)}\r\n className=\"w-full px-3.5 py-2.5 rounded-lg bg-[color:color-mix(in_srgb,var(--th-ov-base)_5%,transparent)] border border-[color:color-mix(in_srgb,var(--th-ov-base)_8%,transparent)]\r\n text-[13px] text-[color:var(--th-text-1)]\r\n focus:border-[#7c3aed] outline-none transition-colors\"\r\n />\r\n </div>\r\n </div>\r\n\r\n <div className=\"flex gap-3 mt-6\">\r\n <button\r\n onClick={onClose}\r\n className=\"flex-1 py-2.5 rounded-lg bg-[color:color-mix(in_srgb,var(--th-ov-base)_5%,transparent)] hover:bg-[color:color-mix(in_srgb,var(--th-ov-base)_10%,transparent)]\r\n text-[color:var(--th-text-3)] text-[13px] font-medium transition-colors\"\r\n >\r\n Cancel\r\n </button>\r\n <button\r\n onClick={() => mutation.mutate()}\r\n disabled={!name.trim() || mutation.isPending}\r\n className=\"flex-1 py-2.5 rounded-lg bg-[#7c3aed] hover:bg-[#8b4df0]\r\n disabled:opacity-40 text-white text-[13px] font-medium\r\n transition-colors flex items-center justify-center gap-2\"\r\n >\r\n {mutation.isPending && (\r\n <Icon icon=\"Loader2\" size={14} className=\"animate-spin\" />\r\n )}\r\n {mutation.isPending ? 'Creating…' : 'Create Survey'}\r\n </button>\r\n </div>\r\n </Card>\r\n </div>\r\n );\r\n};\r\n\r\n/* ─── template card ─── */\r\nconst TemplateCard = ({\r\n t,\r\n onUse,\r\n}: {\r\n t: SurveyTemplateItem;\r\n onUse: (t: SurveyTemplateItem) => void;\r\n}) => (\r\n <Card className=\"p-5 hover:border-[#7c3aed]/30 transition-all group\">\r\n <div className=\"flex items-start justify-between mb-3\">\r\n <div className=\"flex-1 min-w-0 pr-3\">\r\n <h3 className=\"text-[14px] font-semibold text-white group-hover:text-[color:var(--th-accent-soft)] transition-colors\">\r\n {t.name}\r\n </h3>\r\n <p className=\"text-[12px] text-[color:var(--th-text-3)] mt-1 leading-relaxed\">\r\n {t.description}\r\n </p>\r\n </div>\r\n {t.isSystem && (\r\n <span\r\n className=\"shrink-0 text-[9px] px-1.5 py-0.5 rounded\r\n bg-[#7c3aed]/20 text-[color:var(--th-accent-soft)] font-medium\"\r\n >\r\n OFFICIAL\r\n </span>\r\n )}\r\n </div>\r\n\r\n <div className=\"flex items-center gap-3 mb-5 text-[11px] text-[color:var(--th-text-3)]\">\r\n <span className=\"flex items-center gap-1\">\r\n <Icon icon=\"FileText\" size={11} />\r\n {t.questionCount ?? 0} questions\r\n </span>\r\n {t.category && (\r\n <span\r\n className={`px-2 py-0.5 rounded text-[10px] font-medium ${CATEGORY_STYLES[t.category] ?? 'bg-[color:color-mix(in_srgb,var(--th-ov-base)_5%,transparent)] text-[color:var(--th-text-3)]'\r\n }`}\r\n >\r\n {t.category}\r\n </span>\r\n )}\r\n </div>\r\n\r\n <button\r\n onClick={() => onUse(t)}\r\n className=\"flex items-center gap-2 px-4 py-2 rounded-lg\r\n bg-[#7c3aed] hover:bg-[#8b4df0]\r\n text-white text-[12px] font-medium transition-colors\"\r\n >\r\n <Icon icon=\"ClipboardCopy\" size={12} />\r\n Use Template\r\n </button>\r\n </Card>\r\n);\r\n\r\n/* ─── skeleton ─── */\r\nconst Skeleton = () => (\r\n <div className={styles.cards}>\r\n {Array.from({ length: 6 }).map((_, i) => (\r\n <Card key={i} className=\"p-5 animate-pulse h-44\">{null}</Card>\r\n ))}\r\n </div>\r\n);\r\n\r\n/* ─── page ─── */\r\n/** Renders the survey templates component. */\r\nexport const SurveyTemplates = () => {\r\n const [activeCategory, setActiveCategory] = useState<string | null>(null);\r\n const [selected, setSelected] = useState<SurveyTemplateItem | null>(null);\r\n\r\n const {\r\n data: templates,\r\n isLoading,\r\n isError,\r\n refetch,\r\n } = useQuery({\r\n queryKey: ['survey-templates'],\r\n queryFn: surveysApi.getTemplates,\r\n staleTime: 5 * 60 * 1000,\r\n });\r\n\r\n /* ── bulletproof list extraction ── */\r\n const list: SurveyTemplateItem[] = Array.isArray(templates)\r\n ? templates.filter((t): t is SurveyTemplateItem => Boolean(t?.id))\r\n : [];\r\n\r\n const categories = [\r\n ...new Set(list.map((t) => t.category).filter(Boolean) as string[]),\r\n ];\r\n\r\n const filtered = activeCategory\r\n ? list.filter((t) => t.category === activeCategory)\r\n : list;\r\n\r\n return (\r\n <div className={styles.wrapper}>\r\n <Header\r\n title=\"Survey Templates\"\r\n subtitle=\"Analytics · pre-built templates to get started quickly\"\r\n />\r\n\r\n {/* category tabs */}\r\n <div className=\"flex flex-wrap gap-2\">\r\n {['All', ...categories].map((cat) => {\r\n const isActive =\r\n cat === 'All' ? !activeCategory : activeCategory === cat;\r\n return (\r\n <button\r\n key={cat}\r\n onClick={() => setActiveCategory(cat === 'All' ? null : cat)}\r\n className={`px-3.5 py-1.5 rounded-lg text-[12px] font-medium transition-colors ${isActive\r\n ? 'bg-[#7c3aed] text-white'\r\n : 'bg-[color:color-mix(in_srgb,var(--th-ov-base)_5%,transparent)] text-[color:var(--th-text-3)] hover:text-[color:var(--th-text-1)] hover:bg-[color:color-mix(in_srgb,var(--th-ov-base)_10%,transparent)]'\r\n }`}\r\n >\r\n {cat}\r\n </button>\r\n );\r\n })}\r\n </div>\r\n\r\n {/* content */}\r\n {isLoading ? (\r\n <Skeleton />\r\n ) : isError ? (\r\n <Card className=\"p-20 text-center space-y-3\">\r\n <Icon\r\n icon=\"AlertTriangle\"\r\n size={40}\r\n className=\"text-[color:var(--th-danger-soft)] mx-auto\"\r\n />\r\n <p className=\"text-[15px] text-[color:var(--th-text-3)]\">Failed to load templates</p>\r\n <button\r\n onClick={() => refetch()}\r\n className=\"text-[13px] text-[#7c3aed] hover:text-[#8b4df0] underline\"\r\n >\r\n Retry\r\n </button>\r\n </Card>\r\n ) : filtered.length === 0 ? (\r\n <Card className=\"p-20 text-center\">\r\n <Icon\r\n icon=\"FileText\"\r\n size={40}\r\n className=\"text-[color:var(--th-text-3)] mx-auto mb-4\"\r\n />\r\n <p className=\"text-[15px] text-[color:var(--th-text-3)]\">\r\n {activeCategory\r\n ? 'No templates in this category'\r\n : 'No templates available yet'}\r\n </p>\r\n </Card>\r\n ) : (\r\n <div className={styles.cards}>\r\n {filtered.map((t) => (\r\n <TemplateCard key={t.id} t={t} onUse={setSelected} />\r\n ))}\r\n </div>\r\n )}\r\n\r\n {/* modal */}\r\n {selected && (\r\n <UseTemplateModal\r\n template={selected}\r\n onClose={() => setSelected(null)}\r\n />\r\n )}\r\n </div>\r\n );\r\n};\r\n\r\n\r\n\r\n","// src/modules/survey/Pages/Responses/Responses.tsx\r\nimport StatCard from '../../components/StatCard/StatCard';\r\nimport { DataTable } from '../../components/DataTable/DataTable';\r\nimport { Header } from '../../components/layout/Header';\r\nimport React, { useMemo } from 'react';\r\nimport { useSurveyResponses } from '../../hooks/useSurveyResponses';\r\nimport type { SurveyResponseItem } from '../../types/survey.types';\r\nimport styles from '../surveyPage.module.scss';\r\nimport {\r\n buildResponsesFilters,\r\n responsesColumns,\r\n responsesSearchConfig,\r\n responsesSortConfig,\r\n} from './responsesTable.config';\r\n\r\n/** Renders the responses component. */\r\nexport const Responses: React.FC = () => {\r\n const { items, totalCount, isLoading, hasMore, loadMore } = useSurveyResponses();\r\n\r\n const surveyNames = useMemo(() => Array.from(new Set(items.map((r) => r.surveyName))).sort(), [items]);\r\n const filters = useMemo(() => buildResponsesFilters(surveyNames), [surveyNames]);\r\n\r\n const stats = useMemo(() => {\r\n const count = (c: SurveyResponseItem['npsCategory']) => items.filter((r) => r.npsCategory === c).length;\r\n return { promoters: count('promoter'), passives: count('passive'), detractors: count('detractor') };\r\n }, [items]);\r\n\r\n return (\r\n <div className={styles.wrapper}>\r\n <Header title=\"Responses\" subtitle=\"Analytics · individual survey responses\" />\r\n\r\n <div className={styles.statsgrid}>\r\n <StatCard icon=\"MessageSquare\" label=\"Total responses\" value={totalCount.toLocaleString()} trendDirection=\"neutral\" color=\"#7c3aed\" />\r\n <StatCard icon=\"ThumbsUp\" label=\"Promoters\" value={stats.promoters.toLocaleString()} trendDirection=\"neutral\" color=\"#4edea3\" />\r\n <StatCard icon=\"Minus\" label=\"Passives\" value={stats.passives.toLocaleString()} trendDirection=\"neutral\" color=\"#ffcc6b\" />\r\n <StatCard icon=\"ThumbsDown\" label=\"Detractors\" value={stats.detractors.toLocaleString()} trendDirection=\"neutral\" color=\"#ffb4ab\" />\r\n </div>\r\n\r\n <DataTable<SurveyResponseItem>\r\n currentPage=\"survey-responses\"\r\n columns={responsesColumns}\r\n data={items}\r\n totalCount={totalCount}\r\n isLoading={isLoading}\r\n hasMore={hasMore}\r\n onLoadMore={loadMore}\r\n searchConfig={responsesSearchConfig}\r\n filters={filters}\r\n sortConfig={responsesSortConfig}\r\n /* ROW CLICK → Survey Analytics page for that survey */\r\n rowClickBehavior={{ type: 'navigate', path: (r) => `/app/survey-analytics/${r.surveyId}` }}\r\n rowHeight={64}\r\n stickyHeader\r\n height=\"clac(100vh - 250px)\"\r\n emptyMessage=\"No responses yet.\"\r\n />\r\n </div>\r\n );\r\n};\r\n\r\nexport default Responses;\r\n\r\n\r\n\r\n","// src/modules/survey/Pages/NPStracker/NPStracker.tsx\r\nimport StatCard from '../../components/StatCard/StatCard';\r\nimport { Header } from '../../components/layout/Header';\r\nimport { useQuery } from '@tanstack/react-query';\r\nimport React from 'react';\r\nimport { Card } from '../../components/ui/Card';\r\nimport { surveysApi } from '../../services/api/surveys.api';\r\nimport type { NpsTrendPoint } from '../../types/survey.types';\r\nimport styles from '../surveyPage.module.scss';\r\n\r\nconst barColor = (score: number) => (score >= 70 ? '#4edea3' : score >= 50 ? '#7c3aed' : '#ffb4ab');\r\n\r\n/** Renders the NPS tracker component. */\r\nexport const NPSTracker: React.FC = () => {\r\n const { data, isLoading } = useQuery({\r\n queryKey: ['nps-summary'],\r\n queryFn: () => surveysApi.getNps(12),\r\n staleTime: 5 * 60 * 1000,\r\n });\r\n\r\n const delta = data?.scoreDelta ?? 0;\r\n const trend: NpsTrendPoint[] = Array.isArray(data?.trend) ? data!.trend : [];\r\n const pct = (v?: number) => (data ? `${v ?? 0}%` : '—');\r\n\r\n return (\r\n <div className={styles.wrapper}>\r\n <Header title=\"NPS Tracker\" subtitle=\"Analytics · Net Promoter Score over time.\" />\r\n\r\n <div className={styles.statsgrid}>\r\n <StatCard\r\n icon=\"Gauge\"\r\n label=\"Current NPS\"\r\n value={data ? String(data.currentScore ?? 0) : '—'}\r\n trendDirection={delta > 0 ? 'up' : delta < 0 ? 'down' : 'neutral'}\r\n color=\"#adc6ff\"\r\n />\r\n <StatCard icon=\"ThumbsUp\" label=\"Promoters\" value={pct(data?.promotersPercent)} trendDirection=\"neutral\" color=\"#4edea3\" />\r\n <StatCard icon=\"Activity\" label=\"Passives\" value={pct(data?.passivesPercent)} trendDirection=\"neutral\" color=\"#ffcc6b\" />\r\n <StatCard icon=\"ThumbsDown\" label=\"Detractors\" value={pct(data?.detractorsPercent)} trendDirection=\"neutral\" color=\"#ffb4ab\" />\r\n </div>\r\n\r\n <Card className=\"p-6\">\r\n <h2 className=\"mb-6 text-[16px] font-semibold text-white\">\r\n NPS Trend\r\n {data && (\r\n <span className=\"ml-3 text-[11px] font-normal text-[color:var(--th-text-3)]\">\r\n {delta >= 0 ? '+' : ''}\r\n {delta} from prior period\r\n </span>\r\n )}\r\n </h2>\r\n\r\n {isLoading ? (\r\n <div className=\"h-48 animate-pulse rounded-lg bg-[color:color-mix(in_srgb,var(--th-ov-base)_5%,transparent)]\" />\r\n ) : (\r\n <div className=\"flex h-48 items-end gap-3\">\r\n {trend.map((d, i) => (\r\n <div key={d?.period ?? i} className=\"flex flex-1 flex-col items-center gap-1\">\r\n <span className=\"text-[10px] tabular-nums text-[color:var(--th-text-3)]\">{d?.score ?? 0}</span>\r\n <div className=\"relative w-full\" style={{ height: 140 }}>\r\n <div\r\n className=\"absolute bottom-0 w-full rounded-t-sm\"\r\n style={{\r\n height: `${Math.max(d?.score ?? 0, 5)}%`,\r\n backgroundColor: barColor(d?.score ?? 0),\r\n opacity: 0.4 + (i / Math.max(trend.length, 1)) * 0.6,\r\n }}\r\n />\r\n </div>\r\n <span className=\"text-[9px] text-[color:var(--th-text-3)]\">{d?.period?.split(' ')[1] ?? ''}</span>\r\n </div>\r\n ))}\r\n </div>\r\n )}\r\n </Card>\r\n </div>\r\n );\r\n};\r\n\r\n\r\n\r\n","import type { ColumnDef, FilterConfig, SearchConfig, SortConfig } from '../../components/DataTable/types';\r\nimport type { SurveyAnalyticsRow } from '../../types/survey.types';\r\n\r\n/* Tabs / Search / Filter / Sort / Columns for the Survey Analytics table.\r\n cellType values must match cells/SurveyCells.tsx registrations. */\r\n\r\n/* ── health rule used by the tabs + \"Need attention\" stat ── */\r\n/**\r\n * Helper for needs attention.\r\n *\r\n * /param r - The r.\r\n * /returns The result.\r\n */\r\nexport const needsAttention = (r: SurveyAnalyticsRow) =>\r\n (r.npsScore ?? 0) < 50 || (r.completionRate ?? 0) < 70;\r\n\r\n/** Allowed values for analytics tab key. */\r\nexport type AnalyticsTabKey = 'all' | 'healthy' | 'attention';\r\n\r\n/**\r\n * Builds the analytics tabs.\r\n *\r\n * /param rows - The rows.\r\n * /returns The result.\r\n */\r\nexport const buildAnalyticsTabs = (rows: SurveyAnalyticsRow[]) => {\r\n const attention = rows.filter(needsAttention).length;\r\n return [\r\n { key: 'all', label: 'All', count: rows.length },\r\n { key: 'healthy', label: 'Healthy', count: rows.length - attention },\r\n { key: 'attention', label: 'Needs attention', count: attention },\r\n ];\r\n};\r\n\r\n/**\r\n * Filters by tab.\r\n *\r\n * /param rows - The rows.\r\n * /param tab - The tab.\r\n * /returns The result.\r\n */\r\nexport const filterByTab = (rows: SurveyAnalyticsRow[], tab: string) =>\r\n tab === 'healthy' ? rows.filter((r) => !needsAttention(r))\r\n : tab === 'attention' ? rows.filter(needsAttention)\r\n : rows;\r\n\r\n/* ── SEARCH ── */\r\nexport const analyticsSearchConfig: SearchConfig<SurveyAnalyticsRow> = {\r\n placeholder: 'Search surveys, themes…',\r\n keys: ['surveyName', 'topTheme', 'bottomTheme'],\r\n debounceMs: 150,\r\n};\r\n\r\n/* ── SORT ── */\r\nexport const analyticsSortConfig: SortConfig<SurveyAnalyticsRow> = {\r\n defaultId: 'responses',\r\n options: [\r\n { id: 'responses', label: 'Most responses', comparator: (a, b) => (b.totalResponses ?? 0) - (a.totalResponses ?? 0) },\r\n { id: 'nps', label: 'NPS: High → Low', comparator: (a, b) => (b.npsScore ?? -1) - (a.npsScore ?? -1) },\r\n { id: 'completion', label: 'Completion: High → Low', comparator: (a, b) => (b.completionRate ?? 0) - (a.completionRate ?? 0) },\r\n { id: 'name', label: 'Name: A–Z', comparator: (a, b) => a.surveyName.localeCompare(b.surveyName) },\r\n ],\r\n};\r\n\r\n/* ── FILTERS ── */\r\nexport const analyticsFilters: FilterConfig<SurveyAnalyticsRow>[] = [\r\n {\r\n id: 'nps',\r\n label: 'NPS',\r\n options: [\r\n { value: 'all', label: 'All' },\r\n { value: 'great', label: '70+' },\r\n { value: 'ok', label: '50–69' },\r\n { value: 'low', label: 'Below 50' },\r\n ],\r\n defaultValue: 'all',\r\n predicate: (r, v) => {\r\n const n = r.npsScore ?? -1;\r\n return v === 'great' ? n >= 70 : v === 'ok' ? n >= 50 && n < 70 : v === 'low' ? n < 50 : true;\r\n },\r\n },\r\n {\r\n id: 'completion',\r\n label: 'Completion',\r\n options: [\r\n { value: 'all', label: 'All' },\r\n { value: 'high', label: '80%+' },\r\n { value: 'low', label: 'Below 70%' },\r\n ],\r\n defaultValue: 'all',\r\n predicate: (r, v) => {\r\n const c = r.completionRate ?? 0;\r\n return v === 'high' ? c >= 80 : v === 'low' ? c < 70 : true;\r\n },\r\n },\r\n];\r\n\r\n/* ── COLUMNS ── */\r\nexport const analyticsColumns: ColumnDef<SurveyAnalyticsRow>[] = [\r\n {\r\n key: 'surveyName', label: 'Survey', cellType: 'analyticsSurvey', sortable: true, minWidth: 260,\r\n sortFn: (a, b, d) => a.surveyName.localeCompare(b.surveyName) * (d === 'asc' ? 1 : -1),\r\n },\r\n {\r\n key: 'totalResponses', label: 'Responses', sortable: true, width: 120,\r\n sortFn: (a, b, d) => ((a.totalResponses ?? 0) - (b.totalResponses ?? 0)) * (d === 'asc' ? 1 : -1),\r\n },\r\n {\r\n key: 'completionRate', label: 'Completion', cellType: 'analyticsCompletion', sortable: true, width: 150,\r\n sortFn: (a, b, d) => ((a.completionRate ?? 0) - (b.completionRate ?? 0)) * (d === 'asc' ? 1 : -1),\r\n },\r\n { key: 'avgCompletionTime', label: 'Avg time', width: 110 },\r\n {\r\n key: 'npsScore', label: 'NPS', cellType: 'npsScore', sortable: true, width: 90,\r\n sortFn: (a, b, d) => ((a.npsScore ?? -1) - (b.npsScore ?? -1)) * (d === 'asc' ? 1 : -1),\r\n },\r\n {\r\n key: 'averageRating', label: 'Rating', cellType: 'analyticsRating', sortable: true, width: 100,\r\n sortFn: (a, b, d) => ((a.averageRating ?? 0) - (b.averageRating ?? 0)) * (d === 'asc' ? 1 : -1),\r\n },\r\n { key: 'topTheme', label: 'Top theme', minWidth: 160 },\r\n { key: 'bottomTheme', label: 'Needs improvement', minWidth: 160 },\r\n];\r\n\r\n\r\n\r\n\r\n","// src/modules/survey/Pages/Surveyanalytics/Surveyanalytics.tsx\r\nimport StatCard from '../../components/StatCard/StatCard';\r\nimport { DataTable } from '../../components/DataTable/DataTable';\r\nimport { Header } from '../../components/layout/Header';\r\nimport { Icon } from '../../components/ui/Icon';\r\nimport { useQuery } from '@tanstack/react-query';\r\nimport React, { useEffect, useMemo, useState } from 'react';\r\nimport { useNavigate, useParams } from 'react-router-dom';\r\nimport { Card } from '../../components/ui/Card';\r\nimport { surveysApi } from '../../services/api/surveys.api';\r\nimport type { SurveyAnalyticsRow } from '../../types/survey.types';\r\nimport styles from '../surveyPage.module.scss';\r\nimport {\r\n analyticsColumns,\r\n analyticsFilters,\r\n analyticsSearchConfig,\r\n analyticsSortConfig,\r\n buildAnalyticsTabs,\r\n filterByTab,\r\n needsAttention,\r\n} from './analyticsTable.config';\r\n\r\n/** Renders the survey analytics component. */\r\nexport const SurveyAnalytics: React.FC = () => {\r\n const navigate = useNavigate();\r\n const { surveyId } = useParams<{ surveyId?: string }>();\r\n\r\n const { data, isLoading } = useQuery({\r\n queryKey: ['survey-analytics'],\r\n queryFn: surveysApi.getAnalytics,\r\n staleTime: 2 * 60 * 1000,\r\n });\r\n\r\n const rows: SurveyAnalyticsRow[] = useMemo(\r\n () =>\r\n (Array.isArray(data) ? data : [])\r\n .filter((s) => Boolean(s?.surveyId))\r\n .map((s) => ({ ...s, id: s.surveyId })),\r\n [data]\r\n );\r\n\r\n const [tab, setTab] = useState('all');\r\n // arriving from a Responses row pre-selects that survey in the detail panel\r\n const [activeId, setActiveId] = useState<string | null>(surveyId ?? null);\r\n useEffect(() => setActiveId(surveyId ?? null), [surveyId]);\r\n\r\n const tabs = useMemo(() => buildAnalyticsTabs(rows), [rows]);\r\n const tabRows = useMemo(() => filterByTab(rows, tab), [rows, tab]);\r\n const active = useMemo(() => rows.find((r) => r.id === activeId), [rows, activeId]);\r\n\r\n /* ── stats ── */\r\n const stats = useMemo(() => {\r\n const totalResp = rows.reduce((a, r) => a + (r.totalResponses ?? 0), 0);\r\n const avgCompletion = rows.length\r\n ? Math.round(rows.reduce((a, r) => a + (r.completionRate ?? 0), 0) / rows.length)\r\n : null;\r\n return { totalResp, avgCompletion, attention: rows.filter(needsAttention).length };\r\n }, [rows]);\r\n\r\n const dash = (v: string | number | null) => (isLoading || v === null ? '—' : String(v));\r\n\r\n return (\r\n <div className={styles.wrapper}>\r\n {surveyId && (\r\n <button\r\n type=\"button\"\r\n onClick={() => navigate('/app/responses')}\r\n className=\"flex w-fit cursor-pointer items-center gap-1.5 text-[13px] text-[color:var(--th-text-3)] transition-colors hover:text-[color:var(--th-text-2)]\"\r\n >\r\n <Icon icon=\"ArrowLeft\" size={15} /> Back to responses\r\n </button>\r\n )}\r\n\r\n <Header title=\"Survey Analytics\" subtitle=\"Aggregated survey insights and trends across your surveys.\" />\r\n\r\n <div className={styles.statsgrid}>\r\n <StatCard icon=\"BarChart3\" label=\"Surveys\" value={dash(rows.length)} trendDirection=\"neutral\" color=\"#f59e0b\" />\r\n <StatCard icon=\"AlertTriangle\" label=\"Need attention\" value={dash(stats.attention)} trendDirection=\"neutral\" color=\"#ef4444\" />\r\n <StatCard icon=\"MessageSquare\" label=\"Total responses\" value={dash(stats.totalResp.toLocaleString())} trendDirection=\"neutral\" color=\"#6366f1\" />\r\n <StatCard icon=\"CheckCircle2\" label=\"Avg completion\" value={dash(stats.avgCompletion === null ? null : `${stats.avgCompletion}%`)} trendDirection=\"neutral\" color=\"#10b981\" />\r\n </div>\r\n\r\n <div className={styles.split}>\r\n <div className={styles.main}>\r\n <DataTable<SurveyAnalyticsRow>\r\n currentPage=\"survey-analytics\"\r\n columns={analyticsColumns}\r\n data={tabRows}\r\n totalCount={tabRows.length}\r\n isLoading={isLoading}\r\n tabs={tabs}\r\n activeTab={tab}\r\n onTabChange={setTab}\r\n searchConfig={analyticsSearchConfig}\r\n filters={analyticsFilters}\r\n sortConfig={analyticsSortConfig}\r\n rowClickBehavior={{ type: 'callback', handler: (r) => setActiveId(r.id) }}\r\n rowHeight={64}\r\n stickyHeader\r\n height=\"calc(100vh - 250px)\"\r\n emptyMessage={surveyId ? 'No analytics for this survey yet.' : 'No analytics data yet.'}\r\n />\r\n </div>\r\n\r\n {active && (\r\n <aside className={styles.detail}>\r\n <Card className=\"p-5\">\r\n <div className=\"flex items-start justify-between gap-3\">\r\n <h2 className=\"text-[15px] font-semibold text-white\">{active.surveyName}</h2>\r\n <button\r\n type=\"button\"\r\n onClick={() => setActiveId(null)}\r\n className=\"cursor-pointer text-[color:var(--th-text-3)] hover:text-[color:var(--th-text-1)]\"\r\n >\r\n ✕\r\n </button>\r\n </div>\r\n\r\n <dl className=\"mt-4 space-y-2.5 text-[12.5px]\">\r\n {[\r\n ['Responses', (active.totalResponses ?? 0).toLocaleString()],\r\n ['Completion', `${active.completionRate ?? 0}%`],\r\n ['Avg time', active.avgCompletionTime ?? '—'],\r\n ['NPS', active.npsScore != null ? String(active.npsScore) : '—'],\r\n ['Avg rating', (active.averageRating ?? 0).toFixed(1)],\r\n ].map(([k, v]) => (\r\n <div key={k} className=\"flex justify-between gap-3\">\r\n <dt className=\"text-[color:var(--th-text-3)]\">{k}</dt>\r\n <dd className=\"text-right font-mono text-[color:var(--th-text-2)]\">{v}</dd>\r\n </div>\r\n ))}\r\n </dl>\r\n\r\n <div className=\"mt-4 rounded-xl border border-[color:color-mix(in_srgb,var(--th-success)_10%,transparent)] bg-[color:color-mix(in_srgb,var(--th-success)_4%,transparent)] p-3.5\">\r\n <div className=\"mb-1.5 flex items-center gap-2\">\r\n <Icon icon=\"ThumbsUp\" size={13} className=\"text-[color:var(--th-success)]\" />\r\n <span className=\"text-[11.5px] font-semibold text-[color:var(--th-success)]\">Top Theme</span>\r\n </div>\r\n <p className=\"text-[13px] text-[color:var(--th-text-1)]\">{active.topTheme ?? '—'}</p>\r\n </div>\r\n <div className=\"mt-3 rounded-xl border border-[color:color-mix(in_srgb,var(--th-danger-soft)_10%,transparent)] bg-[color:color-mix(in_srgb,var(--th-danger-soft)_4%,transparent)] p-3.5\">\r\n <div className=\"mb-1.5 flex items-center gap-2\">\r\n <Icon icon=\"ThumbsDown\" size={13} className=\"text-[color:var(--th-danger-soft)]\" />\r\n <span className=\"text-[11.5px] font-semibold text-[color:var(--th-danger-soft)]\">Needs Improvement</span>\r\n </div>\r\n <p className=\"text-[13px] text-[color:var(--th-text-1)]\">{active.bottomTheme ?? '—'}</p>\r\n </div>\r\n </Card>\r\n </aside>\r\n )}\r\n </div>\r\n </div>\r\n );\r\n};\r\n\r\n\r\n\r\n"],"names":["l","n","p","q","r","t","u","v","w","x","y","z","A","a","B","C","D","E","b","e","F","G","H","I","J","K","L","M","d","c","k","h","g","f","m","N","O","escape","P","Q","R","S","T","V","W","X","react_production_min","ReactVersion","REACT_ELEMENT_TYPE","REACT_PORTAL_TYPE","REACT_FRAGMENT_TYPE","REACT_STRICT_MODE_TYPE","REACT_PROFILER_TYPE","REACT_PROVIDER_TYPE","REACT_CONTEXT_TYPE","REACT_FORWARD_REF_TYPE","REACT_SUSPENSE_TYPE","REACT_SUSPENSE_LIST_TYPE","REACT_MEMO_TYPE","REACT_LAZY_TYPE","REACT_OFFSCREEN_TYPE","MAYBE_ITERATOR_SYMBOL","FAUX_ITERATOR_SYMBOL","getIteratorFn","maybeIterable","maybeIterator","ReactCurrentDispatcher","ReactCurrentBatchConfig","ReactCurrentActQueue","ReactCurrentOwner","ReactDebugCurrentFrame","currentExtraStackFrame","setExtraStackFrame","stack","impl","enableScopeAPI","enableCacheElement","enableTransitionTracing","enableLegacyHidden","enableDebugTracing","ReactSharedInternals","warn","format","_len","args","_key","printWarning","error","_len2","_key2","level","argsWithFormat","item","didWarnStateUpdateForUnmountedComponent","warnNoop","publicInstance","callerName","_constructor","componentName","warningKey","ReactNoopUpdateQueue","callback","completeState","partialState","assign","emptyObject","Component","props","context","updater","deprecatedAPIs","defineDeprecationWarning","methodName","info","fnName","ComponentDummy","PureComponent","pureComponentPrototype","createRef","refObject","isArrayImpl","isArray","typeName","value","hasToStringTag","type","willCoercionThrow","testStringCoercion","checkKeyStringCoercion","getWrappedName","outerType","innerType","wrapperName","displayName","functionName","getContextName","getComponentNameFromType","provider","outerName","lazyComponent","payload","init","hasOwnProperty","RESERVED_PROPS","specialPropKeyWarningShown","specialPropRefWarningShown","didWarnAboutStringRefs","hasValidRef","config","getter","hasValidKey","defineKeyPropWarningGetter","warnAboutAccessingKey","defineRefPropWarningGetter","warnAboutAccessingRef","warnIfStringRefCannotBeAutoConverted","ReactElement","key","ref","self","source","owner","element","createElement","children","propName","childrenLength","childArray","i","defaultProps","cloneAndReplaceKey","oldElement","newKey","newElement","cloneElement","isValidElement","object","SEPARATOR","SUBSEPARATOR","escapeRegex","escaperLookup","escapedString","match","didWarnAboutMaps","userProvidedKeyEscapeRegex","escapeUserProvidedKey","text","getElementKey","index","mapIntoArray","array","escapedPrefix","nameSoFar","invokeCallback","_child","mappedChild","childKey","escapedChildKey","child","nextName","subtreeCount","nextNamePrefix","iteratorFn","iterableChildren","iterator","step","ii","childrenString","mapChildren","func","result","count","countChildren","forEachChildren","forEachFunc","forEachContext","toArray","onlyChild","createContext","defaultValue","hasWarnedAboutUsingNestedContextConsumers","hasWarnedAboutUsingConsumerProvider","hasWarnedAboutDisplayNameOnConsumer","Consumer","_Provider","_currentValue","_currentValue2","_threadCount","Uninitialized","Pending","Resolved","Rejected","lazyInitializer","ctor","thenable","moduleObject","resolved","rejected","pending","lazy","lazyType","propTypes","newDefaultProps","newPropTypes","forwardRef","render","elementType","ownName","name","REACT_MODULE_REFERENCE","isValidElementType","memo","compare","resolveDispatcher","dispatcher","useContext","Context","realContext","useState","initialState","useReducer","reducer","initialArg","useRef","initialValue","useEffect","create","deps","useInsertionEffect","useLayoutEffect","useCallback","useMemo","useImperativeHandle","useDebugValue","formatterFn","useTransition","useDeferredValue","useId","useSyncExternalStore","subscribe","getSnapshot","getServerSnapshot","disabledDepth","prevLog","prevInfo","prevWarn","prevError","prevGroup","prevGroupCollapsed","prevGroupEnd","disabledLog","disableLogs","reenableLogs","ReactCurrentDispatcher$1","prefix","describeBuiltInComponentFrame","ownerFn","reentry","componentFrameCache","PossiblyWeakMap","describeNativeComponentFrame","fn","construct","frame","control","previousPrepareStackTrace","previousDispatcher","Fake","sample","sampleLines","controlLines","s","_frame","syntheticFrame","describeFunctionComponentFrame","shouldConstruct","prototype","describeUnknownElementTypeFrameInDEV","loggedTypeFailures","ReactDebugCurrentFrame$1","setCurrentlyValidatingElement","checkPropTypes","typeSpecs","values","location","has","typeSpecName","error$1","err","ex","setCurrentlyValidatingElement$1","propTypesMisspellWarningShown","getDeclarationErrorAddendum","getSourceInfoErrorAddendum","fileName","lineNumber","getSourceInfoErrorAddendumForProps","elementProps","ownerHasKeyUseWarning","getCurrentComponentErrorInfo","parentType","parentName","validateExplicitKey","currentComponentErrorInfo","childOwner","validateChildKeys","node","validatePropTypes","_name","validateFragmentProps","fragment","keys","createElementWithValidation","validType","sourceInfo","typeString","didWarnAboutDeprecatedCreateFactory","createFactoryWithValidation","validatedFactory","cloneElementWithValidation","startTransition","scope","options","prevTransition","currentTransition","updatedFibersCount","didWarnAboutMessageChannel","enqueueTaskImpl","enqueueTask","task","requireString","nodeRequire","module","channel","actScopeDepth","didWarnNoAwaitAct","act","prevActScopeDepth","prevIsBatchingLegacy","queue","flushActQueue","popActScope","thenableResult","wasAwaited","resolve","reject","returnValue","recursivelyFlushAsyncActWork","_queue","_thenable","_thenable2","isFlushing","createElement$1","cloneElement$1","createFactory","Children","exports","reactModule","require$$0","require$$1","AllSurveys","Allsurvey","SurveyDetails","Surveydetails","CreateSurvey","Createsurvey","SurveyTemplates","Surveytemplates","Responses","Responses$1","NPSTracker","NPStracker","SurveyAnalytics","Surveyanalytics","SurveyRoutes","surveyNav","reactJsxRuntime_production_min","React","jsxDEV","maybeKey","ReactCurrentOwner$1","didWarnAboutKeySpread","jsxWithValidation","isStaticChildren","beforeExample","afterExample","jsxWithValidationStatic","jsxWithValidationDynamic","jsx","jsxs","reactJsxRuntime_development","jsxRuntimeModule","Icon","icon","size","label","paths","StatCard","trendDirection","color","_extends","Action","invariant","message","warning","cond","parsePath","path","parsedPath","hashIndex","searchIndex","ResultType","resolvePath","to","fromPathname","toPathname","search","hash","pathname","removeDoubleSlashes","resolvePathname","normalizeSearch","normalizeHash","relativePath","segments","segment","getInvalidPathError","char","field","dest","getPathContributingMatches","matches","getResolveToMatches","v7_relativeSplatPath","pathMatches","idx","resolveTo","toArg","routePathnames","locationPathname","isPathRelative","isEmptyPath","from","routePathnameIndex","toSegments","hasExplicitTrailingSlash","hasCurrentTrailingSlash","joinPaths","validMutationMethodsArr","validRequestMethodsArr","DataRouterContext","React.createContext","DataRouterStateContext","AwaitContext","NavigationContext","LocationContext","RouteContext","RouteErrorContext","useInRouterContext","React.useContext","useLocation","UNSAFE_invariant","navigateEffectWarning","useIsomorphicLayoutEffect","cb","React.useLayoutEffect","useNavigate","isDataRoute","useNavigateStable","useNavigateUnstable","dataRouterContext","basename","future","navigator","routePathnamesJson","UNSAFE_getResolveToMatches","activeRef","React.useRef","React.useCallback","UNSAFE_warning","useParams","routeMatch","DataRouterHook","DataRouterStateHook","getDataRouterConsoleError","hookName","useDataRouterContext","ctx","useRouteContext","route","useCurrentRouteId","thisRoute","router","id","asSurvey","row","asAnalytics","asResponse","str","num","STATUS","SurveyStatusCell","status","SurveyNameCell","description","npsScore","ResponseProgressCell","responses","target","pct","NpsScoreCell","cls","SurveyActionsCell","extra","actions","_a","NPS_CAT","ResponseUserCell","ResponseNpsCategoryCell","cat","ResponseRatingCell","rating","_","ResponseTextCell","AnalyticsSurveyCell","AnalyticsCompletionCell","AnalyticsRatingCell","registerSurveyCells","surveyCellRenderers","component","DataTable","columns","data","totalCount","isLoading","hasMore","onLoadMore","tabs","activeTab","onTabChange","controls","searchConfig","filters","selectable","selectedIds","onSelectionChange","rowClickBehavior","onRowClick","currentPage","onEditRow","onActionClick","sortBy","sortOrder","onSort","className","height","stickyHeader","emptyMessage","availableViews","CardRenderer","gridCols","navigate","setSearch","filterValues","setFilterValues","view","setView","localSort","setLocalSort","visibleColumns","column","activeSort","filteredRows","rows","query","filter","av","bv","toggleSelection","next","selectAll","checked","handleRowClick","gridStyle","tab","event","old","option","order","rowIndex","Cell","ConfirmModal","open","onClose","onConfirm","title","confirmLabel","confirmTone","requireConfirmText","typedText","setTypedText","canConfirm","Header","subtitle","primaryText","primaryIcon","onPrimaryClick","QueryClientContext","useQueryClient","queryClient","client","defaultTimeoutProvider","delay","timeoutId","intervalId","TimeoutManager","__privateAdd","_provider","_providerCalled","__privateGet","__privateSet","timeoutManager","systemSetTimeoutZero","isServer","noop","isValidTimeout","timeUntilStale","updatedAt","staleTime","resolveQueryValue","hashKey","queryKey","val","isPlainObject","hasOwn","replaceEqualDeep","depth","isPlainArray","aSize","bItems","bSize","copy","equalItems","aItem","bItem","shallowEqualObjects","o","hasObjectPrototype","objectPrototype","prot","replaceData","prevData","shouldThrowError","throwOnError","params","isServerFn","isServer$1","Subscribable","listener","FocusManager","_focused","_cleanup","_setup","onFocus","setup","focused","isFocused","focusManager","defaultScheduler","createNotifyManager","transactions","notifyFn","batchNotifyFn","scheduleFn","schedule","flush","originalQueue","notifyManager","OnlineManager","_online","onOnline","onlineListener","offlineListener","online","onlineManager","canFetch","networkMode","getNextPageParam","pages","pageParams","lastIndex","getPreviousPageParam","hasNextPage","hasPreviousPage","fetchState","QueryObserver","_QueryObserver_instances","_client","_currentQuery","_currentQueryInitialState","_currentResult","_currentResultState","_currentResultOptions","_selectError","_selectFn","_selectResult","_lastQueryWithDefinedData","_staleTimeoutId","_refetchIntervalId","_currentRefetchInterval","_trackedProps","shouldFetchOnMount","__privateMethod","executeFetch_fn","updateTimers_fn","shouldFetchOn","clearStaleTimeout_fn","clearRefetchInterval_fn","prevOptions","prevQuery","updateQuery_fn","mounted","shouldFetchOptionally","updateStaleTimeout_fn","nextRefetchInterval","computeRefetchInterval_fn","updateRefetchInterval_fn","onPropTracked","defaultedOptions","unsubscribe","resolveEarly","cachePromise","fetchOptions","prevResult","prevResultState","prevResultOptions","queryInitialState","state","newState","isPlaceholderData","fetchOnMount","fetchOptionally","errorUpdatedAt","skipSelect","placeholderData","selectError","isFetching","isPending","isError","hasData","isStale","nextResult","notifyListeners","notifyOnChangeProps","notifyOnChangePropsValue","promise","shouldScheduleTimer_fn","timeout","nextInterval","shouldLoadOnMount","InfiniteQueryObserver","parentResult","isRefetching","isRefetchError","fetchDirection","_b","isFetchNextPageError","isFetchingNextPage","isFetchPreviousPageError","isFetchingPreviousPage","getDefaultState","MutationObserver","_MutationObserver_instances","_currentMutation","_mutateOptions","updateResult_fn","action","notify_fn","variables","mutateOptions","onMutateResult","_c","_d","IsRestoringContext","useIsRestoring","createValue","isReset","QueryErrorResetBoundaryContext","useQueryErrorResetBoundary","ensurePreventErrorBoundaryRetry","errorResetBoundary","useClearResetErrorBoundary","React.useEffect","getHasError","suspense","ensureSuspenseTimers","clamp","originalStaleTime","shouldSuspend","fetchOptimistic","observer","useBaseQuery","Observer","isRestoring","subscribed","React.useState","shouldSubscribe","React.useSyncExternalStore","onStoreChange","useQuery","useMutation","mutate","useInfiniteQuery","bind","thisArg","toString","getPrototypeOf","toStringTag","obj","prop","isUnsafeObjectKey","isPrototypeBoundary","isSafeAndFullyMutable","descriptor","hasOwnInPrototypeChain","thing","seen","getSafeProp","toSafeFlatObject","sourcePrototype","merged","current","kindOf","cache","kindOfTest","typeOfTest","isUndefined","isBuffer","isFunction","isArrayBuffer","isArrayBufferView","isString","isNumber","isObject","isBoolean","isEmptyObject","isDate","isFile","isReactNativeBlob","isReactNative","formData","isBlob","isFileList","isSet","isStream","getGlobal","FormDataCtor","isFormData","proto","kind","isURLSearchParams","isReadableStream","isRequest","isResponse","isHeaders","trim","forEach","allOwnKeys","len","findKey","_global","isContextDefined","merge","objs","caseless","skipUndefined","lowerCaseKeys","assignValue","targetKey","lowerKey","knownKey","existing","symbols","j","symbol","propertyIsEnumerable","extend","stripBOM","content","inherits","constructor","superConstructor","descriptors","toFlatObject","sourceObj","destObj","propFilter","endsWith","searchString","position","indexes","arr","isTypedArray","TypedArray","forEachEntry","_iterator","pair","matchAll","regExp","isHTMLForm","toCamelCase","p1","p2","isRegExp","reduceDescriptors","reducedDescriptors","ret","freezeMethods","toObjectSet","arrayOrString","delimiter","define","toFiniteNumber","isSpecCompliantForm","toJSONObject","visited","visit","reducedValue","isAsyncFn","isThenable","_setImmediate","setImmediateSupported","postMessageSupported","token","callbacks","asap","isIterable","isSafeIterable","utils$1","ignoreDuplicateOf","utils","parseHeaders","rawHeaders","parsed","line","hasKey","trimSPorHTAB","start","end","code","INVALID_UNICODE_HEADER_VALUE_CHARS","INVALID_BYTE_STRING_HEADER_VALUE_CHARS","sanitizeValue","invalidChars","sanitizeHeaderValue","sanitizeByteStringHeaderValue","toByteStringHeaderObject","headers","byteStringHeaders","header","$internals","normalizeHeader","normalizeValue","parseTokens","tokens","tokensRE","parameterNameRE","trimOWS","decodeQuotedString","last","decoded","parseParameters","parameters","quoted","escaped","parseParameter","part","equals","normalizedName","parameterValue","isValidHeaderName","PROTO_HEADER_SLOT","headerSlot","matchHeaderValue","isHeaderNameFilter","formatHeader","buildAccessors","accessorName","arg1","arg2","arg3","AxiosHeaders$1","valueOrRewrite","rewrite","setHeader","_value","_header","_rewrite","lHeader","setHeaders","entry","parser","matcher","deleted","deleteHeader","normalized","targets","asStrings","first","computed","accessors","defineAccessor","AxiosHeaders","mapped","headerValue","REDACTED","hasOwnOrPrototypeToJSON","redactConfig","redactKeys","lowerKeys","stringifySafely","aggregateErrorMessage","CAUSED_BY_SEPARATOR","$causeStack","getCauseStackIndex","causeStack","appendCauseStack","sourceStack","targetStack","AxiosError","request","response","customProps","axiosError","serializedConfig","httpAdapter","DEFAULT_FORM_DATA_MAX_DEPTH","isVisitable","removeBrackets","renderKey","dots","isFlatArray","predicates","toFormData","fallback","metaTokens","visitor","defaultVisitor","_Blob","maxDepth","useBlob","convertValue","throwIfMaxDepthExceeded","stringifyWithDepthLimit","ancestors","currentValue","el","exposedHelpers","build","encode","charMap","AxiosURLSearchParams","encoder","_encode","buildURL","url","_options","serializeFn","serializedParams","hashmarkIndex","countHandlers","handlers","trimHandlers","normalizeHandlerId","syncHandlerEntries","manager","internals","length","InterceptorManager","fulfilled","handler","handlerId","transitionalDefaults","URLSearchParams$1","FormData$1","Blob$1","platform$1","URLSearchParams","FormData","Blob","hasBrowserEnv","_navigator","hasStandardBrowserEnv","hasStandardBrowserWebWorkerEnv","origin","platform","toURLEncodedForm","helpers","MAX_DEPTH","throwIfDepthExceeded","parsePropPath","pattern","arrayToObject","normalizeArray","normalizeArrays","formDataToJSON","buildPath","isNumericKey","isLast","methodList","own","rawValue","defaults","contentType","hasJSONContentType","isObjectPayload","formSerializer","env","_FormData","transitional","forcedJSONParsing","responseType","JSONRequested","strictJSONParsing","method","transformData","fns","isCancel","settle","validateStatus","urlParserControlCharacters","normalizeURLForProtocolCheck","parseProtocol","decodeCookieValue","cookies","expires","domain","secure","sameSite","cookie","cookieString","eq","store","speedometer","samplesCount","min","bytes","timestamps","head","tail","firstSampleTS","chunkLength","now","startedAt","bytesCount","passed","throttle","freq","timestamp","threshold","lastArgs","timer","invoke","progressEventReducer","isDownloadStream","bytesNotified","_speedometer","rawLoaded","total","loaded","progressBytes","rate","progressEventDecorator","throttled","lengthComputable","asyncDecorator","scheduler","isURLSameOrigin","isAbsoluteURL","combineURLs","baseURL","relativeURL","malformedHttpProtocol","redactFragment","separator","parameterName","redactSensitiveURLParts","redactedURL","fragmentIndex","redactedURLWithoutFragment","assertValidHttpProtocolURL","normalizedURL","buildFullPath","requestedURL","allowAbsoluteUrls","isRelativeUrl","assertParamsAcyclic","active","done","headersToObject","ownEnumerableKeys","mergeParams","copies","empty","base","bases","baseKeys","sourceKeys","hasSource","previous","getMergedValue","mergeDeepProperties","valueFromConfig2","defaultToConfig2","getMergedTransitionalOption","config1","config2","transitional2","transitional1","mergeDirectKeys","mergeHeaders","hasOwnPropertyDescriptor","mergeMap","mergeConfig","configValue","FORM_DATA_CONTENT_HEADERS","setFormDataHeaders","formHeaders","policy","encodeUTF8","hex","readCookie","resolveConfig","readXsrfCookie","newConfig","withXSRFToken","xsrfHeaderName","xsrfCookieName","auth","username","password","encodeUsername","getHeaders","xsrfValue","isXHRAdapterSupported","xhrAdapter","useAsyncXsrf","_config","requestData","requestHeaders","onUploadProgress","onDownloadProgress","onCanceled","uploadThrottled","downloadThrottled","flushUpload","flushDownload","flushDownloadWithEvent","onloadend","responseHeaders","msg","timeoutErrorMessage","cancel","CanceledError","xhr","protocol","sendRequest","deadline","abortOnTimeout","scheduleTimeout","remaining","headerName","composeSignals","signals","controller","aborted","onabort","reason","signal","unsubscribeSignal","streamChunk","chunk","chunkSize","pos","readBytes","iterable","readStream","stream","reader","trackStream","onProgress","onFinish","_onFinish","loadedBytes","CRLF","normalizeLines","escapeName","stringBytes","normalize","FormDataError","formDataToBlob","form","limit","limitError","boundary","footer","parts","checkLength","valueLength","partLength","blobParts","createMultipartBody","crypto","random","isHexDigit","charCode","isPercentEncodedByte","hexValue","isBase64Char","isBase64Whitespace","base64Bytes","significant","groups","remainder","estimateBase64BufferAllocation","body","padding","estimatePercentDecodedBase64Bytes","invalid","estimateDataURLBytes","estimateBase64","base64Pattern","comma","meta","estimateDataURLDecodedBytes","VERSION","DEFAULT_CHUNK_SIZE","DEFAULT_REQUEST_OPTIONS","decodeURIComponentSafe","test","maybeWithAuthCredentials","protocolIndex","urlToCheck","factory","globalObject","ReadableStream","TextEncoder","envFetch","Request","Response","isFetchSupported","isRequestSupported","isResponseSupported","isReadableStreamSupported","encodeText","supportsRequestStream","duplexAccessed","hasContentType","supportsResponseStream","requestDefaults","resolvers","res","getBodyLength","resolveBodyLength","cancelToken","withCredentials","maxContentLength","maxBodyLength","maxRedirects","hasMaxContentLength","hasMaxBodyLength","_fetch","composedSignal","requestContentLength","pendingBodyError","pendingResponseError","maxBodyLengthError","configAuth","parsedURL","urlUsername","urlPassword","formContentType","formBoundary","outboundLength","mustEnforceStreamBody","trackRequestStream","_request","contentTypeHeader","isCredentialsSupported","safeFetchOptions","resolvedOptions","declaredLength","isStreamResponse","responseContentLength","bytesRead","onChunkProgress","responseData","materializedSize","canceledError","networkError","seedCache","getFetch","configuredEnv","fetch","seeds","seed","map","knownAdapters","fetchAdapter.getFetch","renderReason","isResolvedHandle","adapter","getAdapter","adapters","nameOrAdapter","rejectedReasons","reasons","throwIfCancellationRequested","elapsedSince","dispatchRequest","validators","deprecatedWarnings","validator","version","formatMessage","opt","desc","opts","correctSpelling","assertOptions","schema","allowUnknown","isHeadersBucket","Axios$1","instanceConfig","configOrUrl","dummy","dummyStack","firstNewlineIndex","secondNewlineIndex","duplicateCheckSuffix","currentStack","causeIndex","stackHead","causeSection","paramsSerializer","commonHeaders","methodHeaders","contextHeaders","requestInterceptorChain","synchronousRequestInterceptors","interceptor","responseInterceptorChain","chain","onFulfilled","onRejected","rejectedResult","rejectedError","fullPath","Axios","generateHTTPMethod","isForm","CancelToken$1","CancelToken","executor","resolvePromise","onfulfilled","_resolve","abort","spread","isAxiosError","HttpStatusCode","createInstance","defaultConfig","instance","axios","promises","all","Cancel","formToJSON","BASE","useTableConfig","tableName","col","useTableData","fetchFn","pageSize","defaultSortBy","defaultSortOrder","setSortBy","setSortOrder","setActiveTab","setFilters","buildParams","cursor","fetchNextPage","refetch","pageParam","lastPage","items","loadMore","handleSort","handleTabChange","updateFilter","prev","optimisticUpdate","page","optimisticRemove","surveysApi","weeks","templateId","Card","SC","SurveyGridCard","isSelected","onSelect","sc","surveysColumns","tableConfig","rawItems","setSelectedIds","deleteTarget","setDeleteTarget","isDeleting","setIsDeleting","handleDelete","goCreate","stats","totalResp","scored","avgNps","styles","Fragment","TC","setName","setDescription","setTarget","questions","setQuestions","submitting","setSubmitting","created","setCreated","errors","setErrors","addQ","updateQ","handleSubmit","errs","oi","useSurveyResponses","at","dir","NPS_CATEGORIES","responsesSearchConfig","responsesSortConfig","buildResponsesFilters","surveyNames","responsesColumns","detailColumns","detailSearch","fmtDate","STATUS_STYLE","surveyId","survey","analytics","insight","resp","surveyResponses","goBack","backButton","CATEGORY_STYLES","UseTemplateModal","template","mutation","handleBackdrop","TemplateCard","onUse","Skeleton","activeCategory","setActiveCategory","selected","setSelected","templates","list","categories","filtered","isActive","barColor","score","delta","trend","needsAttention","buildAnalyticsTabs","attention","filterByTab","analyticsSearchConfig","analyticsSortConfig","analyticsFilters","analyticsColumns","setTab","activeId","setActiveId","tabRows","avgCompletion","dash"],"mappings":";;;;;;;;;;;;;;;;;;;AASa,MAAIA,IAAE,OAAO,IAAI,eAAe,GAAEC,IAAE,OAAO,IAAI,cAAc,GAAEC,IAAE,OAAO,IAAI,gBAAgB,GAAEC,IAAE,OAAO,IAAI,mBAAmB,GAAEC,IAAE,OAAO,IAAI,gBAAgB,GAAEC,IAAE,OAAO,IAAI,gBAAgB,GAAEC,IAAE,OAAO,IAAI,eAAe,GAAEC,IAAE,OAAO,IAAI,mBAAmB,GAAEC,IAAE,OAAO,IAAI,gBAAgB,GAAEC,IAAE,OAAO,IAAI,YAAY,GAAEC,IAAE,OAAO,IAAI,YAAY,GAAEC,IAAE,OAAO;AAAS,WAASC,EAAEC,GAAE;AAAC,WAAUA,MAAP,QAAqB,OAAOA,KAAlB,WAA2B,QAAKA,IAAEF,KAA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,MAAK,MAAK,YAAW,MAAM,IAAI,WAAU,kCAAiC;AAAA,YAC3EJ,gBAAAA,EAAAA,IAAC,QAAA,EAAK,WAAU,8DAA6D,UAAA,YAAA,CAAS;AAAA,UAAA,GACxF;AAAA,gCACC,KAAA,EAAE,WAAU,6CAA6C,UAAAyyB,EAAO,YAAY,IAAA,CAAI;AAAA,QAAA,GACnF;AAAA,QACAxyB,gBAAAA,EAAAA,KAAC,OAAA,EAAI,WAAU,2KACb,UAAA;AAAA,UAAAA,gBAAAA,EAAAA,KAAC,OAAA,EAAI,WAAU,kCACb,UAAA;AAAA,YAAAD,gBAAAA,MAACI,MAAK,MAAK,cAAa,MAAM,IAAI,WAAU,sCAAqC;AAAA,YACjFJ,gBAAAA,EAAAA,IAAC,QAAA,EAAK,WAAU,kEAAiE,UAAA,oBAAA,CAAiB;AAAA,UAAA,GACpG;AAAA,gCACC,KAAA,EAAE,WAAU,6CAA6C,UAAAyyB,EAAO,eAAe,IAAA,CAAI;AAAA,QAAA,EAAA,CACtF;AAAA,MAAA,EAAA,CACF,EAAA,CACF;AAAA,IAAA,EAAA,CAEJ;AAAA,EAAA,GACF;AAEJ;;;;","x_google_ignoreList":[0,1,2,5,6,7,10,11,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96]}